1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! `Rows.db` in-trie payload decoding (`RowIndexReader` / `TrieIndexEntry`).
//!
//! IMPORTANT: `Rows.db` in-trie payloads are NOT the `Partitions.db` payload
//! format (which is a hash byte + SizedInts *signed* position). A `Rows.db`
//! trie leaf carries a `RowIndexReader.IndexInfo` whose byte layout is defined
//! authoritatively by `RowIndexReader.readPayload`
//! (cassandra-5.0.0 `RowIndexReader.java:111-125`):
//!
//! static IndexInfo readPayload(ByteBuffer buf, int ppos, int bits, Version v) {
//! if (bits == 0) return null;
//! int bytes = bits & ~FLAG_OPEN_MARKER; // FLAG_OPEN_MARKER = 8
//! long offset = SizedInts.read(buf, ppos, bytes); // SizedInts, NOT a vint
//! ppos += bytes;
//! DeletionTime del = (bits & FLAG_OPEN_MARKER) != 0
//! ? DeletionTime.deserialize(buf, ppos) : null;
//! return new IndexInfo(offset, del);
//! }
//!
//! So the low nibble of the node header byte (`payloadBits`) splits as:
//! - low 3 bits → the number of `SizedInts` bytes encoding the block offset
//! - bit 0x8 → FLAG_OPEN_MARKER: an open-deletion `DeletionTime` follows
//!
//! The `offset` field is the block's offset **relative to the partition start**
//! in `Data.db`, so absolute Data.db position = `entry.data_position + offset`.
//!
//! Reference: docs/sstables-definitive-guide chapter 17 (Rows.db footer);
//! cassandra-5.0.0 `RowIndexReader.java`, `RowIndexWriter.java`,
//! `TrieIndexEntry.java`, `SizedInts.java`.
use crate::;
use ;
use sized_ints_read_from_slice;
use ;
use ;
// referenced in doc-links
use BtiPartitionLocation;
/// The `FLAG_OPEN_MARKER` bit in a `Rows.db` trie node's `payloadBits`
/// (low nibble of the header byte). When set, an open-deletion `DeletionTime`
/// follows the `SizedInts` block offset. Mirrors
/// `RowIndexReader.FLAG_OPEN_MARKER`.
pub const FLAG_OPEN_MARKER: u8 = 0x8;
/// A decoded `Rows.db` in-trie row-index block entry (`RowIndexReader.IndexInfo`).
///
/// The headline field is [`data_offset`](Self::data_offset): the block's offset
/// **relative to the partition start** in `Data.db`. To obtain the absolute
/// `Data.db` byte position, add the partition's data position (see
/// [`BtiRowIndexHeader::data_position`]).
/// Read an unsigned VInt (Cassandra count-leading-ones encoding, **not** ZigZag)
/// from `data`, returning `(value, bytes_consumed)`.
///
/// This is the encoding Cassandra uses for Data.db positions in the row index
/// (`DataOutputPlus.writeUnsignedVInt`). The number of extra bytes equals the
/// number of leading 1-bits in the first byte; the value is big-endian across
/// the remaining bits.
/// Read a signed VInt (Cassandra zig-zag, `DataInputPlus.readVInt`) from `data`,
/// returning `(value, bytes_consumed)`.
/// Test-only re-export of [`read_unsigned_vint_from_slice`] so the BTI `Rows.db`
/// writer (`writer::partitions_writer`) can assert its unsigned-VInt encoder is
/// the exact inverse of this reader decoder.
/// Test-only re-export of [`read_signed_vint_from_slice`].
/// The modern (DA/BTI) `DeletionTime` "live" sentinel byte.
///
/// In the `da`-family on-disk serializer, a `DeletionTime` written by the BTI
/// row-index / trie-index path is encoded as a single `0x80` byte when it is
/// `DeletionTime.LIVE` (no deletion), and otherwise as the full value (see
/// [`decode_da_deletion_time`]).
const DA_DELETION_TIME_LIVE_SENTINEL: u8 = 0x80;
/// Width of a non-live modern (DA) `DeletionTime` body: `i64 markedForDeleteAt`
/// followed by `u32 localDeletionTime`.
const DA_DELETION_TIME_BODY_LEN: usize = 12;
/// Decode a modern (DA/BTI) `DeletionTime` at `data[start..]`, returning
/// `(deletion, bytes_consumed)` where `deletion` is `None` for the LIVE
/// sentinel (issue #832 Finding 2).
///
/// Layout (mirrors `org.apache.cassandra.db.DeletionTime.Serializer` in the
/// `da`/trie-index format, cassandra-5.0.0):
///
/// - a single `0x80` byte → `DeletionTime.LIVE` (no deletion); consumes 1 byte.
/// - otherwise the body is `[markedForDeleteAt : i64 BE][localDeletionTime :
/// u32 BE]` — `markedForDeleteAt` FIRST, then `localDeletionTime`; consumes
/// 12 bytes. This differs from the LEGACY layout in BOTH field order and
/// the width/signedness of `localDeletionTime` (modern: `u32`).
///
/// Returns the deletion as `(local_deletion_time, marked_for_delete_at)` to
/// match [`BtiRowIndexEntry::open_marker`]'s existing tuple ordering, even
/// though the modern wire order is the reverse.
///
/// # Errors
/// Returns a parse error if `start` is out of bounds or a non-live value is
/// truncated.
/// Whether `byte` is the modern (DA/BTI) `DeletionTime` LIVE-sentinel byte.
///
/// NOTE for callers that need a LENGTH rather than a decode: this test is
/// PREFIX-AMBIGUOUS by construction. `0x80` is both the one-byte LIVE sentinel and
/// the leading big-endian byte of a full 12-byte body whose `markedForDeleteAt` lies
/// in the `Long.MIN_VALUE` octant, and nothing later in the encoding distinguishes
/// them. [`decode_da_deletion_time`] resolves the ambiguity the way Cassandra's own
/// reader does (sentinel first), which is right for decoding a value; a consumer
/// that measures a surrounding structure must consider BOTH widths — see
/// [`super::rows_root::RowsNodeExtent`].
pub
/// Width of a NON-live modern (DA/BTI) `DeletionTime` body
/// ([`DA_DELETION_TIME_BODY_LEN`]), so the on-disk widths live in exactly one place
/// and [`super::rows_root`]'s node-extent computation cannot drift from the decoder.
pub
/// Decode a `Rows.db` in-trie payload (`RowIndexReader.IndexInfo`) at
/// `payload_start` inside `trie_data`, given the node's `payload_bits` (low
/// nibble of the header byte).
///
/// Layout (mirrors `RowIndexReader.readPayload`, cassandra-5.0.0
/// `RowIndexReader.java:111-125`):
/// - `bytes = payload_bits & !FLAG_OPEN_MARKER` → block offset is a
/// `SizedInts` value of `bytes` bytes (the offset is relative to the
/// partition's data position).
/// - if `payload_bits & FLAG_OPEN_MARKER`, an open-deletion `DeletionTime`
/// follows in the MODERN DA form ([`decode_da_deletion_time`]).
///
/// A `payload_bits` of `0` is not a valid leaf payload here (the caller filters
/// such nodes out) and yields an error.
/// Enumerate every row-index entry in a `Rows.db` trie (rooted at `root_offset`)
/// in byte-comparable order: `(reconstructed_clustering_key, BtiRowIndexEntry)`.
///
/// The per-node payload primitive lives in [`super::rows_floor`], alongside the
/// O(key-length) floor/ceiling walks that share it (issue #1647 / L1).
pub
/// Enumerate every row-index entry in a `Rows.db` row-index trie **rooted at an
/// explicit `root_offset`**, in byte-comparable order
/// (`(reconstructed_clustering_key, BtiRowIndexEntry)`).
///
/// ## Why the root must be supplied by the caller
///
/// A real Cassandra 5.0 `Rows.db` is NOT a single whole-file trie: it holds
/// **many independent per-partition row-index tries** concatenated together.
/// There is one row-index trie per (wide) partition, and the root of a given
/// partition's trie is the `RowsOffset` returned from the corresponding
/// `Partitions.db` lookup ([`BtiPartitionLocation::RowsOffset`]) — it is NOT the
/// 8-byte file footer, which spans the whole file and would misparse any
/// multi-partition `Rows.db`.
///
/// This is therefore the correct general entry point: pass the full `Rows.db`
/// bytes as `trie_data` and the partition's `RowsOffset` as `root_offset`.
///
/// An out-of-bounds `root_offset` (e.g. on empty `trie_data`) yields a clean
/// parse error rather than a panic.
// ─────────────────────────────────────────────────────────────────────────────
// Per-partition Rows.db entry resolution — TrieIndexEntry (issue #832 Finding A)
// ─────────────────────────────────────────────────────────────────────────────
//
// The positive `position` stored in a `Partitions.db` leaf payload
// (`BtiPartitionLocation::RowsOffset`) does NOT point at a row-index trie root.
// It points at this partition's **row-index entry** in `Rows.db`, which must be
// deserialized to recover the actual trie root (plus the partition's Data.db
// position, block count and partition-level deletion).
//
// On-disk layout at `RowsOffset`:
// [u16 key_length][partition key bytes] ← short-length-prefixed key
// [data file position : unsigned vint] ← partition start in Data.db
// [trie_root - base : SIGNED vint] ← base = RowsOffset + 2 + key_length
// [row index block count : unsigned vint32]
// [partition DeletionTime] ← delta/compact form; best-effort
//
// `TrieIndexEntry.deserialize` computes `indexTrieRoot = readVInt() + base`, where
// `base` is the position AFTER the short-length-prefixed key: cassandra-5.0.8 takes
// it as `rowIndexWriter.position()` after `writeWithShortLength`
// (`BtiTableWriter.IndexWriter.append`) and as `in.getFilePointer()` after
// `readWithShortLength` (`BtiTableReader.retrieveEntryIfAcceptable`) — NOT
// `RowsOffset + key_length`, which is 2 bytes low and drops the root node's own
// (empty-separator = block 0) payload (issue #3002).
// ─────────────────────────────────────────────────────────────────────────────
/// A single `Rows.db` row-index entry paired with its reconstructed
/// byte-comparable clustering separator key, as yielded by the in-order DFS.
pub type BtiRowIndexEntryWithKey = ;
/// A deserialized per-partition `Rows.db` row-index entry (Cassandra
/// `TrieIndexEntry`). Produced by [`resolve_rows_db_entry`] from the
/// `RowsOffset` returned by a `Partitions.db` lookup.
/// Resolve a partition's row-index entry in `Rows.db`, given the `RowsOffset`
/// from a `Partitions.db` lookup ([`BtiPartitionLocation::RowsOffset`]).
///
/// This is the fix for issue #832 Finding A: `RowsOffset` is the offset of the
/// per-partition `TrieIndexEntry`, NOT a trie root. This deserializes that
/// entry — recovering the partition's Data.db position, the actual row-index
/// trie root, the block count and the partition deletion — so traversal can be
/// rooted correctly.
///
/// `rows_db` is the full `Rows.db` file contents; `rows_offset` is the
/// `RowsOffset` value. All reads are bounds-checked.
///
/// The recovered trie root is STRUCTURALLY VALIDATED before it is exposed
/// ([`super::rows_root::validate_rows_trie_root`], issue #3002): an unusable root
/// yields `Ok` with [`BtiRowIndexHeader::trie_root`] set to `Err(reason)`, NOT a
/// failed resolution — `data_position`/`block_count` are decoded independently and
/// the paths that consume only those (point lookup, successor walk) must keep
/// working.
///
/// # Errors
/// Returns a parse error if `rows_offset` is out of bounds, the key length is
/// implausible, or the vint fields are truncated.
/// `TrieIndexEntry.deserialize` WITHOUT the L1 `ROWS_DB_ENTRY_RESOLVES` counter
/// (issue #2058). Identical decode to [`resolve_rows_db_entry`]; used by the
/// next-partition SUCCESSOR walk, which resolves a WIDE successor partition's
/// `data_position` only to compute the target partition's exclusive END bound — that
/// is seek-bound work, NOT the clustering-window per-partition resolve the L1
/// invariant (`ROWS_DB_ENTRY_RESOLVES == 1`) accounts for, so it must not bump it.
pub
/// Select the row-index blocks that may contain clustering keys in the
/// inclusive byte-comparable range `[start, end]`, applying row-index
/// **separator** semantics (issue #832 Finding B).
///
/// ## Why naive `[start, end]` filtering is wrong
///
/// A `Rows.db` row-index trie stores **separators**, not block start keys. For
/// consecutive blocks the writer (`RowIndexWriter.add`) stores the shortest
/// `sep` with `prevMax < sep <= nextBlockFirstKey`, and `complete()` appends a
/// trailing separator after the last block. Consequently the separator `s_i`
/// labels the boundary at the START of block `i`'s key range, and block `i`
/// covers the half-open key interval `[s_i, s_{i+1})` (the final block runs to
/// the trailing separator). A reader locates the block for a key `K` via the
/// trie *floor* of `K` (`RowIndexReader.separatorFloor`).
///
/// Therefore a block `i` overlaps the requested clustering range `[start, end]`
/// iff its key interval `[s_i, s_{i+1})` intersects `[start, end]`:
///
/// `s_i <= end` AND `s_{i+1} > start`
///
/// (For the last block, `s_{i+1}` is treated as +∞.)
///
/// `entries` MUST be the full ascending-order `(separator, block)` list for one
/// partition (as produced by [`iterate_rows_in_bti_trie`]). `start`/`end` are
/// byte-comparable clustering bounds in the **same encoding as the trie keys**.
/// Reversed bounds (`start > end`) yield an empty result.
///
/// ## Implicit first block (issue #1968)
///
/// The trie stores a separator per block EXCEPT the first: the block covering
/// keys BELOW `entries[0]`'s separator lives at the partition body start and has
/// NO entry here (mirroring `RowIndexReader.separatorFloor`, which returns the
/// partition start for a key below the first separator). This function therefore
/// only ever returns STORED blocks — it CANNOT return that implicit first block.
/// A caller whose `start` sorts below `entries[0]`'s separator (e.g. an OPEN lower
/// bound, `start == b""`) MUST additionally decode from the partition body start
/// so the earliest clustering rows are not dropped; see
/// `resolve_bti_clustering_seek_window` in `reader/data_access/bti.rs`.
/// Enumerate every row-index block entry for the partition whose `Rows.db`
/// row-index entry is at `rows_offset` (the `RowsOffset` from `Partitions.db`),
/// in ascending byte-comparable (clustering) order.
///
/// This is the convenience entry point that combines [`resolve_rows_db_entry`]
/// (Finding A) with [`iterate_rows_in_bti_trie`]: it resolves the real trie root
/// from the per-partition entry and then traverses from that root. Each
/// returned [`BtiRowIndexEntry::data_offset`] is **relative to the partition
/// start**; add `header.data_position` for an absolute `Data.db` position.
///
/// Returns `(header, entries)`.
///
/// # Errors
/// Propagates the entry-resolution error and, per issue #3002, FAILS when the
/// entry's root did not pass structural validation — a full enumeration has no
/// narrower fallback to take, and a malformed row index is exactly what
/// `verify`'s `BtiTrieCorrupt` finding should report.
/// Enumerate row-index entries in a `Rows.db` file that is a **single-partition**
/// trie rooted at its 8-byte footer, in byte-comparable order.
///
/// ## Precondition
///
/// This treats the WHOLE file as one trie whose root is named by the trailing
/// 8-byte footer. That is only correct when the `Rows.db` contains exactly one
/// partition's row-index trie (or is empty). For a real multi-partition
/// `Rows.db` you MUST instead use [`iterate_rows_in_bti_trie`] with the
/// per-partition `RowsOffset` obtained from `Partitions.db`.
///
/// A `< 8`-byte (e.g. 0-byte) `Rows.db` yields an empty Vec without erroring.