object_log/sequencer.rs
1//! The sequencing seam: offset assignment, the offset→location index, and
2//! retention. The engine owns storage + buffering; a `Sequencer` owns offsets.
3
4use crate::ObjectLogError;
5use serde::{Deserialize, Serialize};
6use std::collections::{HashMap, HashSet};
7use std::sync::Mutex;
8
9/// Opaque, engine-visible identifier for an independent offset stream (one dense,
10/// monotonic offset space). A Kafka broker maps `(topic, partition)` onto one of
11/// these; a WAL maps a shard. object-log treats it as an opaque key.
12#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
13pub struct PartitionKey(pub String);
14
15impl PartitionKey {
16 /// Borrow the key as a string slice.
17 pub fn as_str(&self) -> &str {
18 &self.0
19 }
20}
21
22/// Where a batch's bytes live inside its object. **Authored by the engine** (it
23/// owns object layout); the sequencer stores it in the index and returns it from
24/// [`Sequencer::lookup`].
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26pub struct BatchLocation {
27 /// Key of the object holding the batch.
28 pub object_id: String,
29 /// Byte offset of the batch within the object.
30 pub byte_start: u32,
31 /// Byte length of the batch.
32 pub byte_len: u32,
33}
34
35/// One batch presented to [`Sequencer::commit`]. The engine fills `partition`,
36/// `record_count`, and `location` (all engine-visible); `meta` is forwarded
37/// **uninterpreted** — only the sequencer reads it.
38pub struct CommitBatch<'a, M> {
39 /// The offset stream this batch belongs to.
40 pub partition: PartitionKey,
41 /// Number of records in the batch (offsets advance by this).
42 pub record_count: i32,
43 /// Where the batch lives in its (already-durable) object.
44 pub location: BatchLocation,
45 /// Sequencer-private metadata (e.g. idempotent-producer identity). Opaque to
46 /// the engine.
47 pub meta: &'a M,
48 /// Fence epoch the caller believes owns this partition. [`ManifestSequencer`](crate::ManifestSequencer)
49 /// rejects the batch when the stored index epoch differs. Other sequencers
50 /// ignore it.
51 pub epoch: u64,
52}
53
54/// Per-batch result of [`Sequencer::commit`].
55#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
56pub enum CommitOutcome {
57 /// A fresh, contiguous offset range was assigned starting at `base_offset`.
58 Assigned {
59 /// First offset assigned to the batch.
60 base_offset: i64,
61 /// Number of records committed.
62 record_count: i32,
63 },
64 /// A retried batch was recognized as already committed (idempotent no-op);
65 /// the original `base_offset` is returned.
66 Duplicate {
67 /// The originally assigned first offset.
68 base_offset: i64,
69 },
70 /// This batch was not indexed. Other batches in the same call may already
71 /// be durable. The caller must rewrite this batch in a new data object
72 /// rather than reuse the offsets it expected.
73 Rejected {
74 /// Why the conditional update did not land.
75 reason: String,
76 },
77}
78
79/// An index entry resolving an offset range to its bytes.
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct IndexEntry {
82 /// Where the batch's bytes live.
83 pub location: BatchLocation,
84 /// First offset in the batch.
85 pub base_offset: i64,
86 /// Number of records in the batch.
87 pub record_count: i32,
88}
89
90/// The linearization point: assigns offsets to durably-stored batches and owns
91/// the offset→location index.
92///
93/// **Synchronous on purpose** — a lin-point is a critical section, not async I/O.
94/// The engine calls it from its flush worker (a dedicated thread / blocking
95/// task), so a blocking implementation (a `Mutex`, a SQL transaction) is fine.
96///
97/// Contract: [`commit`](Sequencer::commit) is **atomic across the whole slice**
98/// (all supplied batches commit together or not at all), and the engine
99/// presents batches for any single [`PartitionKey`] in arrival order and never
100/// splits one partition across concurrent `commit` calls.
101pub trait Sequencer: Send + Sync {
102 /// Sequencer-private per-batch metadata, forwarded uninterpreted by the
103 /// engine. object-log's default sequencers use `()`; a Kafka coordinator uses
104 /// its producer-identity fields.
105 type Meta: Send + Sync;
106
107 /// Opt in to atomic commits containing already-durable batches from several
108 /// data objects, in creation order. Default preserves one-object calls for
109 /// custom sequencers that rely on that boundary.
110 fn supports_multi_object_commit(&self) -> bool {
111 false
112 }
113
114 /// Assign offsets to durably uploaded batches and persist the index.
115 /// By default these belong to one object; an opted-in implementation may
116 /// receive several objects in one ordered call.
117 /// Returns one [`CommitOutcome`] per input batch, in order.
118 ///
119 /// On `Err`, nothing from this call was indexed. A [`CommitOutcome::Rejected`]
120 /// batch was not indexed either; earlier batches in the same call may already
121 /// be durable when the sequencer commits one partition at a time.
122 fn commit(
123 &self,
124 batches: &[CommitBatch<'_, Self::Meta>],
125 ) -> Result<Vec<CommitOutcome>, ObjectLogError>;
126
127 /// Resolve `fetch_offset` to the ordered index entries covering it onward.
128 fn lookup(
129 &self,
130 partition: &PartitionKey,
131 fetch_offset: i64,
132 ) -> Result<Vec<IndexEntry>, ObjectLogError>;
133
134 /// The next offset to be assigned (index-only; no object reads).
135 fn high_watermark(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError>;
136
137 /// The first readable offset (advances on [`truncate_before`](Sequencer::truncate_before)).
138 fn log_start_offset(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError>;
139
140 /// Retention MECHANISM (not policy): drop index entries below `offset` and
141 /// return object ids that now have **no** live references from **any**
142 /// partition (objects are multiplexed and shared), for the engine to delete.
143 fn truncate_before(
144 &self,
145 partition: &PartitionKey,
146 offset: i64,
147 ) -> Result<Vec<String>, ObjectLogError>;
148
149 /// Move the stored fence epoch for `partition` from `expected` to `new_epoch`.
150 ///
151 /// The default succeeds without storing anything. [`ManifestSequencer`](crate::ManifestSequencer)
152 /// reads that partition's durable index, fails when its epoch is neither
153 /// `expected` nor `new_epoch`, and otherwise stores `new_epoch`, creating the
154 /// index when it is missing. Once this returns, a writer that has not seen
155 /// the new epoch cannot commit to the partition.
156 fn fence_epoch(
157 &self,
158 partition: &PartitionKey,
159 expected: u64,
160 new_epoch: u64,
161 ) -> Result<(), ObjectLogError> {
162 let _ = (partition, expected, new_epoch);
163 Ok(())
164 }
165
166 /// Reload `partition`'s index from durable storage, so this handle sees
167 /// commits made by other writers since it opened.
168 ///
169 /// The default does nothing: a sequencer with a single writer is already
170 /// current.
171 fn refresh_partition(&self, partition: &PartitionKey) -> Result<(), ObjectLogError> {
172 let _ = partition;
173 Ok(())
174 }
175}
176
177/// Per-partition in-memory index state.
178#[derive(Default)]
179struct PartState {
180 next_offset: i64,
181 log_start: i64,
182 entries: Vec<IndexEntry>,
183}
184
185/// A single-node, in-memory [`Sequencer`] (`Meta = ()`): assigns dense offsets and
186/// keeps the offset→location index in memory.
187///
188/// The log *bytes* live durably in the `BlobStore`, but this index does not
189/// survive a restart — use it for tests and single-process work, or persist the
190/// index yourself for a crash-durable standalone log.
191#[derive(Default)]
192pub struct InMemorySequencer {
193 state: Mutex<HashMap<PartitionKey, PartState>>,
194}
195
196impl InMemorySequencer {
197 /// Create an empty sequencer.
198 pub fn new() -> Self {
199 Self::default()
200 }
201
202 /// Object ids referenced by any live index entry (for orphan reaping).
203 pub fn live_object_ids(&self) -> HashSet<String> {
204 let state = self.state.lock().expect("poisoned");
205 let mut live = HashSet::new();
206 for ps in state.values() {
207 for e in &ps.entries {
208 live.insert(e.location.object_id.clone());
209 }
210 }
211 live
212 }
213}
214
215impl Sequencer for InMemorySequencer {
216 type Meta = ();
217
218 fn supports_multi_object_commit(&self) -> bool {
219 true
220 }
221
222 fn commit(
223 &self,
224 batches: &[CommitBatch<'_, Self::Meta>],
225 ) -> Result<Vec<CommitOutcome>, ObjectLogError> {
226 let mut state = self.state.lock().expect("poisoned");
227 let mut outcomes = Vec::with_capacity(batches.len());
228 for cb in batches {
229 let ps = state.entry(cb.partition.clone()).or_default();
230 let base = ps.next_offset;
231 ps.entries.push(IndexEntry {
232 location: cb.location.clone(),
233 base_offset: base,
234 record_count: cb.record_count,
235 });
236 ps.next_offset = base + cb.record_count as i64;
237 outcomes.push(CommitOutcome::Assigned {
238 base_offset: base,
239 record_count: cb.record_count,
240 });
241 }
242 Ok(outcomes)
243 }
244
245 fn lookup(
246 &self,
247 partition: &PartitionKey,
248 fetch_offset: i64,
249 ) -> Result<Vec<IndexEntry>, ObjectLogError> {
250 let state = self.state.lock().expect("poisoned");
251 let Some(ps) = state.get(partition) else {
252 return Ok(Vec::new());
253 };
254 Ok(ps
255 .entries
256 .iter()
257 .filter(|e| e.base_offset + e.record_count as i64 > fetch_offset)
258 .cloned()
259 .collect())
260 }
261
262 fn high_watermark(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError> {
263 Ok(self
264 .state
265 .lock()
266 .expect("poisoned")
267 .get(partition)
268 .map_or(0, |ps| ps.next_offset))
269 }
270
271 fn log_start_offset(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError> {
272 Ok(self
273 .state
274 .lock()
275 .expect("poisoned")
276 .get(partition)
277 .map_or(0, |ps| ps.log_start))
278 }
279
280 fn truncate_before(
281 &self,
282 partition: &PartitionKey,
283 offset: i64,
284 ) -> Result<Vec<String>, ObjectLogError> {
285 let mut state = self.state.lock().expect("poisoned");
286 let mut dropped: Vec<String> = Vec::new();
287 match state.get_mut(partition) {
288 Some(ps) => {
289 for e in ps.entries.iter() {
290 if e.base_offset + e.record_count as i64 <= offset {
291 dropped.push(e.location.object_id.clone());
292 }
293 }
294 ps.entries
295 .retain(|e| e.base_offset + e.record_count as i64 > offset);
296 if offset > ps.log_start {
297 ps.log_start = offset.min(ps.next_offset);
298 }
299 }
300 None => return Ok(Vec::new()),
301 }
302 // An object is reclaimable only when no entry in ANY partition references it.
303 let mut live: HashSet<String> = HashSet::new();
304 for ps in state.values() {
305 for e in &ps.entries {
306 live.insert(e.location.object_id.clone());
307 }
308 }
309 let mut dead: Vec<String> = Vec::new();
310 let mut seen: HashSet<String> = HashSet::new();
311 for oid in dropped {
312 if !live.contains(&oid) && seen.insert(oid.clone()) {
313 dead.push(oid);
314 }
315 }
316 Ok(dead)
317 }
318}