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

[PR] fix(consensus): close metadata and consensus plane TODOs [iggy]

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

   Clears ten `TODO` markers across the metadata, consensus, and shard planes. One commit per item.
   
   ## Correctness
   
   **Roll back the sequencer on a WAL append failure.** `push_prepare_entry` claims an op before the journal append, so a failed append left the sequencer one ahead of the WAL forever and the next prepare chained over a hole no repair path refills. `rollback_pipelined_prepare` hands the op back and drops the pipeline entry. Refused when a sibling prepare was already projected off the failed op, since unwinding there would hand a live op number out twice.
   
   **Snapshot format versioning.** `version` was a hardcoded `1` with no read-side check. Now exact-equality with fail-stop, plus a `release_format` provenance stamp, TigerBeetle's pair. The version is peeked off the msgpack prefix before the payload is deserialized, so a foreign layout is refused by version rather than by whichever field misparsed. Covers boot recovery and both state-transfer paths.
   
   ## Performance
   
   **Zero-alloc op construction in STM apply.** `Bytes::copy_from_slice` per op body, then borrowed as `&[u8]` and dropped. `WireDecode::decode_from` takes a slice, so the `Bytes` bought nothing. Decodes off the backing buffer via a new `Message::body()`. Also drops a 256-byte header copy per op.
   
   **One frame parse per hop.** Frames were classified twice, once in the router for routing and once in the shard for dispatch. `ShardFrame::Consensus` carries the `MessageBag`; `MessageBag::routing()` / `into_generic()` replace the router's 60-line `extract_routing`. `ShardFrame` stays 160 B, pinned by a `const` assert.
   
   ## Structure
   
   **Stop leaking `&RefCell<Pipeline>`.** 49 call sites move to named accessors plus `with_pipeline` / `with_pipeline_mut`, whose `FnOnce` bound makes a borrow-across-`.await` unrepresentable. Same shape as `IggyPartitions::with_partition`.
   
   **Prepare-timeout lifecycle.** "Ticking iff the pipeline is non-empty" now holds: `sync_prepare_timeout` disarms on empty and restarts otherwise, so a remaining head is timed from now instead of inheriting the drained entry's elapsed ticks. `init()` no longer arms it; a fresh primary has nothing to retransmit.
   
   **One result-section framing.** `build_login_register_reply` and `build_raw_pat_reply` each hand-assembled `[u32 count=0][payload]`; the raw-PAT reply shipped once without the prefix and broke SDK decoding. One helper is now the only way to emit a success reply with a body.
   
   **Stamp request-queue arrival.** `received_at` populated at park from `clock_realtime_micros()`, not `next_monotonic_timestamp()`. The latter advances the prepare-stamping sequence, so parking a request would perturb timestamps replicated to every backup.
   
   **Fold the duplicated view-change entry.** Three sites inlined the same 12-line sequence, differing only in `reason`. Extracted to `enter_view_change`.
   
   ## Tests
   
   **Pump realloc under a live partition borrow.** The borrow tripwire and deterministic executor already covered a concurrent `remove`; this adds the realloc half, where a growing `push` relocates every element. Guarded against passing vacuously by a new `buffer_addr()` and an `assert_ne!` across the insert, and falsification-checked. Swapping the bad read for `with_partition` makes it fail with "tripwire did not fire".
   
   Also: a real-`PrepareJournal` append-failure rollback test, four rollback-outcome tests, two timer-lifecycle tests, a park-stamp test, snapshot version/peek/refusal tests, and a login-register framing test.


-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/metadata/src/impls/recovery.rs:
##########
@@ -1672,47 +1673,63 @@ mod tests {
     }
 
     #[compio::test]
-    async fn recover_accepts_snapshot_written_before_a_trailing_default_field() {
-        // Appending a `#[serde(default)]` field is this repo's forward-compatible
-        // snapshot migration, and msgpack encodes structs positionally: a file the
-        // previous build wrote decodes fine (the default fills the missing element)
-        // but re-encodes with one MORE element. A pairing checksum recomputed by
-        // re-encoding the decoded snapshot would therefore diverge on the FIRST boot
-        // of the new build and refuse every checkpointed node, with the WAL prefix
-        // already drained. Hashing the bytes on disk is what makes that upgrade boot.
-        //
-        // Emulated in the direction the migration runs: strip the trailing element off
-        // a current-shape file, which is what the pre-`client_table` build wrote.
+    async fn recover_refuses_a_snapshot_from_another_format_version() {
+        // A snapshot shape is only as trustworthy as the version stamped on it, so a
+        // foreign one refuses boot rather than restoring whatever msgpack happens to
+        // make of the bytes. Everything else about the directory is healthy: the
+        // superblock pairs with the file on disk, so the refusal can only be the
+        // version.
+        const CHECKPOINT_OP: u64 = 42;
+        let mut snapshot = IggySnapshot::new(CHECKPOINT_OP);
+        snapshot.snapshot_mut().version = SNAPSHOT_FORMAT_VERSION + 1;
+        let foreign = snapshot.encode().unwrap();
+
+        let dir = tempdir().unwrap();
+        let metadata_dir = dir.path().join("metadata");
+        std::fs::create_dir_all(&metadata_dir).unwrap();
+        std::fs::write(metadata_dir.join("snapshot.bin"), &foreign).unwrap();
+        let state = vsr_state_with_checkpoint(CHECKPOINT_OP, checkpoint_checksum(&foreign));
+        {
+            let superblock = PingPongSuperblock::open(&metadata_dir).await.unwrap();
+            superblock.write(&state.to_bytes()).await.unwrap();
+        }
+
+        match recover::<TestStm>(
+            dir.path(),
+            CLUSTERED,
+            journal::prepare_journal::DEFAULT_SLOT_COUNT,
+            CLIENTS_TABLE_MAX,
+            |_| {},
+        )
+        .await
+        {
+            Err(RecoveryError::Snapshot(SnapshotError::UnsupportedFormatVersion {
+                found,
+                expected,
+            })) => {
+                assert_eq!(found, SNAPSHOT_FORMAT_VERSION + 1);
+                assert_eq!(expected, SNAPSHOT_FORMAT_VERSION);
+            }
+            Err(other) => panic!("expected a format-version refusal, got {other}"),
+            Ok(_) => panic!("expected a foreign format version to refuse boot"),
+        }
+    }
+
+    #[compio::test]
+    async fn recover_pairs_the_checkpoint_against_the_bytes_on_disk() {

Review Comment:
   Done.



##########
core/server/src/bootstrap.rs:
##########
@@ -2323,20 +2323,21 @@ fn restore_metadata_consensus(
             commit_watermark,
             restored_op, "re-pipelining recovered uncommitted metadata suffix"
         );
-        let mut pipeline = consensus.pipeline().borrow_mut();
-        #[allow(clippy::cast_possible_truncation)]
-        for op in (commit_watermark + 1)..=restored_op {
-            let Some(header) = journal.header(op as usize) else {
-                warn!(
-                    op,
-                    "recovered journal suffix has a gap; stopping re-pipeline"
-                );
-                break;
-            };
-            let mut entry = PipelineEntry::new(*header);
-            entry.add_ack(topology.self_replica_id);
-            pipeline.push(entry);
-        }
+        consensus.with_pipeline_mut(|pipeline| {

Review Comment:
   Done. 



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {

Review Comment:
   **[blocking]** `rollback_pipelined_prepare` runs after the append await with no view or status fence, and the tail match is by op alone. If a view change completes while the append is parked and this replica is re-elected, `start_pending_view` rewinds the sequencer to the merged head, so a new request can re-project the same op number with a different checksum. The old append's failure then passes both guards here: it pops the new view's live entry, rewinds the sequencer and parent chain under it, the live entry's acks die at `pipeline_holds_entry`, the op number is minted again, and backups panic in `panic_if_hash_chain_would_break_in_same_view`. Suggest refusing unless `header.view == self.view()` and status is `Normal`, and matching the tail by `(op, checksum)`.



##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {
+        if !self.is_primary() {
+            return PrepareRollback::NotPreAdvanced;
+        }
+        let sequence = self.sequencer.current_sequence();
+        if sequence != header.op {
+            return PrepareRollback::Overtaken { sequence };
+        }
+        let removed = self.pipeline.borrow_mut().remove_tail(header.op);
+        debug_assert!(

Review Comment:
   **[blocking]** In release builds a `None` from `remove_tail` falls through this `debug_assert` and the sequencer and parent-chain rewind below still run, mutating state exactly when the invariant they rely on is violated. Returning a refusal on `None` without mutating keeps release behavior aligned with the assertion.



##########
core/metadata/src/stm/snapshot.rs:
##########
@@ -15,12 +15,52 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use iggy_binary_protocol::IGGY_PROTOCOL_VERSION;
 use serde::{Deserialize, Serialize, de::DeserializeOwned};
 use std::fmt;
 
 use crate::stm::stream::StreamsSnapshot;
 use crate::stm::user::UsersSnapshot;
 
+/// The version of the snapshot format in use, reserved for breaking changes.
+///
+/// One version means exactly one serialized shape, and [`MetadataSnapshot::decode`]
+/// accepts nothing else. Bump it in the same change that alters the shape: append,
+/// remove, reorder, retype, or redefine the meaning of any field, at any depth
+/// under [`MetadataSnapshot`]. There is no accepted range and no per-version
+/// translation. A snapshot this build cannot read is refused, not best-effort
+/// decoded.
+///
+/// Nothing softer would hold. msgpack encodes a struct positionally, so a field one
+/// build appends reaches another as an unexplained extra array element; without the
+/// version the reader either fails on an unrelated msgpack error or, for a
+/// same-length change, silently reads one field's bytes as another's.
+///
+/// Bumping it invalidates every `snapshot.bin` already on disk, and a node whose
+/// snapshot is refused refuses boot. That is deliberate. The metadata plane is
+/// pre-production, so the cost is clearing a data directory; once it ships, a bump
+/// needs an explicit translation path added here alongside it.
+///
+/// Version 2: `status` sits at reply-header offset 216 (version 1 carried a
+/// `namespace` word before it), which the client table's cached replies embed as raw
+/// wire bytes msgpack cannot introspect.
+pub const SNAPSHOT_FORMAT_VERSION: u32 = 2;

Review Comment:
   **[blocking]** The serialized shape changes in this PR (`release_format` appended, `#[serde(default)]` dropped from `client_table`) but the version stays 2, and master already writes 6-element version-2 files. On the first cross-build boot the peek passes and `rmp_serde` fails with an invalid-length error, so the refusal surfaces as `SnapshotError::Deserialize`, the corruption-shaped diagnosis this gate exists to prevent. Both upgrade and downgrade directions misreport. This violates the bump rule documented above; bump to 3.



##########
core/metadata/src/impls/metadata.rs:
##########
@@ -1198,28 +1198,35 @@ where
         // violates VSR tail-ahead-of-head, recoverable only via hash-chain
         // fence + view change (burns a view).
         //
-        // TODO(hubcio): the primary path violates the invariant in the
-        // comment above. `consensus::impls::push_prepare_entry` pre-advances
-        // `sequencer.set_sequence(header.op)` and
-        // `set_last_prepare_checksum(header.checksum)` BEFORE this append.
-        // If the append below returns `Err`, sequencer + checksum stay
-        // advanced while the WAL holds no matching entry: the next prepare
-        // chains off a phantom op, cluster state diverges, and the
-        // `MetadataHandoff::Waiter` factory bundle propagates the divergence
-        // to peers. Fix: rollback `sequencer.set_sequence` +
-        // `set_last_prepare_checksum` to their captured prior values on
-        // append failure (preferred per CLAUDE.md "no panics in libraries"),
-        // or abort the shard.
+        // On the primary the pre-advance in `push_prepare_entry` already claimed
+        // this op, so a failed append has to hand it back or the next prepare
+        // chains off a phantom (see `rollback_pipelined_prepare`). The rollback is
+        // refused when a sibling prepare was pipelined during the await and has
+        // already been projected off this op; that log cannot be repaired from
+        // here, so it is reported and left to a view change.
         if let Err(e) = journal.handle().append(message.clone()).await {
+            let rollback = consensus.rollback_pipelined_prepare(&header);
             error!(
                 target: "iggy.metadata.diag",
                 plane = "metadata",
                 replica_id = consensus.replica(),
                 op = header.op,
                 operation = ?header.operation,
                 error = %e,
+                rollback = ?rollback,
                 "journal append failed"
             );
+            if let PrepareRollback::Overtaken { sequence } = rollback {
+                error!(
+                    target: "iggy.metadata.diag",
+                    plane = "metadata",
+                    replica_id = consensus.replica(),
+                    op = header.op,
+                    sequence,
+                    "journal append failed after a sibling prepare was projected off this op; \

Review Comment:
   **[warning]** Nothing triggers the view change this log waits on. The failed op was never broadcast, backups gap-drop the sibling at the hole check, and this primary keeps sending Commit heartbeats that reset the backups' election timers, so the group wedges permanently while looking healthy. A solo group has no peer at all. The wedge itself predates this PR (any append failure did this), but the log text is new and promises repair that cannot come. Either escalate here (cede primaryship or fail-stop, per the removed TODO) or reword to state that no election will follow without operator action.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -1996,11 +1996,9 @@ where
                 // Two-queue: prepare slot -> project+replicate; prepare full +
                 // request room -> buffer; both full -> drop+warn (client retries
                 // via read-timeout).
-                if consensus.pipeline().borrow().is_full() {
-                    let push_result = consensus
-                        .pipeline()
-                        .borrow_mut()
-                        .push_request(consensus::RequestEntry::new(message));
+                if consensus.pipeline_is_full() {
+                    let push_result =
+                        consensus.push_queued_request(consensus::RequestEntry::new(message));

Review Comment:
   **[warning]** Parity gap: the partitions-plane primary has the same pre-advance in `push_prepare_entry`, but its append-failure arm still warns and returns without `rollback_pipelined_prepare`, leaving the sequencer ahead of the WAL on the data plane. The new rollback is plane-agnostic and the failure arm has no half-applied state, so mirroring the metadata call looks safe. Fine as a follow-up since it predates this PR, but worth a tracking issue before merge.



##########
core/consensus/src/impls.rs:
##########
@@ -1418,17 +1493,117 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         self.status.get()
     }
 
-    // TODO(hubcio): returning &RefCell<P> leaks interior mutability - callers
-    // could hold a Ref/RefMut across an .await and cause a runtime panic.
-    // We had this problem with slab + ECS.
+    /// Run `f` against the pipeline.
+    ///
+    /// The borrow cannot escape `f`, so it cannot be held across an `.await` and
+    /// alias a sibling task's `borrow_mut` into a `BorrowMutError` panic. Same
+    /// shape, and the same reason, as `IggyPartitions::with_partition`. Prefer
+    /// the named accessors below; this is for the few callers that need several
+    /// reads under one borrow.
+    pub fn with_pipeline<R>(&self, f: impl FnOnce(&P) -> R) -> R {
+        f(&self.pipeline.borrow())
+    }
+
+    /// [`Self::with_pipeline`] for a mutating operation.
+    ///
+    /// Callers that pop or clear should prefer [`Self::pop_committed_prepare`] /
+    /// [`Self::clear_pipeline`], which also keep the prepare timeout's
+    /// ticking-iff-non-empty invariant. This form does not.
+    pub fn with_pipeline_mut<R>(&self, f: impl FnOnce(&mut P) -> R) -> R {
+        f(&mut self.pipeline.borrow_mut())
+    }
+
+    /// Whether the prepare queue is at its depth bound; callers route to
+    /// [`Self::push_queued_request`] on `true`.
+    #[must_use]
+    pub fn pipeline_is_full(&self) -> bool {
+        self.pipeline.borrow().is_full()
+    }
+
+    #[must_use]
+    pub fn pipeline_is_empty(&self) -> bool {
+        self.pipeline.borrow().is_empty()
+    }
+
+    /// In-flight prepare count.
+    #[must_use]
+    pub fn pipeline_len(&self) -> usize {
+        self.pipeline.borrow().len()
+    }
+
+    /// Requests parked waiting for a prepare slot.
+    #[must_use]
+    pub fn request_queue_len(&self) -> usize {
+        self.pipeline.borrow().request_queue_len()
+    }
+
+    /// Whether either queue already carries a request from `client_id`: the
+    /// metadata plane's in-flight dedup.
+    #[must_use]
+    pub fn pipeline_has_message_from_client(&self, client_id: u128) -> bool {
+        self.pipeline.borrow().has_message_from_client(client_id)
+    }
+
+    /// Header of the oldest in-flight prepare.
     #[must_use]
-    pub const fn pipeline(&self) -> &RefCell<P> {
-        &self.pipeline
+    pub fn pipeline_head_header(&self) -> Option<PrepareHeader> {
+        self.pipeline.borrow().head().map(|entry| entry.header)
     }
 
+    /// Whether an in-flight prepare matches `(op, checksum)`: the ack paths' test
+    /// that the frame they are about to count still describes a live entry.
     #[must_use]
-    pub const fn pipeline_mut(&mut self) -> &mut RefCell<P> {
-        &mut self.pipeline
+    pub fn pipeline_holds_entry(&self, op: u64, checksum: u128) -> bool {
+        self.pipeline
+            .borrow()
+            .entry_by_op_and_checksum(op, checksum)
+            .is_some()
+    }
+
+    /// Promote the oldest parked request, if any.
+    pub fn pop_queued_request(&self) -> Option<P::Request> {
+        self.pipeline.borrow_mut().pop_request()
+    }
+
+    /// Pop the pipeline head once its op has committed, keeping the prepare
+    /// timeout's lifecycle in step.
+    ///
+    /// The timeout measures the age of the oldest un-acked prepare, so draining
+    /// the head has to either stop it (nothing left to retransmit) or restart it
+    /// (the next entry becomes the oldest, and it must be timed from now rather
+    /// than inheriting the drained entry's elapsed ticks). Arming happens in
+    /// [`Self::push_prepare_entry`]; between the two the invariant is "ticking
+    /// iff the pipeline is non-empty".
+    pub fn pop_committed_prepare(&self) -> Option<P::Entry> {
+        let popped = self.pipeline.borrow_mut().pop();
+        if popped.is_some() {
+            self.sync_prepare_timeout();
+        }
+        popped
+    }
+
+    /// Drop every in-flight prepare and parked request, and disarm the prepare
+    /// timeout with them (a view change re-prepares from the new primary; there
+    /// is nothing left here to retransmit).
+    pub fn clear_pipeline(&self) {
+        self.pipeline.borrow_mut().clear();
+        self.timeouts.borrow_mut().stop(TimeoutKind::Prepare);
+    }
+
+    /// Re-establish "prepare timeout ticking iff the pipeline is non-empty".
+    ///
+    /// Stops the timer on an empty pipeline; otherwise restarts it so it times
+    /// the current oldest entry from now. Exposed for the plane-side drains that
+    /// pop through [`Pipeline`] directly (`drain_committable_prefix`) rather than
+    /// through [`Self::pop_committed_prepare`].
+    pub fn sync_prepare_timeout(&self) {
+        let empty = self.pipeline.borrow().is_empty();
+        let mut timeouts = self.timeouts.borrow_mut();
+        if empty {
+            timeouts.stop(TimeoutKind::Prepare);
+        } else {
+            timeouts.reset(TimeoutKind::Prepare);

Review Comment:
   **[nit]** `Timeout::reset` never sets `ticking`, so on a stopped timer with a non-empty pipeline this branch leaves it armed-but-dead and the doc's "restarts it" does not hold. Every current caller happens to be preceded by a start-arm (`advance_commit_max`, become-primary), but the bootstrap re-pipeline gap flagged separately would land on this branch. `start` when not ticking, `reset` otherwise; same trap `advance_commit_max` documents.



##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {
+        if !self.is_primary() {
+            return PrepareRollback::NotPreAdvanced;
+        }
+        let sequence = self.sequencer.current_sequence();
+        if sequence != header.op {
+            return PrepareRollback::Overtaken { sequence };
+        }
+        let removed = self.pipeline.borrow_mut().remove_tail(header.op);
+        debug_assert!(
+            removed.is_some(),
+            "sequencer at op {} but the pipeline tail is not that op",
+            header.op
+        );
+        drop(removed);
+        self.sequencer.set_sequence(header.op.saturating_sub(1));
+        self.set_last_prepare_checksum(header.parent);
+        PrepareRollback::Unwound

Review Comment:
   **[nit]** The `Unwound` path pops the tail without `sync_prepare_timeout`, so unwinding the sole in-flight entry leaves the Prepare timer ticking on an empty pipeline, against the invariant this PR introduces. The backstop in `handle_prepare_timeout` caps the cost at one spurious fire.



##########
core/metadata/src/impls/recovery.rs:
##########
@@ -1672,47 +1673,63 @@ mod tests {
     }
 
     #[compio::test]
-    async fn recover_accepts_snapshot_written_before_a_trailing_default_field() {
-        // Appending a `#[serde(default)]` field is this repo's forward-compatible
-        // snapshot migration, and msgpack encodes structs positionally: a file the
-        // previous build wrote decodes fine (the default fills the missing element)
-        // but re-encodes with one MORE element. A pairing checksum recomputed by
-        // re-encoding the decoded snapshot would therefore diverge on the FIRST boot
-        // of the new build and refuse every checkpointed node, with the WAL prefix
-        // already drained. Hashing the bytes on disk is what makes that upgrade boot.
-        //
-        // Emulated in the direction the migration runs: strip the trailing element off
-        // a current-shape file, which is what the pre-`client_table` build wrote.
+    async fn recover_refuses_a_snapshot_from_another_format_version() {
+        // A snapshot shape is only as trustworthy as the version stamped on it, so a
+        // foreign one refuses boot rather than restoring whatever msgpack happens to
+        // make of the bytes. Everything else about the directory is healthy: the
+        // superblock pairs with the file on disk, so the refusal can only be the
+        // version.
+        const CHECKPOINT_OP: u64 = 42;
+        let mut snapshot = IggySnapshot::new(CHECKPOINT_OP);
+        snapshot.snapshot_mut().version = SNAPSHOT_FORMAT_VERSION + 1;
+        let foreign = snapshot.encode().unwrap();
+
+        let dir = tempdir().unwrap();
+        let metadata_dir = dir.path().join("metadata");
+        std::fs::create_dir_all(&metadata_dir).unwrap();
+        std::fs::write(metadata_dir.join("snapshot.bin"), &foreign).unwrap();
+        let state = vsr_state_with_checkpoint(CHECKPOINT_OP, checkpoint_checksum(&foreign));
+        {
+            let superblock = PingPongSuperblock::open(&metadata_dir).await.unwrap();
+            superblock.write(&state.to_bytes()).await.unwrap();
+        }
+
+        match recover::<TestStm>(
+            dir.path(),
+            CLUSTERED,
+            journal::prepare_journal::DEFAULT_SLOT_COUNT,
+            CLIENTS_TABLE_MAX,
+            |_| {},
+        )
+        .await
+        {
+            Err(RecoveryError::Snapshot(SnapshotError::UnsupportedFormatVersion {
+                found,
+                expected,
+            })) => {
+                assert_eq!(found, SNAPSHOT_FORMAT_VERSION + 1);
+                assert_eq!(expected, SNAPSHOT_FORMAT_VERSION);
+            }
+            Err(other) => panic!("expected a format-version refusal, got {other}"),
+            Ok(_) => panic!("expected a foreign format version to refuse boot"),
+        }
+    }
+
+    #[compio::test]
+    async fn recover_pairs_the_checkpoint_against_the_bytes_on_disk() {

Review Comment:
   **[nit]** This test writes canonical bytes, which re-encode byte-identically (the byte-stability tests pin that), so the recomputed checksum equals the on-disk one under either checksum source and the test passes even if recovery re-encoded the decoded snapshot. Feeding a noncanonical but decodable file, for example the version encoded as a uint32 marker (accepted by `read_int`, canonicalized on re-encode), restores the discrimination the deleted test had.



##########
core/server/src/bootstrap.rs:
##########
@@ -2323,20 +2323,21 @@ fn restore_metadata_consensus(
             commit_watermark,
             restored_op, "re-pipelining recovered uncommitted metadata suffix"
         );
-        let mut pipeline = consensus.pipeline().borrow_mut();
-        #[allow(clippy::cast_possible_truncation)]
-        for op in (commit_watermark + 1)..=restored_op {
-            let Some(header) = journal.header(op as usize) else {
-                warn!(
-                    op,
-                    "recovered journal suffix has a gap; stopping re-pipeline"
-                );
-                break;
-            };
-            let mut entry = PipelineEntry::new(*header);
-            entry.add_ack(topology.self_replica_id);
-            pipeline.push(entry);
-        }
+        consensus.with_pipeline_mut(|pipeline| {

Review Comment:
   **[nit]** This block pushes recovered entries without arming the Prepare timeout, and `init` no longer arms it. The branch is unreachable today (clustered restarts cede primaryship, solo forces the watermark to the restored op), but if it reactivates the recovered suffix never retransmits. Needs a `sync_prepare_timeout` here, which only works once the reset-vs-start issue in that helper is fixed.



##########
core/consensus/src/impls.rs:
##########
@@ -310,6 +320,42 @@ impl RequestEntry {
     }
 }
 
+impl<B, P> VsrConsensus<B, P>
+where
+    B: MessageBus,
+    P: Pipeline<Entry = PipelineEntry, Request = RequestEntry>,
+{
+    /// Park a request that could not take a prepare slot, stamping its arrival
+    /// time so the promotion side can measure how long it waited.
+    ///
+    /// # Errors
+    /// The entry itself, when the request queue is at its depth bound.
+    pub fn push_queued_request(&self, mut entry: RequestEntry) -> Result<(), RequestEntry> {
+        entry.received_at = self.clock_realtime_micros();
+        self.pipeline.borrow_mut().push_request(entry)
+    }
+}
+
+/// Outcome of [`VsrConsensus::rollback_pipelined_prepare`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PrepareRollback {
+    /// Sequencer, parent chain, and pipeline entry all restored. The op is free
+    /// again and the next request reuses it.
+    Unwound,
+    /// This replica never pre-advanced for the prepare, so there is nothing to
+    /// undo. A backup advances only AFTER its append succeeds.
+    NotPreAdvanced,

Review Comment:
   **[nit]** Both labels overclaim. `NotPreAdvanced` is returned for any non-primary, including a demoted ex-primary that did pre-advance (the view-change reset erased it, so the name is operationally true but literally false). `Overtaken` also covers `sequence < header.op` after a state-transfer rewind, where the sibling story in this doc and in the caller's log does not apply. Worth documenting both directions or branching the log text.



##########
core/server/src/responses.rs:
##########
@@ -1303,35 +1303,55 @@ pub(crate) fn build_deny_reply(
 /// Server build version advertised in the login-register response.
 const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
 
+/// Build a metadata reply carrying `payload` behind a success result section.
+///
+/// Every metadata reply is result-framed, and the SDK strips that section off
+/// unconditionally (`split_metadata_result`) before decoding what follows. A
+/// payload written without the leading zero count therefore has its first four
+/// bytes eaten as a result count, and the decode fails or, worse, succeeds on the
+/// shifted remainder. That is not hypothetical: the raw-PAT reply shipped once
+/// without the prefix and broke SDK decoding. This is the only way to emit a
+/// success reply with a body, so the prefix cannot be forgotten again.
+fn build_result_framed_reply(

Review Comment:
   **[nit]** Two overstatements in the doc: the SDK strips the result section only for `is_result_framed()` operations (plus a non-empty Register), not every metadata reply, and `build_reply_from_bytes` still emits success read replies with bodies, so this is not the only path. As written it could lead someone to result-frame a read reply and break decoding in the other direction. Minor: the payload could encode straight into `out[RESULT_COUNT_LEN..]` instead of a temporary `BytesMut`, though this path is cold.



##########
core/consensus/src/impls.rs:
##########
@@ -265,10 +265,20 @@ impl PipelineEntry {
 #[derive(Debug)]
 pub struct RequestEntry {
     pub message: Message<RoutedRequestHeader>,
-    // TODO: populate from monotonic clock at push, promote to `pub` for
-    // age-based filtering. Currently `0`; `pub(crate)` blocks sort-on-stub.
-    #[allow(dead_code)]
-    pub(crate) received_at: i64,
+    /// When the request was parked, in microseconds from the consensus-injected
+    /// clock ([`VsrConsensus::clock_realtime_micros`]). `0` until
+    /// [`VsrConsensus::push_queued_request`] stamps it, which is the only path
+    /// that parks an entry in production.
+    ///
+    /// Read against `clock_realtime_micros` at promotion for the queue wait:
+    /// what age-based shedding would filter on, and the queueing half of
+    /// end-to-end commit latency.
+    ///
+    /// Deliberately the plain clock read rather than
+    /// [`VsrConsensus::next_monotonic_timestamp`]: this must not consume the
+    /// prepare-stamping monotonic sequence, or parking a request would perturb
+    /// the timestamps replicated to every backup.
+    pub received_at: u64,

Review Comment:
   **[nit]** The documented reader pattern `clock_realtime_micros() - received_at` on `u64` underflows if the realtime clock steps back between park and promotion (the old `i64` kept the sign). No reader exists yet; worth stating the `saturating_sub` requirement here before one lands.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/server/src/responses.rs:
##########
@@ -1303,35 +1303,55 @@ pub(crate) fn build_deny_reply(
 /// Server build version advertised in the login-register response.
 const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
 
+/// Build a metadata reply carrying `payload` behind a success result section.
+///
+/// Every metadata reply is result-framed, and the SDK strips that section off
+/// unconditionally (`split_metadata_result`) before decoding what follows. A
+/// payload written without the leading zero count therefore has its first four
+/// bytes eaten as a result count, and the decode fails or, worse, succeeds on the
+/// shifted remainder. That is not hypothetical: the raw-PAT reply shipped once
+/// without the prefix and broke SDK decoding. This is the only way to emit a
+/// success reply with a body, so the prefix cannot be forgotten again.
+fn build_result_framed_reply(

Review Comment:
   Both doc overstatements fixed.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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

   ## [Codecov](https://app.codecov.io/gh/apache/iggy/pull/3870?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 82.25%. Comparing base ([`9cfb2d9`](https://app.codecov.io/gh/apache/iggy/commit/9cfb2d93a1a280f52305eb95057ef36042fbc210?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`86d27cc`](https://app.codecov.io/gh/apache/iggy/commit/86d27cc94ad271376a99bcf141d9d1bc23f65635?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.
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master    #3870      +/-   ##
   ============================================
   - Coverage     82.70%   82.25%   -0.45%     
     Complexity     1296     1296              
   ============================================
     Files          1199     1197       -2     
     Lines        159941   159332     -609     
     Branches     129545   129139     -406     
   ============================================
   - Hits         132281   131065    -1216     
   - Misses        24163    24768     +605     
   - Partials       3497     3499       +2     
   ```
   
   | [Components](https://app.codecov.io/gh/apache/iggy/pull/3870/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/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.21% <ø> (+0.01%)` | :arrow_up: |
   | [Java SDK](https://app.codecov.io/gh/apache/iggy/pull/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `66.15% <ø> (ø)` | |
   | [C# SDK](https://app.codecov.io/gh/apache/iggy/pull/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `75.67% <ø> (ø)` | |
   | [Python SDK](https://app.codecov.io/gh/apache/iggy/pull/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `89.98% <ø> (ø)` | |
   | [PHP SDK](https://app.codecov.io/gh/apache/iggy/pull/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `84.26% <ø> (ø)` | |
   | [Node SDK](https://app.codecov.io/gh/apache/iggy/pull/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `89.43% <ø> (-6.83%)` | :arrow_down: |
   | [Go SDK](https://app.codecov.io/gh/apache/iggy/pull/3870/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `68.60% <ø> (ø)` | |
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/iggy/pull/3870?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [core/consensus/src/impls.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fconsensus%2Fsrc%2Fimpls.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25zZW5zdXMvc3JjL2ltcGxzLnJz) | `89.63% <ø> (+1.55%)` | :arrow_up: |
   | [core/consensus/src/lib.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fconsensus%2Fsrc%2Flib.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25zZW5zdXMvc3JjL2xpYi5ycw==) | `0.00% <ø> (ø)` | |
   | [core/consensus/src/metadata\_helpers.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fconsensus%2Fsrc%2Fmetadata_helpers.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25zZW5zdXMvc3JjL21ldGFkYXRhX2hlbHBlcnMucnM=) | `93.89% <ø> (-0.11%)` | :arrow_down: |
   | [core/consensus/src/plane\_helpers.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fconsensus%2Fsrc%2Fplane_helpers.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25zZW5zdXMvc3JjL3BsYW5lX2hlbHBlcnMucnM=) | `96.35% <ø> (-0.08%)` | :arrow_down: |
   | [core/metadata/src/impls/metadata.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fmetadata%2Fsrc%2Fimpls%2Fmetadata.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9tZXRhZGF0YS9zcmMvaW1wbHMvbWV0YWRhdGEucnM=) | `86.54% <ø> (+0.27%)` | :arrow_up: |
   | [core/metadata/src/impls/recovery.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fmetadata%2Fsrc%2Fimpls%2Frecovery.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9tZXRhZGF0YS9zcmMvaW1wbHMvcmVjb3ZlcnkucnM=) | `84.77% <ø> (-0.27%)` | :arrow_down: |
   | [core/metadata/src/stm/authz.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fmetadata%2Fsrc%2Fstm%2Fauthz.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9tZXRhZGF0YS9zcmMvc3RtL2F1dGh6LnJz) | `87.21% <ø> (-0.04%)` | :arrow_down: |
   | [core/metadata/src/stm/mod.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fmetadata%2Fsrc%2Fstm%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9tZXRhZGF0YS9zcmMvc3RtL21vZC5ycw==) | `84.14% <ø> (-0.56%)` | :arrow_down: |
   | [core/metadata/src/stm/snapshot.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fmetadata%2Fsrc%2Fstm%2Fsnapshot.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9tZXRhZGF0YS9zcmMvc3RtL3NuYXBzaG90LnJz) | `81.66% <ø> (+0.49%)` | :arrow_up: |
   | [core/metadata/src/stm/user.rs](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree&filepath=core%2Fmetadata%2Fsrc%2Fstm%2Fuser.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9tZXRhZGF0YS9zcmMvc3RtL3VzZXIucnM=) | `90.78% <ø> (ø)` | |
   | ... and [11 more](https://app.codecov.io/gh/apache/iggy/pull/3870?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | |
   
   ... and [55 files with indirect coverage changes](https://app.codecov.io/gh/apache/iggy/pull/3870/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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {

Review Comment:
   Done.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/server_common/src/consensus_message.rs:
##########
@@ -555,6 +573,76 @@ pub enum MessageBag {
 }
 
 impl MessageBag {
+    /// `(operation, group)`: everything the shard router needs to pick a
+    /// target, read off the already-typed header without consuming the bag.
+    ///
+    /// `group` is a plain field on every consensus header rather than a
+    /// [`ConsensusHeader`] method, which is why this is a match and not a trait
+    /// call. `RepairPrepare` reads through its wrapped prepare.
+    #[must_use]
+    pub fn routing(&self) -> (Operation, u64) {

Review Comment:
   **[nit]** `header()` runs a checked bytemuck cast per call and each arm here reads it twice; the Request and Prepare arms in `on_message` then re-derive the same tuple, so a hot frame pays four casts where one `let header = message.header();` per arm suffices. Same pattern in `body()`, which re-reads the header for `size` right after the STM macro's scalar read.



##########
core/metadata/src/stm/snapshot.rs:
##########
@@ -15,12 +15,52 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use iggy_binary_protocol::IGGY_PROTOCOL_VERSION;
 use serde::{Deserialize, Serialize, de::DeserializeOwned};
 use std::fmt;
 
 use crate::stm::stream::StreamsSnapshot;
 use crate::stm::user::UsersSnapshot;
 
+/// The version of the snapshot format in use, reserved for breaking changes.
+///
+/// One version means exactly one serialized shape, and [`MetadataSnapshot::decode`]
+/// accepts nothing else. Bump it in the same change that alters the shape: append,
+/// remove, reorder, retype, or redefine the meaning of any field, at any depth
+/// under [`MetadataSnapshot`]. There is no accepted range and no per-version
+/// translation. A snapshot this build cannot read is refused, not best-effort
+/// decoded.
+///
+/// Nothing softer would hold. msgpack encodes a struct positionally, so a field one
+/// build appends reaches another as an unexplained extra array element; without the
+/// version the reader either fails on an unrelated msgpack error or, for a
+/// same-length change, silently reads one field's bytes as another's.
+///
+/// Bumping it invalidates every `snapshot.bin` already on disk, and a node whose
+/// snapshot is refused refuses boot. That is deliberate. The metadata plane is
+/// pre-production, so the cost is clearing a data directory; once it ships, a bump
+/// needs an explicit translation path added here alongside it.
+///
+/// Version 2: `status` sits at reply-header offset 216 (version 1 carried a
+/// `namespace` word before it), which the client table's cached replies embed as raw
+/// wire bytes msgpack cannot introspect.
+pub const SNAPSHOT_FORMAT_VERSION: u32 = 2;
+
+/// The release that wrote a snapshot: the packed `iggy_binary_protocol` semver of
+/// this build. [`iggy_binary_protocol::ProtocolVersion`] documents the packing and
+/// renders it as `major.minor.patch`.
+///
+/// Provenance, never a gate. The format version says whether the bytes are
+/// readable; this says which build produced them, which matters most for a snapshot
+/// that arrived over state transfer from a machine whose build this node otherwise
+/// has no record of.
+///
+/// A build constant, identical on every replica, so two replicas holding identical
+/// state still serialize identically (see [`MetadataSnapshot`]).
+pub const SNAPSHOT_RELEASE_FORMAT: u32 = IGGY_PROTOCOL_VERSION;

Review Comment:
   **[nit]** The name says format but the content is the packed release semver, and it sits next to a real format version; the doc has to argue against the confusion the name creates. `writer_release` or similar would remove the ambiguity.



##########
core/partitions/src/iggy_partitions.rs:
##########
@@ -301,6 +301,22 @@ where
         suspend.await;
     }
 
+    /// TEST / SIMULATOR ONLY. Address of the partitions vec's heap buffer.
+    ///
+    /// Lets a test prove that an [`Self::insert`] actually REALLOCATED rather
+    /// than landing in spare capacity. The distinction is the whole point of the
+    /// realloc half of PR #3557: `swap_remove` invalidates one slot's reference,
+    /// while a growing `push` moves every element and invalidates all of them. A
+    /// test that only checked "insert happened" would pass on a push into spare
+    /// capacity, which moves nothing and proves nothing.
+    #[cfg(any(test, feature = "simulator"))]
+    #[must_use]
+    pub fn buffer_addr(&self) -> usize {

Review Comment:
   **[nit]** The safety comment argues read-only-ness, but the actual soundness precondition is that no pump-side `&mut` is live when this forms a `&Vec` through the `UnsafeCell`; a shared reborrow aliasing a live `&mut` is UB regardless of whether it only reads. Current callers uphold it; worth stating directly.



##########
core/consensus/src/impls.rs:
##########
@@ -3428,8 +3595,13 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
 
     /// Enqueue a self-addressed message for processing in the next loopback drain.
     ///
-    /// Currently only `PrepareOk` messages are routed here (via `send_or_loopback`).
-    // TODO: Route SVC/DVC self-messages through loopback once VsrAction dispatch is implemented.
+    /// Only `PrepareOk` reaches here (via `send_or_loopback`), and deliberately:
+    /// it is a message to a peer that happens to be this replica, so a one-drain
+    /// delay costs nothing. A replica's own SVC/DVC is not that shape -- it is the
+    /// local decision to change view, recorded synchronously with the view and
+    /// status writes in [`Self::enter_view_change`]. Routing it here instead would
+    /// leave a window where the replica has entered a view change without counting
+    /// itself, which on a solo group is the entire quorum.
     pub(crate) fn push_loopback(&self, message: Message<GenericHeader>) {

Review Comment:
   **[nit]** Pre-existing, same class this PR removes on the router hop: `send_or_loopback` erases the self-addressed PrepareOk to generic and the drain re-types it with a full frame-checksum verify per self-ack, once per op per plane on the primary. Typing the loopback queue as `VecDeque<Message<PrepareOkHeader>>` would close it.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/server/src/responses.rs:
##########
@@ -1303,35 +1303,55 @@ pub(crate) fn build_deny_reply(
 /// Server build version advertised in the login-register response.
 const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
 
+/// Build a metadata reply carrying `payload` behind a success result section.
+///
+/// Every metadata reply is result-framed, and the SDK strips that section off
+/// unconditionally (`split_metadata_result`) before decoding what follows. A
+/// payload written without the leading zero count therefore has its first four
+/// bytes eaten as a result count, and the decode fails or, worse, succeeds on the
+/// shifted remainder. That is not hypothetical: the raw-PAT reply shipped once
+/// without the prefix and broke SDK decoding. This is the only way to emit a
+/// success reply with a body, so the prefix cannot be forgotten again.
+fn build_result_framed_reply(

Review Comment:
   Both doc overstatements fixed. It now says the SDK strips the section for operations that are `Operation::is_result_framed()` (metadata ops plus the four consumer-offset ops) and a non-empty `Register`, and that this is the only way to *build* a result-framed success body rather than the only path to a success reply with one, with `build_reply_from_bytes` named. Added your point that framing a non-result-framed reply breaks decoding just as badly in the other direction.
   
   Leaving the `BytesMut` as-is: `WireEncode::encode` takes `&mut BytesMut`, so writing into `out[RESULT_COUNT_LEN..]` needs a new `encode_to_slice` on the trait, which seems too wide for a path that runs once per session. Happy to revisit if you disagree.



##########
core/consensus/src/impls.rs:
##########
@@ -265,10 +265,20 @@ impl PipelineEntry {
 #[derive(Debug)]
 pub struct RequestEntry {
     pub message: Message<RoutedRequestHeader>,
-    // TODO: populate from monotonic clock at push, promote to `pub` for
-    // age-based filtering. Currently `0`; `pub(crate)` blocks sort-on-stub.
-    #[allow(dead_code)]
-    pub(crate) received_at: i64,
+    /// When the request was parked, in microseconds from the consensus-injected
+    /// clock ([`VsrConsensus::clock_realtime_micros`]). `0` until
+    /// [`VsrConsensus::push_queued_request`] stamps it, which is the only path
+    /// that parks an entry in production.
+    ///
+    /// Read against `clock_realtime_micros` at promotion for the queue wait:
+    /// what age-based shedding would filter on, and the queueing half of
+    /// end-to-end commit latency.
+    ///
+    /// Deliberately the plain clock read rather than
+    /// [`VsrConsensus::next_monotonic_timestamp`]: this must not consume the
+    /// prepare-stamping monotonic sequence, or parking a request would perturb
+    /// the timestamps replicated to every backup.
+    pub received_at: u64,

Review Comment:
   Done, as an API rather than a documented requirement, so the reader cannot get it wrong: `RequestEntry::queue_wait_micros(now)` does the `saturating_sub`. The field doc now points at it and says not to subtract directly.



##########
core/metadata/src/stm/snapshot.rs:
##########
@@ -15,12 +15,52 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use iggy_binary_protocol::IGGY_PROTOCOL_VERSION;
 use serde::{Deserialize, Serialize, de::DeserializeOwned};
 use std::fmt;
 
 use crate::stm::stream::StreamsSnapshot;
 use crate::stm::user::UsersSnapshot;
 
+/// The version of the snapshot format in use, reserved for breaking changes.
+///
+/// One version means exactly one serialized shape, and [`MetadataSnapshot::decode`]
+/// accepts nothing else. Bump it in the same change that alters the shape: append,
+/// remove, reorder, retype, or redefine the meaning of any field, at any depth
+/// under [`MetadataSnapshot`]. There is no accepted range and no per-version
+/// translation. A snapshot this build cannot read is refused, not best-effort
+/// decoded.
+///
+/// Nothing softer would hold. msgpack encodes a struct positionally, so a field one
+/// build appends reaches another as an unexplained extra array element; without the
+/// version the reader either fails on an unrelated msgpack error or, for a
+/// same-length change, silently reads one field's bytes as another's.
+///
+/// Bumping it invalidates every `snapshot.bin` already on disk, and a node whose
+/// snapshot is refused refuses boot. That is deliberate. The metadata plane is
+/// pre-production, so the cost is clearing a data directory; once it ships, a bump
+/// needs an explicit translation path added here alongside it.
+///
+/// Version 2: `status` sits at reply-header offset 216 (version 1 carried a
+/// `namespace` word before it), which the client table's cached replies embed as raw
+/// wire bytes msgpack cannot introspect.
+pub const SNAPSHOT_FORMAT_VERSION: u32 = 2;
+
+/// The release that wrote a snapshot: the packed `iggy_binary_protocol` semver of
+/// this build. [`iggy_binary_protocol::ProtocolVersion`] documents the packing and
+/// renders it as `major.minor.patch`.
+///
+/// Provenance, never a gate. The format version says whether the bytes are
+/// readable; this says which build produced them, which matters most for a snapshot
+/// that arrived over state transfer from a machine whose build this node otherwise
+/// has no record of.
+///
+/// A build constant, identical on every replica, so two replicas holding identical
+/// state still serialize identically (see [`MetadataSnapshot`]).
+pub const SNAPSHOT_RELEASE_FORMAT: u32 = IGGY_PROTOCOL_VERSION;

Review Comment:
   Done. `release_format` -> `writer_release`, `SNAPSHOT_RELEASE_FORMAT` -> `SNAPSHOT_WRITER_RELEASE`. This is TB's pairing too: `SuperBlockHeader` carries `version: u16` next to a plainly named `release`.
   
   Free to do: msgpack encodes the struct positionally, so serde field names never reach the wire. No shape change, no bump. The doc no longer has to argue against the name.



##########
core/partitions/src/iggy_partitions.rs:
##########
@@ -301,6 +301,22 @@ where
         suspend.await;
     }
 
+    /// TEST / SIMULATOR ONLY. Address of the partitions vec's heap buffer.
+    ///
+    /// Lets a test prove that an [`Self::insert`] actually REALLOCATED rather
+    /// than landing in spare capacity. The distinction is the whole point of the
+    /// realloc half of PR #3557: `swap_remove` invalidates one slot's reference,
+    /// while a growing `push` moves every element and invalidates all of them. A
+    /// test that only checked "insert happened" would pass on a push into spare
+    /// capacity, which moves nothing and proves nothing.
+    #[cfg(any(test, feature = "simulator"))]
+    #[must_use]
+    pub fn buffer_addr(&self) -> usize {

Review Comment:
   Done. The comment now states the aliasing precondition directly: read-only-ness is not what makes it sound, since a shared reborrow aliasing a live `&mut` is UB whether or not it reads. What makes it sound is that no `&mut` from `get_mut_by_ns` / `namespace_map_mut` is live across the call, those being pump-only and these callers running on the pump.



##########
core/server_common/src/consensus_message.rs:
##########
@@ -555,6 +573,76 @@ pub enum MessageBag {
 }
 
 impl MessageBag {
+    /// `(operation, group)`: everything the shard router needs to pick a
+    /// target, read off the already-typed header without consuming the bag.
+    ///
+    /// `group` is a plain field on every consensus header rather than a
+    /// [`ConsensusHeader`] method, which is why this is a match and not a trait
+    /// call. `RepairPrepare` reads through its wrapped prepare.
+    #[must_use]
+    pub fn routing(&self) -> (Operation, u64) {

Review Comment:
   Partly done, leaving this open for the rest.
   
   Done: one `header()` per arm bound to a local, across all 15 arms of `MessageBag::routing()` and both the Request and Prepare arms in the shard dispatch (which now hoist rather than re-deriving the tuple).
   
   Not done: `body()`, and the underlying cause. Fixing `body()` cleanly means either reintroducing the manual slicing it was created to remove or threading `size` through, both worse than one cast.
   
   The real fix is the one TB makes structurally: `Message` stores `header: *Header` and validates once at the receive boundary (`message_bus.zig:716`), with `valid_checksum` appearing in `replica.zig` only inside `assert` / `if (constants.verify)`. Our invariant nearly holds already, since `try_from` and `try_into_typed` both validate at construction and `Message::new` zeroes (a valid bit pattern). What breaks it is `as_mut_slice()` handing out the header region: 111 call sites, 8 of which write into the header via `try_from_bytes_mut`. So it is "narrow the mutable surface" rather than "delete the check", which is a `server_common` change touching every plane.
   
   Worth noting `Message` lives in `server_common`, which Miri does not currently cover (`-p iggy_binary_protocol -p consensus`), so adding it there is part of that work. I will open a separate issue with the details and measurements rather than grow this PR.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {

Review Comment:
   Done. `rollback_pipelined_prepare` now refuses unless `header.view == self.view()` and the status is `Normal`, checked **before** the sequencer compare, since after a re-election the sequencer can legitimately match `header.op` with a different prepare beneath it. The tail is matched on `(op, checksum)`, so `Pipeline::remove_tail` takes both. New `PrepareRollback::Superseded { view }` covers the refusal.
   
   Covered by `rollback_is_refused_while_a_view_change_is_running`, which asserts the sequencer and parent chain are untouched.



##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {
+        if !self.is_primary() {
+            return PrepareRollback::NotPreAdvanced;
+        }
+        let sequence = self.sequencer.current_sequence();
+        if sequence != header.op {
+            return PrepareRollback::Overtaken { sequence };
+        }
+        let removed = self.pipeline.borrow_mut().remove_tail(header.op);
+        debug_assert!(

Review Comment:
   Done. The `None` arm returns `PrepareRollback::TailMismatch` without mutating.
   
   I dropped the `debug_assert` rather than keeping it alongside the refusal: it panicked debug builds on exactly the state release now declines to act on, which is two behaviors for one condition, and the condition is reachable from a race rather than a bug in this process. The typed refusal plus the caller's fail-stop is the loud signal instead.
   
   Covered by `rollback_is_refused_when_the_tail_is_a_different_prepare`.



##########
core/metadata/src/impls/metadata.rs:
##########
@@ -1198,28 +1198,35 @@ where
         // violates VSR tail-ahead-of-head, recoverable only via hash-chain
         // fence + view change (burns a view).
         //
-        // TODO(hubcio): the primary path violates the invariant in the
-        // comment above. `consensus::impls::push_prepare_entry` pre-advances
-        // `sequencer.set_sequence(header.op)` and
-        // `set_last_prepare_checksum(header.checksum)` BEFORE this append.
-        // If the append below returns `Err`, sequencer + checksum stay
-        // advanced while the WAL holds no matching entry: the next prepare
-        // chains off a phantom op, cluster state diverges, and the
-        // `MetadataHandoff::Waiter` factory bundle propagates the divergence
-        // to peers. Fix: rollback `sequencer.set_sequence` +
-        // `set_last_prepare_checksum` to their captured prior values on
-        // append failure (preferred per CLAUDE.md "no panics in libraries"),
-        // or abort the shard.
+        // On the primary the pre-advance in `push_prepare_entry` already claimed
+        // this op, so a failed append has to hand it back or the next prepare
+        // chains off a phantom (see `rollback_pipelined_prepare`). The rollback is
+        // refused when a sibling prepare was pipelined during the await and has
+        // already been projected off this op; that log cannot be repaired from
+        // here, so it is reported and left to a view change.
         if let Err(e) = journal.handle().append(message.clone()).await {
+            let rollback = consensus.rollback_pipelined_prepare(&header);
             error!(
                 target: "iggy.metadata.diag",
                 plane = "metadata",
                 replica_id = consensus.replica(),
                 op = header.op,
                 operation = ?header.operation,
                 error = %e,
+                rollback = ?rollback,
                 "journal append failed"
             );
+            if let PrepareRollback::Overtaken { sequence } = rollback {
+                error!(
+                    target: "iggy.metadata.diag",
+                    plane = "metadata",
+                    replica_id = consensus.replica(),
+                    op = header.op,
+                    sequence,
+                    "journal append failed after a sibling prepare was projected off this op; \

Review Comment:
   Done, though not the way I first went at it.
   
   The log now describes a real mechanism: every refused rollback fail-stops the process via a new `consensus::fatal(FatalReason::UnreconcilableLogFrontier, ..)`. `Unwound` and `NotPreAdvanced` continue as before.
   
   I initially built this as ceding primaryship, mapping it onto TigerBeetle's `primary_abdicating`. That was the wrong mechanism: TB uses abdication for a prepare that cannot reach quorum, and for a local write that fails it calls `vsr.fatal(.no_space_left, ..)` in `storage.zig` rather than returning the error at all.
   
   Fail-stop also dissolves the solo case you raised. The failed write never reached the WAL, so the durable log is intact at `op-1` and only the in-memory frontier is bad: restart is the complete repair, solo or clustered. `cede_primaryship` was removed again since nothing calls it.



##########
core/consensus/src/impls.rs:
##########
@@ -1418,17 +1493,117 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         self.status.get()
     }
 
-    // TODO(hubcio): returning &RefCell<P> leaks interior mutability - callers
-    // could hold a Ref/RefMut across an .await and cause a runtime panic.
-    // We had this problem with slab + ECS.
+    /// Run `f` against the pipeline.
+    ///
+    /// The borrow cannot escape `f`, so it cannot be held across an `.await` and
+    /// alias a sibling task's `borrow_mut` into a `BorrowMutError` panic. Same
+    /// shape, and the same reason, as `IggyPartitions::with_partition`. Prefer
+    /// the named accessors below; this is for the few callers that need several
+    /// reads under one borrow.
+    pub fn with_pipeline<R>(&self, f: impl FnOnce(&P) -> R) -> R {
+        f(&self.pipeline.borrow())
+    }
+
+    /// [`Self::with_pipeline`] for a mutating operation.
+    ///
+    /// Callers that pop or clear should prefer [`Self::pop_committed_prepare`] /
+    /// [`Self::clear_pipeline`], which also keep the prepare timeout's
+    /// ticking-iff-non-empty invariant. This form does not.
+    pub fn with_pipeline_mut<R>(&self, f: impl FnOnce(&mut P) -> R) -> R {
+        f(&mut self.pipeline.borrow_mut())
+    }
+
+    /// Whether the prepare queue is at its depth bound; callers route to
+    /// [`Self::push_queued_request`] on `true`.
+    #[must_use]
+    pub fn pipeline_is_full(&self) -> bool {
+        self.pipeline.borrow().is_full()
+    }
+
+    #[must_use]
+    pub fn pipeline_is_empty(&self) -> bool {
+        self.pipeline.borrow().is_empty()
+    }
+
+    /// In-flight prepare count.
+    #[must_use]
+    pub fn pipeline_len(&self) -> usize {
+        self.pipeline.borrow().len()
+    }
+
+    /// Requests parked waiting for a prepare slot.
+    #[must_use]
+    pub fn request_queue_len(&self) -> usize {
+        self.pipeline.borrow().request_queue_len()
+    }
+
+    /// Whether either queue already carries a request from `client_id`: the
+    /// metadata plane's in-flight dedup.
+    #[must_use]
+    pub fn pipeline_has_message_from_client(&self, client_id: u128) -> bool {
+        self.pipeline.borrow().has_message_from_client(client_id)
+    }
+
+    /// Header of the oldest in-flight prepare.
     #[must_use]
-    pub const fn pipeline(&self) -> &RefCell<P> {
-        &self.pipeline
+    pub fn pipeline_head_header(&self) -> Option<PrepareHeader> {
+        self.pipeline.borrow().head().map(|entry| entry.header)
     }
 
+    /// Whether an in-flight prepare matches `(op, checksum)`: the ack paths' test
+    /// that the frame they are about to count still describes a live entry.
     #[must_use]
-    pub const fn pipeline_mut(&mut self) -> &mut RefCell<P> {
-        &mut self.pipeline
+    pub fn pipeline_holds_entry(&self, op: u64, checksum: u128) -> bool {
+        self.pipeline
+            .borrow()
+            .entry_by_op_and_checksum(op, checksum)
+            .is_some()
+    }
+
+    /// Promote the oldest parked request, if any.
+    pub fn pop_queued_request(&self) -> Option<P::Request> {
+        self.pipeline.borrow_mut().pop_request()
+    }
+
+    /// Pop the pipeline head once its op has committed, keeping the prepare
+    /// timeout's lifecycle in step.
+    ///
+    /// The timeout measures the age of the oldest un-acked prepare, so draining
+    /// the head has to either stop it (nothing left to retransmit) or restart it
+    /// (the next entry becomes the oldest, and it must be timed from now rather
+    /// than inheriting the drained entry's elapsed ticks). Arming happens in
+    /// [`Self::push_prepare_entry`]; between the two the invariant is "ticking
+    /// iff the pipeline is non-empty".
+    pub fn pop_committed_prepare(&self) -> Option<P::Entry> {
+        let popped = self.pipeline.borrow_mut().pop();
+        if popped.is_some() {
+            self.sync_prepare_timeout();
+        }
+        popped
+    }
+
+    /// Drop every in-flight prepare and parked request, and disarm the prepare
+    /// timeout with them (a view change re-prepares from the new primary; there
+    /// is nothing left here to retransmit).
+    pub fn clear_pipeline(&self) {
+        self.pipeline.borrow_mut().clear();
+        self.timeouts.borrow_mut().stop(TimeoutKind::Prepare);
+    }
+
+    /// Re-establish "prepare timeout ticking iff the pipeline is non-empty".
+    ///
+    /// Stops the timer on an empty pipeline; otherwise restarts it so it times
+    /// the current oldest entry from now. Exposed for the plane-side drains that
+    /// pop through [`Pipeline`] directly (`drain_committable_prefix`) rather than
+    /// through [`Self::pop_committed_prepare`].
+    pub fn sync_prepare_timeout(&self) {
+        let empty = self.pipeline.borrow().is_empty();
+        let mut timeouts = self.timeouts.borrow_mut();
+        if empty {
+            timeouts.stop(TimeoutKind::Prepare);
+        } else {
+            timeouts.reset(TimeoutKind::Prepare);

Review Comment:
   Done. The non-empty branch is now `start`, which is identical to `reset` on a ticking timer and correct on a stopped one, so no branch is needed.
   
   Also added TigerBeetle's guard: `Timeout::reset` now `debug_assert!(self.ticking)`, matching `vsr.zig`, so the armed-but-dead state fails at the call site instead of silently. Audited all 8 `reset` callers first: six fire from a just-fired timer, and `handle_commit`'s is reachable only past the `!is_primary()` / `Normal` / matching-view fences where `NormalHeartbeat` is always armed.



##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {
+        if !self.is_primary() {
+            return PrepareRollback::NotPreAdvanced;
+        }
+        let sequence = self.sequencer.current_sequence();
+        if sequence != header.op {
+            return PrepareRollback::Overtaken { sequence };
+        }
+        let removed = self.pipeline.borrow_mut().remove_tail(header.op);
+        debug_assert!(
+            removed.is_some(),
+            "sequencer at op {} but the pipeline tail is not that op",
+            header.op
+        );
+        drop(removed);
+        self.sequencer.set_sequence(header.op.saturating_sub(1));
+        self.set_last_prepare_checksum(header.parent);
+        PrepareRollback::Unwound

Review Comment:
   Done. `sync_prepare_timeout()` after the pop, which is correct in both directions now that the helper uses `start`.
   
   Covered by `rollback_disarms_the_prepare_timeout_when_it_empties_the_pipeline`.



##########
core/metadata/src/impls/recovery.rs:
##########
@@ -1672,47 +1673,63 @@ mod tests {
     }
 
     #[compio::test]
-    async fn recover_accepts_snapshot_written_before_a_trailing_default_field() {
-        // Appending a `#[serde(default)]` field is this repo's forward-compatible
-        // snapshot migration, and msgpack encodes structs positionally: a file the
-        // previous build wrote decodes fine (the default fills the missing element)
-        // but re-encodes with one MORE element. A pairing checksum recomputed by
-        // re-encoding the decoded snapshot would therefore diverge on the FIRST boot
-        // of the new build and refuse every checkpointed node, with the WAL prefix
-        // already drained. Hashing the bytes on disk is what makes that upgrade boot.
-        //
-        // Emulated in the direction the migration runs: strip the trailing element off
-        // a current-shape file, which is what the pre-`client_table` build wrote.
+    async fn recover_refuses_a_snapshot_from_another_format_version() {
+        // A snapshot shape is only as trustworthy as the version stamped on it, so a
+        // foreign one refuses boot rather than restoring whatever msgpack happens to
+        // make of the bytes. Everything else about the directory is healthy: the
+        // superblock pairs with the file on disk, so the refusal can only be the
+        // version.
+        const CHECKPOINT_OP: u64 = 42;
+        let mut snapshot = IggySnapshot::new(CHECKPOINT_OP);
+        snapshot.snapshot_mut().version = SNAPSHOT_FORMAT_VERSION + 1;
+        let foreign = snapshot.encode().unwrap();
+
+        let dir = tempdir().unwrap();
+        let metadata_dir = dir.path().join("metadata");
+        std::fs::create_dir_all(&metadata_dir).unwrap();
+        std::fs::write(metadata_dir.join("snapshot.bin"), &foreign).unwrap();
+        let state = vsr_state_with_checkpoint(CHECKPOINT_OP, checkpoint_checksum(&foreign));
+        {
+            let superblock = PingPongSuperblock::open(&metadata_dir).await.unwrap();
+            superblock.write(&state.to_bytes()).await.unwrap();
+        }
+
+        match recover::<TestStm>(
+            dir.path(),
+            CLUSTERED,
+            journal::prepare_journal::DEFAULT_SLOT_COUNT,
+            CLIENTS_TABLE_MAX,
+            |_| {},
+        )
+        .await
+        {
+            Err(RecoveryError::Snapshot(SnapshotError::UnsupportedFormatVersion {
+                found,
+                expected,
+            })) => {
+                assert_eq!(found, SNAPSHOT_FORMAT_VERSION + 1);
+                assert_eq!(expected, SNAPSHOT_FORMAT_VERSION);
+            }
+            Err(other) => panic!("expected a format-version refusal, got {other}"),
+            Ok(_) => panic!("expected a foreign format version to refuse boot"),
+        }
+    }
+
+    #[compio::test]
+    async fn recover_pairs_the_checkpoint_against_the_bytes_on_disk() {

Review Comment:
   Done, using your suggestion. A new `with_wide_version_marker` helper re-encodes the leading `version` as an explicit msgpack `u32` marker instead of the canonical fixint: `read_int` accepts it and a re-encode collapses it back, so the two candidate checksums differ.
   
   Guarded against passing vacuously the same way the realloc test is: asserts up front that the file differs from canonical, still decodes, and that hashing a re-encode gives a different checksum. Falsification-checked by pointing recovery at a re-encode.



##########
core/server/src/bootstrap.rs:
##########
@@ -2323,20 +2323,21 @@ fn restore_metadata_consensus(
             commit_watermark,
             restored_op, "re-pipelining recovered uncommitted metadata suffix"
         );
-        let mut pipeline = consensus.pipeline().borrow_mut();
-        #[allow(clippy::cast_possible_truncation)]
-        for op in (commit_watermark + 1)..=restored_op {
-            let Some(header) = journal.header(op as usize) else {
-                warn!(
-                    op,
-                    "recovered journal suffix has a gap; stopping re-pipeline"
-                );
-                break;
-            };
-            let mut entry = PipelineEntry::new(*header);
-            entry.add_ack(topology.self_replica_id);
-            pipeline.push(entry);
-        }
+        consensus.with_pipeline_mut(|pipeline| {

Review Comment:
   Done. `consensus.sync_prepare_timeout()` after the loop, which works now that the reset-vs-start issue in that helper is fixed.
   
   This is the same shape as TB's `transition_to_normal_from_view_change_status`, which does `if (prepare_queue.count > 0) prepare_timeout.start()` after asserting it is not already ticking. Agreed the branch is unreachable today; it stays uncovered until it reactivates.



##########
core/consensus/src/impls.rs:
##########
@@ -310,6 +320,42 @@ impl RequestEntry {
     }
 }
 
+impl<B, P> VsrConsensus<B, P>
+where
+    B: MessageBus,
+    P: Pipeline<Entry = PipelineEntry, Request = RequestEntry>,
+{
+    /// Park a request that could not take a prepare slot, stamping its arrival
+    /// time so the promotion side can measure how long it waited.
+    ///
+    /// # Errors
+    /// The entry itself, when the request queue is at its depth bound.
+    pub fn push_queued_request(&self, mut entry: RequestEntry) -> Result<(), RequestEntry> {
+        entry.received_at = self.clock_realtime_micros();
+        self.pipeline.borrow_mut().push_request(entry)
+    }
+}
+
+/// Outcome of [`VsrConsensus::rollback_pipelined_prepare`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PrepareRollback {
+    /// Sequencer, parent chain, and pipeline entry all restored. The op is free
+    /// again and the next request reuses it.
+    Unwound,
+    /// This replica never pre-advanced for the prepare, so there is nothing to
+    /// undo. A backup advances only AFTER its append succeeds.
+    NotPreAdvanced,

Review Comment:
   Done, both directions documented.
   
   `NotPreAdvanced` now says it covers two histories with the same handling: a backup that never pre-advanced, and a demoted ex-primary whose claim the view-change reset already discarded.
   
   `Overtaken` now splits `sequence > header.op` (the sibling story) from `sequence < header.op` (a state transfer or view change rewound beneath the op, no sibling involved). The caller's log branches on the same split, so the diagnostic no longer tells an operator a sibling story that does not apply.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {
+        if !self.is_primary() {
+            return PrepareRollback::NotPreAdvanced;
+        }
+        let sequence = self.sequencer.current_sequence();
+        if sequence != header.op {
+            return PrepareRollback::Overtaken { sequence };
+        }
+        let removed = self.pipeline.borrow_mut().remove_tail(header.op);
+        debug_assert!(

Review Comment:
   Done. 



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/server_common/src/consensus_message.rs:
##########
@@ -555,6 +573,76 @@ pub enum MessageBag {
 }
 
 impl MessageBag {
+    /// `(operation, group)`: everything the shard router needs to pick a
+    /// target, read off the already-typed header without consuming the bag.
+    ///
+    /// `group` is a plain field on every consensus header rather than a
+    /// [`ConsensusHeader`] method, which is why this is a match and not a trait
+    /// call. `RepairPrepare` reads through its wrapped prepare.
+    #[must_use]
+    pub fn routing(&self) -> (Operation, u64) {

Review Comment:
   Partly done, leaving this open for the rest.
   
   Done: one `header()` per arm bound to a local, across all 15 arms of `MessageBag::routing()` and both the Request and Prepare arms in the shard dispatch (which now hoist rather than re-deriving the tuple).
   
   Not done: `body()`, and the underlying cause. Fixing `body()` cleanly means either reintroducing the manual slicing it was created to remove or threading `size` through, both worse than one cast.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/consensus/src/impls.rs:
##########
@@ -1418,17 +1493,117 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         self.status.get()
     }
 
-    // TODO(hubcio): returning &RefCell<P> leaks interior mutability - callers
-    // could hold a Ref/RefMut across an .await and cause a runtime panic.
-    // We had this problem with slab + ECS.
+    /// Run `f` against the pipeline.
+    ///
+    /// The borrow cannot escape `f`, so it cannot be held across an `.await` and
+    /// alias a sibling task's `borrow_mut` into a `BorrowMutError` panic. Same
+    /// shape, and the same reason, as `IggyPartitions::with_partition`. Prefer
+    /// the named accessors below; this is for the few callers that need several
+    /// reads under one borrow.
+    pub fn with_pipeline<R>(&self, f: impl FnOnce(&P) -> R) -> R {
+        f(&self.pipeline.borrow())
+    }
+
+    /// [`Self::with_pipeline`] for a mutating operation.
+    ///
+    /// Callers that pop or clear should prefer [`Self::pop_committed_prepare`] /
+    /// [`Self::clear_pipeline`], which also keep the prepare timeout's
+    /// ticking-iff-non-empty invariant. This form does not.
+    pub fn with_pipeline_mut<R>(&self, f: impl FnOnce(&mut P) -> R) -> R {
+        f(&mut self.pipeline.borrow_mut())
+    }
+
+    /// Whether the prepare queue is at its depth bound; callers route to
+    /// [`Self::push_queued_request`] on `true`.
+    #[must_use]
+    pub fn pipeline_is_full(&self) -> bool {
+        self.pipeline.borrow().is_full()
+    }
+
+    #[must_use]
+    pub fn pipeline_is_empty(&self) -> bool {
+        self.pipeline.borrow().is_empty()
+    }
+
+    /// In-flight prepare count.
+    #[must_use]
+    pub fn pipeline_len(&self) -> usize {
+        self.pipeline.borrow().len()
+    }
+
+    /// Requests parked waiting for a prepare slot.
+    #[must_use]
+    pub fn request_queue_len(&self) -> usize {
+        self.pipeline.borrow().request_queue_len()
+    }
+
+    /// Whether either queue already carries a request from `client_id`: the
+    /// metadata plane's in-flight dedup.
+    #[must_use]
+    pub fn pipeline_has_message_from_client(&self, client_id: u128) -> bool {
+        self.pipeline.borrow().has_message_from_client(client_id)
+    }
+
+    /// Header of the oldest in-flight prepare.
     #[must_use]
-    pub const fn pipeline(&self) -> &RefCell<P> {
-        &self.pipeline
+    pub fn pipeline_head_header(&self) -> Option<PrepareHeader> {
+        self.pipeline.borrow().head().map(|entry| entry.header)
     }
 
+    /// Whether an in-flight prepare matches `(op, checksum)`: the ack paths' test
+    /// that the frame they are about to count still describes a live entry.
     #[must_use]
-    pub const fn pipeline_mut(&mut self) -> &mut RefCell<P> {
-        &mut self.pipeline
+    pub fn pipeline_holds_entry(&self, op: u64, checksum: u128) -> bool {
+        self.pipeline
+            .borrow()
+            .entry_by_op_and_checksum(op, checksum)
+            .is_some()
+    }
+
+    /// Promote the oldest parked request, if any.
+    pub fn pop_queued_request(&self) -> Option<P::Request> {
+        self.pipeline.borrow_mut().pop_request()
+    }
+
+    /// Pop the pipeline head once its op has committed, keeping the prepare
+    /// timeout's lifecycle in step.
+    ///
+    /// The timeout measures the age of the oldest un-acked prepare, so draining
+    /// the head has to either stop it (nothing left to retransmit) or restart it
+    /// (the next entry becomes the oldest, and it must be timed from now rather
+    /// than inheriting the drained entry's elapsed ticks). Arming happens in
+    /// [`Self::push_prepare_entry`]; between the two the invariant is "ticking
+    /// iff the pipeline is non-empty".
+    pub fn pop_committed_prepare(&self) -> Option<P::Entry> {
+        let popped = self.pipeline.borrow_mut().pop();
+        if popped.is_some() {
+            self.sync_prepare_timeout();
+        }
+        popped
+    }
+
+    /// Drop every in-flight prepare and parked request, and disarm the prepare
+    /// timeout with them (a view change re-prepares from the new primary; there
+    /// is nothing left here to retransmit).
+    pub fn clear_pipeline(&self) {
+        self.pipeline.borrow_mut().clear();
+        self.timeouts.borrow_mut().stop(TimeoutKind::Prepare);
+    }
+
+    /// Re-establish "prepare timeout ticking iff the pipeline is non-empty".
+    ///
+    /// Stops the timer on an empty pipeline; otherwise restarts it so it times
+    /// the current oldest entry from now. Exposed for the plane-side drains that
+    /// pop through [`Pipeline`] directly (`drain_committable_prefix`) rather than
+    /// through [`Self::pop_committed_prepare`].
+    pub fn sync_prepare_timeout(&self) {
+        let empty = self.pipeline.borrow().is_empty();
+        let mut timeouts = self.timeouts.borrow_mut();
+        if empty {
+            timeouts.stop(TimeoutKind::Prepare);
+        } else {
+            timeouts.reset(TimeoutKind::Prepare);

Review Comment:
   Done.



##########
core/consensus/src/impls.rs:
##########
@@ -1484,6 +1659,47 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         }
     }
 
+    /// Undo the [`Self::push_prepare_entry`] pre-advance for a prepare whose
+    /// journal append failed, so the op it claimed is handed back.
+    ///
+    /// The pre-advance runs the sequencer ahead of the WAL on purpose, so that a
+    /// sibling `on_request` racing the append await cannot project a duplicate op.
+    /// The cost is that a failed append leaves the op claimed with nothing durable
+    /// behind it: the next prepare chains off a phantom, the WAL takes a permanent
+    /// hole at that op, and the divergence rides the handoff bundle out to peers.
+    ///
+    /// Rolls the sequencer back to `header.op - 1` and the parent chain to
+    /// `header.parent`, both of which the header records from the moment it was
+    /// projected, and drops the pipeline entry so the reclaimed op is free rather
+    /// than colliding with a live entry. Dropping the entry drops its reply
+    /// sender, so a waiting client observes `Canceled` instead of hanging until
+    /// the request times out.
+    ///
+    /// The observed prepare timestamp is deliberately NOT rolled back:
+    /// [`Self::next_monotonic_timestamp`] only ever needs a lower bound, and
+    /// lowering it back could re-stamp a value a peer already observed.
+    ///
+    /// See [`PrepareRollback`] for the outcomes.
+    pub fn rollback_pipelined_prepare(&self, header: &PrepareHeader) -> PrepareRollback {
+        if !self.is_primary() {
+            return PrepareRollback::NotPreAdvanced;
+        }
+        let sequence = self.sequencer.current_sequence();
+        if sequence != header.op {
+            return PrepareRollback::Overtaken { sequence };
+        }
+        let removed = self.pipeline.borrow_mut().remove_tail(header.op);
+        debug_assert!(
+            removed.is_some(),
+            "sequencer at op {} but the pipeline tail is not that op",
+            header.op
+        );
+        drop(removed);
+        self.sequencer.set_sequence(header.op.saturating_sub(1));
+        self.set_last_prepare_checksum(header.parent);
+        PrepareRollback::Unwound

Review Comment:
   Done.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/metadata/src/impls/metadata.rs:
##########
@@ -1198,28 +1198,35 @@ where
         // violates VSR tail-ahead-of-head, recoverable only via hash-chain
         // fence + view change (burns a view).
         //
-        // TODO(hubcio): the primary path violates the invariant in the
-        // comment above. `consensus::impls::push_prepare_entry` pre-advances
-        // `sequencer.set_sequence(header.op)` and
-        // `set_last_prepare_checksum(header.checksum)` BEFORE this append.
-        // If the append below returns `Err`, sequencer + checksum stay
-        // advanced while the WAL holds no matching entry: the next prepare
-        // chains off a phantom op, cluster state diverges, and the
-        // `MetadataHandoff::Waiter` factory bundle propagates the divergence
-        // to peers. Fix: rollback `sequencer.set_sequence` +
-        // `set_last_prepare_checksum` to their captured prior values on
-        // append failure (preferred per CLAUDE.md "no panics in libraries"),
-        // or abort the shard.
+        // On the primary the pre-advance in `push_prepare_entry` already claimed
+        // this op, so a failed append has to hand it back or the next prepare
+        // chains off a phantom (see `rollback_pipelined_prepare`). The rollback is
+        // refused when a sibling prepare was pipelined during the await and has
+        // already been projected off this op; that log cannot be repaired from
+        // here, so it is reported and left to a view change.
         if let Err(e) = journal.handle().append(message.clone()).await {
+            let rollback = consensus.rollback_pipelined_prepare(&header);
             error!(
                 target: "iggy.metadata.diag",
                 plane = "metadata",
                 replica_id = consensus.replica(),
                 op = header.op,
                 operation = ?header.operation,
                 error = %e,
+                rollback = ?rollback,
                 "journal append failed"
             );
+            if let PrepareRollback::Overtaken { sequence } = rollback {
+                error!(
+                    target: "iggy.metadata.diag",
+                    plane = "metadata",
+                    replica_id = consensus.replica(),
+                    op = header.op,
+                    sequence,
+                    "journal append failed after a sibling prepare was projected off this op; \

Review Comment:
   Done.



-- 
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] fix(consensus): close metadata and consensus plane TODOs [iggy]

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


##########
core/consensus/src/impls.rs:
##########
@@ -310,6 +320,42 @@ impl RequestEntry {
     }
 }
 
+impl<B, P> VsrConsensus<B, P>
+where
+    B: MessageBus,
+    P: Pipeline<Entry = PipelineEntry, Request = RequestEntry>,
+{
+    /// Park a request that could not take a prepare slot, stamping its arrival
+    /// time so the promotion side can measure how long it waited.
+    ///
+    /// # Errors
+    /// The entry itself, when the request queue is at its depth bound.
+    pub fn push_queued_request(&self, mut entry: RequestEntry) -> Result<(), RequestEntry> {
+        entry.received_at = self.clock_realtime_micros();
+        self.pipeline.borrow_mut().push_request(entry)
+    }
+}
+
+/// Outcome of [`VsrConsensus::rollback_pipelined_prepare`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PrepareRollback {
+    /// Sequencer, parent chain, and pipeline entry all restored. The op is free
+    /// again and the next request reuses it.
+    Unwound,
+    /// This replica never pre-advanced for the prepare, so there is nothing to
+    /// undo. A backup advances only AFTER its append succeeds.
+    NotPreAdvanced,

Review Comment:
   Done.



-- 
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