mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 00:15:29 +00:00
feat(mito2)!: add short-series IPC storage for Narthex (#10814)
* feat(mito2): store short Narthex series in Arrow IPC pages Signed-off-by: evenyag <realevenyag@gmail.com> * refactor(mito2): share inline tails across Narthex sample layouts Signed-off-by: evenyag <realevenyag@gmail.com> * refactor(mito2): key sample tails by region file ID Signed-off-by: evenyag <realevenyag@gmail.com> * refactor(mito2): narrow IPC scope and consolidate artifact metadata Signed-off-by: evenyag <realevenyag@gmail.com> * refactor(mito2): read sample sizes from the SST inventory Signed-off-by: evenyag <realevenyag@gmail.com> * refactor(mito2): keep memory sample tails with their bytes Signed-off-by: evenyag <realevenyag@gmail.com> * fix(mito2): use crate-qualified imports in sample IPC codec Signed-off-by: evenyag <realevenyag@gmail.com> * fix(mito2): compile sample key helper only in unit tests Signed-off-by: evenyag <realevenyag@gmail.com> * fix(mito2): bound Narthex IPC pages and reads Signed-off-by: evenyag <realevenyag@gmail.com> * fix(mito-codec)!: cap sparse primary keys at 16 MiB BREAKING CHANGE: Newly encoded sparse primary keys omit the first label that exceeds the key budget and all following labels. Oversized pre-encoded keys are rejected at write admission. Signed-off-by: evenyag <realevenyag@gmail.com> --------- Signed-off-by: evenyag <realevenyag@gmail.com>
This commit is contained in:
+99
-568
@@ -1,590 +1,121 @@
|
||||
# Narthex format: samples
|
||||
# Narthex samples format
|
||||
|
||||
The **Narthex format**, selected by `sst_format = 'narthex'`, is optimized
|
||||
for Prometheus-style metric data. It separates series identities and string tags
|
||||
from timestamped numeric samples.
|
||||
`NarthexSamples` stores timestamps, sequences, operation types, and nullable
|
||||
Float64 or native histogram fields. The [series index](mito-series.md) stores
|
||||
exact series identities and tags.
|
||||
|
||||
The format has two artifact roles: `NarthexSamples` owns sample data, and
|
||||
`NarthexSeriesIndex` indexes exact series identities.
|
||||
Region manifests serialize these roles as `narthex_samples` and
|
||||
`narthex_series_index`.
|
||||
## SST objects
|
||||
|
||||
## Region manifest
|
||||
```text
|
||||
Region manifest
|
||||
└─ narthex_samples
|
||||
└─ parts[part_id] = { file_size, tail_size }
|
||||
|
||||
With `sst_format = 'narthex'`, a samples SST owns
|
||||
`<region_dir>/<file_id>/manifest.json` and its `part-<n>.samples` objects.
|
||||
The region manifest records the manifest size and a `parts` array in part-ID
|
||||
order. Each part record contains its encoded `file_size` in bytes. The
|
||||
[series index specification](mito-series.md#region-manifest) defines coverage.
|
||||
<region_dir>/<file_id>/part-<part_id>.samples
|
||||
┌───────────────────────┬──────────────────────────────────────────────────┐
|
||||
│ header | groups … │ fixed-width group directory | JSON | trailer │
|
||||
└───────────────────────┴──────────────────────────────────────────────────┘
|
||||
↑ tail_size bytes ↑
|
||||
file_size - tail_size EOF
|
||||
```
|
||||
|
||||
## Wire specification
|
||||
- **Header** contains `GTSAMPLE` followed by eight reserved zero bytes.
|
||||
- **JSON descriptor** contains the layout (`series_blocks` or `arrow_ipc`),
|
||||
immutable file identity, timestamp and field schemas, and one part record
|
||||
with the part ID, inclusive series/time bounds, and row and block counts.
|
||||
- **Trailer** is 24 bytes containing `NXSAMPLE`, the directory length as
|
||||
a little-endian u64, and the JSON length as a little-endian u64.
|
||||
- **Group directory** uses 108 bytes per entry. The first group starts after
|
||||
the header. Each following group starts at the end of the previous root page.
|
||||
|
||||
The samples format stores ordered groups of single-series blocks in each sample part.
|
||||
Every group owns its column chunks, exact sparse primary keys, and descriptor
|
||||
pages. The part directory locates the groups and records their ID and time bounds.
|
||||
As a pre-GA exception to the format versioning rule, the manifest and part header
|
||||
retain version 1 across this layout change. Rebuild artifacts written with the
|
||||
earlier embedded or unframed grouped layouts before using this reader.
|
||||
| Group entry | Bytes |
|
||||
| --- | ---: |
|
||||
| First and last `(table_id, tsid)` and min/max timestamp | 40 |
|
||||
| Root payload reference | 24 |
|
||||
| Page depth | 4 |
|
||||
| Payload end, stored key end, logical key end | 8 each |
|
||||
| Row count, block or run count | 8 each |
|
||||
|
||||
Like the Mito Parquet write path, grouped samples add no application-level content
|
||||
checksums. This applies to the group directory, descriptor pages, exact-key frames,
|
||||
and column chunks. Readers validate structure, lengths, and bounds, but rely on
|
||||
the storage layer for byte integrity. A corrupted directory bound that still
|
||||
passes validation can prune matching rows. A same-length change to raw key or
|
||||
value bytes can silently change a series label or a Float64 value.
|
||||
The reader fetches `[file_size - tail_size, file_size)` in one range read per
|
||||
part. The three tail sections supply the schema, layout, and pruning bounds.
|
||||
Part copies preserve the immutable file ID and byte contents.
|
||||
|
||||
Samples store nullable Float64 and native histogram fields, timestamps, sequences,
|
||||
and operation types in single-series blocks bounded by rows and decoded bytes.
|
||||
## Group layouts
|
||||
|
||||
## Artifact manifest
|
||||
```text
|
||||
series_blocks
|
||||
[group start]
|
||||
timestamp / sequence / operation / value chunks
|
||||
key frames [stored lengths: u32 … | frame bytes …]
|
||||
descriptor pages [leaf … | root if depth = 2]
|
||||
[group end]
|
||||
|
||||
The region manifest publishes each samples file and its object sizes. The file's
|
||||
manifest and parts share its generation directory. Readers pin the SST while
|
||||
using those objects.
|
||||
arrow_ipc
|
||||
[group start]
|
||||
Arrow batch [message length: u64 | message | 8-byte padding | body]
|
||||
key frames [Zstd frames of (key length: u32, sparse key bytes) …]
|
||||
series runs [run count: u16 | frame count: u16 | runs … | frames …]
|
||||
[group end]
|
||||
```
|
||||
|
||||
The source file ID and generation use existing `FileId` serialization. The
|
||||
generation is unique for each build. A manifest contains:
|
||||
The streaming writer computes the average rows per exact series over a prefix
|
||||
of up to 4,096 sorted rows, including retained versions and deletes. It uses
|
||||
Arrow IPC at an average of at most eight rows per series and series blocks above
|
||||
that. Each SST uses one layout. Direct flush uploads already encoded series blocks.
|
||||
|
||||
| Field | Meaning |
|
||||
### Series blocks
|
||||
|
||||
```text
|
||||
root ─┬─ leaf ─┬─ block → exact key + column payload references
|
||||
│ └─ block → exact key + column payload references
|
||||
└─ leaf ─── block → exact key + column payload references
|
||||
```
|
||||
|
||||
Each block covers one exact series. Rows are ordered by increasing
|
||||
timestamp and decreasing sequence at the same timestamp. Leaf pages store
|
||||
block descriptors. An internal root stores child bounds and references.
|
||||
A one-leaf group uses that leaf as its root. A block descriptor records
|
||||
the coarse series ID, exact-key offset and length, time bounds, ordinal,
|
||||
row count, and column descriptors. Each column descriptor records the
|
||||
role, column ID, payload reference, and null count.
|
||||
|
||||
Logical key references are offsets into the decoded key stream based at
|
||||
`payload_end`. The stream is split into 64 KiB frames. A frame is raw when its
|
||||
stored length equals its logical length and Zstd-compressed otherwise.
|
||||
|
||||
| Column | Encoding ID and representation |
|
||||
| --- | --- |
|
||||
| `format` | String `columnar-samples` |
|
||||
| `version` | Integer 1 |
|
||||
| `identity_encoding` | String `exact-sparse-key-area`; required, never defaulted. It names the identity *and* the layout that stores it, so `exact-sparse-key` (keys inline in the block descriptors) is different and not readable |
|
||||
| `region_id` | Physical region ID, u64 |
|
||||
| `source_file_id` | Physical samples SST file ID |
|
||||
| `generation` | Physical samples SST file ID, using `FileId` serialization |
|
||||
| `timestamp` | Object with `column_id`, `name`, and `unit` |
|
||||
| `fields` | Ordered objects with `column_id`, `name`, `type`, and `nullable` |
|
||||
| `files` | Ordered part descriptors, defined below |
|
||||
| Timestamp | 1 constant step, 2 delta of delta |
|
||||
| Sequence | 3 constant, 4 delta |
|
||||
| Float64 | 5 nullable XOR |
|
||||
| Operation | 6 constant, 7 raw |
|
||||
| Native histogram | 8 Arrow struct encoded by child |
|
||||
|
||||
The timestamp's ID is u32, its name is the region's time-index name, and its unit
|
||||
is one of `second`, `millisecond`, `microsecond`, or `nanosecond`. Values are
|
||||
signed i64 counts since the Unix epoch in that unit. There is no dataset-relative
|
||||
origin, unit conversion, or timezone in the file. The timestamp is non-null.
|
||||
### Arrow IPC pages
|
||||
|
||||
The field list records the build-time region field schema in metadata order.
|
||||
Require 1..=1,024 fields, each with `type` `"float64"` or `"native_histogram"` and
|
||||
`nullable = true`. `native_histogram` is the canonical nullable
|
||||
`greptime_native_histogram` Arrow struct, the same type the Parquet path stores.
|
||||
A non-nullable source Float64 field is represented by this same nullable logical
|
||||
type with no null values. Sparse logical-table fields may be entirely null.
|
||||
Timestamp and field IDs must be distinct. All output names must be unique,
|
||||
including the internal names below. Tags are not sample fields and are not stored here.
|
||||
The uncompressed Arrow batch contains the timestamp, sequence, operation, and
|
||||
value columns. A serialized batch may occupy up to 128 MiB, with a separate
|
||||
64 MiB budget for the stored key frames. The writer retries with fewer rows
|
||||
when a page exceeds either budget. Each encoded key is at most 16 MiB.
|
||||
The directory uses Zstd with raw fallback.
|
||||
|
||||
The stored logical Arrow schema is `__table_id: UInt32`, `__tsid: UInt64`, the
|
||||
timestamp column with its recorded unit, `__sequence: UInt64`, `__op_type: UInt8`,
|
||||
then the nullable value fields in manifest order, and finally
|
||||
`__primary_key: Binary` naming the exact key of the block that produced each row.
|
||||
The five internal columns and `__primary_key` are non-null; value fields stay
|
||||
nullable, as the manifest declares them. `__table_id`/`__tsid` are the coarse,
|
||||
hash-based prefix of that key. Tag columns are not stored; the exact key is the
|
||||
identity. A reader returns that key once per output batch — each block belongs to
|
||||
exactly one series — instead of materializing the column per row, and rejects a
|
||||
request that projects it.
|
||||
| Directory record | Fields in byte order |
|
||||
| --- | --- |
|
||||
| Run | Table ID u32, TSID u64, cumulative row end u16 |
|
||||
| Key frame | First run u16, offset from payload end u64, stored length u32, decoded length u32 |
|
||||
|
||||
Each `files` entry contains `part_id: u32`, `file_size: u64`, `directory_bytes: u64`, `num_rows: u64`,
|
||||
`num_blocks: u64`, `first`, `last`, `min_timestamp: i64`, and `max_timestamp: i64`.
|
||||
`first` and `last` are inclusive `{ table_id: u32, tsid: u64 }` bounds. Time bounds
|
||||
are the minimum and maximum over **all** blocks in the part, not just its first
|
||||
and last rows. Every part is nonempty. Part IDs start at zero, increase by one,
|
||||
and derive `part-<part_id>.samples` names with decimal IDs and no leading zeros.
|
||||
No object path is stored in a part descriptor.
|
||||
A point lookup binary-searches the group directory and series runs, then reads
|
||||
the required key frames. Both layouts compare the full sparse key when coarse
|
||||
IDs collide.
|
||||
|
||||
Parts follow input order. Adjacent identifier ranges satisfy
|
||||
`previous.last <= next.first`; equality is allowed because a series can continue
|
||||
in another part. The shared boundary series can also have equal timestamps on
|
||||
both sides. These ranges are **not disjoint**, unlike the series-index format.
|
||||
Readers consider every matching part rather than choosing a unique owner.
|
||||
|
||||
`ArtifactMetadata.objects` records the manifest and every part as `{ path, file_size }`;
|
||||
the artifact's `file_size` is their checked sum. An empty artifact has an empty
|
||||
file list and no part files. The manifest is at most 64 MiB.
|
||||
|
||||
Region, source SST, and generation must match the owning SST metadata. The artifact
|
||||
object list must contain exactly the derived manifest and part paths, without
|
||||
duplicates, extra objects, or inconsistent size totals. Part order comes from
|
||||
the manifest.
|
||||
|
||||
## Part file
|
||||
## Payload references
|
||||
|
||||
```text
|
||||
16-byte header
|
||||
group 0:
|
||||
column chunks in block order
|
||||
framed exact keys
|
||||
descriptor leaves and optional internal root
|
||||
group 1 ... group N-1 (same layout)
|
||||
directory (108 bytes per group, in file order)
|
||||
16-byte footer
|
||||
[offset: u64 | stored length: u32 | decoded length: u32
|
||||
| encoding: u16 | compression: u16 | reserved: u32]
|
||||
```
|
||||
|
||||
All fixed-width numbers are little-endian, without alignment padding. Byte ranges
|
||||
are half-open. Physical offsets are measured from the start of the part. Parse each field
|
||||
explicitly. Rust struct layout, enum order, and `usize` are not wire contracts.
|
||||
Reserved fields must be zero, and decoded structures must have no trailing bytes.
|
||||
|
||||
### Header
|
||||
|
||||
| Field | Bytes | Value |
|
||||
| --- | ---: | --- |
|
||||
| Magic | 8 | ASCII `GTSAMPLE` |
|
||||
| File version | 4 | 1 |
|
||||
| Reserved | 4 | Zero |
|
||||
|
||||
### Column payloads and row semantics
|
||||
|
||||
Each block contains exactly one series and names it by that series' exact canonical
|
||||
sparse primary key, which is stored once per series in the group's [key area](#key-area)
|
||||
and referenced by the block descriptor. The key is the SST's own encoding of
|
||||
`(table_id, tsid, label column-id/value pairs sorted by name, non-null only)`, and
|
||||
`(table_id, tsid)` is only its order-preserving prefix. Two distinct series may
|
||||
share a prefix. Timestamp, sequence, operation type, and each present value field
|
||||
are independent chunks; their references are in the metadata, not inline headers.
|
||||
Emit chunks in that order, with value fields following manifest order.
|
||||
|
||||
Rows preserve delete markers, duplicate timestamps, and equal-key ties, including
|
||||
conflicting values at the same sequence. The format does not encode a deduplicated
|
||||
or snapshot-filtered view.
|
||||
|
||||
Block keys are nondecreasing in byte-lexicographic order, timestamps are
|
||||
nondecreasing within one exact key, and sequences are nonincreasing within equal
|
||||
timestamps, including across parts. A change of exact key restarts timestamps and
|
||||
ordinals, even when the coarse `(table_id, tsid)` prefix is unchanged. Equal
|
||||
ordering keys retain input order; operation type is not a sorting key. The key area
|
||||
follows the same order, one copy per series in each group. Block keys never decrease, so a key that
|
||||
is read must not sort before the key read before it; a repeated key must continue its
|
||||
timestamps and ordinals rather than restart them. Because key bytes are read lazily,
|
||||
the descriptor-only checks use the `(table_id, tsid)` prefix and the order, disjointness,
|
||||
and reuse of key references inside one group, and only the keys a request actually loads
|
||||
are checked for byte order and continuation.
|
||||
|
||||
Blocks split on an identity change or before the next row would exceed a packing
|
||||
limit. There is no hourly split and no padding of short blocks. The default row
|
||||
limit is 8,192, also the version-1 reader maximum; a writer may choose a smaller
|
||||
positive limit without changing the version. With `F` manifest fields and `N`
|
||||
rows, the decoded accounting size is:
|
||||
|
||||
```text
|
||||
N * (8 timestamp + 8 sequence + 1 operation + 8 * F values)
|
||||
+ F * ceil(N / 8) validity bytes
|
||||
```
|
||||
|
||||
Require this to be at most 262,144 bytes. A native histogram field counts as one
|
||||
8-byte value per row here, so the formula does not bound its decoded buffers: its
|
||||
18 struct children and bucket lists are bounded only by its chunk, and the reader
|
||||
reserves memory for them from the chunk header (see encoding 8). A
|
||||
writer also ends a block before a histogram chunk's encoded size bound would exceed
|
||||
the 1 MiB chunk limit: 1 byte plus 11 bytes per struct child and per list item for
|
||||
each row, and 16 bytes plus 64 bytes per child and the validity bytes for the
|
||||
chunk. A sample that exceeds the limit on its own is rejected when it is written
|
||||
to a Narthex region. Count all manifest fields, including omitted/all-null
|
||||
fields, and reserve validity bytes even for all-valid fields.
|
||||
Without histogram fields, this is a bound on decoded column buffers, not total
|
||||
allocator usage or RSS.
|
||||
The effective row cap is the largest integer satisfying both limits: 8,192 for
|
||||
one field and 31 for 1,024 fields. Encoded buffers and metadata have separate
|
||||
bounds below. Increasing the reader maximum requires an explicit compatibility
|
||||
decision; it is not merely a writer option in this version.
|
||||
|
||||
### Payload reference
|
||||
|
||||
Every stored column and metadata page uses a 24-byte reference:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Offset | 8 | Absolute location of stored bytes |
|
||||
| Stored length | 4 | Bytes to fetch |
|
||||
| Decoded length | 4 | Bytes after decompression, before column/page decoding |
|
||||
| Encoding ID | 2 | Sample column or metadata encoding, according to context |
|
||||
| Compression ID | 2 | Compression of the encoded bytes |
|
||||
| Reserved | 4 | Zero |
|
||||
|
||||
Lengths are nonzero. Check `offset + stored_length` for u64 overflow before
|
||||
checking the enclosing area. u32 payload lengths do not limit the part or its
|
||||
offsets to 4 GiB. Require exactly the
|
||||
declared decoded length, with bounded output even if a codec frame claims more.
|
||||
|
||||
|
||||
### Key area
|
||||
|
||||
Each group concatenates one copy of each distinct key in block order. A descriptor
|
||||
addresses this logical stream relative to `payload_end`: subtract `payload_end`
|
||||
from the descriptor offset to locate its first byte. Check its nonzero length
|
||||
against `logical_key_end`. One key can span multiple frames.
|
||||
|
||||
Split the stream into 65,536-byte frames with a possibly shorter final frame.
|
||||
The physical key area starts at `payload_end` with one little-endian u32 stored
|
||||
length per frame, followed by their stored bytes. The directory length is `4 * ceil(logical_bytes / 65536)`. A frame whose stored
|
||||
length equals its decoded length is raw. A shorter frame uses Zstd level 1.
|
||||
The frame lengths must exactly cover the physical area ending at `key_end`.
|
||||
|
||||
The samples writer and reader extract the fixed-width ID prefix and treat the
|
||||
remaining bytes as opaque. The reader checks that the ID matches the descriptor
|
||||
and compares full bytes for equality and ordering. It loads only frames needed
|
||||
for selected keys and reuses the current frame across consecutive keys.
|
||||
|
||||
A key reference is an offset into one group's key area, so the references of two groups
|
||||
are unrelated numbers and are never compared. Whether one exact series continues in
|
||||
another group is decided on the exact key bytes: the last key a request loaded from one
|
||||
group is compared with the first it loads from the next, and an equal key must continue
|
||||
timestamps and ordinals, while a greater key starts a new series at ordinal zero.
|
||||
|
||||
Because keys are only read for blocks a request selects, this content check covers the
|
||||
keys actually loaded: unvisited ranges are validated structurally, not by content. It
|
||||
is chained, though, so a selection that skips a block, a page, or a whole part cannot
|
||||
hide the two keys around the gap: the check compares each loaded key with the previous
|
||||
loaded key, not with the previous traversed block. Loaded keys must be nondecreasing.
|
||||
Within one exact key the ordinal must strictly increase, and only immediately adjacent
|
||||
blocks of that same key require it to be exactly one greater; a different key starts a
|
||||
new series at ordinal zero, so no ordering between the two series' ordinals is required.
|
||||
|
||||
### Metadata pages
|
||||
|
||||
A leaf describes blocks. An internal page references leaves. The root is either
|
||||
the only leaf (depth 1) or an internal page (depth 2). Other depths are unsupported
|
||||
in version 1; finish the current group before a third level would be needed.
|
||||
|
||||
As in the series format, the entire page, including its kind and count, is encoded
|
||||
and independently compressed. The reference in the parent or group directory entry supplies
|
||||
its storage location, lengths, and codecs. There is no separate stored
|
||||
page header. Decoded pages begin with `kind: u32` and `entry_count: u64`:
|
||||
|
||||
```text
|
||||
Leaf (kind 0): Internal root (kind 1):
|
||||
kind u32 kind u32
|
||||
entry_count u64 entry_count u64
|
||||
block descriptor 0 page reference 0 64 bytes
|
||||
... ...
|
||||
block descriptor N-1 page reference N-1 64 bytes
|
||||
```
|
||||
|
||||
Pages are nonempty and limited to 65,536 decoded bytes, including the 12-byte
|
||||
prefix. Descriptors never straddle pages, and every descriptor is fixed-width because
|
||||
the key it names is not stored in it. The writer requires the 12-byte leaf prefix and
|
||||
one descriptor to fit in a configured page, which for the 1,024-field maximum is
|
||||
`12 + 56 + 36 * 1,027 = 37,040` decoded bytes. The page limit is a bound on
|
||||
descriptors only: it no longer bounds the length of a series key.
|
||||
|
||||
#### Block descriptor
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Table ID | 4 | Coarse prefix of the constant key in this block |
|
||||
| TSID | 8 | Coarse prefix of the constant key in this block |
|
||||
| Key offset | 8 | Group's `payload_end` plus the byte offset of the key in the group's decompressed key stream |
|
||||
| Key length | 4 | Nonzero; the key's `(table_id, tsid)` prefix must equal the two fields above |
|
||||
| Minimum timestamp | 8 | Signed i64, first row's timestamp |
|
||||
| Maximum timestamp | 8 | Signed i64, last row's timestamp |
|
||||
| Block ordinal | 8 | Per-identifier ordinal across the artifact |
|
||||
| Row count | 4 | Nonzero, subject to decoded-block limits |
|
||||
| Column count | 4 | Number of following column descriptors |
|
||||
| Column descriptors | 36 each | Defined below |
|
||||
|
||||
The fixed prefix is 56 bytes and does not depend on the key: `4 table ID + 8 TSID +
|
||||
8 key offset + 4 key length + 8 minimum timestamp + 8 maximum timestamp + 8 ordinal +
|
||||
4 row count + 4 column count`. Ordinals start at zero for each exact key and increase
|
||||
by one across block and part boundaries while that key continues. Blocks sort by exact
|
||||
key. Adjacent blocks of the same exact key share one key reference and satisfy
|
||||
`previous.max_timestamp <= next.min_timestamp`; equality is permitted. Blocks of
|
||||
different keys have no timestamp relation at all, and a new series' key copy starts at
|
||||
or after the end of the previous copy.
|
||||
|
||||
Each column descriptor is:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Role | 4 | 1 timestamp, 2 sequence, 3 operation type, 4 value field |
|
||||
| Column ID | 4 | Timestamp/field physical ID; zero for sequence/operation |
|
||||
| Payload reference | 24 | Independently stored chunk |
|
||||
| Null count | 4 | Number of null rows |
|
||||
|
||||
Role and column ID together identify a chunk. The role namespace avoids reserving
|
||||
physical field IDs for internal columns. Time, sequence, and operation descriptors
|
||||
are mandatory, appear first in that order, and have zero null counts. Value
|
||||
descriptors follow manifest order with no repeated or unknown IDs. A value with
|
||||
all rows null is omitted and synthesized as null by the reader; present value
|
||||
chunks have `null_count < row_count`. No value statistics are stored.
|
||||
|
||||
A block with `P` present fields has `C = 3 + P` chunks and a descriptor of
|
||||
`56 + 36 * C` bytes, whatever its key's length. For one present field that is
|
||||
`56 + 36 * 4 = 200` bytes; at the 1,024-field maximum it is `56 + 36 * 1,027 = 37,028`
|
||||
bytes, and the 12-byte leaf prefix makes that `37,040`. Key length is therefore not
|
||||
part of any page budget: a part whose exact key is far longer than a page produces the
|
||||
same descriptors, and the earlier `base + key_length` ceiling — 65,344 bytes with no
|
||||
value field, 65,300 with one, and 20,288 at the 1,024-field maximum — no longer
|
||||
exists. All chunks are physically ordered and disjoint in the column area, across
|
||||
blocks as well as within a block, and the key area follows the column area. There is no
|
||||
inline block header or block-wide compression.
|
||||
|
||||
#### Page reference and time bounds
|
||||
|
||||
A page reference carries coarse series bounds, two timestamp bounds, and a payload reference:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| First table ID; first TSID | 4 + 8 | Inclusive first identifier |
|
||||
| Last table ID; last TSID | 4 + 8 | Inclusive last identifier |
|
||||
| Minimum timestamp | 8 | Minimum over all descendant blocks |
|
||||
| Maximum timestamp | 8 | Maximum over all descendant blocks |
|
||||
| Payload reference | 24 | Location and codecs of the child page |
|
||||
|
||||
The reference is 64 bytes. Compare identifiers as integer pairs, not as serialized
|
||||
little-endian bytes. Time bounds use the manifest unit. The time range is an
|
||||
envelope over all identifiers in the page; it need not describe the first or last
|
||||
identifier alone. This can admit extra reads, but cannot exclude matching rows.
|
||||
Every part/page identifier interval requires `first <= last`, and all part/page/
|
||||
block time intervals require `min_timestamp <= max_timestamp`, even when pruning
|
||||
would skip their payloads.
|
||||
|
||||
Child pages follow block order. Their identifier bounds may touch at a shared
|
||||
series, just like part bounds. Do not require strict disjointness or use an
|
||||
exclusive next-child lower bound. Validate each loaded page's derived identifier
|
||||
and time bounds against its reference. At depth 2 all children must be leaves;
|
||||
reject an internal child. Child byte ranges are ordered, disjoint, within the
|
||||
metadata area, and precede the parent. The root ends at the boundary with the next group or the directory.
|
||||
|
||||
An internal root has `12 + 64 * N` decoded bytes, so it holds at most
|
||||
`floor((65536 - 12) / 64) = 1,023` leaf references. The writer must account for the
|
||||
next descriptor's leaf placement before writing its block. If the descriptor
|
||||
would require a 1,024th leaf, finish this group and start the block in a new group.
|
||||
|
||||
#### Navigation and equal-timestamp example
|
||||
|
||||
For a requested qualified identity and optional half-open interval `[start, end)`,
|
||||
select every part, group and page whose identifier interval contains the identity and whose
|
||||
time envelope overlaps the request:
|
||||
|
||||
```text
|
||||
(start is absent || max_timestamp >= start)
|
||||
&& (end is absent || min_timestamp < end)
|
||||
```
|
||||
|
||||
For multiple selected identities, intersect the ordered ID set with the inclusive
|
||||
identifier range. A table restriction also intersects this selection. Visit each
|
||||
selected page once per request. Apply the same overlap test to leaf blocks, then
|
||||
filter decoded timestamps exactly. Metadata bounds are conservative candidates.
|
||||
No predecessor-only or unique-child lookup is used: a shared identity or timestamp
|
||||
can require several adjacent children, and even several parts.
|
||||
|
||||
```text
|
||||
Part 0, group 0, depth 2:
|
||||
Root R
|
||||
├─ Leaf A: IDs [(7,42),(7,42)], times [0,100]
|
||||
│ block ordinal 0: (7,42), times [0,100]
|
||||
└─ Leaf B: IDs [(7,42),(7,43)], times [0,200]
|
||||
block ordinal 1: (7,42), times [100,200]
|
||||
block ordinal 0: (7,43), times [0,50]
|
||||
|
||||
Part 1, group 0:
|
||||
Leaf/root C: IDs [(7,43),(7,43)], times [50,80]
|
||||
block ordinal 1: (7,43), times [50,80]
|
||||
```
|
||||
|
||||
For `(7,42)` and `[100,101)`, visit both A and B, keeping all rows at timestamp
|
||||
100 from blocks 0 and 1. Do not decode `(7,43)` payloads. For `(7,43)` and
|
||||
`[50,51)`, visit B and part 1's C: both may contain rows at 50. A `[51,60)` request
|
||||
for `(7,43)` can skip B's `(7,43)` block even though B's time envelope overlaps.
|
||||
For `(7,42)` and `[90,95)`, A is still visited although its block starts before
|
||||
the requested interval. Global time envelopes must not be computed from just
|
||||
the first and last blocks: B's range is `[0,200]`, not `[100,50]`.
|
||||
|
||||
The series-index format has no sample timestamps or time bounds.
|
||||
|
||||
### Group directory and footer
|
||||
|
||||
Every group has one fixed-width directory entry. Its ID and timestamp bounds
|
||||
are those of its root. Exact keys stay within the group.
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Root page reference | 64 | Inclusive coarse ID and timestamp bounds, location, lengths and codecs |
|
||||
| Index depth | 4 | 1 for a leaf root, 2 for an internal root |
|
||||
| `payload_end` | 8 | End of column chunks and start of exact keys |
|
||||
| `key_end` | 8 | End of exact keys and start of pages |
|
||||
| `logical_key_end` | 8 | `payload_end` plus decoded key bytes |
|
||||
| Row count | 8 | Total rows in the group |
|
||||
| Block count | 8 | Total blocks in the group |
|
||||
|
||||
The footer contains the eight ASCII bytes `NARTGRP1`, and the directory length (u64)
|
||||
in little-endian order. The object size locates the
|
||||
footer. The manifest records the directory length so the reader fetches both in one range and checks the lengths agree. The directory is nonempty, a multiple of 108 bytes and at most 8 MiB.
|
||||
The first group starts at offset 16. Each root ends at the start of the next
|
||||
group, or the directory for the final group. Each group's column, key and page
|
||||
references must fall within its respective area. The reader checks the combined
|
||||
group counts and bounds against the part inventory before using the directory.
|
||||
|
||||
The default writer uses a 4 MiB budget for pending descriptors and distinct
|
||||
key bytes. After 3 MiB it prefers to finish at the next
|
||||
series boundary. A continuing series can span groups at the hard threshold.
|
||||
A single key and descriptor larger than the budget occupy a group on their own.
|
||||
Only directory entries survive group finalization. Parts roll at a 512 MiB
|
||||
encoded-byte target or the directory limit. The last group's metadata and the
|
||||
directory can take the final size above the target.
|
||||
|
||||
## Encodings and compression
|
||||
|
||||
Sample column encoding IDs below are distinct from series column encoding IDs,
|
||||
even where their numeric values coincide. Metadata and compression have separate
|
||||
namespaces as well. Never reuse an assigned ID with a different meaning.
|
||||
|
||||
| Namespace | ID | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Column encoding | 1 | Timestamp constant step |
|
||||
| Column encoding | 2 | Timestamp delta-of-delta |
|
||||
| Column encoding | 3 | Constant sequence |
|
||||
| Column encoding | 4 | Sequence delta |
|
||||
| Column encoding | 5 | Nullable Float64 XOR |
|
||||
| Column encoding | 6 | Constant operation type |
|
||||
| Column encoding | 7 | Raw operation types |
|
||||
| Column encoding | 8 | Native histogram struct, column by child |
|
||||
| Metadata encoding | 1 | Leaf/internal page layout above |
|
||||
| Compression | 0 | Raw encoded bytes |
|
||||
| Compression | 1 | Zstd frame |
|
||||
|
||||
Encode first, then compress each chunk/page independently. The default writer
|
||||
stores sample chunks of 128 bytes or less raw. For larger chunks and descriptor pages it tries Zstd level 1 and chooses it only if strictly smaller than the raw encoded
|
||||
bytes. Compression 0 requires equal stored and
|
||||
decoded lengths. Compression level is a writer choice; decoding information is
|
||||
in the frame.
|
||||
|
||||
Unsigned varints use base-128/LEB128: seven data bits per byte and a high
|
||||
continuation bit. Writers emit the shortest representation. Readers reject
|
||||
truncation, more than ten bytes, a tenth byte greater than 1, and trailing bytes
|
||||
after the expected values. ZigZag maps signed i64 `x` to
|
||||
`((x as u64) << 1) ^ ((x >> 63) as u64)` and reverses that mapping on decode.
|
||||
All wrapping arithmetic below is modulo 2^64, not signed overflowing arithmetic.
|
||||
|
||||
### Timestamp encodings 1 and 2
|
||||
|
||||
Encoding 1 contains `first: i64` and `step: i64`, exactly 16 bytes. Use it when
|
||||
every adjacent difference is the same nonnegative, representable i64. A singleton
|
||||
uses step zero. Reconstruct by checked addition; reject overflow. Zero step is
|
||||
valid for repeated timestamps.
|
||||
|
||||
Encoding 2 contains the first i64, followed for two or more rows by the first
|
||||
delta as a ZigZag varint, then ZigZag varints of differences between deltas.
|
||||
Compute deltas and delta differences with wrapping arithmetic; reconstruct in
|
||||
the same way. This permits differences across the full signed timestamp range.
|
||||
After either decoding, require nondecreasing signed timestamps and exact agreement
|
||||
of first/last values with the descriptor. Consume exactly the recorded row count.
|
||||
Use encoding 1 when applicable, otherwise encoding 2.
|
||||
|
||||
### Sequence encodings 3 and 4
|
||||
|
||||
Encoding 3 contains one u64, repeated for all rows. Encoding 4 contains the first
|
||||
u64 followed by each wrapping u64 difference from its predecessor, reinterpreted
|
||||
as i64 and written as a ZigZag varint. Decode with wrapping addition. Use 3 if
|
||||
all sequences are equal, otherwise 4. Preserve all u64 bit patterns. Sequence
|
||||
need not be monotonic across different timestamps; equal-timestamp runs retain
|
||||
the input's nonincreasing order.
|
||||
|
||||
### Nullable Float64 encoding 5
|
||||
|
||||
```text
|
||||
validity_kind <u8> # 0 = all valid, 1 = bitmap
|
||||
validity <ceil(row_count/8) bytes> # only for kind 1
|
||||
first_non_null_bits <u64>
|
||||
xor_deltas <one uvarint per remaining non-null value>
|
||||
```
|
||||
|
||||
Bitmap bit `i % 8` in byte `i / 8` is one for a present value; unused high bits of
|
||||
the final byte are zero. Kind 0 has no bitmap and requires zero null count. Kind
|
||||
1 requires `0 < null_count < row_count` and an exactly matching count of unset
|
||||
in-range bits. All-null columns have no descriptor or payload, so every stored
|
||||
Float64 chunk contains at least one non-null value.
|
||||
|
||||
Process non-null values in row order. Write the first IEEE-754 bit pattern as
|
||||
u64, then varints of XOR with the previous **non-null** bit pattern. Nulls do not
|
||||
reset that previous value. Decode exactly `row_count - null_count` values and
|
||||
scatter according to validity. Preserve all bits, including signed zero, NaN
|
||||
payloads, infinities, and subnormals. Null and NaN are distinct. The unspecified
|
||||
value-buffer bits behind nulls are not part of the logical preservation contract.
|
||||
|
||||
### Native histogram encoding 8
|
||||
|
||||
```text
|
||||
child_count <u8>
|
||||
child_kinds <u8 x child_count> # 1 Float64, 2 Int32, 3 Int64, 4 Timestamp(ms);
|
||||
# 0x10 | kind for a list
|
||||
list_items <uvarint> # items of all valid lists in the chunk
|
||||
validity <ceil(row_count/8) bytes> # only when the descriptor null count is nonzero
|
||||
per child, in struct order:
|
||||
scalar: section(row_count values)
|
||||
list: section(row_count lengths, null for a null list), then
|
||||
section(list item values) unless the child has no items
|
||||
section(n):
|
||||
null_count <uvarint>
|
||||
unless null_count == n:
|
||||
byte_length <uvarint>
|
||||
body <byte_length bytes> # encoding 5 over the n values
|
||||
```
|
||||
|
||||
The struct order is fixed. The header records only child kinds, so children of the
|
||||
same kind, such as `zero_threshold` and `sum`, are told apart by position alone:
|
||||
|
||||
| # | Child | Kind |
|
||||
| --- | --- | --- |
|
||||
| 0 | `schema` | Int32 |
|
||||
| 1 | `zero_threshold` | Float64 |
|
||||
| 2 | `sum` | Float64 |
|
||||
| 3 | `reset_hint` | Int32 |
|
||||
| 4 | `start_timestamp` | Timestamp(ms) |
|
||||
| 5 | `custom_values` | List of Float64 |
|
||||
| 6 | `positive_span_offsets` | List of Int32 |
|
||||
| 7 | `positive_span_lengths` | List of Int32 |
|
||||
| 8 | `negative_span_offsets` | List of Int32 |
|
||||
| 9 | `negative_span_lengths` | List of Int32 |
|
||||
| 10 | `count_i64` | Int64 |
|
||||
| 11 | `zero_count_i64` | Int64 |
|
||||
| 12 | `positive_buckets_i64` | List of Int64 |
|
||||
| 13 | `negative_buckets_i64` | List of Int64 |
|
||||
| 14 | `count_f64` | Float64 |
|
||||
| 15 | `zero_count_f64` | Float64 |
|
||||
| 16 | `positive_buckets_f64` | List of Float64 |
|
||||
| 17 | `negative_buckets_f64` | List of Float64 |
|
||||
|
||||
A chunk holds every row of the block, null rows included, one child after another.
|
||||
Values map to u64 before encoding 5: Float64 keeps its bit pattern; integers and
|
||||
timestamps are ZigZag-mapped. A null list has no items; the item section holds the
|
||||
items of the valid lists in row order. The descriptor's null count is the struct's
|
||||
own null count, and the validity bitmap follows the rules of encoding 5.
|
||||
|
||||
Child count and kinds must match the manifest field's struct type exactly, so a
|
||||
chunk is never decoded as another type. `list_items` must equal the lengths read and
|
||||
must not exceed 1,048,576. The reader reserves memory from `row_count`, the child
|
||||
count and `list_items` before it decodes a chunk. All-null fields have no descriptor
|
||||
or payload, as for Float64.
|
||||
|
||||
### Operation encodings 6 and 7
|
||||
|
||||
Operation values are u8: 0 delete, 1 put, matching Mito's current `OpType` values.
|
||||
Unknown operation values fail decoding. Encoding 6 stores one byte repeated for
|
||||
the whole block; encoding 7 stores exactly one byte per row. Use 6 when all values
|
||||
are equal, otherwise 7. Neither encoding filters delete rows or discards their
|
||||
field values.
|
||||
|
||||
### Limits and evolution
|
||||
|
||||
An individual chunk has at most 1 MiB of encoded bytes after decompression and
|
||||
1 MiB plus 64 KiB of stored bytes. Pages have at most 65,536 decoded and 131,072
|
||||
stored bytes. Series keys are stored in the key area rather than in a page or a
|
||||
chunk, so a key's length is bounded by the part and by its `u32` reference length,
|
||||
not by `PAGE_LIMIT`; a key longer than a page is a supported part of this version. Bound sizes before allocating, fetching, or decompressing. Validate
|
||||
counts against enclosing bytes before allocating descriptor vectors; row counts
|
||||
must also satisfy the decoded-block formula. Null output materialization remains
|
||||
subject to the same block bound even when chunks are omitted.
|
||||
|
||||
Unknown file versions, depths, reserved fields, roles, or metadata codecs fail
|
||||
open/read explicitly. Column role must agree with its encoding: time 1/2,
|
||||
sequence 3/4, Float64 5, native histogram 8, operation 6/7. A value chunk's known
|
||||
encoding must also be the one its manifest field type is stored with. An unknown
|
||||
column encoding or compression can be skipped if its chunk is not needed, but
|
||||
attempting to decode it returns
|
||||
an unsupported-codec error. Known encodings assigned to a different role are
|
||||
invalid metadata, even for an unprojected column. Unknown fields or malformed
|
||||
references must not be interpreted as omitted all-null columns.
|
||||
|
||||
New column encodings or compression methods receive new IDs. Structural changes,
|
||||
changed field meanings, or incompatible limits require a new version. Deeper
|
||||
metadata trees require an explicit reader-support and rollout decision; an
|
||||
unchanged layout alone does not make them readable by version-1 implementations.
|
||||
Offsets are absolute unless explicitly described as relative. Integers are
|
||||
little-endian. Compression ID 0 means raw and ID 1 means Zstd. The storage
|
||||
layer provides byte integrity. Sample payloads and tails carry no
|
||||
application-level checksums.
|
||||
|
||||
@@ -11,11 +11,10 @@ Region manifests serialize these roles as `narthex_samples` and
|
||||
|
||||
## Region manifest
|
||||
|
||||
With `sst_format = 'narthex'`, samples are authoritative SSTs. Each artifact owns
|
||||
`<region_dir>/<file_id>/manifest.json` and its `part-<n>.samples` or
|
||||
`part-<n>.series` objects. The region manifest records the manifest size and a
|
||||
`parts` array in part-ID order.
|
||||
Each part record contains its encoded `file_size` in bytes.
|
||||
A series index owns `<region_dir>/<file_id>/manifest.json` and its
|
||||
`part-<n>.series` objects. The region manifest records the manifest size and
|
||||
each part's `file_size` in part-ID order. The
|
||||
[samples layout](mito-samples.md) uses inline part tails.
|
||||
|
||||
A native index file belongs to one fixed, epoch-aligned time window. Its region
|
||||
manifest entry requires `window` with inclusive `start` and exclusive `end` in
|
||||
|
||||
@@ -55,9 +55,11 @@ use crate::row_converter::{CompositeValues, PrimaryKeyCodec, PrimaryKeyFilter};
|
||||
///
|
||||
/// ## Requirements
|
||||
/// Encoders supply columns in the layout's order using stable physical-region IDs.
|
||||
/// New keys keep the longest prefix of whole labels that fits [`MAX_SPARSE_KEY_BYTES`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SparsePrimaryKeyCodec {
|
||||
inner: Arc<SparsePrimaryKeyCodecInner>,
|
||||
preserve_labels: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -136,6 +138,13 @@ pub const RESERVED_COLUMN_ID_TSID: ColumnId = ReservedColumnId::tsid();
|
||||
pub const RESERVED_COLUMN_ID_TABLE_ID: ColumnId = ReservedColumnId::table_id();
|
||||
/// The size of the column id in the encoded sparse row.
|
||||
pub const COLUMN_ID_ENCODE_SIZE: usize = 4;
|
||||
/// Maximum size of a newly encoded sparse primary key, including its reserved prefix.
|
||||
pub const MAX_SPARSE_KEY_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// Column ID, non-null and nonempty markers, plus nine bytes per eight string bytes.
|
||||
fn encoded_label_len(value_len: usize) -> usize {
|
||||
6 + value_len.div_ceil(8) * 9
|
||||
}
|
||||
|
||||
// Fixed byte offsets for reserved columns in the sparse encoding.
|
||||
// Layout: [table_id_col_id: 4B][marker: 1B][table_id: 4B][tsid_col_id: 4B][marker: 1B][tsid: 8B]
|
||||
@@ -299,6 +308,7 @@ impl SparsePrimaryKeyCodec {
|
||||
label_field: SortField::new(ConcreteDataType::string_datatype()),
|
||||
columns: Some(columns),
|
||||
}),
|
||||
preserve_labels: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,6 +338,7 @@ impl SparsePrimaryKeyCodec {
|
||||
label_field: SortField::new(ConcreteDataType::string_datatype()),
|
||||
columns: None,
|
||||
}),
|
||||
preserve_labels: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,6 +349,13 @@ impl SparsePrimaryKeyCodec {
|
||||
codec
|
||||
}
|
||||
|
||||
/// Reconstructs existing keys during reads without omitting stored labels.
|
||||
#[must_use]
|
||||
pub fn for_existing_keys(mut self) -> Self {
|
||||
self.preserve_labels = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the field of the given column id.
|
||||
fn get_field(&self, column_id: ColumnId) -> Option<&SortField> {
|
||||
if let Some(columns) = &self.inner.columns
|
||||
@@ -357,13 +375,20 @@ impl SparsePrimaryKeyCodec {
|
||||
where
|
||||
I: Iterator<Item = (ColumnId, ValueRef<'a>)>,
|
||||
{
|
||||
let mut serializer = Serializer::new(buffer);
|
||||
for (column_id, value) in row {
|
||||
if value.is_null() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(field) = self.get_field(column_id) {
|
||||
if !self.preserve_labels
|
||||
&& let ValueRef::String(value) = &value
|
||||
&& encoded_label_len(value.len())
|
||||
> MAX_SPARSE_KEY_BYTES.saturating_sub(buffer.len())
|
||||
{
|
||||
break;
|
||||
}
|
||||
let mut serializer = Serializer::new(&mut *buffer);
|
||||
column_id
|
||||
.serialize(&mut serializer)
|
||||
.context(SerializeFieldSnafu)?;
|
||||
@@ -376,13 +401,28 @@ impl SparsePrimaryKeyCodec {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Appends raw labels to a sparse key, stopping before the first label that does not fit.
|
||||
pub fn encode_raw_tag_value<'a, I>(&self, row: I, buffer: &mut Vec<u8>) -> Result<()>
|
||||
where
|
||||
I: Iterator<Item = (ColumnId, &'a [u8])>,
|
||||
{
|
||||
self.encode_raw_tags(row, buffer, MAX_SPARSE_KEY_BYTES);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encode_raw_tags<'a>(
|
||||
&self,
|
||||
row: impl Iterator<Item = (ColumnId, &'a [u8])>,
|
||||
buffer: &mut Vec<u8>,
|
||||
max_end: usize,
|
||||
) {
|
||||
for (tag_column_id, tag_value) in row {
|
||||
let value_len = tag_value.len();
|
||||
buffer.reserve(6 + value_len.div_ceil(8) * 9);
|
||||
let encoded_len = encoded_label_len(value_len);
|
||||
if !self.preserve_labels && encoded_len > max_end.saturating_sub(buffer.len()) {
|
||||
break;
|
||||
}
|
||||
buffer.reserve(encoded_len);
|
||||
buffer.put_u32(tag_column_id);
|
||||
buffer.put_u8(1);
|
||||
buffer.put_u8(!tag_value.is_empty() as u8);
|
||||
@@ -409,7 +449,6 @@ impl SparsePrimaryKeyCodec {
|
||||
buffer.put_u8(remainder as u8);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes the given bytes into a [`SparseValues`].
|
||||
@@ -437,8 +476,10 @@ impl SparsePrimaryKeyCodec {
|
||||
where
|
||||
I: IntoIterator<Item = (ColumnId, &'a [u8])>,
|
||||
{
|
||||
let max_end = buffer.len().saturating_add(MAX_SPARSE_KEY_BYTES);
|
||||
self.encode_internal(table_id, tsid, buffer)?;
|
||||
self.encode_raw_tag_value(ordered_tags.into_iter(), buffer)
|
||||
self.encode_raw_tags(ordered_tags.into_iter(), buffer, max_end);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decodes the reserved `(table_id, tsid)` prefix from a sparse primary key.
|
||||
@@ -992,6 +1033,76 @@ mod tests {
|
||||
assert_eq!(appended, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_encoding_stops_at_the_key_size_limit() {
|
||||
let codec = SparsePrimaryKeyCodec::schemaless();
|
||||
let large_label = "x".repeat((MAX_SPARSE_KEY_BYTES - TAGS_START_OFFSET - 6) / 9 * 8);
|
||||
let labels = [(1, large_label.as_str()), (2, "suffix")];
|
||||
|
||||
let mut raw = Vec::new();
|
||||
codec
|
||||
.encode_raw(
|
||||
42,
|
||||
7,
|
||||
labels.map(|(id, value)| (id, value.as_bytes())),
|
||||
&mut raw,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(MAX_SPARSE_KEY_BYTES, raw.len());
|
||||
|
||||
let mut typed = Vec::new();
|
||||
codec.encode_internal(42, 7, &mut typed).unwrap();
|
||||
codec
|
||||
.encode_to_vec(
|
||||
labels
|
||||
.map(|(id, value)| (id, ValueRef::String(value)))
|
||||
.into_iter(),
|
||||
&mut typed,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(raw, typed);
|
||||
let decoded = codec.decode_sparse(&raw).unwrap();
|
||||
assert_eq!(codec.decode_ids(&raw).unwrap(), (42, 7));
|
||||
assert!(decoded.get(&1).is_some());
|
||||
assert!(decoded.get(&2).is_none());
|
||||
|
||||
let mut skipped = Vec::new();
|
||||
codec
|
||||
.encode_raw(
|
||||
42,
|
||||
7,
|
||||
[
|
||||
(3, b"first".as_slice()),
|
||||
(1, large_label.as_bytes()),
|
||||
(2, b"suffix"),
|
||||
],
|
||||
&mut skipped,
|
||||
)
|
||||
.unwrap();
|
||||
let decoded = codec.decode_sparse(&skipped).unwrap();
|
||||
assert!(decoded.get(&3).is_some());
|
||||
assert!(decoded.get(&1).is_none());
|
||||
assert!(decoded.get(&2).is_none());
|
||||
|
||||
let mut existing = Vec::new();
|
||||
codec
|
||||
.clone()
|
||||
.for_existing_keys()
|
||||
.encode_raw(
|
||||
42,
|
||||
7,
|
||||
labels.map(|(id, value)| (id, value.as_bytes())),
|
||||
&mut existing,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(existing.len() > MAX_SPARSE_KEY_BYTES);
|
||||
assert!(existing.starts_with(&raw));
|
||||
assert_eq!(
|
||||
codec.decode_sparse(&existing).unwrap().get(&2),
|
||||
Some(&Value::from("suffix"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_to_vec() {
|
||||
let region_metadata = test_region_metadata();
|
||||
|
||||
+4
-1
@@ -94,7 +94,10 @@ pending. DDL cancellation retains its existing scheduling fence and priority.
|
||||
checks. Shared SSTs require Enterprise capability. Compatibility fixtures:
|
||||
`tests/compatibility/manifest/table_compaction/` and
|
||||
`tests/compatibility/manifest/pending_tails/`.
|
||||
- **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files.
|
||||
- **SST layout** (`sst/`): readers must stay compatible with existing files.
|
||||
[Narthex samples](../../docs/formats/mito-samples.md) use series blocks or
|
||||
Arrow IPC with a shared part tail. The region manifest records each part and
|
||||
tail size for reads, cache, copy, and cleanup.
|
||||
Metadata COUNT (`read/scan_region/aggr.rs`) uses the footer for both file-local
|
||||
uniqueness and all-Put evidence. Only writers that fold versions may add
|
||||
`greptimedb.deduped`. LastNonNull can retain delete barriers, so it requires
|
||||
|
||||
Vendored
+11
-6
@@ -43,7 +43,7 @@ pub(crate) struct MetadataPart {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum MetadataIdentity {
|
||||
SeriesManifest(FileId),
|
||||
SamplesManifest(crate::sst::file::RegionFileId, Arc<str>, u64),
|
||||
SamplesTails(crate::sst::file::RegionFileId),
|
||||
SeriesTrailer(MetadataPart),
|
||||
SamplesDirectory(MetadataPart),
|
||||
SeriesPage {
|
||||
@@ -63,7 +63,7 @@ pub(crate) const COLUMNAR_META: &str = "columnar_metadata";
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum NarthexMetadata {
|
||||
SeriesManifest(Arc<(Arc<series::Manifest>, SchemaRef)>),
|
||||
SamplesManifest(Arc<samples::reader::SamplesDescriptor>),
|
||||
SamplesTails(Arc<samples::reader::SamplesDescriptor>),
|
||||
SeriesTrailer(Arc<series::Trailer>),
|
||||
SamplesDirectory(Arc<Vec<samples::Group>>),
|
||||
SeriesPage(Arc<series::Page>),
|
||||
@@ -91,7 +91,7 @@ macro_rules! metadata_value {
|
||||
};
|
||||
}
|
||||
metadata_value!((Arc<series::Manifest>, SchemaRef), SeriesManifest);
|
||||
metadata_value!(samples::reader::SamplesDescriptor, SamplesManifest);
|
||||
metadata_value!(samples::reader::SamplesDescriptor, SamplesTails);
|
||||
metadata_value!(series::Trailer, SeriesTrailer);
|
||||
metadata_value!(Vec<samples::Group>, SamplesDirectory);
|
||||
metadata_value!(series::Page, SeriesPage);
|
||||
@@ -210,6 +210,12 @@ impl ObjectReader {
|
||||
})
|
||||
}
|
||||
|
||||
/// Enables refill on a miss for payload reads.
|
||||
pub(crate) fn with_refill(mut self) -> Self {
|
||||
self.refill_on_read = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn queue_refill(&self) {
|
||||
if let (Some(refill), Some((disk, key))) = (&self.refill, &self.local)
|
||||
&& !refill
|
||||
@@ -271,14 +277,13 @@ pub(crate) struct PartArea {
|
||||
|
||||
impl PartArea {
|
||||
pub(crate) fn new(
|
||||
mut reader: ObjectReader,
|
||||
reader: ObjectReader,
|
||||
cache: Option<MetadataCache>,
|
||||
part: MetadataPart,
|
||||
bounds: std::ops::Range<u64>,
|
||||
) -> Self {
|
||||
reader.refill_on_read = true;
|
||||
Self {
|
||||
reader,
|
||||
reader: reader.with_refill(),
|
||||
cache,
|
||||
part,
|
||||
bounds,
|
||||
|
||||
Vendored
+6
-2
@@ -833,12 +833,16 @@ impl IndexKey {
|
||||
let Some(objects) = file.narthex_objects(region_dir) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let manifest_index = objects.len() - 1;
|
||||
let has_manifest = matches!(
|
||||
&file.format,
|
||||
crate::sst::file::FileFormat::NarthexSeriesIndex(_)
|
||||
);
|
||||
let manifest_index = has_manifest.then(|| objects.len() - 1);
|
||||
objects
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, object)| {
|
||||
let part = (i != manifest_index).then_some(i as u32);
|
||||
let part = (Some(i) != manifest_index).then_some(i as u32);
|
||||
let kind = match &file.format {
|
||||
crate::sst::file::FileFormat::NarthexSamples(_) => FileType::Samples(part),
|
||||
crate::sst::file::FileFormat::NarthexSeriesIndex(_) => FileType::Series(part),
|
||||
|
||||
Vendored
+1
@@ -1036,6 +1036,7 @@ mod tests {
|
||||
ArtifactObject {
|
||||
path,
|
||||
file_size: 16,
|
||||
tail_size: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1263,7 +1263,6 @@ async fn test_region_storage_format_admission(
|
||||
|
||||
let foreign_format = if source_format == "narthex" {
|
||||
FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
|
||||
manifest_size: 1,
|
||||
parts: Default::default(),
|
||||
}))
|
||||
} else {
|
||||
|
||||
@@ -468,10 +468,12 @@ async fn narthex_import_preloads_all_parts_from_the_physical_owner() {
|
||||
file_size: 10,
|
||||
format: crate::sst::file::FileFormat::NarthexSamples(Box::new(
|
||||
crate::sst::file::NarthexSamplesMeta {
|
||||
manifest_size: 5,
|
||||
parts: [2, 3]
|
||||
parts: [4, 6]
|
||||
.into_iter()
|
||||
.map(|file_size| crate::sst::file::NarthexPartMeta { file_size })
|
||||
.map(|file_size| crate::sst::file::NarthexSamplePartMeta {
|
||||
file_size,
|
||||
tail_size: 1,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
)),
|
||||
|
||||
@@ -136,13 +136,6 @@ async fn direct_narthex_flush_manifest_failure(#[case] failure: ManifestWriteFai
|
||||
assert!(!armed.load(Ordering::SeqCst));
|
||||
let landed = matches!(failure, ManifestWriteFailure::AfterWrite);
|
||||
let store = region.access_layer.object_store();
|
||||
assert_eq!(
|
||||
landed,
|
||||
store
|
||||
.exists(&crate::sst::location::narthex_manifest_path(&prefix))
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
landed,
|
||||
store
|
||||
@@ -151,23 +144,19 @@ async fn direct_narthex_flush_manifest_failure(#[case] failure: ManifestWriteFai
|
||||
.unwrap()
|
||||
);
|
||||
let disk = engine.cache_manager().write_cache().unwrap().file_cache();
|
||||
let cache_keys = [Some(0), None].map(|part| {
|
||||
crate::cache::file_cache::IndexKey::new(
|
||||
id,
|
||||
file_id,
|
||||
crate::cache::file_cache::FileType::Samples(part),
|
||||
)
|
||||
});
|
||||
for key in cache_keys {
|
||||
assert_eq!(disk.get(key).await.is_some(), landed);
|
||||
assert_eq!(
|
||||
disk.local_store()
|
||||
.exists(&disk.cache_file_path(key))
|
||||
.await
|
||||
.unwrap(),
|
||||
landed
|
||||
);
|
||||
}
|
||||
let key = crate::cache::file_cache::IndexKey::new(
|
||||
id,
|
||||
file_id,
|
||||
crate::cache::file_cache::FileType::Samples(Some(0)),
|
||||
);
|
||||
assert_eq!(disk.get(key).await.is_some(), landed);
|
||||
assert_eq!(
|
||||
disk.local_store()
|
||||
.exists(&disk.cache_file_path(key))
|
||||
.await
|
||||
.unwrap(),
|
||||
landed
|
||||
);
|
||||
if !landed {
|
||||
flush_region(&engine, id, None).await;
|
||||
assert!(
|
||||
@@ -175,9 +164,7 @@ async fn direct_narthex_flush_manifest_failure(#[case] failure: ManifestWriteFai
|
||||
.files
|
||||
.contains_key(&file_id)
|
||||
);
|
||||
for key in cache_keys {
|
||||
assert!(disk.get(key).await.is_some());
|
||||
}
|
||||
assert!(disk.get(key).await.is_some());
|
||||
}
|
||||
reopen_region(&engine, id, dir, true, HashMap::new()).await;
|
||||
let stream = engine
|
||||
|
||||
@@ -603,14 +603,6 @@ async fn check_sparse_upsert_after_adding_nullable_tag(format: &str) -> Whatever
|
||||
encoded.file_id(),
|
||||
);
|
||||
let store = layer.object_store();
|
||||
assert_eq!(
|
||||
&store
|
||||
.read(&crate::sst::location::narthex_manifest_path(&prefix))
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes(),
|
||||
encoded.manifest()
|
||||
);
|
||||
for (i, part) in encoded.parts().iter().enumerate() {
|
||||
assert_eq!(
|
||||
&store
|
||||
@@ -618,7 +610,7 @@ async fn check_sparse_upsert_after_adding_nullable_tag(format: &str) -> Whatever
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes(),
|
||||
part
|
||||
&part.bytes
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -752,7 +744,7 @@ async fn test_narthex_index_counts_rows_across_flushes() -> WhateverResult<()> {
|
||||
.await
|
||||
.expect("Narthex write-through");
|
||||
if key.file_id == encoded.file_id() {
|
||||
let bytes = encoded.parts().get(i).unwrap_or_else(|| encoded.manifest());
|
||||
let bytes = &encoded.parts()[i].bytes;
|
||||
assert_eq!(&cached[0], bytes);
|
||||
}
|
||||
assert_eq!(
|
||||
|
||||
@@ -71,7 +71,7 @@ use crate::memtable::time_series::{ValueBuilder, Values};
|
||||
use crate::memtable::{BoxedRecordBatchIterator, EncodedData, MemScanMetrics, MemtableStats};
|
||||
use crate::region::options::MergeMode;
|
||||
use crate::sst::SeriesEstimator;
|
||||
use crate::sst::file::{FileFormat, NarthexPartMeta, NarthexSamplesMeta};
|
||||
use crate::sst::file::{FileFormat, NarthexSamplePartMeta, NarthexSamplesMeta};
|
||||
use crate::sst::index::IndexOutput;
|
||||
use crate::sst::parquet::flat_format::primary_key_column_index;
|
||||
use crate::sst::parquet::format::{PrimaryKeyArray, PrimaryKeyArrayBuilder};
|
||||
@@ -1365,26 +1365,22 @@ impl EncodedBulkPart {
|
||||
pub(crate) fn to_sst_info(&self, file_id: FileId) -> Option<SstInfo> {
|
||||
if let EncodedBulkPayload::Narthex(part) = &self.payload {
|
||||
let unit = self.metadata.region_metadata.time_index_type().unit();
|
||||
let manifest_size = part.manifest().len() as u64;
|
||||
let parts = part
|
||||
.parts()
|
||||
.iter()
|
||||
.map(NarthexSamplePartMeta::from)
|
||||
.collect::<smallvec::SmallVec<[_; 1]>>();
|
||||
|
||||
return Some(SstInfo {
|
||||
file_id: part.file_id(),
|
||||
time_range: (
|
||||
Timestamp::new(self.metadata.min_timestamp, unit),
|
||||
Timestamp::new(self.metadata.max_timestamp, unit),
|
||||
),
|
||||
file_size: manifest_size + part.parts().iter().map(|p| p.len() as u64).sum::<u64>(),
|
||||
file_size: parts.iter().map(|part| part.file_size).sum(),
|
||||
num_rows: self.metadata.num_rows,
|
||||
num_series: self.metadata.num_series,
|
||||
format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
|
||||
manifest_size,
|
||||
parts: part
|
||||
.parts()
|
||||
.iter()
|
||||
.map(|p| NarthexPartMeta {
|
||||
file_size: p.len() as u64,
|
||||
})
|
||||
.collect(),
|
||||
})),
|
||||
format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta { parts })),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ use datatypes::data_type::ConcreteDataType;
|
||||
use datatypes::prelude::DataType;
|
||||
use datatypes::value::Value;
|
||||
use datatypes::vectors::{Helper, VectorRef};
|
||||
use mito_codec::row_converter::sparse::SparsePrimaryKeyCodec;
|
||||
use mito_codec::row_converter::{
|
||||
CompositeValues, PrimaryKeyCodec, SortField, build_primary_key_codec,
|
||||
build_primary_key_codec_with_fields,
|
||||
@@ -422,7 +423,12 @@ impl FlatRewritePrimaryKey {
|
||||
if expect.primary_key_encoding == actual.primary_key_encoding {
|
||||
return None;
|
||||
}
|
||||
let codec = build_primary_key_codec(expect);
|
||||
let codec: Arc<dyn PrimaryKeyCodec> =
|
||||
if expect.primary_key_encoding == PrimaryKeyEncoding::Sparse {
|
||||
Arc::new(SparsePrimaryKeyCodec::new(expect).for_existing_keys())
|
||||
} else {
|
||||
build_primary_key_codec(expect)
|
||||
};
|
||||
let old_codec = build_primary_key_codec(actual);
|
||||
|
||||
Some(FlatRewritePrimaryKey {
|
||||
@@ -574,8 +580,12 @@ impl FlatCompatPrimaryKey {
|
||||
debug_assert!(!fields.is_empty());
|
||||
|
||||
// Create converter to append values.
|
||||
let converter =
|
||||
build_primary_key_codec_with_fields(expect.primary_key_encoding, fields.into_iter());
|
||||
let converter: Arc<dyn PrimaryKeyCodec> =
|
||||
if expect.primary_key_encoding == PrimaryKeyEncoding::Sparse {
|
||||
Arc::new(SparsePrimaryKeyCodec::with_fields(fields).for_existing_keys())
|
||||
} else {
|
||||
build_primary_key_codec_with_fields(expect.primary_key_encoding, fields.into_iter())
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
rewriter,
|
||||
|
||||
@@ -463,7 +463,7 @@ impl ColumnarPreparedSource {
|
||||
// Identity is the exact canonical sparse key. `tsid` is a hash, so rows
|
||||
// that differ only in labels are different series and must both survive:
|
||||
// re-encoding the artifact's own tags reproduces the SST key byte for byte.
|
||||
let codec = SparsePrimaryKeyCodec::schemaless();
|
||||
let codec = SparsePrimaryKeyCodec::schemaless().for_existing_keys();
|
||||
let mut offsets = mito_codec::row_converter::SparseOffsetsCache::new();
|
||||
let mut identity = Vec::new();
|
||||
let mut previous: Option<Vec<u8>> = None;
|
||||
@@ -753,8 +753,17 @@ impl ColumnarPreparedSource {
|
||||
let bounds = context.input.time_range.as_ref();
|
||||
let start = bounds.and_then(|r| *r.start()).and_then(|t| t.convert_to_ceil(unit)).map(|t| t.value());
|
||||
let end = bounds.and_then(|r| *r.end()).and_then(|t| t.convert_to_ceil(unit)).map(|t| t.value());
|
||||
let page_batches = reader.supports_page_batches() && sample_partition.is_none()
|
||||
&& sample_schema.as_ref().is_some_and(|schema| schema.fields().iter().all(|field| {
|
||||
metadata.column_by_name(field.name()).is_none_or(|column| column.semantic_type != SemanticType::Tag)
|
||||
}));
|
||||
let mut projection = sample_projection(&schema, &context);
|
||||
if page_batches && let Some(merge_schema) = &sample_schema {
|
||||
projection.retain(|name| merge_schema.index_of(name).is_ok());
|
||||
}
|
||||
let mut batches = reader.read(SamplesReadRequest {
|
||||
projection: sample_projection(&schema, &context),
|
||||
projection,
|
||||
page_batches,
|
||||
memory_pool: Some(scan_pool.clone()),
|
||||
keys: Some(keys),
|
||||
start,
|
||||
@@ -762,20 +771,23 @@ impl ColumnarPreparedSource {
|
||||
..Default::default()
|
||||
})?;
|
||||
while let Some(samples) = batches.try_next().await? {
|
||||
// A block belongs to exactly one series, so the reader returns its
|
||||
// exact key once and the whole batch is attributed at once.
|
||||
let SamplesBatch { batch, key } = samples;
|
||||
let ordinal = candidates[range.clone()]
|
||||
.binary_search_by(|candidate| {
|
||||
candidate.key.as_slice().cmp(key.bytes())
|
||||
})
|
||||
.map_err(|_| invalid("sample contains an unselected series"))?
|
||||
+ range.start;
|
||||
let started = std::time::Instant::now();
|
||||
let flat = sample_to_flat(batch, &candidates[ordinal], &context, sample_schema.as_ref())?;
|
||||
let flat = match &sample_partition {
|
||||
Some(filter) => filter.filter(flat, &candidates[ordinal])?,
|
||||
None => flat,
|
||||
let flat = match samples {
|
||||
SamplesBatch::Page(batch) => sample_page_to_flat(
|
||||
batch,
|
||||
sample_schema.as_ref().ok_or_else(|| invalid("missing page merge schema"))?,
|
||||
)?,
|
||||
SamplesBatch::Series { batch, key } => {
|
||||
let ordinal = candidates[range.clone()]
|
||||
.binary_search_by(|candidate| candidate.key.as_slice().cmp(key.bytes()))
|
||||
.map_err(|_| invalid("sample contains an unselected series"))?
|
||||
+ range.start;
|
||||
let flat = sample_to_flat(batch, &candidates[ordinal], &context, sample_schema.as_ref())?;
|
||||
match &sample_partition {
|
||||
Some(filter) => filter.filter(flat, &candidates[ordinal])?,
|
||||
None => flat,
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut flat = filter_visibility(flat, &context)?;
|
||||
for filter in time_filters.iter() {
|
||||
@@ -942,6 +954,30 @@ pub(crate) fn sample_merge_schema(
|
||||
Ok(Some(schema))
|
||||
}
|
||||
|
||||
fn sample_page_to_flat(batch: RecordBatch, schema: &SchemaRef) -> Result<RecordBatch> {
|
||||
let columns = schema
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let Some(array) = batch.column_by_name(field.name()) else {
|
||||
if field.is_nullable() {
|
||||
return Ok(datatypes::arrow::array::new_null_array(
|
||||
field.data_type(),
|
||||
batch.num_rows(),
|
||||
));
|
||||
}
|
||||
return Err(invalid(format!("missing sample column {}", field.name())));
|
||||
};
|
||||
if array.data_type() == field.data_type() {
|
||||
Ok(array.clone())
|
||||
} else {
|
||||
cast(array, field.data_type()).context(ComputeArrowSnafu)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
RecordBatch::try_new(schema.clone(), columns).context(NewRecordBatchSnafu)
|
||||
}
|
||||
|
||||
fn sample_to_flat(
|
||||
batch: RecordBatch,
|
||||
candidate: &Candidate,
|
||||
|
||||
@@ -225,6 +225,10 @@ struct NarthexSamplesReader {
|
||||
}
|
||||
|
||||
impl SamplesFormatReader for NarthexSamplesReader {
|
||||
fn supports_page_batches(&self) -> bool {
|
||||
self.reader.supports_page_batches()
|
||||
}
|
||||
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.reader.schema()
|
||||
}
|
||||
@@ -238,11 +242,11 @@ impl SamplesFormatReader for NarthexSamplesReader {
|
||||
Ok(Box::pin(async_stream::try_stream! {
|
||||
while let Some(mut samples) = stream.try_next().await? {
|
||||
if let Some(sequence) = sequence
|
||||
&& let Ok(index) = samples.batch.schema().index_of(SEQUENCE_COLUMN_NAME)
|
||||
&& let Ok(index) = samples.schema().index_of(SEQUENCE_COLUMN_NAME)
|
||||
{
|
||||
let mut columns = samples.batch.columns().to_vec();
|
||||
columns[index] = Arc::new(UInt64Array::from(vec![sequence; samples.batch.num_rows()]));
|
||||
samples.batch = RecordBatch::try_new(samples.batch.schema(), columns).context(NewRecordBatchSnafu)?;
|
||||
let mut columns = samples.columns().to_vec();
|
||||
columns[index] = Arc::new(UInt64Array::from(vec![sequence; samples.num_rows()]));
|
||||
*samples.batch_mut() = RecordBatch::try_new(samples.schema(), columns).context(NewRecordBatchSnafu)?;
|
||||
}
|
||||
yield samples;
|
||||
}
|
||||
@@ -309,10 +313,11 @@ impl FormatReader for NarthexSeriesReader {
|
||||
let mut previous: Option<ExactSeriesKey> = None;
|
||||
let mut keys = Vec::with_capacity(1024);
|
||||
while let Some(samples) = stream.try_next().await? {
|
||||
if previous.as_ref() == Some(&samples.key) { continue; }
|
||||
previous = Some(samples.key.clone());
|
||||
if request.ids.as_ref().is_some_and(|ids| !ids.contains(&samples.key.id())) { continue; }
|
||||
keys.push(samples.key);
|
||||
let key = samples.into_key().ok_or_else(|| invalid("expected a series discovery key"))?;
|
||||
if previous.as_ref() == Some(&key) { continue; }
|
||||
previous = Some(key.clone());
|
||||
if request.ids.as_ref().is_some_and(|ids| !ids.contains(&key.id())) { continue; }
|
||||
keys.push(key);
|
||||
if keys.len() == 1024 {
|
||||
yield series_batch(&schema, &tags, &keys, &request)?;
|
||||
keys.clear();
|
||||
@@ -417,7 +422,7 @@ impl SamplesFormatReader for NarthexMemtableReader {
|
||||
let batch = RecordBatch::try_new_with_options(schema.clone(), vec![],
|
||||
&datatypes::arrow::record_batch::RecordBatchOptions::new().with_row_count(Some(1)))
|
||||
.context(NewRecordBatchSnafu)?;
|
||||
yield SamplesBatch { batch, key };
|
||||
yield SamplesBatch::Series { batch, key };
|
||||
}
|
||||
}
|
||||
}));
|
||||
@@ -444,7 +449,7 @@ impl SamplesFormatReader for NarthexMemtableReader {
|
||||
let key = ExactSeriesKey::from_sparse_key(bytes, &mut offsets)?;
|
||||
if request.table_id.is_none_or(|table| key.id().table_id == table)
|
||||
&& request.keys.as_ref().is_none_or(|keys| keys.contains(&key)) {
|
||||
yield SamplesBatch { batch: projected.slice(start, end-start), key };
|
||||
yield SamplesBatch::Series { batch: projected.slice(start, end-start), key };
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
|
||||
@@ -522,9 +522,7 @@ pub(crate) fn make_stream(
|
||||
if next_index >= values.len() || !values.is_valid(next_index) {
|
||||
yield Err(invalid("invalid primary-key dictionary value")); return;
|
||||
}
|
||||
if super::primary_key_at(primary_key, values, end)
|
||||
== super::primary_key_at(primary_key, values, start)
|
||||
{
|
||||
if next_index == index || values.value(next_index) == values.value(index) {
|
||||
end += 1;
|
||||
} else {
|
||||
break;
|
||||
|
||||
@@ -3593,26 +3593,26 @@ mod tests {
|
||||
use futures::StreamExt;
|
||||
|
||||
use super::ManifestSstProjection;
|
||||
use crate::sst::file::{FileFormat, FileMeta, NarthexPartMeta, NarthexSamplesMeta};
|
||||
use crate::sst::file::{FileFormat, FileMeta, NarthexSamplePartMeta, NarthexSamplesMeta};
|
||||
|
||||
let env = SchedulerEnv::new().await;
|
||||
let region = build_test_region(&env).await;
|
||||
let id = FileId::random();
|
||||
let path = format!(
|
||||
"{}manifest.json",
|
||||
crate::sst::location::narthex_file_dir(
|
||||
®ion.access_layer.build_region_dir(region.region_id),
|
||||
id
|
||||
)
|
||||
let dir = crate::sst::location::narthex_file_dir(
|
||||
®ion.access_layer.build_region_dir(region.region_id),
|
||||
id,
|
||||
);
|
||||
let path = crate::sst::location::narthex_part_path(&dir, 0, "samples");
|
||||
let mut edit = empty_edit();
|
||||
edit.files_to_add.push(FileMeta {
|
||||
file_id: id,
|
||||
region_id: region.region_id,
|
||||
file_size: 2,
|
||||
format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
|
||||
manifest_size: 1,
|
||||
parts: smallvec::smallvec![NarthexPartMeta { file_size: 1 }],
|
||||
parts: smallvec::smallvec![NarthexSamplePartMeta {
|
||||
file_size: 2,
|
||||
tail_size: 1
|
||||
}],
|
||||
})),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ use crate::region_write_ctx::{RegionWriteCtx, WriteSource};
|
||||
use crate::request::OptionOutputTx;
|
||||
use crate::schedule::scheduler::SchedulerRef;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::file::FileHandle;
|
||||
use crate::sst::file::{FileFormat, FileHandle};
|
||||
use crate::sst::file_purger::{FilePurgerRef, create_file_purger};
|
||||
use crate::sst::file_ref::FileReferenceManagerRef;
|
||||
use crate::sst::index::IndexBuildType;
|
||||
@@ -1342,14 +1342,13 @@ fn maybe_load_cache(
|
||||
write_cache.load_region_cache(task);
|
||||
}
|
||||
|
||||
/// Uses only a resident manifest or a local region backend during startup.
|
||||
/// Loads descriptors from resident objects or a local region backend during startup.
|
||||
async fn preload_narthex_descriptor(
|
||||
manager: &CacheManagerRef,
|
||||
file: FileHandle,
|
||||
region_dir: &str,
|
||||
local_store: Option<&object_store::ObjectStore>,
|
||||
) -> Result<bool> {
|
||||
let id = file.file_id();
|
||||
let Some(context) = crate::cache::columnar::MetadataCache::preload(manager) else {
|
||||
return Ok(false);
|
||||
};
|
||||
@@ -1358,12 +1357,17 @@ async fn preload_narthex_descriptor(
|
||||
store.clone()
|
||||
} else if let Some(write) = manager.write_cache() {
|
||||
let disk = write.file_cache();
|
||||
let kind = if series {
|
||||
FileType::Series(None)
|
||||
} else {
|
||||
FileType::Samples(None)
|
||||
let id = file.file_id();
|
||||
let is_resident =
|
||||
|kind| disk.contains_key(&IndexKey::new(id.region_id(), id.file_id(), kind));
|
||||
let resident = match &file.meta_ref().format {
|
||||
FileFormat::NarthexSamples(meta) => {
|
||||
(0..meta.parts.len()).all(|part| is_resident(FileType::Samples(Some(part as u32))))
|
||||
}
|
||||
FileFormat::NarthexSeriesIndex(_) => is_resident(FileType::Series(None)),
|
||||
FileFormat::Parquet => false,
|
||||
};
|
||||
if !disk.contains_key(&IndexKey::new(id.region_id(), id.file_id(), kind)) {
|
||||
if !resident {
|
||||
return Ok(false);
|
||||
}
|
||||
disk.local_store()
|
||||
|
||||
@@ -241,7 +241,7 @@ impl RemapManifest {
|
||||
// ownership and object inventory must still agree in all builds.
|
||||
let same_inventory = match (&existing.format, &file_meta.format) {
|
||||
(FileFormat::NarthexSamples(left), FileFormat::NarthexSamples(right)) => {
|
||||
left.manifest_size == right.manifest_size && left.parts == right.parts
|
||||
left == right
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
@@ -23,12 +23,14 @@ use api::helper::{
|
||||
proto_value_type_match,
|
||||
};
|
||||
use api::v1::column_def::options_from_column_schema;
|
||||
use api::v1::value::ValueData;
|
||||
use api::v1::{ColumnDataType, ColumnSchema, OpType, Rows, SemanticType, Value, WriteHint};
|
||||
use common_telemetry::info;
|
||||
use datatypes::arrow::array::{Array, ArrayRef};
|
||||
use datatypes::arrow::array::{Array, ArrayRef, AsArray};
|
||||
use datatypes::arrow::datatypes::DataType as ArrowDataType;
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::prelude::DataType;
|
||||
use mito_codec::row_converter::sparse::MAX_SPARSE_KEY_BYTES;
|
||||
use partition::expr::PartitionExpr;
|
||||
use prometheus::HistogramTimer;
|
||||
use prost::Message;
|
||||
@@ -184,6 +186,20 @@ impl WriteRequest {
|
||||
reason: "sparse regions require pre-encoded primary keys",
|
||||
}
|
||||
);
|
||||
if self.primary_key_encoding() == PrimaryKeyEncoding::Sparse
|
||||
&& let Some(index) = self.column_index_by_name(PRIMARY_KEY_COLUMN_NAME)
|
||||
{
|
||||
ensure!(
|
||||
!self.rows.rows.iter().any(|row| matches!(
|
||||
&row.values[index].value_data,
|
||||
Some(ValueData::BinaryValue(key)) if key.len() > MAX_SPARSE_KEY_BYTES
|
||||
)),
|
||||
InvalidRequestSnafu {
|
||||
region_id: self.region_id,
|
||||
reason: oversized_sparse_key_reason(),
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -632,6 +648,13 @@ pub fn check_bulk_insert_batch(metadata: &RegionMetadata, batch: &RecordBatch) -
|
||||
),
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
!sparse_key_array_exceeds_limit(primary_key.as_ref()),
|
||||
InvalidRequestSnafu {
|
||||
region_id,
|
||||
reason: oversized_sparse_key_reason(),
|
||||
}
|
||||
);
|
||||
}
|
||||
let mut needs_fill = false;
|
||||
check_request_columns(region_id, metadata, columns, |column| {
|
||||
@@ -645,6 +668,30 @@ pub fn check_bulk_insert_batch(metadata: &RegionMetadata, batch: &RecordBatch) -
|
||||
Ok(needs_fill)
|
||||
}
|
||||
|
||||
fn oversized_sparse_key_reason() -> String {
|
||||
format!("encoded sparse primary key exceeds {MAX_SPARSE_KEY_BYTES} bytes")
|
||||
}
|
||||
|
||||
/// Checks lengths after the bulk schema has established the Binary key type.
|
||||
fn sparse_key_array_exceeds_limit(keys: &dyn Array) -> bool {
|
||||
if let Some(dictionary) = keys.as_any_dictionary_opt() {
|
||||
let values = dictionary.values().as_binary::<i32>();
|
||||
values
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|key| key.len() > MAX_SPARSE_KEY_BYTES)
|
||||
&& dictionary
|
||||
.normalized_keys()
|
||||
.into_iter()
|
||||
.any(|index| values.value_length(index) as usize > MAX_SPARSE_KEY_BYTES)
|
||||
} else {
|
||||
keys.as_binary::<i32>()
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|key| key.len() > MAX_SPARSE_KEY_BYTES)
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate proto value schema.
|
||||
pub(crate) fn validate_proto_value(
|
||||
region_id: RegionId,
|
||||
|
||||
@@ -17,6 +17,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use store_api::storage::FileId;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::series_index::columnar::invalid;
|
||||
use crate::sst::file::NarthexSamplePartMeta;
|
||||
|
||||
/// Persisted artifact identifiers. Concrete codecs are added with their implementations.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) enum ArtifactFormat {
|
||||
@@ -31,6 +35,23 @@ pub(crate) enum ArtifactFormat {
|
||||
pub(crate) struct ArtifactObject {
|
||||
pub(crate) path: String,
|
||||
pub(crate) file_size: u64,
|
||||
/// Encoded metadata at the end of a samples part.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) tail_size: Option<u64>,
|
||||
}
|
||||
|
||||
impl TryFrom<&ArtifactObject> for NarthexSamplePartMeta {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(object: &ArtifactObject) -> Result<Self, Self::Error> {
|
||||
let tail_size = object
|
||||
.tail_size
|
||||
.ok_or_else(|| invalid("missing sample part tail size"))?;
|
||||
Ok(Self {
|
||||
file_size: object.file_size,
|
||||
tail_size,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies the exact bytes produced by one backend build.
|
||||
|
||||
@@ -305,7 +305,7 @@ impl ColumnarReader {
|
||||
.map(|tag| (tag.name.as_str(), tag.column_id))
|
||||
.collect();
|
||||
let mut metrics = ColumnarReadMetrics::default();
|
||||
let codec = SparsePrimaryKeyCodec::schemaless();
|
||||
let codec = SparsePrimaryKeyCodec::schemaless().for_existing_keys();
|
||||
let mut offsets = SparseOffsetsCache::new();
|
||||
let mut encoded = Vec::new();
|
||||
while let Some((area, page)) = pages.try_next().await? {
|
||||
|
||||
@@ -385,6 +385,7 @@ impl ColumnarWriter {
|
||||
objects.push(ArtifactObject {
|
||||
path: self.manifest.part_path(part.part_id),
|
||||
file_size: part.file_size,
|
||||
tail_size: None,
|
||||
});
|
||||
file_size = file_size
|
||||
.checked_add(part.file_size)
|
||||
@@ -393,6 +394,7 @@ impl ColumnarWriter {
|
||||
objects.push(ArtifactObject {
|
||||
path: self.manifest.path(),
|
||||
file_size: manifest_size,
|
||||
tail_size: None,
|
||||
});
|
||||
self.outputs.open(self.manifest.path()).await?;
|
||||
self.outputs.write(bytes).await?;
|
||||
|
||||
@@ -66,34 +66,64 @@ pub(crate) struct SamplesReadRequest {
|
||||
pub(crate) memory_pool: Option<Arc<dyn datafusion::execution::memory_pool::MemoryPool>>,
|
||||
pub(crate) projection: Vec<String>,
|
||||
pub(crate) table_id: Option<u32>,
|
||||
/// Allow the reader to return multiple series with an Arrow key dictionary.
|
||||
pub(crate) page_batches: bool,
|
||||
/// Exact selection. A block whose key is absent here is never read, even when its
|
||||
/// coarse `(table_id, tsid)` is present. The reader derives its coarse pruning set
|
||||
/// from these keys, so the selection cannot disagree with itself.
|
||||
/// from these keys.
|
||||
pub(crate) keys: Option<BTreeSet<ExactSeriesKey>>,
|
||||
pub(crate) start: Option<i64>,
|
||||
pub(crate) end: Option<i64>,
|
||||
}
|
||||
|
||||
/// One samples output batch and the exact series that owns every row in it.
|
||||
///
|
||||
/// A sample block belongs to exactly one series, so the exact key travels with the batch
|
||||
/// instead of being repeated once per row: consumers attribute the whole batch at once.
|
||||
/// Series blocks carry a key once. Page batches carry keys in the Arrow dictionary.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct SamplesBatch {
|
||||
pub(crate) batch: RecordBatch,
|
||||
pub(crate) key: ExactSeriesKey,
|
||||
pub(crate) enum SamplesBatch {
|
||||
Series {
|
||||
batch: RecordBatch,
|
||||
key: ExactSeriesKey,
|
||||
},
|
||||
Page(RecordBatch),
|
||||
}
|
||||
|
||||
impl SamplesBatch {
|
||||
pub(crate) fn batch_mut(&mut self) -> &mut RecordBatch {
|
||||
match self {
|
||||
Self::Series { batch, .. } | Self::Page(batch) => batch,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn into_key(self) -> Option<ExactSeriesKey> {
|
||||
match self {
|
||||
Self::Series { key, .. } => Some(key),
|
||||
Self::Page(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn key(&self) -> &ExactSeriesKey {
|
||||
match self {
|
||||
Self::Series { key, .. } => key,
|
||||
Self::Page(_) => panic!("expected a series sample batch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Batches read as batches: the key is the only column the wrapped batch does not carry.
|
||||
impl std::ops::Deref for SamplesBatch {
|
||||
type Target = RecordBatch;
|
||||
|
||||
fn deref(&self) -> &RecordBatch {
|
||||
&self.batch
|
||||
match self {
|
||||
Self::Series { batch, .. } | Self::Page(batch) => batch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait SamplesFormatReader: Send + Sync {
|
||||
fn supports_page_batches(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn schema(&self) -> SchemaRef;
|
||||
fn read(&self, request: SamplesReadRequest)
|
||||
-> Result<BoxStream<'static, Result<SamplesBatch>>>;
|
||||
|
||||
@@ -22,6 +22,7 @@ use std::cmp::Ordering;
|
||||
use std::fmt;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use bytes::Bytes;
|
||||
use mito_codec::row_converter::SparseOffsetsCache;
|
||||
use mito_codec::row_converter::sparse::SparsePrimaryKeyView;
|
||||
use snafu::ResultExt;
|
||||
@@ -112,7 +113,7 @@ pub(crate) struct ExactSeriesKey {
|
||||
/// Order-preserving `(table_id, tsid)` prefix decoded from `key`.
|
||||
id: MetricSeriesId,
|
||||
/// Canonical sparse primary-key encoding of the whole series.
|
||||
key: Box<[u8]>,
|
||||
key: Bytes,
|
||||
}
|
||||
|
||||
impl ExactSeriesKey {
|
||||
@@ -140,10 +141,15 @@ impl ExactSeriesKey {
|
||||
mito_codec::row_converter::sparse::read_prevalidated_series_ids(key)?;
|
||||
Some(Self {
|
||||
id: MetricSeriesId { table_id, tsid },
|
||||
key: key.into(),
|
||||
key: Bytes::copy_from_slice(key),
|
||||
})
|
||||
}
|
||||
|
||||
/// Wraps an exact key with the ID stored alongside it by the IPC writer.
|
||||
pub(crate) fn from_ipc_directory(id: MetricSeriesId, key: Bytes) -> Self {
|
||||
Self { id, key }
|
||||
}
|
||||
|
||||
/// The reserved `(table_id, tsid)` prefix. It is a coarse bucket, not identity.
|
||||
pub(crate) fn id(&self) -> MetricSeriesId {
|
||||
self.id
|
||||
@@ -161,7 +167,7 @@ impl ExactSeriesKey {
|
||||
table_id: view.table_id(),
|
||||
tsid: view.tsid(),
|
||||
},
|
||||
key: key.into(),
|
||||
key: Bytes::copy_from_slice(key),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,7 +215,7 @@ impl std::borrow::Borrow<[u8]> for ExactSeriesKey {
|
||||
|
||||
impl Hash for ExactSeriesKey {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.key.hash(state);
|
||||
self.bytes().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
pub(crate) mod bulk;
|
||||
mod codec;
|
||||
mod histogram;
|
||||
mod ipc_pages;
|
||||
mod key_pages;
|
||||
mod metadata;
|
||||
#[cfg(test)]
|
||||
@@ -42,7 +43,7 @@ use crate::series_index::artifact::ArtifactFormat;
|
||||
use crate::series_index::columnar::{invalid, require, unsupported};
|
||||
use crate::series_index::identity::IdentityEncoding;
|
||||
use crate::series_index::{MetricSeriesId, TABLE_ID_COLUMN, TSID_COLUMN};
|
||||
use crate::sst::location;
|
||||
use crate::sst::file::NarthexSamplePartMeta;
|
||||
|
||||
/// Reject unsupported narthex schemas before accepting mutations that cannot flush.
|
||||
pub(crate) fn validate_narthex_metadata(
|
||||
@@ -117,7 +118,6 @@ pub(crate) fn check_histogram_batch(
|
||||
.try_for_each(histogram::check_array_sample_sizes)
|
||||
}
|
||||
|
||||
const VERSION: u32 = 1;
|
||||
const MANIFEST_LIMIT: usize = 64 * 1024 * 1024;
|
||||
const MAX_ROWS: usize = 8192;
|
||||
const MAX_FIELDS: usize = 1024;
|
||||
@@ -130,6 +130,7 @@ const PRIMARY_KEY: &str = store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
|
||||
/// Internal packing knobs; the backend is disabled unless selected explicitly.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct ColumnarSamplesFormat {
|
||||
pub(crate) ipc_pages: bool,
|
||||
pub(crate) block_rows: usize,
|
||||
pub(crate) part_bytes: u64,
|
||||
pub(crate) metadata_bytes: usize,
|
||||
@@ -139,6 +140,7 @@ pub(crate) struct ColumnarSamplesFormat {
|
||||
impl Default for ColumnarSamplesFormat {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
ipc_pages: false,
|
||||
block_rows: MAX_ROWS,
|
||||
part_bytes: 512 * 1024 * 1024,
|
||||
metadata_bytes: 4 * 1024 * 1024,
|
||||
@@ -148,13 +150,13 @@ impl Default for ColumnarSamplesFormat {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct TimestampColumn {
|
||||
column_id: u32,
|
||||
name: String,
|
||||
unit: TimestampUnit,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum TimestampUnit {
|
||||
Second,
|
||||
@@ -180,7 +182,7 @@ impl TimestampUnit {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct ValueColumn {
|
||||
column_id: u32,
|
||||
name: String,
|
||||
@@ -236,8 +238,6 @@ impl ValueColumn {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct Part {
|
||||
part_id: u32,
|
||||
directory_bytes: u64,
|
||||
file_size: u64,
|
||||
num_rows: u64,
|
||||
num_blocks: u64,
|
||||
first: MetricSeriesId,
|
||||
@@ -246,7 +246,7 @@ struct Part {
|
||||
max_timestamp: i64,
|
||||
}
|
||||
impl Part {
|
||||
fn from_groups(part_id: u32, file_size: u64, groups: &[metadata::Group]) -> Result<Self> {
|
||||
fn from_groups(part_id: u32, groups: &[metadata::Group]) -> Result<Self> {
|
||||
let mut bounds = groups
|
||||
.first()
|
||||
.ok_or_else(|| invalid("empty sample part"))?
|
||||
@@ -265,8 +265,6 @@ impl Part {
|
||||
}
|
||||
Ok(Self {
|
||||
part_id,
|
||||
file_size,
|
||||
directory_bytes: (groups.len() * metadata::GROUP_BYTES) as u64,
|
||||
num_rows: rows,
|
||||
num_blocks: blocks,
|
||||
first: bounds.first,
|
||||
@@ -276,27 +274,44 @@ impl Part {
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum SamplesLayout {
|
||||
SeriesBlocks,
|
||||
ArrowIpc,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct Manifest {
|
||||
/// Resolved from the owning file, not persisted in the codec manifest.
|
||||
#[serde(skip)]
|
||||
prefix: String,
|
||||
format: ArtifactFormat,
|
||||
version: u32,
|
||||
layout: SamplesLayout,
|
||||
/// Mandatory discriminator; see [`IdentityEncoding`]. Never defaulted on read.
|
||||
identity_encoding: IdentityEncoding,
|
||||
region_id: u64,
|
||||
source_file_id: FileId,
|
||||
generation: FileId,
|
||||
timestamp: TimestampColumn,
|
||||
fields: Vec<ValueColumn>,
|
||||
files: Vec<Part>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct MemorySamplePart {
|
||||
pub(crate) bytes: Bytes,
|
||||
pub(crate) tail_size: u64,
|
||||
}
|
||||
|
||||
impl From<&MemorySamplePart> for NarthexSamplePartMeta {
|
||||
fn from(part: &MemorySamplePart) -> Self {
|
||||
Self {
|
||||
file_size: part.bytes.len() as u64,
|
||||
tail_size: part.tail_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MemoryArtifact {
|
||||
file_id: FileId,
|
||||
manifest: Bytes,
|
||||
parts: Vec<Bytes>,
|
||||
parts: Vec<MemorySamplePart>,
|
||||
/// Decoded keys addressed by the resident block descriptors.
|
||||
keys: Bytes,
|
||||
blocks: Vec<(usize, metadata::Block)>,
|
||||
@@ -306,7 +321,6 @@ struct MemoryArtifact {
|
||||
impl Manifest {
|
||||
fn retained_size(&self) -> usize {
|
||||
std::mem::size_of::<Self>()
|
||||
+ self.prefix.capacity()
|
||||
+ self.timestamp.name.capacity()
|
||||
+ self.files.capacity() * std::mem::size_of::<Part>()
|
||||
+ self.fields.capacity() * std::mem::size_of::<ValueColumn>()
|
||||
@@ -317,12 +331,6 @@ impl Manifest {
|
||||
.sum::<usize>()
|
||||
}
|
||||
|
||||
fn path(&self) -> String {
|
||||
location::narthex_manifest_path(&self.prefix)
|
||||
}
|
||||
fn part_path(&self, id: u32) -> String {
|
||||
location::narthex_part_path(&self.prefix, id as usize, "samples")
|
||||
}
|
||||
fn validate_schema(&self) -> Result<()> {
|
||||
require(
|
||||
(1..=MAX_FIELDS).contains(&self.fields.len()),
|
||||
|
||||
@@ -26,8 +26,8 @@ use crate::cache::file_cache::{FileType, IndexKey};
|
||||
use crate::cache::write_cache::{UploadOptions, WriteCache};
|
||||
use crate::error::{OpenDalSnafu, Result};
|
||||
use crate::series_index::samples::metadata::{Block, Column};
|
||||
use crate::series_index::samples::{MemoryArtifact, ValueColumn};
|
||||
use crate::sst::location::{narthex_manifest_path, narthex_part_path};
|
||||
use crate::series_index::samples::{MemoryArtifact, MemorySamplePart, ValueColumn};
|
||||
use crate::sst::location::narthex_part_path;
|
||||
use crate::sst::{DEFAULT_WRITE_BUFFER_SIZE, DEFAULT_WRITE_CONCURRENCY};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -36,10 +36,13 @@ pub(crate) struct NarthexBulkPart(pub(super) Arc<MemoryArtifact>, usize);
|
||||
impl NarthexBulkPart {
|
||||
pub(super) fn new(artifact: MemoryArtifact) -> Self {
|
||||
let retained_bytes = size_of::<MemoryArtifact>()
|
||||
+ artifact.manifest.len()
|
||||
+ artifact.keys.len()
|
||||
+ artifact.parts.capacity() * size_of::<Bytes>()
|
||||
+ artifact.parts.iter().map(Bytes::len).sum::<usize>()
|
||||
+ artifact.parts.capacity() * size_of::<MemorySamplePart>()
|
||||
+ artifact
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| part.bytes.len())
|
||||
.sum::<usize>()
|
||||
+ artifact.blocks.capacity() * size_of::<(usize, Block)>()
|
||||
+ artifact
|
||||
.blocks
|
||||
@@ -62,18 +65,10 @@ impl NarthexBulkPart {
|
||||
region_id: RegionId,
|
||||
cache: Option<&WriteCache>,
|
||||
) -> Result<()> {
|
||||
let parts = self.parts().iter().enumerate().map(|(i, data)| {
|
||||
(
|
||||
narthex_part_path(prefix, i, "samples"),
|
||||
Some(i as u32),
|
||||
data,
|
||||
)
|
||||
});
|
||||
for (path, part, bytes) in parts.chain(std::iter::once((
|
||||
narthex_manifest_path(prefix),
|
||||
None,
|
||||
self.manifest(),
|
||||
))) {
|
||||
for (index, sample_part) in self.parts().iter().enumerate() {
|
||||
let bytes = &sample_part.bytes;
|
||||
let path = narthex_part_path(prefix, index, "samples");
|
||||
let part = Some(index as u32);
|
||||
if let Some(cache) = cache {
|
||||
let key = IndexKey::new(region_id, self.file_id(), FileType::Samples(part));
|
||||
let files = cache.file_cache();
|
||||
@@ -116,10 +111,7 @@ impl NarthexBulkPart {
|
||||
pub(crate) fn file_id(&self) -> FileId {
|
||||
self.0.file_id
|
||||
}
|
||||
pub(crate) fn manifest(&self) -> &Bytes {
|
||||
&self.0.manifest
|
||||
}
|
||||
pub(crate) fn parts(&self) -> &[Bytes] {
|
||||
pub(crate) fn parts(&self) -> &[MemorySamplePart] {
|
||||
&self.0.parts
|
||||
}
|
||||
pub(crate) fn size_bytes(&self) -> usize {
|
||||
|
||||
@@ -0,0 +1,873 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use bytes::Bytes;
|
||||
use datafusion::execution::memory_pool::MemoryReservation;
|
||||
use datatypes::arrow::array::{
|
||||
Array, ArrayRef, BinaryArray, BinaryBuilder, DictionaryArray, RecordBatch, RecordBatchOptions,
|
||||
UInt32Array, UInt64Array,
|
||||
};
|
||||
use datatypes::arrow::buffer::Buffer;
|
||||
use datatypes::arrow::compute::take;
|
||||
use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef, UInt32Type};
|
||||
use datatypes::arrow::ipc::{
|
||||
self,
|
||||
reader::read_record_batch,
|
||||
writer::{DictionaryTracker, EncodedData, IpcDataGenerator, IpcWriteContext, IpcWriteOptions},
|
||||
};
|
||||
use mito_codec::row_converter::sparse::{MAX_SPARSE_KEY_BYTES, read_prevalidated_series_ids};
|
||||
use snafu::ResultExt;
|
||||
use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
|
||||
|
||||
use crate::cache::columnar::ObjectReader;
|
||||
use crate::error::{OpenDalSnafu, Result};
|
||||
use crate::metrics::ColumnarReadMetrics;
|
||||
use crate::series_index::format::{SamplesBatch, SamplesReadRequest};
|
||||
use crate::series_index::identity::ExactSeriesKey;
|
||||
use crate::series_index::samples::metadata::{self, Bounds, Group, PageReference};
|
||||
use crate::series_index::samples::reader::reserve_scan;
|
||||
use crate::series_index::samples::{Manifest, MetricSeriesId, codec, invalid, require};
|
||||
|
||||
pub(super) const PAGE_ROWS: usize = 1024;
|
||||
const KEY_BYTES: usize = 64 * 1024;
|
||||
const KEY_COUNT: usize = 128;
|
||||
const TARGET_SAMPLE_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_SAMPLE_BYTES: usize = 128 * 1024 * 1024;
|
||||
const MAX_KEY_AREA_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
fn failure(error: impl std::fmt::Display) -> crate::error::Error {
|
||||
invalid(format!("sample IPC: {error}"))
|
||||
}
|
||||
|
||||
fn series_id(key: &[u8]) -> Result<MetricSeriesId> {
|
||||
let (table_id, tsid) = read_prevalidated_series_ids(key)
|
||||
.ok_or_else(|| invalid("invalid IPC sample series prefix"))?;
|
||||
Ok(MetricSeriesId { table_id, tsid })
|
||||
}
|
||||
|
||||
pub(super) fn input_columns(
|
||||
batch: &RecordBatch,
|
||||
manifest: &Manifest,
|
||||
) -> Result<(RecordBatch, usize)> {
|
||||
let key = batch
|
||||
.schema()
|
||||
.index_of(super::PRIMARY_KEY)
|
||||
.map_err(failure)?;
|
||||
let schema = manifest.schema();
|
||||
let fields = schema
|
||||
.fields()
|
||||
.iter()
|
||||
.skip(2)
|
||||
.take(3 + manifest.fields.len())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let arrays = fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
batch
|
||||
.column_by_name(field.name())
|
||||
.cloned()
|
||||
.ok_or_else(|| invalid("missing IPC sample column"))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let samples = RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).map_err(failure)?;
|
||||
Ok((samples, key))
|
||||
}
|
||||
|
||||
struct Run {
|
||||
id: MetricSeriesId,
|
||||
end: u16,
|
||||
}
|
||||
|
||||
struct Chunk {
|
||||
first: u16,
|
||||
offset: u64,
|
||||
stored: u32,
|
||||
decoded: u32,
|
||||
}
|
||||
|
||||
pub(super) struct Encoder {
|
||||
options: IpcWriteOptions,
|
||||
ipc: IpcWriteContext,
|
||||
dictionaries: DictionaryTracker,
|
||||
key_compressor: zstd::bulk::Compressor<'static>,
|
||||
directory_compressor: zstd::bulk::Compressor<'static>,
|
||||
raw: Vec<u8>,
|
||||
stored: Vec<u8>,
|
||||
key_area: Vec<u8>,
|
||||
previous_key: Vec<u8>,
|
||||
#[cfg(test)]
|
||||
pub(crate) sample_bytes_limit: usize,
|
||||
}
|
||||
|
||||
pub(super) struct EncodedPage {
|
||||
pub(super) sample: EncodedData,
|
||||
pub(super) key_area: Vec<u8>,
|
||||
pub(super) directory: Vec<u8>,
|
||||
pub(super) group: Group,
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
pub(super) fn new() -> Result<Self> {
|
||||
Ok(Self {
|
||||
options: IpcWriteOptions::default(),
|
||||
ipc: IpcWriteContext::default(),
|
||||
dictionaries: DictionaryTracker::new(false),
|
||||
key_compressor: zstd::bulk::Compressor::new(1).map_err(failure)?,
|
||||
directory_compressor: zstd::bulk::Compressor::new(1).map_err(failure)?,
|
||||
raw: Vec::new(),
|
||||
stored: Vec::new(),
|
||||
key_area: Vec::new(),
|
||||
previous_key: Vec::new(),
|
||||
#[cfg(test)]
|
||||
sample_bytes_limit: MAX_SAMPLE_BYTES,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn page_rows(batch: &RecordBatch) -> usize {
|
||||
// Also bound pages for wide schemas and large variable-width arrays.
|
||||
let average = batch
|
||||
.get_array_memory_size()
|
||||
.div_ceil(batch.num_rows().max(1));
|
||||
PAGE_ROWS.min((TARGET_SAMPLE_BYTES / average.max(1)).max(1))
|
||||
}
|
||||
|
||||
/// Returns `None` when the page needs a smaller row slice.
|
||||
pub(super) fn encode(
|
||||
&mut self,
|
||||
samples: &RecordBatch,
|
||||
keys: &dyn Array,
|
||||
first: usize,
|
||||
start: u64,
|
||||
) -> Result<Option<EncodedPage>> {
|
||||
let dictionary = keys.as_any().downcast_ref::<DictionaryArray<UInt32Type>>();
|
||||
let binary = if let Some(dictionary) = dictionary {
|
||||
dictionary.values().as_any().downcast_ref::<BinaryArray>()
|
||||
} else {
|
||||
keys.as_any().downcast_ref::<BinaryArray>()
|
||||
}
|
||||
.ok_or_else(|| invalid("unsupported IPC key array"))?;
|
||||
let mut keys_in_page = Vec::<(&[u8], u16)>::new();
|
||||
let mut prior_index = None;
|
||||
for row in first..first + samples.num_rows() {
|
||||
require(keys.is_valid(row), "null IPC sample key")?;
|
||||
let index = dictionary.map_or(row, |dict| dict.keys().value(row) as usize);
|
||||
let end = (row - first + 1) as u16;
|
||||
if dictionary.is_some() && prior_index == Some(index) {
|
||||
keys_in_page.last_mut().unwrap().1 = end;
|
||||
continue;
|
||||
}
|
||||
require(
|
||||
index < binary.len() && binary.is_valid(index),
|
||||
"invalid IPC key dictionary entry",
|
||||
)?;
|
||||
let key = binary.value(index);
|
||||
match keys_in_page.last_mut() {
|
||||
Some((last, count)) if *last == key => *count = end,
|
||||
Some((last, _)) => {
|
||||
require(*last < key, "unsorted IPC page keys")?;
|
||||
keys_in_page.push((key, end));
|
||||
}
|
||||
None => keys_in_page.push((key, end)),
|
||||
}
|
||||
prior_index = Some(index);
|
||||
}
|
||||
require(
|
||||
self.previous_key.as_slice() <= keys_in_page[0].0,
|
||||
"unsorted IPC page boundary",
|
||||
)?;
|
||||
let (dictionaries, data) = IpcDataGenerator::default()
|
||||
.encode(
|
||||
samples,
|
||||
&mut self.dictionaries,
|
||||
&self.options,
|
||||
&mut self.ipc,
|
||||
)
|
||||
.map_err(failure)?;
|
||||
require(dictionaries.is_empty(), "unexpected sample IPC dictionary")?;
|
||||
let metadata_len = data.ipc_message.len();
|
||||
let body_offset = 8 + metadata_len.next_multiple_of(8);
|
||||
let size = body_offset + data.arrow_data.len();
|
||||
#[cfg(not(test))]
|
||||
let sample_bytes_limit = MAX_SAMPLE_BYTES;
|
||||
#[cfg(test)]
|
||||
let sample_bytes_limit = self.sample_bytes_limit;
|
||||
if size > sample_bytes_limit {
|
||||
return Ok(None);
|
||||
}
|
||||
let payload_end = start + size as u64;
|
||||
self.key_area.clear();
|
||||
let mut chunks = Vec::new();
|
||||
let mut runs = Vec::with_capacity(keys_in_page.len());
|
||||
let mut offset = 0;
|
||||
while offset < keys_in_page.len() {
|
||||
self.raw.clear();
|
||||
let first = offset;
|
||||
while let Some(&(key, end)) = keys_in_page.get(offset) {
|
||||
require(
|
||||
key.len() <= MAX_SPARSE_KEY_BYTES,
|
||||
"IPC key exceeds byte limit",
|
||||
)?;
|
||||
if first != offset
|
||||
&& (offset - first == KEY_COUNT || self.raw.len() + key.len() + 4 > KEY_BYTES)
|
||||
{
|
||||
break;
|
||||
}
|
||||
self.raw.extend((key.len() as u32).to_le_bytes());
|
||||
self.raw.extend_from_slice(key);
|
||||
runs.push(Run {
|
||||
id: series_id(key)?,
|
||||
end,
|
||||
});
|
||||
offset += 1;
|
||||
}
|
||||
self.stored.clear();
|
||||
self.stored
|
||||
.reserve(zstd::zstd_safe::compress_bound(self.raw.len()));
|
||||
self.key_compressor
|
||||
.compress_to_buffer(&self.raw, &mut self.stored)
|
||||
.map_err(failure)?;
|
||||
chunks.push(Chunk {
|
||||
first: first as u16,
|
||||
offset: self.key_area.len() as u64,
|
||||
stored: self.stored.len() as u32,
|
||||
decoded: self.raw.len() as u32,
|
||||
});
|
||||
if self.key_area.len() + self.stored.len() > MAX_KEY_AREA_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
self.key_area.extend_from_slice(&self.stored);
|
||||
}
|
||||
let key_end = payload_end + self.key_area.len() as u64;
|
||||
self.raw.clear();
|
||||
self.raw.extend((runs.len() as u16).to_le_bytes());
|
||||
self.raw.extend((chunks.len() as u16).to_le_bytes());
|
||||
for run in &runs {
|
||||
self.raw.extend(run.id.table_id.to_le_bytes());
|
||||
self.raw.extend(run.id.tsid.to_le_bytes());
|
||||
self.raw.extend(run.end.to_le_bytes());
|
||||
}
|
||||
for c in &chunks {
|
||||
self.raw.extend(c.first.to_le_bytes());
|
||||
self.raw.extend(c.offset.to_le_bytes());
|
||||
self.raw.extend(c.stored.to_le_bytes());
|
||||
self.raw.extend(c.decoded.to_le_bytes());
|
||||
}
|
||||
let (payload, bytes) = metadata::pack_page_into(
|
||||
&mut self.directory_compressor,
|
||||
&self.raw,
|
||||
&mut self.stored,
|
||||
key_end,
|
||||
)?;
|
||||
let (time, _) = datatypes::timestamp::timestamp_array_to_primitive(samples.column(0))
|
||||
.ok_or_else(|| invalid("IPC page lacks timestamp"))?;
|
||||
let min = time
|
||||
.values()
|
||||
.iter()
|
||||
.copied()
|
||||
.min()
|
||||
.ok_or_else(|| invalid("empty IPC page"))?;
|
||||
let max = time.values().iter().copied().max().unwrap();
|
||||
let bounds = Bounds {
|
||||
first: runs[0].id,
|
||||
last: runs.last().unwrap().id,
|
||||
min,
|
||||
max,
|
||||
};
|
||||
self.previous_key.clear();
|
||||
self.previous_key
|
||||
.extend_from_slice(keys_in_page.last().unwrap().0);
|
||||
Ok(Some(EncodedPage {
|
||||
sample: data,
|
||||
key_area: std::mem::take(&mut self.key_area),
|
||||
directory: bytes.to_vec(),
|
||||
group: Group {
|
||||
start,
|
||||
rows: samples.num_rows() as u64,
|
||||
blocks: runs.len() as u64,
|
||||
root: PageReference { bounds, payload },
|
||||
depth: 1,
|
||||
payload_end,
|
||||
key_end,
|
||||
logical_key_end: key_end,
|
||||
},
|
||||
}))
|
||||
}
|
||||
pub(super) fn recycle_key_area(&mut self, bytes: Vec<u8>) {
|
||||
self.key_area = bytes;
|
||||
}
|
||||
}
|
||||
|
||||
fn number<const N: usize>(bytes: &[u8], at: usize) -> Result<[u8; N]> {
|
||||
bytes
|
||||
.get(at..at + N)
|
||||
.ok_or_else(|| invalid("truncated IPC page directory"))?
|
||||
.try_into()
|
||||
.map_err(failure)
|
||||
}
|
||||
|
||||
// Unfiltered scans can read the adjacent sample and key payloads with the directory.
|
||||
pub(super) const MAX_COALESCED_GROUP: u64 = 256 * 1024;
|
||||
|
||||
pub(super) fn record_group_io(metrics: &mut ColumnarReadMetrics, bytes: usize, started: Instant) {
|
||||
*metrics.bytes.entry("ipc_group_read").or_default() += bytes as u64;
|
||||
*metrics.counts.entry("ipc_group_read").or_default() += 1;
|
||||
metrics.add_elapsed("ipc_group_range_wall", started.elapsed());
|
||||
}
|
||||
|
||||
struct ReadChunk {
|
||||
rows: Range<usize>,
|
||||
first: usize,
|
||||
decoded: usize,
|
||||
range: Range<u64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Decoder {
|
||||
zstd: Option<zstd::bulk::Decompressor<'static>>,
|
||||
directory: codec::PayloadDecoder,
|
||||
}
|
||||
|
||||
impl Decoder {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn read_group(
|
||||
&mut self,
|
||||
reader: &ObjectReader,
|
||||
group: &Group,
|
||||
prefetched: Option<Bytes>,
|
||||
request: &SamplesReadRequest,
|
||||
ids: Option<&BTreeSet<MetricSeriesId>>,
|
||||
projection: &[usize],
|
||||
schema: SchemaRef,
|
||||
disk_schema: SchemaRef,
|
||||
page_schema: Option<&SchemaRef>,
|
||||
metrics: &mut ColumnarReadMetrics,
|
||||
reservation: Option<&MemoryReservation>,
|
||||
) -> Result<Vec<SamplesBatch>> {
|
||||
let directory_started = Instant::now();
|
||||
let reference = &group.root.payload;
|
||||
let end = reference.end()?;
|
||||
let needs_samples = projection.iter().any(|&column| column >= 2)
|
||||
|| request.start.is_some()
|
||||
|| request.end.is_some();
|
||||
let start = if needs_samples {
|
||||
group.start
|
||||
} else {
|
||||
group.payload_end
|
||||
};
|
||||
let full_scan = ids.is_none() && request.table_id.is_none();
|
||||
// Cap extra key bytes independently of the full-scan window. Coalesce a small
|
||||
// group if several selected IDs would use its chunks.
|
||||
let selected_group = needs_samples
|
||||
&& group.key_end - group.payload_end <= 32 * 1024
|
||||
&& (ids.is_some_and(|ids| ids.len() == 1)
|
||||
|| ids.is_some_and(|ids| {
|
||||
ids.range(group.root.bounds.first..=group.root.bounds.last)
|
||||
.nth(3)
|
||||
.is_some()
|
||||
}));
|
||||
let whole = (full_scan || selected_group)
|
||||
&& request.start.is_none()
|
||||
&& request.end.is_none()
|
||||
&& end
|
||||
.checked_sub(start)
|
||||
.is_some_and(|size| size <= MAX_COALESCED_GROUP);
|
||||
let whole = whole || prefetched.is_some();
|
||||
let window_start = if whole { start } else { reference.offset };
|
||||
let window_bytes = if prefetched.is_none() {
|
||||
(end - window_start) as usize
|
||||
} else {
|
||||
0
|
||||
};
|
||||
reserve_scan(reservation, window_bytes + reference.decoded as usize)?;
|
||||
let window = if let Some(bytes) = prefetched {
|
||||
bytes
|
||||
} else {
|
||||
let read_started = Instant::now();
|
||||
let window = reader.read(window_start..end).await.context(OpenDalSnafu)?;
|
||||
record_group_io(metrics, window.len(), read_started);
|
||||
if whole {
|
||||
*metrics.counts.entry("payload_reads").or_default() += 1;
|
||||
}
|
||||
window
|
||||
};
|
||||
require(
|
||||
window.len() as u64 == end - window_start,
|
||||
"truncated IPC directory window",
|
||||
)?;
|
||||
if whole {
|
||||
*metrics.bytes.entry("fetched").or_default() += reference.offset - start;
|
||||
}
|
||||
let directory = window.slice((reference.offset - window_start) as usize..);
|
||||
let unpack_started = Instant::now();
|
||||
let index = reference.unpack_with_decoder(&directory, &mut self.directory)?;
|
||||
let prune_started = Instant::now();
|
||||
metrics.add_elapsed("ipc_directory_unpack", prune_started - unpack_started);
|
||||
let run_count = u16::from_le_bytes(number(index, 0)?) as usize;
|
||||
let chunk_count = u16::from_le_bytes(number(index, 2)?) as usize;
|
||||
require(
|
||||
run_count > 0
|
||||
&& run_count as u64 == group.blocks
|
||||
&& chunk_count > 0
|
||||
&& index.len() == 4 + run_count * 14 + chunk_count * 18,
|
||||
"invalid IPC directory length",
|
||||
)?;
|
||||
// One group reservation covers run bookkeeping, row indices and array headers.
|
||||
reserve_scan(
|
||||
reservation,
|
||||
run_count * (256 + projection.len() * 128)
|
||||
+ group.rows.min(u16::MAX.into()) as usize * 32,
|
||||
)?;
|
||||
let (runs, _) = index[4..4 + run_count * 14].as_chunks::<14>();
|
||||
let id_at = |entry: &[u8; 14]| MetricSeriesId {
|
||||
table_id: u32::from_le_bytes(entry[..4].try_into().unwrap()),
|
||||
tsid: u64::from_le_bytes(entry[4..12].try_into().unwrap()),
|
||||
};
|
||||
let end_at = |entry: &[u8; 14]| u16::from_le_bytes([entry[12], entry[13]]);
|
||||
let point = ids.filter(|ids| ids.len() == 1).and_then(BTreeSet::first);
|
||||
let (first, last) = if let Some(id) = point {
|
||||
// The writer sorts sparse keys by their big-endian table and series
|
||||
// prefix. Take the whole ID run to preserve exact-key collisions.
|
||||
let first = runs.partition_point(|entry| id_at(entry) < *id);
|
||||
let last = runs.partition_point(|entry| id_at(entry) <= *id);
|
||||
require(first <= last, "unordered IPC series runs")?;
|
||||
(first, last)
|
||||
} else {
|
||||
(0, run_count)
|
||||
};
|
||||
let mut selected = Vec::new();
|
||||
let mut previous = if first == 0 {
|
||||
0
|
||||
} else {
|
||||
end_at(&runs[first - 1])
|
||||
};
|
||||
for (i, entry) in (first..last).zip(&runs[first..last]) {
|
||||
let current = Run {
|
||||
id: id_at(entry),
|
||||
end: end_at(entry),
|
||||
};
|
||||
require(
|
||||
current.end > previous && u64::from(current.end) <= group.rows,
|
||||
"invalid IPC row span",
|
||||
)?;
|
||||
let start = previous;
|
||||
previous = current.end;
|
||||
if ids.is_none_or(|ids| ids.contains(¤t.id))
|
||||
&& request.table_id.is_none_or(|id| id == current.id.table_id)
|
||||
{
|
||||
selected.push((i, start, current));
|
||||
}
|
||||
}
|
||||
require(
|
||||
u64::from(end_at(&runs[run_count - 1])) == group.rows,
|
||||
"invalid IPC group row count",
|
||||
)?;
|
||||
metrics.add_elapsed("ipc_directory_prune", prune_started.elapsed());
|
||||
metrics.add_elapsed("columnar_metadata_wall", directory_started.elapsed());
|
||||
if selected.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// The prepared merge can express a full scan as an exact-key set. A group whose
|
||||
// every directory run survives coarse pruning can still read a single payload window.
|
||||
let grouped_payload = if !whole
|
||||
&& selected.len() == run_count
|
||||
&& group.key_end - start <= MAX_COALESCED_GROUP
|
||||
{
|
||||
reserve_scan(reservation, (group.key_end - start) as usize)?;
|
||||
let started = Instant::now();
|
||||
let bytes = reader
|
||||
.read(start..group.key_end)
|
||||
.await
|
||||
.context(OpenDalSnafu)?;
|
||||
require(
|
||||
bytes.len() as u64 == group.key_end - start,
|
||||
"truncated IPC payload window",
|
||||
)?;
|
||||
record_group_io(metrics, bytes.len(), started);
|
||||
*metrics.bytes.entry("fetched").or_default() += bytes.len() as u64;
|
||||
*metrics.counts.entry("payload_reads").or_default() += 1;
|
||||
metrics.add_elapsed("columnar_payload_fetch_wall", started.elapsed());
|
||||
Some(bytes)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let payload_window = if whole {
|
||||
Some(&window)
|
||||
} else {
|
||||
grouped_payload.as_ref()
|
||||
};
|
||||
let batch = if !needs_samples {
|
||||
None
|
||||
} else {
|
||||
let len = group.payload_end - group.start;
|
||||
require(
|
||||
len <= MAX_SAMPLE_BYTES as u64,
|
||||
"IPC sample page exceeds byte limit",
|
||||
)?;
|
||||
// Arrow can retain the input and copy its columns for a scattered projection.
|
||||
let copies =
|
||||
usize::from(payload_window.is_none()) + 1 + usize::from(page_schema.is_some());
|
||||
reserve_scan(reservation, len as usize * copies)?;
|
||||
let sample_started = Instant::now();
|
||||
let payload = if let Some(bytes) = payload_window {
|
||||
bytes.slice(..len as usize)
|
||||
} else {
|
||||
let payload = reader
|
||||
.read(group.start..group.payload_end)
|
||||
.await
|
||||
.context(OpenDalSnafu)?;
|
||||
*metrics.bytes.entry("fetched").or_default() += payload.len() as u64;
|
||||
*metrics.counts.entry("payload_reads").or_default() += 1;
|
||||
record_group_io(metrics, payload.len(), sample_started);
|
||||
payload
|
||||
};
|
||||
metrics.add_elapsed("columnar_payload_fetch_wall", sample_started.elapsed());
|
||||
let decode_started = Instant::now();
|
||||
let batch = decode_batch(payload, disk_schema)?;
|
||||
metrics.add_elapsed("columnar_decode", decode_started.elapsed());
|
||||
require(
|
||||
batch.num_rows() as u64 == group.rows,
|
||||
"IPC batch row mismatch",
|
||||
)?;
|
||||
Some(batch)
|
||||
};
|
||||
let time = if request.start.is_some() || request.end.is_some() {
|
||||
Some(
|
||||
datatypes::timestamp::timestamp_array_to_primitive(
|
||||
batch
|
||||
.as_ref()
|
||||
.ok_or_else(|| invalid("missing IPC sample page"))?
|
||||
.column(0),
|
||||
)
|
||||
.ok_or_else(|| invalid("IPC batch lacks timestamp"))?
|
||||
.0,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Arrow Binary offsets are signed. Large keys still work through the series path.
|
||||
let page_batches = if page_schema.is_some() && batch.is_some() {
|
||||
let mut decoded_key_bytes = 0u64;
|
||||
for chunk in 0..chunk_count {
|
||||
let at = 4 + run_count * 14 + chunk * 18;
|
||||
decoded_key_bytes += u64::from(u32::from_le_bytes(number(index, at + 14)?));
|
||||
}
|
||||
decoded_key_bytes <= i32::MAX as u64
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let mut keys = page_batches.then(BinaryBuilder::new);
|
||||
let mut row_indices = Vec::new();
|
||||
let mut key_indices = Vec::new();
|
||||
let mut tables = Vec::new();
|
||||
let mut tsids = Vec::new();
|
||||
let want_table = page_batches && projection.contains(&0);
|
||||
let want_tsid = page_batches && projection.contains(&1);
|
||||
let mut output = Vec::new();
|
||||
let mut position = 0;
|
||||
let mut chunks = Vec::with_capacity(chunk_count);
|
||||
for chunk_idx in 0..chunk_count {
|
||||
let at = 4 + run_count * 14 + chunk_idx * 18;
|
||||
let first = u16::from_le_bytes(number(index, at)?) as usize;
|
||||
let stored = u32::from_le_bytes(number(index, at + 10)?) as usize;
|
||||
let decoded = u32::from_le_bytes(number(index, at + 14)?) as usize;
|
||||
let offset = u64::from_le_bytes(number(index, at + 2)?);
|
||||
let end = if chunk_idx + 1 == chunk_count {
|
||||
run_count
|
||||
} else {
|
||||
u16::from_le_bytes(number(index, at + 18)?) as usize
|
||||
};
|
||||
require(
|
||||
first < end
|
||||
&& end <= run_count
|
||||
&& decoded <= MAX_SPARSE_KEY_BYTES + 4
|
||||
&& stored <= zstd::zstd_safe::compress_bound(decoded),
|
||||
"invalid IPC key chunk",
|
||||
)?;
|
||||
let next = position + selected[position..].partition_point(|(i, _, _)| *i < end);
|
||||
if next == position {
|
||||
continue;
|
||||
}
|
||||
require(selected[position].0 >= first, "invalid IPC key chunk order")?;
|
||||
let offset = group
|
||||
.payload_end
|
||||
.checked_add(offset)
|
||||
.ok_or_else(|| invalid("IPC key offset overflow"))?;
|
||||
let limit = offset
|
||||
.checked_add(stored as u64)
|
||||
.ok_or_else(|| invalid("IPC key range overflow"))?;
|
||||
require(limit <= group.key_end, "IPC key chunk outside key area")?;
|
||||
chunks.push(ReadChunk {
|
||||
rows: position..next,
|
||||
first,
|
||||
decoded,
|
||||
range: offset..limit,
|
||||
});
|
||||
position = next;
|
||||
}
|
||||
require(position == selected.len(), "missing IPC key chunk")?;
|
||||
let decoded_keys: usize = chunks.iter().map(|chunk| chunk.decoded).sum();
|
||||
let largest_key_frame = chunks.iter().map(|chunk| chunk.decoded).max().unwrap_or(0);
|
||||
let key_window_bytes = if payload_window.is_none() {
|
||||
chunks
|
||||
.iter()
|
||||
.map(|chunk| (chunk.range.end - chunk.range.start) as usize)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.max((group.key_end - group.payload_end).min(MAX_COALESCED_GROUP) as usize)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// Decoded frames can back returned keys. A separate frame-sized allowance covers
|
||||
// scratch, and dictionary output can briefly retain the building and final buffers.
|
||||
let key_copies = if page_batches { 3 } else { 1 };
|
||||
reserve_scan(
|
||||
reservation,
|
||||
2 * key_window_bytes + largest_key_frame + decoded_keys * key_copies,
|
||||
)?;
|
||||
let mut raw = Vec::new();
|
||||
let mut key_window = Bytes::new();
|
||||
let mut key_range = 0..0;
|
||||
for (index, chunk) in chunks.iter().enumerate() {
|
||||
let ReadChunk {
|
||||
rows,
|
||||
first,
|
||||
decoded,
|
||||
range,
|
||||
} = chunk;
|
||||
let first = *first;
|
||||
let decoded = *decoded;
|
||||
let key_started = Instant::now();
|
||||
let stored = if let Some(bytes) = payload_window {
|
||||
bytes.slice((range.start - start) as usize..(range.end - start) as usize)
|
||||
} else {
|
||||
if range.start < key_range.start || range.end > key_range.end {
|
||||
let mut end = range.end;
|
||||
for next in &chunks[index + 1..] {
|
||||
if next.range.start != end
|
||||
|| next.range.end - range.start > MAX_COALESCED_GROUP
|
||||
{
|
||||
break;
|
||||
}
|
||||
end = next.range.end;
|
||||
}
|
||||
key_range = range.start..end;
|
||||
key_window = reader.read(key_range.clone()).await.context(OpenDalSnafu)?;
|
||||
require(
|
||||
key_window.len() as u64 == key_range.end - key_range.start,
|
||||
"truncated IPC key window",
|
||||
)?;
|
||||
*metrics.bytes.entry("fetched").or_default() += key_window.len() as u64;
|
||||
*metrics.counts.entry("payload_reads").or_default() += 1;
|
||||
record_group_io(metrics, key_window.len(), key_started);
|
||||
}
|
||||
key_window.slice(
|
||||
(range.start - key_range.start) as usize
|
||||
..(range.end - key_range.start) as usize,
|
||||
)
|
||||
};
|
||||
metrics.add_elapsed("columnar_payload_fetch_wall", key_started.elapsed());
|
||||
let key_decode_started = Instant::now();
|
||||
if self.zstd.is_none() {
|
||||
self.zstd = Some(zstd::bulk::Decompressor::new().map_err(failure)?);
|
||||
}
|
||||
raw.clear();
|
||||
raw.reserve_exact(decoded);
|
||||
self.zstd
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.decompress_to_buffer(&stored, &mut raw)
|
||||
.map_err(failure)?;
|
||||
metrics.add_elapsed("columnar_key_page_decode", key_decode_started.elapsed());
|
||||
require(
|
||||
raw.len() == decoded,
|
||||
"IPC key chunk decoded length mismatch",
|
||||
)?;
|
||||
// A lone selection should not pin an entire decoded key chunk.
|
||||
let shared =
|
||||
(!page_batches && rows.len() > 1).then(|| Bytes::from(std::mem::take(&mut raw)));
|
||||
let raw = shared.as_deref().unwrap_or(&raw);
|
||||
let output_started = Instant::now();
|
||||
let mut cursor = 0;
|
||||
let mut slot = first;
|
||||
for (i, start, run) in &selected[rows.clone()] {
|
||||
while slot < *i {
|
||||
cursor += 4 + u32::from_le_bytes(number(raw, cursor)?) as usize;
|
||||
slot += 1;
|
||||
}
|
||||
let len = u32::from_le_bytes(number(raw, cursor)?) as usize;
|
||||
let key = raw
|
||||
.get(cursor + 4..cursor + 4 + len)
|
||||
.ok_or_else(|| invalid("truncated IPC key"))?;
|
||||
if request
|
||||
.keys
|
||||
.as_ref()
|
||||
.is_some_and(|keys| !keys.contains(key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let rows = usize::from(run.end - *start);
|
||||
let (low, high) = time.as_ref().map_or((0, rows), |time| {
|
||||
let values = &time.values()[usize::from(*start)..usize::from(run.end)];
|
||||
let low = request
|
||||
.start
|
||||
.map_or(0, |start| values.partition_point(|&v| v < start));
|
||||
let high = request
|
||||
.end
|
||||
.map_or(rows, |end| values.partition_point(|&v| v < end));
|
||||
(low, high)
|
||||
});
|
||||
if low >= high {
|
||||
continue;
|
||||
}
|
||||
let count = high - low;
|
||||
let offset = usize::from(*start) + low;
|
||||
if let Some(keys) = &mut keys {
|
||||
require(
|
||||
keys.values_slice().len() + key.len() <= i32::MAX as usize,
|
||||
"IPC page key dictionary exceeds Arrow binary limit",
|
||||
)?;
|
||||
let index = keys.offsets_slice().len() as u32 - 1;
|
||||
keys.append_value(key);
|
||||
key_indices.extend(std::iter::repeat_n(index, count));
|
||||
row_indices.extend(offset as u32..(offset + count) as u32);
|
||||
if want_table {
|
||||
tables.extend(std::iter::repeat_n(run.id.table_id, count));
|
||||
}
|
||||
if want_tsid {
|
||||
tsids.extend(std::iter::repeat_n(run.id.tsid, count));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// The writer derives the directory ID from this exact key. The normal read
|
||||
// path trusts that mapping and uses the full bytes for collision-safe lookup.
|
||||
let key = match &shared {
|
||||
Some(chunk) => chunk.slice(cursor + 4..cursor + 4 + len),
|
||||
None => Bytes::copy_from_slice(key),
|
||||
};
|
||||
let key = ExactSeriesKey::from_ipc_directory(run.id, key);
|
||||
let arrays = projection
|
||||
.iter()
|
||||
.map(|&index| match index {
|
||||
0 => Arc::new(UInt32Array::from(vec![run.id.table_id; count])) as _,
|
||||
1 => Arc::new(UInt64Array::from(vec![run.id.tsid; count])) as _,
|
||||
index => batch
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.column(index - 2)
|
||||
.slice(offset, count),
|
||||
})
|
||||
.collect();
|
||||
let output_batch = RecordBatch::try_new_with_options(
|
||||
schema.clone(),
|
||||
arrays,
|
||||
&RecordBatchOptions::new().with_row_count(Some(count)),
|
||||
)
|
||||
.map_err(failure)?;
|
||||
output.push(SamplesBatch::Series {
|
||||
batch: output_batch,
|
||||
key,
|
||||
});
|
||||
}
|
||||
metrics.add_elapsed("columnar_ipc_key_and_batch", output_started.elapsed());
|
||||
}
|
||||
if let Some(mut keys) = keys.filter(|_| !row_indices.is_empty()) {
|
||||
let started = Instant::now();
|
||||
let batch = batch
|
||||
.as_ref()
|
||||
.ok_or_else(|| invalid("missing IPC sample page"))?;
|
||||
let first = row_indices[0] as usize;
|
||||
let count = row_indices.len();
|
||||
let contiguous = row_indices[count - 1] as usize - first + 1 == count;
|
||||
let rows = (!contiguous).then(|| UInt32Array::from(row_indices));
|
||||
let table: ArrayRef = Arc::new(UInt32Array::from(tables));
|
||||
let tsid: ArrayRef = Arc::new(UInt64Array::from(tsids));
|
||||
let mut columns = projection
|
||||
.iter()
|
||||
.map(|&index| match index {
|
||||
0 => Ok(table.clone()),
|
||||
1 => Ok(tsid.clone()),
|
||||
index => {
|
||||
let column = batch.column(index - 2);
|
||||
match &rows {
|
||||
Some(rows) => take(column.as_ref(), rows, None).map_err(failure),
|
||||
None if count == batch.num_rows() => Ok(column.clone()),
|
||||
None => Ok(column.slice(first, count)),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let dictionary = DictionaryArray::<UInt32Type>::try_new(
|
||||
UInt32Array::from(key_indices),
|
||||
Arc::new(keys.finish()),
|
||||
)
|
||||
.map_err(failure)?;
|
||||
columns.push(Arc::new(dictionary));
|
||||
let schema = page_schema
|
||||
.ok_or_else(|| invalid("missing IPC page schema"))?
|
||||
.clone();
|
||||
*metrics.counts.entry("ipc_flat_batches").or_default() += 1;
|
||||
output.push(SamplesBatch::Page(
|
||||
RecordBatch::try_new(schema, columns).map_err(failure)?,
|
||||
));
|
||||
metrics.add_elapsed("columnar_ipc_key_and_batch", started.elapsed());
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decode_batch(bytes: Bytes, schema: SchemaRef) -> Result<RecordBatch> {
|
||||
let length = u64::from_le_bytes(number(&bytes, 0)?) as usize;
|
||||
require(
|
||||
length <= bytes.len().saturating_sub(8),
|
||||
"invalid IPC metadata length",
|
||||
)?;
|
||||
let offset = 8 + length.next_multiple_of(8);
|
||||
require(offset <= bytes.len(), "invalid IPC body offset")?;
|
||||
let data = Buffer::from(bytes);
|
||||
let message = ipc::root_as_message(&data[8..8 + length]).map_err(failure)?;
|
||||
let batch = message
|
||||
.header_as_record_batch()
|
||||
.ok_or_else(|| invalid("invalid IPC sample message"))?;
|
||||
read_record_batch(
|
||||
&data.slice(offset),
|
||||
batch,
|
||||
schema,
|
||||
&HashMap::new(),
|
||||
None,
|
||||
&message.version(),
|
||||
)
|
||||
.map_err(failure)
|
||||
}
|
||||
|
||||
pub(super) fn disk_schema(schema: &Schema) -> SchemaRef {
|
||||
Arc::new(Schema::new(
|
||||
schema.fields()[2..schema.fields().len() - 1].to_vec(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn flat_page_schema(projected: &Schema) -> SchemaRef {
|
||||
let mut fields = projected.fields().to_vec();
|
||||
fields.push(Arc::new(Field::new(
|
||||
PRIMARY_KEY_COLUMN_NAME,
|
||||
DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
|
||||
false,
|
||||
)));
|
||||
Arc::new(Schema::new(fields))
|
||||
}
|
||||
@@ -17,13 +17,10 @@
|
||||
use crate::error::Result;
|
||||
use crate::series_index::samples::codec::{self, Cursor, put_u32, put_u64};
|
||||
use crate::series_index::samples::{
|
||||
Manifest, MetricSeriesId, VERSION, histogram, invalid, require, unsupported, valid_rows,
|
||||
Manifest, MetricSeriesId, histogram, invalid, require, unsupported, valid_rows,
|
||||
};
|
||||
|
||||
pub(super) const MAGIC: &[u8; 8] = b"GTSAMPLE";
|
||||
pub(super) const HEADER_SIZE: u64 = 16;
|
||||
pub(super) const FOOTER_SIZE: u64 = 16;
|
||||
const FOOTER_MAGIC: &[u8; 8] = b"NARTGRP1";
|
||||
/// Limit a single directory fetch even for a malformed footer.
|
||||
pub(super) const MAX_GROUPS: usize = (8 * 1024 * 1024) / GROUP_BYTES;
|
||||
pub(super) const PAGE_LIMIT: usize = 65536;
|
||||
@@ -706,21 +703,8 @@ impl Page {
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
pub(super) fn header() -> Vec<u8> {
|
||||
let mut out = MAGIC.to_vec();
|
||||
put_u32(&mut out, VERSION);
|
||||
put_u32(&mut out, 0);
|
||||
out
|
||||
}
|
||||
pub(super) fn validate_header(bytes: &[u8]) -> Result<()> {
|
||||
let mut c = Cursor::new(bytes);
|
||||
require(c.take(8)? == MAGIC, "sample header magic")?;
|
||||
if c.u32()? != VERSION {
|
||||
return Err(unsupported("samples file version"));
|
||||
}
|
||||
require(c.u32()? == 0, "nonzero sample header reserved field")?;
|
||||
c.end()
|
||||
}
|
||||
pub(super) const HEADER: &[u8; HEADER_SIZE as usize] = b"GTSAMPLE\0\0\0\0\0\0\0\0";
|
||||
|
||||
/// One part-directory entry. The first group starts after the header; subsequent
|
||||
/// groups start at the end of the preceding root page.
|
||||
pub(super) const GROUP_BYTES: usize = 64 + 4 + 5 * 8;
|
||||
@@ -767,83 +751,200 @@ impl Group {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Encodes the directory followed by its fixed-size footer.
|
||||
pub(super) fn encode_directory(groups: &[Group]) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity(groups.len() * GROUP_BYTES + FOOTER_SIZE as usize);
|
||||
pub(super) const TAIL_TRAILER_SIZE: usize = 24;
|
||||
const TAIL_MAGIC: &[u8; 8] = b"NXSAMPLE";
|
||||
|
||||
pub(super) fn encode_part_tail(groups: &[Group], descriptor: &[u8]) -> Vec<u8> {
|
||||
let mut bytes =
|
||||
Vec::with_capacity(groups.len() * GROUP_BYTES + descriptor.len() + TAIL_TRAILER_SIZE);
|
||||
for group in groups {
|
||||
group.encode(&mut bytes);
|
||||
}
|
||||
let length = bytes.len() as u64;
|
||||
bytes.extend(FOOTER_MAGIC);
|
||||
put_u64(&mut bytes, length);
|
||||
let index_len = bytes.len();
|
||||
bytes.extend_from_slice(descriptor);
|
||||
bytes.extend_from_slice(TAIL_MAGIC);
|
||||
put_u64(&mut bytes, index_len as u64);
|
||||
put_u64(&mut bytes, descriptor.len() as u64);
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(super) struct DirectoryFooter {
|
||||
pub length: u64,
|
||||
pub(super) fn decode_part_tail(bytes: &[u8]) -> Result<(&[u8], &[u8])> {
|
||||
let data_len = bytes
|
||||
.len()
|
||||
.checked_sub(TAIL_TRAILER_SIZE)
|
||||
.ok_or_else(|| invalid("truncated sample part tail"))?;
|
||||
let (data, trailer) = bytes.split_at(data_len);
|
||||
let (index_len, descriptor_len) = decode_tail_trailer(trailer)?;
|
||||
require(
|
||||
index_len.checked_add(descriptor_len) == Some(data_len as u64),
|
||||
"invalid sample part tail lengths",
|
||||
)?;
|
||||
Ok(data.split_at(index_len as usize))
|
||||
}
|
||||
impl DirectoryFooter {
|
||||
pub fn decode(bytes: &[u8]) -> Result<Self> {
|
||||
let mut c = Cursor::new(bytes);
|
||||
require(c.take(8)? == FOOTER_MAGIC, "invalid sample directory magic")?;
|
||||
let length = c.u64()?;
|
||||
|
||||
pub(super) fn decode_tail_trailer(trailer: &[u8]) -> Result<(u64, u64)> {
|
||||
let mut trailer = Cursor::new(trailer);
|
||||
require(
|
||||
trailer.take(8)? == TAIL_MAGIC,
|
||||
"invalid sample part tail magic",
|
||||
)?;
|
||||
let index_len = trailer.u64()?;
|
||||
let descriptor_len = trailer.u64()?;
|
||||
require(
|
||||
index_len > 0
|
||||
&& index_len <= (MAX_GROUPS * GROUP_BYTES) as u64
|
||||
&& index_len.is_multiple_of(GROUP_BYTES as u64)
|
||||
&& descriptor_len > 0
|
||||
&& descriptor_len <= super::MANIFEST_LIMIT as u64,
|
||||
"invalid sample part tail lengths",
|
||||
)?;
|
||||
Ok((index_len, descriptor_len))
|
||||
}
|
||||
|
||||
pub(super) fn decode_groups(bytes: &[u8], end: u64) -> Result<Vec<Group>> {
|
||||
let mut start = HEADER_SIZE;
|
||||
let mut groups: Vec<Group> = Vec::with_capacity(bytes.len() / GROUP_BYTES);
|
||||
// The trailer already fixes the entry width. Decode the fixed offsets
|
||||
// after checking that width once, then validate the decoded references.
|
||||
let (entries, remainder) = bytes.as_chunks::<GROUP_BYTES>();
|
||||
require(remainder.is_empty(), "truncated sample directory entry")?;
|
||||
for entry in entries {
|
||||
let group = decode_group(entry, start, end)?;
|
||||
let next = group.root.payload.end()?;
|
||||
if let Some(previous) = groups.last() {
|
||||
require(
|
||||
previous.root.bounds.last <= group.root.bounds.first,
|
||||
"unordered sample groups",
|
||||
)?;
|
||||
}
|
||||
groups.push(group);
|
||||
start = next;
|
||||
}
|
||||
require(start == end, "sample directory does not follow last group")?;
|
||||
Ok(groups)
|
||||
}
|
||||
|
||||
fn decode_group(entry: &[u8; GROUP_BYTES], start: u64, end: u64) -> Result<Group> {
|
||||
let u16_at = |offset| u16::from_le_bytes(entry[offset..][..2].try_into().unwrap());
|
||||
let u32_at = |offset| u32::from_le_bytes(entry[offset..][..4].try_into().unwrap());
|
||||
let u64_at = |offset| u64::from_le_bytes(entry[offset..][..8].try_into().unwrap());
|
||||
let root = PageReference {
|
||||
bounds: Bounds {
|
||||
first: MetricSeriesId {
|
||||
table_id: u32_at(0),
|
||||
tsid: u64_at(4),
|
||||
},
|
||||
last: MetricSeriesId {
|
||||
table_id: u32_at(12),
|
||||
tsid: u64_at(16),
|
||||
},
|
||||
min: u64_at(24) as i64,
|
||||
max: u64_at(32) as i64,
|
||||
},
|
||||
payload: PayloadReference {
|
||||
offset: u64_at(40),
|
||||
stored: u32_at(48),
|
||||
decoded: u32_at(52),
|
||||
encoding: u16_at(56),
|
||||
compression: u16_at(58),
|
||||
},
|
||||
};
|
||||
root.bounds.validate()?;
|
||||
require(u32_at(60) == 0, "nonzero sample payload reserved field")?;
|
||||
if root.payload.encoding != 1 || root.payload.compression > 1 {
|
||||
return Err(unsupported("samples metadata codec"));
|
||||
}
|
||||
let depth = u32_at(64);
|
||||
let payload_end = u64_at(68);
|
||||
let key_end = u64_at(76);
|
||||
let logical_key_end = u64_at(84);
|
||||
let rows = u64_at(92);
|
||||
let blocks = u64_at(100);
|
||||
let next = root.payload.end()?;
|
||||
require(
|
||||
(1..=2).contains(&depth)
|
||||
&& rows >= blocks
|
||||
&& blocks > 0
|
||||
&& start < payload_end
|
||||
&& payload_end < key_end
|
||||
&& payload_end < logical_key_end
|
||||
&& next <= end,
|
||||
"invalid sample group boundaries",
|
||||
)?;
|
||||
root.payload.validate(key_end, next, true)?;
|
||||
Ok(Group {
|
||||
start,
|
||||
rows,
|
||||
blocks,
|
||||
root,
|
||||
depth,
|
||||
payload_end,
|
||||
key_end,
|
||||
logical_key_end,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) struct PartTailIndex {
|
||||
bytes: bytes::Bytes,
|
||||
end: u64,
|
||||
}
|
||||
|
||||
impl PartTailIndex {
|
||||
pub(super) fn new(bytes: bytes::Bytes, end: u64, part: &super::Part) -> Result<Self> {
|
||||
let (entries, remainder) = bytes.as_chunks::<GROUP_BYTES>();
|
||||
require(
|
||||
length > 0
|
||||
&& length <= (MAX_GROUPS * GROUP_BYTES) as u64
|
||||
&& length.is_multiple_of(GROUP_BYTES as u64),
|
||||
"invalid sample directory length",
|
||||
!entries.is_empty() && remainder.is_empty(),
|
||||
"invalid sample tail index length",
|
||||
)?;
|
||||
c.end()?;
|
||||
Ok(Self { length })
|
||||
require(
|
||||
Self::id(&entries[0], 0) == part.first
|
||||
&& Self::id(entries.last().unwrap(), 12) == part.last
|
||||
&& Self::group_end(entries.last().unwrap())? == end,
|
||||
"sample tail index bounds mismatch",
|
||||
)?;
|
||||
Ok(Self { bytes, end })
|
||||
}
|
||||
|
||||
pub fn groups(&self, bytes: &[u8], end: u64) -> Result<Vec<Group>> {
|
||||
require(
|
||||
bytes.len() as u64 == self.length,
|
||||
"invalid sample directory length",
|
||||
)?;
|
||||
let mut start = HEADER_SIZE;
|
||||
let mut c = Cursor::new(bytes);
|
||||
let mut groups: Vec<Group> = Vec::with_capacity(bytes.len() / GROUP_BYTES);
|
||||
while c.remaining() > 0 {
|
||||
let root = PageReference::decode(&mut c)?;
|
||||
let depth = c.u32()?;
|
||||
let payload_end = c.u64()?;
|
||||
let key_end = c.u64()?;
|
||||
let logical_key_end = c.u64()?;
|
||||
let rows = c.u64()?;
|
||||
let blocks = c.u64()?;
|
||||
let next = root.payload.end()?;
|
||||
require(
|
||||
(1..=2).contains(&depth)
|
||||
&& rows >= blocks
|
||||
&& blocks > 0
|
||||
&& start < payload_end
|
||||
&& payload_end < logical_key_end
|
||||
&& payload_end < key_end
|
||||
&& next <= end,
|
||||
"invalid sample group boundaries",
|
||||
)?;
|
||||
root.payload.validate(key_end, next, true)?;
|
||||
if let Some(previous) = groups.last() {
|
||||
require(
|
||||
previous.root.bounds.last <= root.bounds.first,
|
||||
"unordered sample groups",
|
||||
)?;
|
||||
}
|
||||
groups.push(Group {
|
||||
start,
|
||||
rows,
|
||||
blocks,
|
||||
root,
|
||||
depth,
|
||||
payload_end,
|
||||
key_end,
|
||||
logical_key_end,
|
||||
});
|
||||
start = next;
|
||||
pub(super) fn retained_size(&self) -> usize {
|
||||
std::mem::size_of::<Self>() + self.bytes.len()
|
||||
}
|
||||
|
||||
fn id(entry: &[u8; GROUP_BYTES], offset: usize) -> MetricSeriesId {
|
||||
MetricSeriesId {
|
||||
table_id: u32::from_le_bytes(entry[offset..offset + 4].try_into().unwrap()),
|
||||
tsid: u64::from_le_bytes(entry[offset + 4..offset + 12].try_into().unwrap()),
|
||||
}
|
||||
require(start == end, "sample directory does not follow last group")?;
|
||||
}
|
||||
|
||||
fn group_end(entry: &[u8; GROUP_BYTES]) -> Result<u64> {
|
||||
let offset = u64::from_le_bytes(entry[40..48].try_into().unwrap());
|
||||
let size = u32::from_le_bytes(entry[48..52].try_into().unwrap());
|
||||
offset
|
||||
.checked_add(u64::from(size))
|
||||
.ok_or_else(|| invalid("sample group offset overflow"))
|
||||
}
|
||||
|
||||
pub(super) fn point(&self, id: MetricSeriesId) -> Result<Vec<Group>> {
|
||||
let (entries, _) = self.bytes.as_chunks::<GROUP_BYTES>();
|
||||
let start = entries.partition_point(|entry| Self::id(entry, 12) < id);
|
||||
let end = entries.partition_point(|entry| Self::id(entry, 0) <= id);
|
||||
require(start <= end, "unordered sample groups")?;
|
||||
(start..end)
|
||||
.map(|index| {
|
||||
let offset = if index == 0 {
|
||||
HEADER_SIZE
|
||||
} else {
|
||||
Self::group_end(&entries[index - 1])?
|
||||
};
|
||||
decode_group(&entries[index], offset, self.end)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn all(&self, part: &super::Part) -> Result<Vec<Group>> {
|
||||
let groups = decode_groups(&self.bytes, self.end)?;
|
||||
let expected = super::Part::from_groups(part.part_id, &groups)?;
|
||||
require(*part == expected, "sample tail part inventory mismatch")?;
|
||||
Ok(groups)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
//! Lazy, selective sample reads with independent traversal and pinned lifetimes.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
|
||||
@@ -46,17 +46,26 @@ use crate::series_index::samples::metadata::{
|
||||
self, Areas, Block, BlockOrder, Bounds, Column, Page, PageReference,
|
||||
};
|
||||
use crate::series_index::samples::{
|
||||
MANIFEST_LIMIT, Manifest, MetricSeriesId, TimestampUnit, VERSION, codec, histogram, invalid,
|
||||
require, unsupported,
|
||||
Manifest, MetricSeriesId, TimestampUnit, codec, histogram, invalid, require, unsupported,
|
||||
};
|
||||
use crate::sst::file::{FileFormat, FileHandle};
|
||||
use crate::series_index::samples::{SamplesLayout, ipc_pages};
|
||||
use crate::sst::file::{FileFormat, FileHandle, NarthexSamplePartMeta, NarthexSamplesMeta};
|
||||
use crate::sst::location;
|
||||
|
||||
pub(crate) struct SamplesDescriptor {
|
||||
inventory: NarthexSamplesMeta,
|
||||
tail_groups: Arc<Vec<metadata::PartTailIndex>>,
|
||||
manifest: Arc<Manifest>,
|
||||
schema: SchemaRef,
|
||||
}
|
||||
|
||||
fn samples_meta(handle: &FileHandle) -> Result<&NarthexSamplesMeta> {
|
||||
let FileFormat::NarthexSamples(meta) = &handle.meta_ref().format else {
|
||||
return Err(invalid("expected Narthex samples file"));
|
||||
};
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
fn decode_float_column(
|
||||
bytes: &[u8],
|
||||
rows: usize,
|
||||
@@ -115,7 +124,7 @@ impl NarthexBulkPart {
|
||||
};
|
||||
let payload = col.payload;
|
||||
let bytes = payload.unpack(
|
||||
&part.0.parts[*i][payload.offset as usize..payload.end()? as usize],
|
||||
&part.0.parts[*i].bytes[payload.offset as usize..payload.end()? as usize],
|
||||
)?;
|
||||
match role {
|
||||
1 => {
|
||||
@@ -147,13 +156,17 @@ impl NarthexBulkPart {
|
||||
}
|
||||
}
|
||||
|
||||
type PartReaders = Arc<Vec<OnceCell<ObjectReader>>>;
|
||||
|
||||
pub(crate) struct SamplesReader {
|
||||
tail_groups: Arc<Vec<metadata::PartTailIndex>>,
|
||||
store: ObjectStore,
|
||||
manifest: Arc<Manifest>,
|
||||
schema: SchemaRef,
|
||||
cache: Option<MetadataCache>,
|
||||
handle: FileHandle,
|
||||
parts: Arc<Vec<OnceCell<ObjectReader>>>,
|
||||
parts: PartReaders,
|
||||
prefix: Arc<str>,
|
||||
}
|
||||
impl SamplesReader {
|
||||
pub(crate) async fn open_cached(
|
||||
@@ -163,18 +176,17 @@ impl SamplesReader {
|
||||
cache: Option<MetadataCache>,
|
||||
) -> Result<Self> {
|
||||
let file = handle.meta_ref();
|
||||
let FileFormat::NarthexSamples(samples) = &file.format else {
|
||||
return Err(invalid("expected Narthex samples file"));
|
||||
};
|
||||
let identity = MetadataIdentity::SamplesManifest(
|
||||
handle.file_id(),
|
||||
region_dir.into(),
|
||||
samples.manifest_size,
|
||||
);
|
||||
require(file.valid_inventory(), "invalid sample tail inventory")?;
|
||||
let samples = samples_meta(&handle)?;
|
||||
let identity = MetadataIdentity::SamplesTails(handle.file_id());
|
||||
let prefix: Arc<str> = location::narthex_file_dir(region_dir, file.file_id).into();
|
||||
// Object readers stay scan-local. The shared cache keeps only metadata.
|
||||
let opened_parts = Arc::new(OnceLock::new());
|
||||
let loader_parts = opened_parts.clone();
|
||||
let loader_store = store.clone();
|
||||
let loader_handle = handle.clone();
|
||||
let loader_cache = cache.clone();
|
||||
let region_dir = region_dir.to_owned();
|
||||
let loader_prefix = prefix.clone();
|
||||
let descriptor = metadata_cache::load(
|
||||
cache.as_ref(),
|
||||
identity,
|
||||
@@ -182,7 +194,20 @@ impl SamplesReader {
|
||||
let SamplesDescriptor {
|
||||
manifest, schema, ..
|
||||
} = descriptor;
|
||||
let inventory = &descriptor.inventory.parts;
|
||||
let inventory_heap_size = if inventory.spilled() {
|
||||
inventory.capacity() * std::mem::size_of::<NarthexSamplePartMeta>()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
manifest.retained_size()
|
||||
+ std::mem::size_of::<NarthexSamplesMeta>()
|
||||
+ inventory_heap_size
|
||||
+ descriptor
|
||||
.tail_groups
|
||||
.iter()
|
||||
.map(metadata::PartTailIndex::retained_size)
|
||||
.sum::<usize>()
|
||||
+ 8 * std::mem::size_of::<usize>()
|
||||
+ std::mem::size_of::<datatypes::arrow::datatypes::Schema>()
|
||||
+ schema
|
||||
@@ -192,45 +217,34 @@ impl SamplesReader {
|
||||
.sum::<usize>()
|
||||
},
|
||||
move || async move {
|
||||
Self::open_descriptor(
|
||||
let (descriptor, readers) = Self::open_tail_descriptor(
|
||||
loader_store,
|
||||
loader_handle,
|
||||
®ion_dir,
|
||||
&loader_prefix,
|
||||
loader_cache.as_ref(),
|
||||
)
|
||||
.await
|
||||
.await?;
|
||||
let _ = loader_parts.set(readers);
|
||||
Ok(descriptor)
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
require(
|
||||
descriptor.manifest.files.len() == samples.parts.len()
|
||||
&& descriptor
|
||||
.manifest
|
||||
.files
|
||||
.iter()
|
||||
.zip(&samples.parts)
|
||||
.all(|(part, entry)| part.file_size == entry.file_size),
|
||||
"sample part inventory mismatch",
|
||||
)?;
|
||||
require(
|
||||
descriptor
|
||||
.manifest
|
||||
.files
|
||||
.iter()
|
||||
.try_fold(samples.manifest_size, |total, part| {
|
||||
total.checked_add(part.file_size)
|
||||
})
|
||||
== Some(file.file_size),
|
||||
"sample artifact size mismatch",
|
||||
)?;
|
||||
let parts = if let Some(readers) = opened_parts.get() {
|
||||
readers.clone()
|
||||
} else {
|
||||
// A cache hit must agree with the part inventory on the current handle.
|
||||
require(
|
||||
descriptor.inventory == *samples,
|
||||
"sample tail part inventory mismatch",
|
||||
)?;
|
||||
Arc::new((0..samples.parts.len()).map(|_| OnceCell::new()).collect())
|
||||
};
|
||||
Ok(Self {
|
||||
store,
|
||||
handle,
|
||||
parts: Arc::new(
|
||||
(0..descriptor.manifest.files.len())
|
||||
.map(|_| OnceCell::new())
|
||||
.collect(),
|
||||
),
|
||||
parts,
|
||||
prefix,
|
||||
tail_groups: descriptor.tail_groups.clone(),
|
||||
manifest: descriptor.manifest.clone(),
|
||||
schema: descriptor.schema.clone(),
|
||||
cache,
|
||||
@@ -246,86 +260,117 @@ impl SamplesReader {
|
||||
Self::open_cached(store, handle, region_dir, None).await
|
||||
}
|
||||
|
||||
async fn open_descriptor(
|
||||
async fn open_tail_descriptor(
|
||||
store: ObjectStore,
|
||||
handle: FileHandle,
|
||||
region_dir: &str,
|
||||
prefix: &str,
|
||||
cache: Option<&MetadataCache>,
|
||||
) -> Result<SamplesDescriptor> {
|
||||
) -> Result<(SamplesDescriptor, PartReaders)> {
|
||||
let file = handle.meta_ref();
|
||||
let FileFormat::NarthexSamples(samples) = &file.format else {
|
||||
return Err(invalid("expected Narthex samples file"));
|
||||
};
|
||||
let prefix = location::narthex_file_dir(region_dir, file.file_id);
|
||||
let path = location::narthex_manifest_path(&prefix);
|
||||
let length = samples.manifest_size;
|
||||
require(
|
||||
length > 0 && length <= MANIFEST_LIMIT as u64,
|
||||
"samples manifest exceeds limit",
|
||||
)?;
|
||||
let object = ObjectReader::open(
|
||||
cache,
|
||||
Some(&handle),
|
||||
crate::cache::file_cache::FileType::Samples(None),
|
||||
&store,
|
||||
&path,
|
||||
length,
|
||||
)
|
||||
.await?;
|
||||
let bytes = object.read(0..length).await.context(OpenDalSnafu)?;
|
||||
// A manifest that the current format cannot read predates exact identity or is
|
||||
// corrupt; either way it must never be reused.
|
||||
let mut manifest: Manifest = serde_json::from_slice(&bytes).map_err(|error| {
|
||||
invalid(format!(
|
||||
"samples manifest is not readable; rebuild the artifact: {error}"
|
||||
))
|
||||
})?;
|
||||
manifest.prefix = prefix;
|
||||
if manifest.version != VERSION {
|
||||
return Err(unsupported("samples manifest version"));
|
||||
}
|
||||
// Old artifacts can be structurally valid and perfectly ordered, so identity
|
||||
// encoding is the only thing that keeps their lost labels out of reads.
|
||||
if manifest.identity_encoding != IdentityEncoding::CURRENT_SAMPLES {
|
||||
return Err(unsupported(
|
||||
"samples manifest identity encoding; rebuild the samples artifact",
|
||||
));
|
||||
}
|
||||
require(
|
||||
manifest.format == ArtifactFormat::ColumnarSamples
|
||||
&& manifest.region_id == file.region_id.as_u64()
|
||||
&& manifest.source_file_id == file.file_id
|
||||
&& manifest.generation == file.file_id,
|
||||
"samples manifest identity mismatch",
|
||||
)?;
|
||||
manifest.validate_schema()?;
|
||||
let mut previous = None;
|
||||
for (index, part) in manifest.files.iter().enumerate() {
|
||||
let samples = samples_meta(&handle)?;
|
||||
let mut manifest: Option<Manifest> = None;
|
||||
let mut directories = Vec::with_capacity(samples.parts.len());
|
||||
let mut readers = Vec::with_capacity(samples.parts.len());
|
||||
let mut metrics = ColumnarReadMetrics::default();
|
||||
for (index, part) in samples.parts.iter().enumerate() {
|
||||
let tail_size = part.tail_size;
|
||||
let part_id = u32::try_from(index).map_err(|_| invalid("too many sample parts"))?;
|
||||
let start = part
|
||||
.file_size
|
||||
.checked_sub(tail_size)
|
||||
.filter(|&start| start >= metadata::HEADER_SIZE)
|
||||
.ok_or_else(|| invalid("sample metadata tail outside part"))?;
|
||||
require(
|
||||
index as u64 == u64::from(part.part_id)
|
||||
&& part.num_rows > 0
|
||||
&& part.num_blocks > 0
|
||||
&& part.num_blocks <= part.num_rows
|
||||
&& part.first <= part.last
|
||||
&& part.min_timestamp <= part.max_timestamp
|
||||
&& part.file_size
|
||||
>= metadata::HEADER_SIZE
|
||||
+ metadata::FOOTER_SIZE
|
||||
+ metadata::GROUP_BYTES as u64,
|
||||
"invalid sample part descriptor",
|
||||
tail_size
|
||||
<= (super::MANIFEST_LIMIT
|
||||
+ metadata::MAX_GROUPS * metadata::GROUP_BYTES
|
||||
+ metadata::TAIL_TRAILER_SIZE) as u64,
|
||||
"sample metadata tail exceeds limit",
|
||||
)?;
|
||||
if let Some(last) = previous {
|
||||
require(last <= part.first, "unordered sample parts")?;
|
||||
let path = location::narthex_part_path(prefix, index, "samples");
|
||||
let started = Instant::now();
|
||||
let reader = ObjectReader::open(
|
||||
cache,
|
||||
Some(&handle),
|
||||
crate::cache::file_cache::FileType::Samples(Some(part_id)),
|
||||
&store,
|
||||
&path,
|
||||
part.file_size,
|
||||
)
|
||||
.await?;
|
||||
metrics.add_elapsed("samples_part_reader", started.elapsed());
|
||||
let started = Instant::now();
|
||||
let tail = reader
|
||||
.read(start..part.file_size)
|
||||
.await
|
||||
.context(OpenDalSnafu)?;
|
||||
metrics.add_elapsed("samples_part_footer_read", started.elapsed());
|
||||
require(
|
||||
tail.len() as u64 == tail_size,
|
||||
"truncated sample metadata tail",
|
||||
)?;
|
||||
let started = Instant::now();
|
||||
let (directory, descriptor) = metadata::decode_part_tail(&tail)?;
|
||||
let directory_len = directory.len();
|
||||
let mut descriptor: Manifest = serde_json::from_slice(descriptor)
|
||||
.map_err(|error| invalid(format!("invalid sample tail descriptor: {error}")))?;
|
||||
// Copies retain the immutable file ID and may change the owning region.
|
||||
require(
|
||||
descriptor.format == ArtifactFormat::ColumnarSamples
|
||||
&& descriptor.identity_encoding == IdentityEncoding::CURRENT_SAMPLES
|
||||
&& descriptor.source_file_id == file.file_id
|
||||
&& descriptor.generation == file.file_id,
|
||||
"sample tail descriptor identity mismatch",
|
||||
)?;
|
||||
require(
|
||||
descriptor.files.len() == 1
|
||||
&& descriptor.files[0].part_id == part_id
|
||||
&& descriptor.files[0].num_rows >= descriptor.files[0].num_blocks
|
||||
&& descriptor.files[0].num_blocks > 0
|
||||
&& descriptor.files[0].min_timestamp <= descriptor.files[0].max_timestamp,
|
||||
"sample tail part inventory mismatch",
|
||||
)?;
|
||||
let expected = &descriptor.files[0];
|
||||
let directory =
|
||||
metadata::PartTailIndex::new(tail.slice(..directory_len), start, expected)?;
|
||||
let first = expected.first;
|
||||
if let Some(manifest) = &mut manifest {
|
||||
require(
|
||||
manifest.layout == descriptor.layout
|
||||
&& manifest.timestamp == descriptor.timestamp
|
||||
&& manifest.fields == descriptor.fields
|
||||
&& manifest
|
||||
.files
|
||||
.last()
|
||||
.is_some_and(|previous| previous.last <= first),
|
||||
"inconsistent sample part tails",
|
||||
)?;
|
||||
manifest.files.append(&mut descriptor.files);
|
||||
} else {
|
||||
descriptor.validate_schema()?;
|
||||
manifest = Some(descriptor);
|
||||
}
|
||||
previous = Some(part.last);
|
||||
directories.push(directory);
|
||||
readers.push(OnceCell::new_with(Some(reader)));
|
||||
metrics.add_elapsed("samples_part_index_decode", started.elapsed());
|
||||
}
|
||||
Ok(SamplesDescriptor {
|
||||
schema: manifest.schema(),
|
||||
manifest: Arc::new(manifest),
|
||||
})
|
||||
let manifest = manifest.ok_or_else(|| invalid("missing sample part tail"))?;
|
||||
Ok((
|
||||
SamplesDescriptor {
|
||||
inventory: samples.clone(),
|
||||
schema: manifest.schema(),
|
||||
manifest: Arc::new(manifest),
|
||||
tail_groups: Arc::new(directories),
|
||||
},
|
||||
Arc::new(readers),
|
||||
))
|
||||
}
|
||||
}
|
||||
impl SamplesFormatReader for SamplesReader {
|
||||
fn supports_page_batches(&self) -> bool {
|
||||
self.manifest.layout == SamplesLayout::ArrowIpc
|
||||
}
|
||||
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
@@ -355,18 +400,16 @@ impl SamplesFormatReader for SamplesReader {
|
||||
.is_none_or(|(start, end)| start <= end),
|
||||
"reversed sample time range",
|
||||
)?;
|
||||
let empty = request.keys.as_ref().is_some_and(|keys| keys.is_empty())
|
||||
|| request.start.zip(request.end).is_some_and(|(a, b)| a == b);
|
||||
let complete = request.keys.is_none()
|
||||
&& request.table_id.is_none()
|
||||
&& request.start.is_none()
|
||||
&& request.end.is_none();
|
||||
// Coarse pruning bounds come from the exact selection itself, so a reader can never
|
||||
// prune away a part or page that owns one of the selected series.
|
||||
let ids: Option<BTreeSet<MetricSeriesId>> = request
|
||||
let ids: Option<BTreeSet<_>> = request
|
||||
.keys
|
||||
.as_ref()
|
||||
.map(|keys| keys.iter().map(ExactSeriesKey::id).collect());
|
||||
let empty = ids.as_ref().is_some_and(BTreeSet::is_empty)
|
||||
|| request.start.zip(request.end).is_some_and(|(a, b)| a == b);
|
||||
let complete = ids.is_none()
|
||||
&& request.table_id.is_none()
|
||||
&& request.start.is_none()
|
||||
&& request.end.is_none();
|
||||
let projected = Arc::new(
|
||||
schema
|
||||
.project(&projection)
|
||||
@@ -382,13 +425,111 @@ impl SamplesFormatReader for SamplesReader {
|
||||
.collect();
|
||||
let cache = self.cache.clone();
|
||||
let manifest = self.manifest.clone();
|
||||
let location: Arc<str> = manifest.prefix.as_str().into();
|
||||
let prefix = self.prefix.clone();
|
||||
let store = self.store.clone();
|
||||
let handle = self.handle.clone();
|
||||
let parts = self.parts.clone();
|
||||
let tail_groups = self.tail_groups.clone();
|
||||
if manifest.layout == SamplesLayout::ArrowIpc {
|
||||
let disk_schema = ipc_pages::disk_schema(&schema);
|
||||
let page_schema = request
|
||||
.page_batches
|
||||
.then(|| ipc_pages::flat_page_schema(&projected));
|
||||
return Ok(Box::pin(async_stream::try_stream! {
|
||||
if empty { return; }
|
||||
let samples = samples_meta(&handle)?;
|
||||
let mut decoder = ipc_pages::Decoder::default();
|
||||
let consumer = |name| {
|
||||
request.memory_pool.as_ref().map(|pool| MemoryConsumer::new(name).register(pool))
|
||||
};
|
||||
let mut metrics = ColumnarReadMetrics::default();
|
||||
for part in &manifest.files {
|
||||
let bounds = Bounds { first: part.first, last: part.last, min: part.min_timestamp, max: part.max_timestamp };
|
||||
if !matches(bounds, &request, ids.as_ref()) { continue; }
|
||||
let path = location::narthex_part_path(&prefix, part.part_id as usize, "samples");
|
||||
let reader = parts[part.part_id as usize].get_or_try_init(|| async {
|
||||
let part_open_started = Instant::now();
|
||||
let result =
|
||||
ObjectReader::open(cache.as_ref(), Some(&handle), crate::cache::file_cache::FileType::Samples(Some(part.part_id)), &store, &path, samples.parts[part.part_id as usize].file_size).await;
|
||||
metrics.add_elapsed("samples_part_reader", part_open_started.elapsed());
|
||||
result
|
||||
}).await?;
|
||||
let reader = reader.clone().with_refill();
|
||||
let object = MetadataPart { samples_location: Some((handle.region_id(), prefix.clone())), generation: manifest.generation, part_id: part.part_id };
|
||||
let descriptor = part.clone();
|
||||
let point = ids.as_ref().filter(|ids| ids.len() == 1).and_then(|ids| ids.first()).copied();
|
||||
let groups = if let Some(id) = point {
|
||||
Arc::new(tail_groups[part.part_id as usize].point(id)?)
|
||||
} else {
|
||||
let tail_groups = tail_groups.clone();
|
||||
metadata_cache::load(
|
||||
cache.as_ref(), MetadataIdentity::SamplesDirectory(object),
|
||||
|groups: &Vec<metadata::Group>| groups.capacity() * std::mem::size_of::<metadata::Group>(),
|
||||
move || async move { tail_groups[descriptor.part_id as usize].all(&descriptor) },
|
||||
).await?
|
||||
};
|
||||
// A full sample scan can stream adjacent groups with one bounded read.
|
||||
// Keys-only discovery leaves samples on disk and uses group-local ranges.
|
||||
let read_ahead = complete
|
||||
&& projection.iter().any(|&column| column >= 2);
|
||||
let mut window = None;
|
||||
let window_reservation = consumer("Narthex IPC read-ahead");
|
||||
let mut window_offset = 0;
|
||||
let mut window_limit = 0;
|
||||
// Adjacent groups can share an exact-key boundary. Keep both
|
||||
// ends inclusive so we retain every fragment of a selected series.
|
||||
for (index, group) in groups.iter().enumerate() {
|
||||
if !matches(group.root.bounds, &request, ids.as_ref()) { continue; }
|
||||
if index >= window_limit {
|
||||
window = None;
|
||||
if let Some(reservation) = &window_reservation {
|
||||
reservation.free();
|
||||
}
|
||||
if read_ahead {
|
||||
let start = group.start;
|
||||
let cap = start.saturating_add(ipc_pages::MAX_COALESCED_GROUP);
|
||||
let mut limit = index;
|
||||
let mut end = start;
|
||||
for next in &groups[index..] {
|
||||
let next_end = next.root.payload.end()?;
|
||||
if next_end > cap { break; }
|
||||
limit += 1;
|
||||
end = next_end;
|
||||
}
|
||||
if limit > index + 1
|
||||
&& reserve_scan(window_reservation.as_ref(), (end - start) as usize).is_ok()
|
||||
{
|
||||
let started = Instant::now();
|
||||
let bytes = reader.read(start..end).await.context(OpenDalSnafu)?;
|
||||
require(bytes.len() as u64 == end - start, "truncated IPC group window")?;
|
||||
ipc_pages::record_group_io(&mut metrics, bytes.len(), started);
|
||||
*metrics.counts.entry("payload_reads").or_default() += 1;
|
||||
window = Some(bytes);
|
||||
window_offset = start;
|
||||
window_limit = limit;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The reservation follows the group through every yield.
|
||||
let reservation = consumer("Narthex IPC group");
|
||||
let prefetched = match &window {
|
||||
Some(bytes) => Some(bytes.slice(
|
||||
(group.start - window_offset) as usize
|
||||
..(group.root.payload.end()? - window_offset) as usize,
|
||||
)),
|
||||
None => None,
|
||||
};
|
||||
for batch in decoder.read_group(&reader, group, prefetched, &request, ids.as_ref(), &projection, projected.clone(), disk_schema.clone(), page_schema.as_ref(), &mut metrics, reservation.as_ref()).await? {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
Ok(Box::pin(async_stream::try_stream! {
|
||||
let mut metrics = ColumnarReadMetrics::default();
|
||||
if empty { return; }
|
||||
let samples = samples_meta(&handle)?;
|
||||
// One decoder and one scratch per stream, reused by every block. The decoder holds
|
||||
// the only zstd context this stream builds, and the scratch keeps its containers
|
||||
// instead of rebuilding them per block. Neither is shared with another stream.
|
||||
@@ -425,19 +566,19 @@ impl SamplesFormatReader for SamplesReader {
|
||||
for part in &manifest.files {
|
||||
let bounds = Bounds { first: part.first, last: part.last, min: part.min_timestamp, max: part.max_timestamp };
|
||||
if !matches(bounds, &request, ids.as_ref()) { adjacent = false; continue; }
|
||||
let path = manifest.part_path(part.part_id);
|
||||
let path = location::narthex_part_path(&prefix, part.part_id as usize, "samples");
|
||||
// One lazy reader per accessed part, shared across this query's streams.
|
||||
let reader = parts[part.part_id as usize].get_or_try_init(|| async {
|
||||
ObjectReader::open(cache.as_ref(), Some(&handle), crate::cache::file_cache::FileType::Samples(Some(part.part_id)), &store, &path, part.file_size).await
|
||||
ObjectReader::open(cache.as_ref(), Some(&handle), crate::cache::file_cache::FileType::Samples(Some(part.part_id)), &store, &path, samples.parts[part.part_id as usize].file_size).await
|
||||
}).await?;
|
||||
let object = MetadataPart { samples_location: Some((handle.region_id(), location.clone())), generation: manifest.generation, part_id: part.part_id };
|
||||
let object = MetadataPart { samples_location: Some((handle.region_id(), prefix.clone())), generation: manifest.generation, part_id: part.part_id };
|
||||
let metadata_started = Instant::now();
|
||||
let framing = reader.clone();
|
||||
let directories = tail_groups.clone();
|
||||
let descriptor = part.clone();
|
||||
let groups = metadata_cache::load(
|
||||
cache.as_ref(), MetadataIdentity::SamplesDirectory(object.clone()),
|
||||
|groups: &Vec<metadata::Group>| groups.capacity() * std::mem::size_of::<metadata::Group>(),
|
||||
move || async move { load_groups(&framing, &descriptor).await },
|
||||
move || async move { directories[descriptor.part_id as usize].all(&descriptor) },
|
||||
).await?;
|
||||
metrics.add_elapsed("columnar_metadata_wall", metadata_started.elapsed());
|
||||
for (index, group) in groups.iter().enumerate() {
|
||||
@@ -575,7 +716,7 @@ impl SamplesFormatReader for SamplesReader {
|
||||
*metrics.counts.entry("batches").or_default() += 1;
|
||||
*metrics.counts.entry("output_rows").or_default() += batch.num_rows() as u64;
|
||||
// The block's key is emitted once, not once per row.
|
||||
yield SamplesBatch { batch, key };
|
||||
yield SamplesBatch::Series { batch, key };
|
||||
}
|
||||
previous = Some(order); adjacent = true;
|
||||
}
|
||||
@@ -603,45 +744,6 @@ impl SamplesFormatReader for SamplesReader {
|
||||
}))
|
||||
}
|
||||
}
|
||||
/// Read one part directory. Authenticate its ranges and reconcile the aggregate
|
||||
/// bounds and counts with the manifest before pruning individual groups.
|
||||
async fn load_groups(reader: &ObjectReader, part: &super::Part) -> Result<Vec<metadata::Group>> {
|
||||
metadata::validate_header(
|
||||
&reader
|
||||
.read(0..metadata::HEADER_SIZE)
|
||||
.await
|
||||
.context(OpenDalSnafu)?,
|
||||
)?;
|
||||
let length = part.directory_bytes;
|
||||
require(
|
||||
length > 0
|
||||
&& length.is_multiple_of(metadata::GROUP_BYTES as u64)
|
||||
&& length <= (metadata::MAX_GROUPS * metadata::GROUP_BYTES) as u64,
|
||||
"invalid sample directory length",
|
||||
)?;
|
||||
let start = part
|
||||
.file_size
|
||||
.checked_sub(metadata::FOOTER_SIZE + length)
|
||||
.filter(|&n| n >= metadata::HEADER_SIZE)
|
||||
.ok_or_else(|| invalid("sample directory offset outside part"))?;
|
||||
let tail = reader
|
||||
.read(start..part.file_size)
|
||||
.await
|
||||
.context(OpenDalSnafu)?;
|
||||
require(
|
||||
tail.len() as u64 == part.file_size - start,
|
||||
"sample range length mismatch",
|
||||
)?;
|
||||
let (entries, footer) = tail.split_at(length as usize);
|
||||
let footer = metadata::DirectoryFooter::decode(footer)?;
|
||||
let groups = footer.groups(entries, start)?;
|
||||
require(
|
||||
&super::Part::from_groups(part.part_id, part.file_size, &groups)? == part,
|
||||
"sample directory/part inventory mismatch",
|
||||
)?;
|
||||
Ok(groups)
|
||||
}
|
||||
|
||||
/// Every block records the exact series key that owns its rows. A coarse identifier
|
||||
/// match is not ownership: a colliding partner shares the identifier.
|
||||
fn owns(key: &[u8], request: &SamplesReadRequest) -> bool {
|
||||
@@ -687,14 +789,14 @@ fn retain_boundary_key(
|
||||
if let Some(pool) = group_pool {
|
||||
pool.shrink(bytes);
|
||||
}
|
||||
reserve_keys(reservation, bytes)?;
|
||||
reserve_scan(reservation, bytes)?;
|
||||
*slot = Some(key.clone());
|
||||
*charged = bytes;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reserve_keys(reservation: Option<&MemoryReservation>, bytes: usize) -> Result<()> {
|
||||
pub(crate) fn reserve_scan(reservation: Option<&MemoryReservation>, bytes: usize) -> Result<()> {
|
||||
if let Some(reservation) = reservation {
|
||||
reservation
|
||||
.try_grow(bytes)
|
||||
@@ -723,7 +825,7 @@ impl GroupKeyReader {
|
||||
.checked_mul(4)
|
||||
.filter(|n| *n <= 8 * 1024 * 1024 && *n < group.key_end - group.payload_end)
|
||||
.ok_or_else(|| invalid("invalid key frame directory size"))?;
|
||||
reserve_keys(pool, (count as usize + 1) * 8 + bytes as usize)?;
|
||||
reserve_scan(pool, (count as usize + 1) * 8 + bytes as usize)?;
|
||||
let range = group.payload_end..group.payload_end + bytes;
|
||||
let directory = fetch_ranges(reader, std::slice::from_ref(&range), pool, metrics)
|
||||
.await?
|
||||
@@ -755,7 +857,7 @@ impl GroupKeyReader {
|
||||
let assembly_bytes = if spans_frames { length } else { 0 };
|
||||
let charge = retained_key_bytes(block.key.length) + assembly_bytes;
|
||||
if carried.is_none() {
|
||||
reserve_keys(pool, charge)?;
|
||||
reserve_scan(pool, charge)?;
|
||||
}
|
||||
if self.offsets.is_empty() {
|
||||
self.load_directory(reader, group, pool, metrics).await?;
|
||||
@@ -777,7 +879,7 @@ impl GroupKeyReader {
|
||||
(group.logical_key_end - group.payload_end - index as u64 * PAGE_BYTES as u64)
|
||||
.min(PAGE_BYTES as u64) as usize;
|
||||
let stored = (range.end - range.start) as usize;
|
||||
reserve_keys(
|
||||
reserve_scan(
|
||||
pool,
|
||||
if stored == decoded {
|
||||
stored
|
||||
@@ -811,7 +913,7 @@ impl GroupKeyReader {
|
||||
if let Some(prior) = matching
|
||||
&& prior.bytes()[consumed..consumed + take] != *slice
|
||||
{
|
||||
reserve_keys(pool, charge)?;
|
||||
reserve_scan(pool, charge)?;
|
||||
assembled.reserve_exact(assembly_bytes);
|
||||
assembled.extend_from_slice(&prior.bytes()[..consumed]);
|
||||
matching = None;
|
||||
|
||||
@@ -31,7 +31,7 @@ use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::{FileId, RegionId};
|
||||
|
||||
use super::metadata::{Bounds, FOOTER_SIZE, Group, HEADER_SIZE, Page, PayloadReference};
|
||||
use super::metadata::{Bounds, Group, HEADER_SIZE, Page, PayloadReference, TAIL_TRAILER_SIZE};
|
||||
use super::*;
|
||||
use crate::series_index::columnar::codec as columnar_codec;
|
||||
use crate::series_index::format::{
|
||||
@@ -39,8 +39,9 @@ use crate::series_index::format::{
|
||||
};
|
||||
use crate::series_index::identity::ExactSeriesKey;
|
||||
use crate::sst::file::{
|
||||
FileFormat, FileHandle, FileMeta, NarthexPartMeta, NarthexSamplesMeta, RegionFileId,
|
||||
FileFormat, FileHandle, FileMeta, NarthexSamplePartMeta, NarthexSamplesMeta, RegionFileId,
|
||||
};
|
||||
use crate::sst::location;
|
||||
use crate::test_util::new_noop_file_purger;
|
||||
use crate::test_util::sst_util::{new_sparse_primary_key, sst_region_metadata_with_encoding};
|
||||
|
||||
@@ -263,27 +264,27 @@ impl ColumnarSamplesFormat {
|
||||
|
||||
fn samples_handle(
|
||||
id: RegionFileId,
|
||||
manifest_size: u64,
|
||||
parts: impl Iterator<Item = u64>,
|
||||
parts: smallvec::SmallVec<[NarthexSamplePartMeta; 1]>,
|
||||
) -> FileHandle {
|
||||
let samples = NarthexSamplesMeta {
|
||||
manifest_size,
|
||||
parts: parts
|
||||
.map(|file_size| NarthexPartMeta { file_size })
|
||||
.collect(),
|
||||
};
|
||||
FileHandle::new(
|
||||
FileMeta {
|
||||
region_id: id.region_id(),
|
||||
file_id: id.file_id(),
|
||||
file_size: manifest_size + samples.parts.iter().map(|p| p.file_size).sum::<u64>(),
|
||||
format: FileFormat::NarthexSamples(Box::new(samples)),
|
||||
file_size: parts.iter().map(|p| p.file_size).sum(),
|
||||
format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta { parts })),
|
||||
..Default::default()
|
||||
},
|
||||
new_noop_file_purger(),
|
||||
)
|
||||
}
|
||||
|
||||
fn sample_parts(handle: &FileHandle) -> &smallvec::SmallVec<[NarthexSamplePartMeta; 1]> {
|
||||
match &handle.meta_ref().format {
|
||||
FileFormat::NarthexSamples(meta) => &meta.parts,
|
||||
_ => panic!("expected samples"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn build(
|
||||
format: &ColumnarSamplesFormat,
|
||||
store: &ObjectStore,
|
||||
@@ -299,11 +300,14 @@ async fn build(
|
||||
writer.write(batch).await.unwrap();
|
||||
}
|
||||
let artifact = writer.finish().await.unwrap();
|
||||
let (manifest, parts) = artifact.objects.split_first().unwrap();
|
||||
samples_handle(
|
||||
RegionFileId::new(meta.region_id, file_id),
|
||||
manifest.file_size,
|
||||
parts.iter().map(|part| part.file_size),
|
||||
artifact
|
||||
.objects
|
||||
.iter()
|
||||
.map(NarthexSamplePartMeta::try_from)
|
||||
.collect::<Result<_>>()
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -316,38 +320,46 @@ async fn upload_memory_part(
|
||||
part.upload(store, &prefix, region_id, None).await.unwrap();
|
||||
samples_handle(
|
||||
RegionFileId::new(region_id, part.file_id()),
|
||||
part.manifest().len() as u64,
|
||||
part.parts().iter().map(|p| p.len() as u64),
|
||||
part.parts()
|
||||
.iter()
|
||||
.map(NarthexSamplePartMeta::from)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Replaces a single part and updates the manifest and SST sizes to match.
|
||||
async fn rewrite_part(
|
||||
store: &ObjectStore,
|
||||
handle: FileHandle,
|
||||
manifest: Manifest,
|
||||
bytes: Vec<u8>,
|
||||
) -> FileHandle {
|
||||
rewrite_numbered_part(store, handle, manifest, 0, bytes).await
|
||||
fn part_tail_size(bytes: &[u8]) -> usize {
|
||||
let (index, descriptor) =
|
||||
metadata::decode_tail_trailer(&bytes[bytes.len() - TAIL_TRAILER_SIZE..]).unwrap();
|
||||
index as usize + descriptor as usize + TAIL_TRAILER_SIZE
|
||||
}
|
||||
|
||||
fn encode_tail(manifest: &Manifest, part: u32, groups: &[Group]) -> Vec<u8> {
|
||||
let mut descriptor = manifest.clone();
|
||||
descriptor.files = vec![manifest.files[part as usize].clone()];
|
||||
metadata::encode_part_tail(groups, &serde_json::to_vec(&descriptor).unwrap())
|
||||
}
|
||||
|
||||
/// Replaces a single part and updates its recorded sizes.
|
||||
async fn rewrite_part(store: &ObjectStore, handle: FileHandle, bytes: Vec<u8>) -> FileHandle {
|
||||
rewrite_numbered_part(store, handle, 0, bytes).await
|
||||
}
|
||||
|
||||
async fn rewrite_numbered_part(
|
||||
store: &ObjectStore,
|
||||
handle: FileHandle,
|
||||
mut manifest: Manifest,
|
||||
part: u32,
|
||||
bytes: Vec<u8>,
|
||||
) -> FileHandle {
|
||||
manifest.files[part as usize].file_size = bytes.len() as u64;
|
||||
store.write(&manifest.part_path(part), bytes).await.unwrap();
|
||||
let json = serde_json::to_vec(&manifest).unwrap();
|
||||
let manifest_size = json.len() as u64;
|
||||
store.write(&manifest.path(), json).await.unwrap();
|
||||
samples_handle(
|
||||
handle.file_id(),
|
||||
manifest_size,
|
||||
manifest.files.iter().map(|part| part.file_size),
|
||||
)
|
||||
let mut parts = sample_parts(&handle).clone();
|
||||
parts[part as usize] = NarthexSamplePartMeta {
|
||||
file_size: bytes.len() as u64,
|
||||
tail_size: part_tail_size(&bytes) as u64,
|
||||
};
|
||||
store
|
||||
.write(&sample_part_path(&handle, part), bytes)
|
||||
.await
|
||||
.unwrap();
|
||||
samples_handle(handle.file_id(), parts)
|
||||
}
|
||||
|
||||
/// Return the logical bytes indexed by descriptor offsets in this fixture.
|
||||
@@ -375,12 +387,9 @@ fn logical_key_area(group: &Group, bytes: &[u8]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn part_groups(bytes: &[u8]) -> Vec<Group> {
|
||||
let footer_start = bytes.len() - FOOTER_SIZE as usize;
|
||||
let footer = metadata::DirectoryFooter::decode(&bytes[footer_start..]).unwrap();
|
||||
let start = footer_start - footer.length as usize;
|
||||
footer
|
||||
.groups(&bytes[start..footer_start], start as u64)
|
||||
.unwrap()
|
||||
let start = bytes.len() - part_tail_size(bytes);
|
||||
let (directory, _) = metadata::decode_part_tail(&bytes[start..]).unwrap();
|
||||
metadata::decode_groups(directory, start as u64).unwrap()
|
||||
}
|
||||
|
||||
/// Reads the descriptor and root page of a one-part artifact, plus the part's bytes. Tests
|
||||
@@ -393,7 +402,7 @@ async fn root_page(store: &ObjectStore, handle: &FileHandle) -> (Manifest, Group
|
||||
"one part keeps the root page addressable"
|
||||
);
|
||||
let bytes = store
|
||||
.read(&manifest.part_path(0))
|
||||
.read(&sample_part_path(handle, 0))
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
@@ -413,13 +422,108 @@ async fn root_page(store: &ObjectStore, handle: &FileHandle) -> (Manifest, Group
|
||||
(manifest, trailer, page, bytes)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_sample_tails_resolve_parts_in_the_current_directory() {
|
||||
let store = store();
|
||||
let meta = metadata();
|
||||
let rows = [(1, 1, 0, 1, 1, Some(42))];
|
||||
let handle = build(
|
||||
&ColumnarSamplesFormat::default(),
|
||||
&store,
|
||||
meta.clone(),
|
||||
&[batch(&meta, &rows, true)],
|
||||
)
|
||||
.await;
|
||||
let strategy = crate::cache::CacheStrategy::EnableAll(Arc::new(
|
||||
crate::cache::CacheManager::builder()
|
||||
.sst_meta_cache_size(1024 * 1024)
|
||||
.build(),
|
||||
));
|
||||
reader::SamplesReader::open_cached(
|
||||
store.clone(),
|
||||
handle.clone(),
|
||||
REGION_DIR,
|
||||
strategy.columnar_metadata(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let source = sample_part_path(&handle, 0);
|
||||
let other_dir = "other-region/";
|
||||
let target = location::narthex_part_path(
|
||||
&location::narthex_file_dir(other_dir, handle.meta_ref().file_id),
|
||||
0,
|
||||
"samples",
|
||||
);
|
||||
store
|
||||
.write(&target, store.read(&source).await.unwrap().to_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
store.delete(&source).await.unwrap();
|
||||
|
||||
let reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let observed = reads.clone();
|
||||
let store = store.layer(
|
||||
MockLayerBuilder::default()
|
||||
.reader_factory(Arc::new(move |path, _, inner| {
|
||||
Box::new(RecordingRead {
|
||||
inner,
|
||||
path: path.into(),
|
||||
reads: observed.clone(),
|
||||
})
|
||||
}))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let reader =
|
||||
reader::SamplesReader::open_cached(store, handle, other_dir, strategy.columnar_metadata())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
reads.lock().unwrap().is_empty(),
|
||||
"the tail should come from cache"
|
||||
);
|
||||
let batches = reader
|
||||
.read(full_request())
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows.as_slice(), collect_rows(&batches));
|
||||
assert!(
|
||||
reads
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|(path, _)| path == &target)
|
||||
);
|
||||
}
|
||||
|
||||
fn sample_part_path(handle: &FileHandle, part: u32) -> String {
|
||||
let prefix = location::narthex_file_dir(REGION_DIR, handle.meta_ref().file_id);
|
||||
location::narthex_part_path(&prefix, part as usize, "samples")
|
||||
}
|
||||
|
||||
async fn manifest(store: &ObjectStore, handle: &FileHandle) -> Manifest {
|
||||
let prefix = location::narthex_file_dir(REGION_DIR, handle.meta_ref().file_id);
|
||||
let path = location::narthex_manifest_path(&prefix);
|
||||
let mut manifest: Manifest =
|
||||
serde_json::from_slice(&store.read(&path).await.unwrap().to_bytes()).unwrap();
|
||||
manifest.prefix = prefix;
|
||||
manifest
|
||||
let mut result: Option<Manifest> = None;
|
||||
for (index, part) in sample_parts(handle).iter().enumerate() {
|
||||
let path = location::narthex_part_path(&prefix, index, "samples");
|
||||
let bytes = store
|
||||
.read_with(&path)
|
||||
.range(part.file_size - part.tail_size..part.file_size)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes();
|
||||
let (_, json) = metadata::decode_part_tail(&bytes).unwrap();
|
||||
let mut descriptor: Manifest = serde_json::from_slice(json).unwrap();
|
||||
if let Some(result) = &mut result {
|
||||
result.files.append(&mut descriptor.files);
|
||||
} else {
|
||||
result = Some(descriptor);
|
||||
}
|
||||
}
|
||||
result.unwrap()
|
||||
}
|
||||
fn request(names: &[&str]) -> SamplesReadRequest {
|
||||
SamplesReadRequest {
|
||||
@@ -631,7 +735,11 @@ async fn equal_timestamps_cross_leaves_and_parts() {
|
||||
let handle = build(&format, &store, m.clone(), &[batch(&m, &rows, true)]).await;
|
||||
let manifest = manifest(&store, &handle).await;
|
||||
assert!(manifest.files.len() >= 2);
|
||||
let first = store.read(&manifest.part_path(0)).await.unwrap().to_bytes();
|
||||
let first = store
|
||||
.read(&sample_part_path(&handle, 0))
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes();
|
||||
let groups = part_groups(&first);
|
||||
assert!(groups.len() >= 2);
|
||||
assert_eq!(groups[0].depth, 2);
|
||||
@@ -738,11 +846,17 @@ async fn long_keys_round_trip() {
|
||||
/// The captured pair in the samples artifact: two distinct series with one
|
||||
/// `table_id`/`tsid` whose timestamps restart. Every block records which exact key
|
||||
/// owns it, so each series keeps its own samples and never sees the partner's.
|
||||
#[rstest::rstest]
|
||||
#[case::grouped(false)]
|
||||
#[case::ipc(true)]
|
||||
#[tokio::test]
|
||||
async fn colliding_tsids_are_retained_and_owned_exactly() {
|
||||
async fn colliding_tsids_are_retained_and_owned_exactly(#[case] ipc_pages: bool) {
|
||||
let store = store();
|
||||
let meta = metadata();
|
||||
let format = ColumnarSamplesFormat::default();
|
||||
let format = ColumnarSamplesFormat {
|
||||
ipc_pages,
|
||||
..Default::default()
|
||||
};
|
||||
let first = new_sparse_primary_key(&["host-020078", "z"], &meta, 1, 7);
|
||||
let partner = new_sparse_primary_key(&["host-029838", "z"], &meta, 1, 7);
|
||||
for dictionary in [false, true] {
|
||||
@@ -952,22 +1066,22 @@ async fn empty_selection_and_validation() {
|
||||
let store = store();
|
||||
let m = metadata();
|
||||
let format = ColumnarSamplesFormat::default();
|
||||
let handle = build(&format, &store, m, &[]).await;
|
||||
assert!(manifest(&store, &handle).await.files.is_empty());
|
||||
assert_eq!(
|
||||
handle.meta_ref().narthex_objects(REGION_DIR).unwrap().len(),
|
||||
1
|
||||
);
|
||||
let reader = format.reader(store, handle).await.unwrap();
|
||||
let empty = build(&format, &store, m.clone(), &[]).await;
|
||||
assert!(
|
||||
reader
|
||||
.read(full_request())
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
empty
|
||||
.meta_ref()
|
||||
.narthex_objects(REGION_DIR)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
let handle = build(
|
||||
&format,
|
||||
&store,
|
||||
m.clone(),
|
||||
&[batch(&m, &[(1, 1, 0, 1, 1, Some(42))], false)],
|
||||
)
|
||||
.await;
|
||||
let reader = format.reader(store, handle).await.unwrap();
|
||||
assert!(reader.read(request(&["unknown"])).is_err());
|
||||
assert!(reader.read(request(&["ts", "ts"])).is_err());
|
||||
let mut req = request(&[]);
|
||||
@@ -1091,7 +1205,7 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
};
|
||||
let manifest = manifest(&store, &handle).await;
|
||||
assert_eq!(1, manifest.files.len());
|
||||
let path = manifest.part_path(0);
|
||||
let path = sample_part_path(&handle, 0);
|
||||
let bytes = store.read(&path).await.unwrap().to_bytes();
|
||||
let groups = part_groups(&bytes);
|
||||
assert_eq!(4, groups.len());
|
||||
@@ -1121,7 +1235,7 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(batches.len(), 1);
|
||||
assert_eq!(batches[0].key, selected);
|
||||
assert_eq!(batches[0].key(), &selected);
|
||||
let rows = collect_rows(&batches);
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].2, 50);
|
||||
@@ -1179,11 +1293,10 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// Queue a manifest download behind any part refill. Once the FIFO worker reaches
|
||||
// the manifest, a part refill triggered by the pruned read would already be visible.
|
||||
// Queue an independent download behind any part refill so we can observe the FIFO worker.
|
||||
use crate::cache::file_cache::{FileType, IndexKey};
|
||||
let disk = write_cache.file_cache();
|
||||
let manifest_key = IndexKey::new(
|
||||
let barrier_key = IndexKey::new(
|
||||
handle.region_id(),
|
||||
FileId::random(),
|
||||
FileType::Samples(None),
|
||||
@@ -1192,14 +1305,14 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
unreachable!()
|
||||
};
|
||||
disk.queue_download(
|
||||
manifest_key,
|
||||
manifest.path(),
|
||||
barrier_key,
|
||||
path.clone(),
|
||||
store.clone(),
|
||||
meta.manifest_size,
|
||||
meta.parts[0].file_size,
|
||||
Some(handle.clone()),
|
||||
);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while !disk.contains_key(&manifest_key) {
|
||||
while !disk.contains_key(&barrier_key) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
@@ -1211,32 +1324,28 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
FileType::Samples(Some(0))
|
||||
)));
|
||||
|
||||
let mut conflict = handle.meta_ref().clone();
|
||||
conflict.file_size += 1;
|
||||
let bad_size = FileHandle::new(conflict, new_noop_file_purger());
|
||||
assert!(
|
||||
reader::SamplesReader::open_cached(
|
||||
store.clone(),
|
||||
bad_size,
|
||||
REGION_DIR,
|
||||
strategy.columnar_metadata()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let mut conflict = handle.meta_ref().clone();
|
||||
conflict.region_id = store_api::storage::RegionId::from_u64(conflict.region_id.as_u64() + 1);
|
||||
let bad_owner = FileHandle::new(conflict, new_noop_file_purger());
|
||||
assert!(
|
||||
reader::SamplesReader::open_cached(
|
||||
store.clone(),
|
||||
bad_owner,
|
||||
REGION_DIR,
|
||||
strategy.columnar_metadata()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
for change_tail_size in [false, true] {
|
||||
let mut conflict = handle.meta_ref().clone();
|
||||
if change_tail_size {
|
||||
let FileFormat::NarthexSamples(samples) = &mut conflict.format else {
|
||||
unreachable!()
|
||||
};
|
||||
samples.parts[0].tail_size += 1;
|
||||
} else {
|
||||
conflict.file_size += 1;
|
||||
}
|
||||
let bad_size = FileHandle::new(conflict, new_noop_file_purger());
|
||||
assert!(
|
||||
reader::SamplesReader::open_cached(
|
||||
store.clone(),
|
||||
bad_size,
|
||||
REGION_DIR,
|
||||
strategy.columnar_metadata()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let expected = format
|
||||
.reader(store.clone(), handle.clone())
|
||||
.await
|
||||
@@ -1263,8 +1372,8 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
.unwrap();
|
||||
assert_eq!(collect_rows(&actual), collect_rows(&expected));
|
||||
assert_eq!(
|
||||
actual.iter().map(|b| &b.key).collect::<Vec<_>>(),
|
||||
expected.iter().map(|b| &b.key).collect::<Vec<_>>()
|
||||
actual.iter().map(|b| b.key()).collect::<Vec<_>>(),
|
||||
expected.iter().map(|b| b.key()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1273,7 +1382,7 @@ async fn group_pruning_preserves_colliding_keys_and_skips_unselected_ranges(#[ca
|
||||
let mut bad = groups;
|
||||
bad[1].payload_end = bad[0].payload_end;
|
||||
let mut rewritten = bytes[..directory_start].to_vec();
|
||||
rewritten.extend(metadata::encode_directory(&bad));
|
||||
rewritten.extend(encode_tail(&manifest, 0, &bad));
|
||||
store.write(&path, rewritten).await.unwrap();
|
||||
let reader = format.reader(store, handle).await.unwrap();
|
||||
let err = reader
|
||||
@@ -1316,11 +1425,11 @@ async fn selective_reads_pin_the_artifact() {
|
||||
}))
|
||||
.build()
|
||||
.unwrap();
|
||||
let tail_size = sample_parts(&handle)[0].tail_size;
|
||||
let reader = format
|
||||
.reader(store.layer(layer), handle.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
reads.lock().unwrap().clear();
|
||||
let mut req = request(&["field_0"]);
|
||||
req.table_id = Some(2);
|
||||
let stream = reader.read(req).unwrap();
|
||||
@@ -1331,14 +1440,13 @@ async fn selective_reads_pin_the_artifact() {
|
||||
let result = stream.try_collect::<Vec<_>>().await.unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0].column(0).null_count(), 1);
|
||||
// Header, footer, directory, one leaf/root, and the selected block's key from the key area. The
|
||||
// all-null projected field has no payload.
|
||||
// One tail, one leaf/root and the selected key frame. The all-null field has no payload.
|
||||
let reads = reads.lock().unwrap();
|
||||
assert_eq!(reads.len(), 5);
|
||||
assert_eq!(reads.len(), 4);
|
||||
assert!(
|
||||
reads
|
||||
.iter()
|
||||
.any(|(_, range)| range.size() == Some(metadata::GROUP_BYTES as u64 + FOOTER_SIZE)),
|
||||
.any(|(_, range)| range.size() == Some(tail_size)),
|
||||
"the cold scan must fetch the directory and footer together"
|
||||
);
|
||||
}
|
||||
@@ -1404,7 +1512,7 @@ async fn malformed_framing_and_payload_corruption() {
|
||||
)
|
||||
.await;
|
||||
let manifest = manifest(&store, &handle).await;
|
||||
let path = manifest.part_path(0);
|
||||
let path = sample_part_path(&handle, 0);
|
||||
let original = store.read(&path).await.unwrap().to_vec();
|
||||
let trailer = part_groups(&original).remove(0);
|
||||
let end = trailer.root.payload.end().unwrap() as usize;
|
||||
@@ -1412,14 +1520,9 @@ async fn malformed_framing_and_payload_corruption() {
|
||||
let mut bad = trailer.clone();
|
||||
bad.root.payload.encoding = encoding;
|
||||
bad.root.payload.compression = compression;
|
||||
let directory = metadata::encode_directory(&[bad]);
|
||||
let (entries, footer) = directory.split_at(metadata::GROUP_BYTES);
|
||||
assert!(
|
||||
metadata::DirectoryFooter::decode(footer)
|
||||
.unwrap()
|
||||
.groups(entries, end as u64)
|
||||
.is_err()
|
||||
);
|
||||
let tail = encode_tail(&manifest, 0, &[bad]);
|
||||
let (entries, _) = metadata::decode_part_tail(&tail).unwrap();
|
||||
assert!(metadata::decode_groups(entries, end as u64).is_err());
|
||||
}
|
||||
let decoded = trailer
|
||||
.root
|
||||
@@ -1451,18 +1554,20 @@ async fn malformed_framing_and_payload_corruption() {
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
for offset in [0, end + 64, original.len() - 8] {
|
||||
for offset in [
|
||||
end + 64,
|
||||
original.len() - TAIL_TRAILER_SIZE,
|
||||
original.len() - 8,
|
||||
] {
|
||||
let mut bad = original.clone();
|
||||
bad[offset] ^= 3;
|
||||
store.write(&path, bad).await.unwrap();
|
||||
assert!(
|
||||
reader
|
||||
.read(full_request())
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let result = async {
|
||||
let reader = format.reader(store.clone(), handle.clone()).await?;
|
||||
reader.read(full_request())?.try_collect::<Vec<_>>().await
|
||||
}
|
||||
.await;
|
||||
assert!(result.is_err());
|
||||
}
|
||||
for length in 0..decoded.len() {
|
||||
assert!(
|
||||
@@ -1485,60 +1590,6 @@ async fn malformed_framing_and_payload_corruption() {
|
||||
assert!(format.reader(store, bad).await.is_err());
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct FrozenV1Manifest {
|
||||
region_id: u64,
|
||||
source_file_id: FileId,
|
||||
}
|
||||
|
||||
async fn frozen_v1_handle(store: &ObjectStore) -> FileHandle {
|
||||
let bytes =
|
||||
include_str!("../../../../../tests/compatibility/wire/mito_columnar_samples/v1-part.hex")
|
||||
.split_whitespace()
|
||||
.collect::<String>();
|
||||
let bytes = (0..bytes.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&bytes[i..i + 2], 16).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
let json = include_str!(
|
||||
"../../../../../tests/compatibility/wire/mito_columnar_samples/v1-manifest.json"
|
||||
);
|
||||
let frozen: FrozenV1Manifest = serde_json::from_str(json).unwrap();
|
||||
let prefix = location::narthex_file_dir(REGION_DIR, frozen.source_file_id);
|
||||
let manifest_path = location::narthex_manifest_path(&prefix);
|
||||
let part_path = format!("{prefix}part-0.samples");
|
||||
let part_size = bytes.len() as u64;
|
||||
store.write(&part_path, bytes).await.unwrap();
|
||||
store.write(&manifest_path, json).await.unwrap();
|
||||
samples_handle(
|
||||
RegionFileId::new(
|
||||
store_api::storage::RegionId::from_u64(frozen.region_id),
|
||||
frozen.source_file_id,
|
||||
),
|
||||
json.len() as u64,
|
||||
std::iter::once(part_size),
|
||||
)
|
||||
}
|
||||
|
||||
/// A frozen artifact written under hash-only identity must be rejected, never read:
|
||||
/// it is structurally valid and ordered, so nothing else distinguishes it, and the
|
||||
/// labels a collapsed block lost cannot be recovered from it.
|
||||
#[tokio::test]
|
||||
async fn frozen_v1_samples_fixture_is_rejected() {
|
||||
let store = store();
|
||||
let handle = frozen_v1_handle(&store).await;
|
||||
let format = ColumnarSamplesFormat::default();
|
||||
let error = format
|
||||
.reader(store.clone(), handle)
|
||||
.await
|
||||
.err()
|
||||
.expect("a v1 samples artifact must be rejected");
|
||||
// The compatibility property, not the wording of the discriminator: the artifact is
|
||||
// refused, and the remedy the caller is told about is a rebuild.
|
||||
let message = error.to_string();
|
||||
assert!(message.contains("rebuild"), "{message}");
|
||||
}
|
||||
|
||||
/// Rewrites the stored root page so every field column carries an unknown codec, and returns a
|
||||
/// handle whose descriptor sizes match the rewritten bytes. Everything else stays valid.
|
||||
async fn unknown_field_codec(store: &ObjectStore, handle: FileHandle) -> FileHandle {
|
||||
@@ -1567,8 +1618,8 @@ async fn unknown_field_codec(store: &ObjectStore, handle: FileHandle) -> FileHan
|
||||
};
|
||||
// The payload area ends where the pages begin, so only the page's own reference and the
|
||||
// file length change.
|
||||
bytes.extend_from_slice(&metadata::encode_directory(&[trailer]));
|
||||
rewrite_part(store, handle, manifest, bytes).await
|
||||
bytes.extend_from_slice(&encode_tail(&manifest, 0, &[trailer]));
|
||||
rewrite_part(store, handle, bytes).await
|
||||
}
|
||||
|
||||
/// A column whose codec the format does not know can only be skipped: a query that does not
|
||||
@@ -1715,8 +1766,11 @@ impl mock::Write for FaultyWriter {
|
||||
#[tokio::test]
|
||||
async fn output_failures_and_cancelled_finish_clean_up(#[values(false, true)] direct: bool) {
|
||||
let m = metadata();
|
||||
let format = ColumnarSamplesFormat::default();
|
||||
for (manifest_only, fail_write, cancel) in [
|
||||
let format = ColumnarSamplesFormat {
|
||||
part_bytes: 1,
|
||||
..Default::default()
|
||||
};
|
||||
for (second_part_only, fail_write, cancel) in [
|
||||
(false, true, false),
|
||||
(false, false, false),
|
||||
(true, false, false),
|
||||
@@ -1728,7 +1782,7 @@ async fn output_failures_and_cancelled_finish_clean_up(#[values(false, true)] di
|
||||
let observed = closing.clone();
|
||||
let layer = MockLayerBuilder::default()
|
||||
.writer_factory(Arc::new(move |path, _, inner| {
|
||||
if !manifest_only || path.ends_with("manifest.json") {
|
||||
if !second_part_only || path.ends_with("part-1.samples") {
|
||||
Box::new(FaultyWriter {
|
||||
inner,
|
||||
fail_write,
|
||||
@@ -1830,6 +1884,7 @@ async fn batches_column_io_reuses_readers_and_releases_reservations() {
|
||||
unreachable!()
|
||||
};
|
||||
let part_size = samples.parts[0].file_size;
|
||||
let tail_size = samples.parts[0].tail_size;
|
||||
let reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let creations = Arc::new(AtomicUsize::new(0));
|
||||
let observed = reads.clone();
|
||||
@@ -1865,11 +1920,10 @@ async fn batches_column_io_reuses_readers_and_releases_reservations() {
|
||||
assert_eq!(1, creations.load(Ordering::Relaxed));
|
||||
{
|
||||
let reads = reads.lock().unwrap();
|
||||
// Each stream reads framing/root, one payload read across both blocks, and the part's
|
||||
// exact keys from the key area.
|
||||
assert_eq!(12, reads.len());
|
||||
// Both streams reuse the tail, then read the root, payload, and key frames.
|
||||
assert_eq!(8, reads.len());
|
||||
assert_eq!(
|
||||
2 * part_size,
|
||||
2 * (part_size - HEADER_SIZE - tail_size),
|
||||
reads
|
||||
.iter()
|
||||
.map(|(_, range)| range.size().unwrap())
|
||||
@@ -1971,15 +2025,14 @@ async fn boundary_blocks_fetch_remaining_columns_only_for_selected_rows() {
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(batches.is_empty());
|
||||
assert_eq!(1, creations.load(Ordering::Relaxed));
|
||||
assert_eq!(2, creations.load(Ordering::Relaxed));
|
||||
// Anchor the timestamp read by provenance rather than by position: the timestamp chunk is
|
||||
// the first chunk of a part, so its read starts at the payload header. Positional indexing
|
||||
// would silently point at the key-area read instead.
|
||||
let timestamp_read = {
|
||||
let reads = reads.lock().unwrap();
|
||||
// Header, footer, directory, root, the selected block's key, then timestamps only. The other part
|
||||
// is pruned.
|
||||
assert_eq!(6, reads.len());
|
||||
// Only the first part reads its root, key frames, and timestamps.
|
||||
assert_eq!(4, reads.len());
|
||||
reads
|
||||
.iter()
|
||||
.find(|(_, range)| range.offset() == HEADER_SIZE)
|
||||
@@ -2000,9 +2053,8 @@ async fn boundary_blocks_fetch_remaining_columns_only_for_selected_rows() {
|
||||
assert_eq!(input[1..5], collect_rows(&batches));
|
||||
assert_eq!(2, creations.load(Ordering::Relaxed));
|
||||
let reads = reads.lock().unwrap();
|
||||
// Both boundary blocks read timestamps before fetching remaining columns, and each part
|
||||
// reads its own directory and keys.
|
||||
assert_eq!(14, reads.len());
|
||||
// Both boundary blocks read timestamps before fetching remaining columns.
|
||||
assert_eq!(10, reads.len());
|
||||
assert_eq!(
|
||||
Some(×tamp_read),
|
||||
reads
|
||||
@@ -2050,11 +2102,8 @@ async fn series_read_windows_are_bounded_and_gap_rows_are_not_returned() {
|
||||
assert_eq!(input, collect_rows(&all));
|
||||
let (full_bytes, first_window_bytes) = {
|
||||
let reads = reads.lock().unwrap();
|
||||
// Header, footer, directory, root (one leaf: a fixed 56-byte descriptor no longer carries the
|
||||
// series key, so this fixture's 260 blocks fit one page where a key-carrying descriptor
|
||||
// needed two), three windows of at most 128 blocks, and one merged key read for the
|
||||
// page's selected keys.
|
||||
assert_eq!(8, reads.len());
|
||||
// One root, three payload windows, and the selected keys. The tail was read at open.
|
||||
assert_eq!(6, reads.len());
|
||||
// The initial read-ahead window is the first read of block 0's first column: it starts
|
||||
// at the payload header, while the header, trailer, and page reads do not. Anchor on
|
||||
// that range rather than on an index so a reordered traversal cannot point the
|
||||
@@ -2117,7 +2166,7 @@ async fn series_read_windows_are_bounded_and_gap_rows_are_not_returned() {
|
||||
assert_eq!(vec![input[0], input[2]], collect_rows(&selected));
|
||||
// The intervening series is read as a gap, but never decoded or returned: only the
|
||||
// leaf that owns both selected blocks and one payload window are fetched.
|
||||
assert_eq!(6, reads.lock().unwrap().len());
|
||||
assert_eq!(4, reads.lock().unwrap().len());
|
||||
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};
|
||||
// The first pool rejects read-ahead outright. The second admits the first 128-block,
|
||||
@@ -2325,12 +2374,12 @@ async fn exact_key_is_emitted_once_per_batch() {
|
||||
.unwrap();
|
||||
assert_eq!(8192, batches.iter().map(|b| b.num_rows()).sum::<usize>());
|
||||
let expected = exact(&m, &[label.as_str(), "z"], 1, 7);
|
||||
assert!(batches.iter().all(|batch| batch.key == expected));
|
||||
assert!(batches.iter().all(|batch| batch.key() == &expected));
|
||||
// The key is the batch's, not a column: the artifact schema keeps it, output batches do not.
|
||||
assert!(
|
||||
batches
|
||||
.iter()
|
||||
.all(|batch| batch.batch.column_by_name(PRIMARY_KEY).is_none())
|
||||
.all(|batch| batch.column_by_name(PRIMARY_KEY).is_none())
|
||||
);
|
||||
assert_eq!(0, pool.reserved());
|
||||
}
|
||||
@@ -2718,7 +2767,7 @@ async fn narthex_prepared_discovery_empty_projection_skips_payload() {
|
||||
2,
|
||||
discovered
|
||||
.iter()
|
||||
.map(|batch| &batch.key)
|
||||
.map(|batch| batch.key())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len()
|
||||
);
|
||||
@@ -2736,8 +2785,11 @@ async fn narthex_prepared_discovery_empty_projection_skips_payload() {
|
||||
/// Native histogram fields round-trip through an artifact. A block ends before its histogram
|
||||
/// chunk would outgrow the chunk limit, and the stored chunk is only readable as the field type
|
||||
/// the manifest records.
|
||||
#[rstest::rstest]
|
||||
#[case::series_blocks(false)]
|
||||
#[case::ipc_retry(true)]
|
||||
#[tokio::test]
|
||||
async fn native_histogram_fields_round_trip_and_split_by_chunk_limit() {
|
||||
async fn native_histogram_fields_round_trip_and_split_by_chunk_limit(#[case] ipc_pages: bool) {
|
||||
use datatypes::arrow::compute::concat;
|
||||
|
||||
use super::histogram::tests::{TestHistogram, fixture, histogram_array};
|
||||
@@ -2802,6 +2854,71 @@ async fn native_histogram_fields_round_trip_and_split_by_chunk_limit() {
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
if ipc_pages {
|
||||
let store = store();
|
||||
let format = ColumnarSamplesFormat {
|
||||
ipc_pages: true,
|
||||
..Default::default()
|
||||
};
|
||||
let file_id = FileId::random();
|
||||
let prefix = location::narthex_file_dir(REGION_DIR, file_id);
|
||||
let mut writer = writer::SamplesWriter::new(
|
||||
format.clone(),
|
||||
m.clone(),
|
||||
store.clone(),
|
||||
&prefix,
|
||||
file_id,
|
||||
file_id,
|
||||
)
|
||||
.unwrap();
|
||||
// The first attempt crosses the series boundary and exceeds the cap.
|
||||
// Each individual row fits, so nothing should be lost during retry.
|
||||
writer.set_ipc_sample_bytes_limit(256 * 1024);
|
||||
writer.write(&input).await.unwrap();
|
||||
let artifact = Box::new(writer).finish().await.unwrap();
|
||||
let handle = samples_handle(
|
||||
RegionFileId::new(m.region_id, file_id),
|
||||
artifact
|
||||
.objects
|
||||
.iter()
|
||||
.map(NarthexSamplePartMeta::try_from)
|
||||
.collect::<Result<_>>()
|
||||
.unwrap(),
|
||||
);
|
||||
let bytes = store
|
||||
.read(&sample_part_path(&handle, 0))
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
assert!(part_groups(&bytes).len() > 1);
|
||||
let batches = format
|
||||
.reader(store, handle)
|
||||
.await
|
||||
.unwrap()
|
||||
.read(request(&["field_0", "ts"]))
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let decoded = concat(
|
||||
&batches
|
||||
.iter()
|
||||
.map(|batch| batch.column(0).as_ref())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(&values, &decoded);
|
||||
let decoded_time = concat(
|
||||
&batches
|
||||
.iter()
|
||||
.map(|batch| batch.column(1).as_ref())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(input.column_by_name("ts").unwrap(), &decoded_time);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut bulk = super::writer::SamplesWriter::memory(m.clone(), Default::default()).unwrap();
|
||||
bulk.push_memory(&input).unwrap();
|
||||
let encoded = bulk.finish_memory().unwrap();
|
||||
@@ -2853,13 +2970,15 @@ async fn native_histogram_fields_round_trip_and_split_by_chunk_limit() {
|
||||
|
||||
let mut stored = manifest(&store, &handle).await;
|
||||
stored.fields[0].data_type = FLOAT64_TYPE.to_string();
|
||||
let json = serde_json::to_vec(&stored).unwrap();
|
||||
store.write(&stored.path(), json.clone()).await.unwrap();
|
||||
let handle = samples_handle(
|
||||
handle.file_id(),
|
||||
json.len() as u64,
|
||||
stored.files.iter().map(|part| part.file_size),
|
||||
);
|
||||
let bytes = store
|
||||
.read(&sample_part_path(&handle, 0))
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
let groups = part_groups(&bytes);
|
||||
let mut rewritten = bytes[..bytes.len() - part_tail_size(&bytes)].to_vec();
|
||||
rewritten.extend(encode_tail(&stored, 0, &groups));
|
||||
let handle = rewrite_part(&store, handle, rewritten).await;
|
||||
let error = read(handle).await.unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("does not match its field type"),
|
||||
@@ -3027,6 +3146,145 @@ async fn samples_preserve_opaque_label_suffix() {
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(batches[0].key.bytes(), key);
|
||||
assert_eq!(batches[0].key().bytes(), key);
|
||||
assert!(ExactSeriesKey::from_prevalidated_sparse_key(&key[..21]).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ipc_pages_round_trip_with_series_spanning_parts() {
|
||||
let store = store();
|
||||
let meta = metadata();
|
||||
let format = ColumnarSamplesFormat {
|
||||
ipc_pages: true,
|
||||
part_bytes: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let mut rows: Vec<_> = (0..1100)
|
||||
.map(|i| (1, 7, i, 2, (i % 2) as u8, (i % 3 != 0).then_some(i as u64)))
|
||||
.collect();
|
||||
rows.push((1, 8, 0, 1, 0, Some(99)));
|
||||
let handle = build(&format, &store, meta.clone(), &[batch(&meta, &rows, true)]).await;
|
||||
let objects = handle.meta_ref().narthex_objects(REGION_DIR).unwrap();
|
||||
assert_eq!(2, objects.len());
|
||||
let reader = format.reader(store, handle).await.unwrap();
|
||||
let batches = reader
|
||||
.read(full_request())
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_rows(&batches), rows);
|
||||
let request = SamplesReadRequest {
|
||||
keys: Some(std::collections::BTreeSet::from([batches[0].key().clone()])),
|
||||
start: Some(1023),
|
||||
end: Some(1025),
|
||||
..full_request()
|
||||
};
|
||||
let filtered = reader
|
||||
.read(request)
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_rows(&filtered), rows[1023..1025]);
|
||||
|
||||
let pages = reader
|
||||
.read(SamplesReadRequest {
|
||||
page_batches: true,
|
||||
..full_request()
|
||||
})
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_rows(&pages), rows);
|
||||
assert!(
|
||||
pages
|
||||
.iter()
|
||||
.all(|batch| matches!(batch, SamplesBatch::Page(_)))
|
||||
);
|
||||
}
|
||||
|
||||
/// Exercise the production writer at the cutoff with a series split between batches.
|
||||
#[tokio::test]
|
||||
async fn streamed_sst_selects_ipc_at_short_series_cutoff() {
|
||||
use crate::access_layer::{AccessLayer, Metrics, OperationType, SstWriteRequest, WriteType};
|
||||
use crate::cache::CacheManager;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::parquet::WriteOptions;
|
||||
use crate::test_util::TestEnv;
|
||||
use crate::test_util::sst_util::new_flat_source_from_record_batches;
|
||||
use store_api::region_request::PathType;
|
||||
|
||||
let mut env = TestEnv::new().await;
|
||||
let access_layer = AccessLayer::new(
|
||||
"test",
|
||||
PathType::Bare,
|
||||
env.init_object_store_manager(),
|
||||
env.get_puffin_manager(),
|
||||
env.get_intermediate_manager(),
|
||||
);
|
||||
let metadata = metadata();
|
||||
for (points, expect_ipc) in [(7, true), (8, true), (9, false)] {
|
||||
let rows = (1..=3)
|
||||
.flat_map(|id| (0..points).map(move |time| (1, id, time, 2, 1, Some(id))))
|
||||
.collect::<Vec<_>>();
|
||||
let split = points as usize + 1;
|
||||
let source = new_flat_source_from_record_batches(vec![
|
||||
batch(&metadata, &rows[..split], true),
|
||||
batch(&metadata, &rows[split..], true),
|
||||
]);
|
||||
let files = access_layer
|
||||
.write_sst(
|
||||
SstWriteRequest {
|
||||
index_build_inputs: None,
|
||||
op_type: OperationType::Compact,
|
||||
metadata: metadata.clone(),
|
||||
source,
|
||||
cache_manager: Arc::new(CacheManager::builder().build()),
|
||||
max_sequence: None,
|
||||
sst_write_format: FormatType::Narthex,
|
||||
preserve_row_sequence: true,
|
||||
index_options: Default::default(),
|
||||
index_config: Default::default(),
|
||||
inverted_index_config: Default::default(),
|
||||
fulltext_index_config: Default::default(),
|
||||
bloom_filter_index_config: Default::default(),
|
||||
},
|
||||
&WriteOptions::default(),
|
||||
&mut Metrics::new(WriteType::Compaction),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let [file] = files.as_slice() else {
|
||||
panic!("expected one samples SST")
|
||||
};
|
||||
assert_eq!(3, file.num_series);
|
||||
assert_eq!(rows.len(), file.num_rows);
|
||||
let handle = FileHandle::new(
|
||||
FileMeta {
|
||||
region_id: metadata.region_id,
|
||||
file_id: file.file_id,
|
||||
file_size: file.file_size,
|
||||
format: file.format.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
new_noop_file_purger(),
|
||||
);
|
||||
let reader = reader::SamplesReader::open(
|
||||
access_layer.object_store().clone(),
|
||||
handle,
|
||||
&access_layer.build_region_dir(metadata.region_id),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(expect_ipc, reader.supports_page_batches());
|
||||
let batches = reader
|
||||
.read(full_request())
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, collect_rows(&batches));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ fn collect_times(batches: &[SamplesBatch]) -> Vec<(u32, u64, i64)> {
|
||||
}
|
||||
|
||||
fn exact_keys(batches: &[SamplesBatch]) -> Vec<ExactSeriesKey> {
|
||||
batches.iter().map(|batch| batch.key.clone()).collect()
|
||||
batches.iter().map(|batch| batch.key().clone()).collect()
|
||||
}
|
||||
|
||||
/// A region with the 1,024 fields the manifest allows, so the widest possible descriptor and
|
||||
@@ -149,7 +149,7 @@ async fn key_longer_than_one_page_round_trips() {
|
||||
assert_eq!(vec![(1, 7, 100), (1, 7, 200)], collect_times(&batches));
|
||||
assert_eq!(vec![selection], exact_keys(&batches));
|
||||
// The stored key is the writer's key byte for byte.
|
||||
let (manifest, trailer, page, bytes) = root_page(&store, &handle).await;
|
||||
let (_, trailer, page, bytes) = root_page(&store, &handle).await;
|
||||
let Page::Leaf(blocks) = page else {
|
||||
panic!("one leaf page holds the fixture")
|
||||
};
|
||||
@@ -174,7 +174,7 @@ async fn key_longer_than_one_page_round_trips() {
|
||||
assert!(metadata::descriptor_bytes(blocks[0].columns.len()) + 12 < 65_536 / 2);
|
||||
// The key area is part of the part, not of any page.
|
||||
assert!(trailer.key_end > trailer.payload_end);
|
||||
assert!(manifest.files[0].file_size > trailer.key_end);
|
||||
assert!(super::sample_parts(&handle)[0].file_size > trailer.key_end);
|
||||
}
|
||||
|
||||
/// At the 1,024-field maximum the old layout left `65,536 - (12 + 48 + 44 * 1,027) = 20,288`
|
||||
@@ -296,8 +296,8 @@ async fn corrupt_key_reference_is_rejected_before_rows() {
|
||||
encoding: 1,
|
||||
compression: 0,
|
||||
};
|
||||
rewritten.extend_from_slice(&metadata::encode_directory(&[trailer]));
|
||||
let handle = rewrite_part(&store, handle, manifest, rewritten).await;
|
||||
rewritten.extend_from_slice(&super::encode_tail(&manifest, 0, &[trailer]));
|
||||
let handle = rewrite_part(&store, handle, rewritten).await;
|
||||
let reader = format.reader(store, handle).await.unwrap();
|
||||
let mut stream = reader.read(request(&[TABLE_ID_COLUMN])).unwrap();
|
||||
let error = stream
|
||||
@@ -509,7 +509,7 @@ async fn key_bytes_that_disagree_with_the_descriptor_are_rejected() {
|
||||
async fn part_root(store: &ObjectStore, handle: &FileHandle, part: u32) -> (Group, Page, Vec<u8>) {
|
||||
let manifest = super::manifest(store, handle).await;
|
||||
let bytes = store
|
||||
.read(&manifest.part_path(part))
|
||||
.read(&super::sample_part_path(handle, part))
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
@@ -552,8 +552,8 @@ async fn edit_keys(
|
||||
group.key_end = replacement.len() as u64;
|
||||
replacement.extend_from_slice(&bytes[old..group.root.payload.end().unwrap() as usize]);
|
||||
group.root.payload.offset = group.key_end;
|
||||
replacement.extend(metadata::encode_directory(&[group]));
|
||||
super::rewrite_numbered_part(store, handle, manifest, part, replacement).await
|
||||
replacement.extend(super::encode_tail(&manifest, part, &[group]));
|
||||
super::rewrite_numbered_part(store, handle, part, replacement).await
|
||||
}
|
||||
|
||||
/// Rewrites the two stored key entries of a two-series part in place.
|
||||
@@ -1444,6 +1444,6 @@ async fn carried_key_with_a_different_final_frame_keeps_its_own_identity() {
|
||||
.unwrap();
|
||||
assert_eq!(batches.len(), 2);
|
||||
for (batch, key) in batches.iter().zip(keys) {
|
||||
assert_eq!(batch.key.bytes(), key);
|
||||
assert_eq!(batch.key().bytes(), key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,21 +40,27 @@ use crate::series_index::format::FormatWriter;
|
||||
use crate::series_index::identity::{ExactSeriesKey, IdentityEncoding};
|
||||
use crate::series_index::samples::bulk::NarthexBulkPart;
|
||||
use crate::series_index::samples::histogram::ChunkBound;
|
||||
use crate::series_index::samples::ipc_pages;
|
||||
use crate::series_index::samples::metadata::{self, Block, Column, KeyRef, Page, PageReference};
|
||||
use crate::series_index::samples::{
|
||||
ColumnarSamplesFormat, FLOAT64_ENCODING, MANIFEST_LIMIT, MAX_ROWS, Manifest, MemoryArtifact,
|
||||
MetricSeriesId, Part, TimestampColumn, TimestampUnit, VERSION, ValueColumn, codec, histogram,
|
||||
invalid, require, valid_rows, validate_narthex_metadata,
|
||||
MemorySamplePart, MetricSeriesId, Part, SamplesLayout, TimestampColumn, TimestampUnit,
|
||||
ValueColumn, codec, histogram, invalid, require, valid_rows, validate_narthex_metadata,
|
||||
};
|
||||
use crate::sst::file::NarthexSamplePartMeta;
|
||||
use crate::sst::location::narthex_part_path;
|
||||
|
||||
use crate::sst::DEFAULT_WRITE_BUFFER_SIZE;
|
||||
|
||||
/// Both destinations receive exactly the same file framing and codec output.
|
||||
enum Destination {
|
||||
Store(Outputs),
|
||||
Store {
|
||||
outputs: Outputs,
|
||||
parts: smallvec::SmallVec<[NarthexSamplePartMeta; 1]>,
|
||||
},
|
||||
Memory {
|
||||
current: Option<Vec<u8>>,
|
||||
objects: Vec<Bytes>,
|
||||
parts: Vec<MemorySamplePart>,
|
||||
blocks: Vec<(usize, Block)>,
|
||||
keys: Vec<u8>,
|
||||
},
|
||||
@@ -63,14 +69,21 @@ enum Destination {
|
||||
impl Destination {
|
||||
fn is_open(&self) -> bool {
|
||||
match self {
|
||||
Self::Store(outputs) => outputs.active.is_some(),
|
||||
Self::Store { outputs, .. } => outputs.active.is_some(),
|
||||
Self::Memory { current, .. } => current.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
fn part_count(&self) -> usize {
|
||||
match self {
|
||||
Self::Store { parts, .. } => parts.len(),
|
||||
Self::Memory { parts, .. } => parts.len(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn open(&mut self, path: String) -> Result<()> {
|
||||
match self {
|
||||
Self::Store(outputs) => outputs.open(path).await,
|
||||
Self::Store { outputs, .. } => outputs.open(path).await,
|
||||
Self::Memory { current, .. } => {
|
||||
*current = Some(Vec::new());
|
||||
Ok(())
|
||||
@@ -80,7 +93,7 @@ impl Destination {
|
||||
|
||||
async fn write(&mut self, bytes: Vec<u8>) -> Result<()> {
|
||||
match self {
|
||||
Self::Store(outputs) => outputs.write(bytes).await,
|
||||
Self::Store { outputs, .. } => outputs.write(bytes).await,
|
||||
Self::Memory { current, .. } => {
|
||||
current.as_mut().expect("open memory object").extend(bytes);
|
||||
Ok(())
|
||||
@@ -88,25 +101,30 @@ impl Destination {
|
||||
}
|
||||
}
|
||||
|
||||
async fn close(&mut self) -> Result<()> {
|
||||
async fn close(&mut self, file_size: u64, tail_size: u64) -> Result<()> {
|
||||
match self {
|
||||
Self::Store(outputs) => outputs.close().await,
|
||||
Self::Memory {
|
||||
current, objects, ..
|
||||
} => {
|
||||
objects.push(Bytes::from(
|
||||
Self::Store { outputs, parts } => {
|
||||
outputs.close().await?;
|
||||
parts.push(NarthexSamplePartMeta {
|
||||
file_size,
|
||||
tail_size,
|
||||
});
|
||||
}
|
||||
Self::Memory { current, parts, .. } => {
|
||||
let bytes = Bytes::from(
|
||||
current
|
||||
.take()
|
||||
.expect("open memory object")
|
||||
.into_boxed_slice(),
|
||||
));
|
||||
Ok(())
|
||||
);
|
||||
parts.push(MemorySamplePart { bytes, tail_size });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cleanup(&mut self) -> Result<()> {
|
||||
if let Self::Store(outputs) = self {
|
||||
if let Self::Store { outputs, .. } = self {
|
||||
outputs.cleanup().await?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -209,8 +227,10 @@ enum FieldInput<'a> {
|
||||
Histogram(&'a ArrayRef, &'a StructArray),
|
||||
}
|
||||
pub(crate) struct SamplesWriter {
|
||||
ipc_encoder: Option<ipc_pages::Encoder>,
|
||||
options: ColumnarSamplesFormat,
|
||||
manifest: Manifest,
|
||||
prefix: String,
|
||||
outputs: Destination,
|
||||
compressor: zstd::bulk::Compressor<'static>,
|
||||
output_buffer: SampleBuffer,
|
||||
@@ -233,12 +253,11 @@ pub(crate) struct SamplesWriter {
|
||||
/// Exact keys for the active group. Pending blocks reference offsets
|
||||
/// within this buffer until the final payload position is known.
|
||||
keys: Vec<u8>,
|
||||
manifest_bytes: usize,
|
||||
failed: bool,
|
||||
}
|
||||
impl SamplesWriter {
|
||||
pub(crate) fn set_upload(&mut self, upload: crate::cache::write_cache::NarthexUpload) {
|
||||
if let Destination::Store(outputs) = &mut self.outputs {
|
||||
if let Destination::Store { outputs, .. } = &mut self.outputs {
|
||||
outputs.upload = Some(upload);
|
||||
}
|
||||
}
|
||||
@@ -254,13 +273,16 @@ impl SamplesWriter {
|
||||
Self::with_destination(
|
||||
options,
|
||||
metadata,
|
||||
Destination::Store(Outputs {
|
||||
store,
|
||||
active: None,
|
||||
paths: Vec::new(),
|
||||
committed: false,
|
||||
upload: None,
|
||||
}),
|
||||
Destination::Store {
|
||||
outputs: Outputs {
|
||||
store,
|
||||
active: None,
|
||||
paths: Vec::new(),
|
||||
committed: false,
|
||||
upload: None,
|
||||
},
|
||||
parts: Default::default(),
|
||||
},
|
||||
prefix,
|
||||
source_file_id,
|
||||
generation,
|
||||
@@ -293,13 +315,19 @@ impl SamplesWriter {
|
||||
.field_columns()
|
||||
.map(ValueColumn::new)
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let ipc_encoder = options
|
||||
.ipc_pages
|
||||
.then(ipc_pages::Encoder::new)
|
||||
.transpose()?;
|
||||
let pending_fields = fields.iter().map(PendingField::new).collect();
|
||||
let manifest = Manifest {
|
||||
prefix: prefix.to_string(),
|
||||
format: ArtifactFormat::ColumnarSamples,
|
||||
version: VERSION,
|
||||
layout: if options.ipc_pages {
|
||||
SamplesLayout::ArrowIpc
|
||||
} else {
|
||||
SamplesLayout::SeriesBlocks
|
||||
},
|
||||
identity_encoding: IdentityEncoding::CURRENT_SAMPLES,
|
||||
region_id: metadata.region_id.as_u64(),
|
||||
source_file_id,
|
||||
generation,
|
||||
timestamp: TimestampColumn {
|
||||
@@ -315,14 +343,11 @@ impl SamplesWriter {
|
||||
prefix.ends_with('/') && !prefix.split('/').any(|part| part == ".."),
|
||||
"invalid samples output prefix",
|
||||
)?;
|
||||
let manifest_bytes = serde_json::to_vec(&manifest).context(SerdeJsonSnafu)?.len();
|
||||
require(
|
||||
manifest_bytes <= MANIFEST_LIMIT,
|
||||
"samples schema exceeds manifest limit",
|
||||
)?;
|
||||
Ok(Self {
|
||||
ipc_encoder,
|
||||
options,
|
||||
manifest,
|
||||
prefix: prefix.to_owned(),
|
||||
outputs,
|
||||
compressor: zstd::bulk::Compressor::new(1)
|
||||
.map_err(|e| invalid(format!("sample compression: {e}")))?,
|
||||
@@ -342,7 +367,6 @@ impl SamplesWriter {
|
||||
group_rows: 0,
|
||||
group_blocks: 0,
|
||||
keys: Vec::new(),
|
||||
manifest_bytes,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
@@ -356,7 +380,7 @@ impl SamplesWriter {
|
||||
metadata,
|
||||
Destination::Memory {
|
||||
current: None,
|
||||
objects: Vec::new(),
|
||||
parts: Vec::new(),
|
||||
blocks: Vec::new(),
|
||||
keys: Vec::new(),
|
||||
},
|
||||
@@ -374,11 +398,11 @@ impl SamplesWriter {
|
||||
}
|
||||
|
||||
pub(crate) fn finish_memory(mut self) -> Result<NarthexBulkPart> {
|
||||
self.complete()
|
||||
self.finish_parts()
|
||||
.now_or_never()
|
||||
.expect("memory writer is synchronous")?;
|
||||
let Destination::Memory {
|
||||
mut objects,
|
||||
parts,
|
||||
keys,
|
||||
blocks,
|
||||
..
|
||||
@@ -386,17 +410,86 @@ impl SamplesWriter {
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
let manifest = objects.pop().expect("completed samples manifest");
|
||||
Ok(NarthexBulkPart::new(MemoryArtifact {
|
||||
file_id: self.manifest.source_file_id,
|
||||
manifest,
|
||||
parts: objects,
|
||||
parts,
|
||||
keys: Bytes::from(keys.into_boxed_slice()),
|
||||
blocks,
|
||||
fields: self.manifest.fields,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn set_ipc_sample_bytes_limit(&mut self, limit: usize) {
|
||||
self.ipc_encoder.as_mut().unwrap().sample_bytes_limit = limit;
|
||||
}
|
||||
|
||||
async fn write_ipc_batch(&mut self, batch: &RecordBatch) -> Result<()> {
|
||||
if batch.num_rows() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let (samples, key) = ipc_pages::input_columns(batch, &self.manifest)?;
|
||||
let page_rows = ipc_pages::Encoder::page_rows(&samples);
|
||||
let mut offset = 0;
|
||||
while offset < samples.num_rows() {
|
||||
if !self.outputs.is_open() {
|
||||
let id = u32::try_from(self.outputs.part_count())
|
||||
.map_err(|_| invalid("too many sample parts"))?;
|
||||
self.outputs
|
||||
.open(narthex_part_path(&self.prefix, id as usize, "samples"))
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, metadata::HEADER)
|
||||
.await?;
|
||||
self.position = metadata::HEADER_SIZE;
|
||||
}
|
||||
let mut rows = page_rows.min(samples.num_rows() - offset);
|
||||
let encoder = self.ipc_encoder.as_mut().unwrap();
|
||||
let page = loop {
|
||||
let input = samples.slice(offset, rows);
|
||||
if let Some(page) =
|
||||
encoder.encode(&input, batch.column(key).as_ref(), offset, self.position)?
|
||||
{
|
||||
break page;
|
||||
}
|
||||
require(rows > 1, "single IPC sample exceeds page byte limit")?;
|
||||
rows /= 2;
|
||||
};
|
||||
let end = page.group.root.payload.end()?;
|
||||
let length = page.sample.ipc_message.len();
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, &(length as u64).to_le_bytes())
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, &page.sample.ipc_message)
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(
|
||||
&mut self.outputs,
|
||||
&[0; 7][..length.next_multiple_of(8) - length],
|
||||
)
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, &page.sample.arrow_data)
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, &page.key_area)
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, &page.directory)
|
||||
.await?;
|
||||
encoder.recycle_key_area(page.key_area);
|
||||
offset += rows;
|
||||
self.groups.push(page.group);
|
||||
self.position = end;
|
||||
if self.position >= self.options.part_bytes || self.groups.len() == metadata::MAX_GROUPS
|
||||
{
|
||||
self.finish_part().await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_batch(&mut self, batch: &RecordBatch) -> Result<()> {
|
||||
require(batch.num_columns() >= 4, "samples require flat batches")?;
|
||||
let column = |name: &str| {
|
||||
@@ -614,11 +707,13 @@ impl SamplesWriter {
|
||||
}
|
||||
}
|
||||
if !self.outputs.is_open() {
|
||||
let id = u32::try_from(self.manifest.files.len())
|
||||
let id = u32::try_from(self.outputs.part_count())
|
||||
.map_err(|_| invalid("too many sample parts"))?;
|
||||
self.outputs.open(self.manifest.part_path(id)).await?;
|
||||
self.outputs
|
||||
.open(narthex_part_path(&self.prefix, id as usize, "samples"))
|
||||
.await?;
|
||||
self.output_buffer
|
||||
.write(&mut self.outputs, &metadata::header())
|
||||
.write(&mut self.outputs, metadata::HEADER)
|
||||
.await?;
|
||||
self.position = metadata::HEADER_SIZE;
|
||||
}
|
||||
@@ -684,7 +779,7 @@ impl SamplesWriter {
|
||||
let frames = super::key_pages::encode(&self.keys, &mut self.compressor)?;
|
||||
if let Destination::Memory {
|
||||
blocks,
|
||||
objects,
|
||||
parts,
|
||||
keys,
|
||||
..
|
||||
} = &mut self.outputs
|
||||
@@ -694,7 +789,7 @@ impl SamplesWriter {
|
||||
keys.extend_from_slice(&self.keys);
|
||||
blocks.extend(self.leaves.iter().flatten().cloned().map(|mut block| {
|
||||
block.key.offset += base;
|
||||
(objects.len(), block)
|
||||
(parts.len(), block)
|
||||
}));
|
||||
}
|
||||
self.keys.clear();
|
||||
@@ -743,56 +838,53 @@ impl SamplesWriter {
|
||||
if groups.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = metadata::encode_directory(&groups);
|
||||
let file_length = self
|
||||
let part_id = u32::try_from(self.outputs.part_count())
|
||||
.map_err(|_| invalid("too many sample parts"))?;
|
||||
self.manifest
|
||||
.files
|
||||
.push(Part::from_groups(part_id, &groups)?);
|
||||
let descriptor = serde_json::to_vec(&self.manifest).context(SerdeJsonSnafu)?;
|
||||
self.manifest.files.clear();
|
||||
require(
|
||||
descriptor.len() <= MANIFEST_LIMIT,
|
||||
"sample part descriptor exceeds limit",
|
||||
)?;
|
||||
let bytes = metadata::encode_part_tail(&groups, &descriptor);
|
||||
let tail_size = bytes.len() as u64;
|
||||
let file_size = self
|
||||
.position
|
||||
.checked_add(bytes.len() as u64)
|
||||
.checked_add(tail_size)
|
||||
.ok_or_else(|| invalid("sample part length overflow"))?;
|
||||
self.output_buffer.write(&mut self.outputs, &bytes).await?;
|
||||
self.output_buffer.flush(&mut self.outputs).await?;
|
||||
self.outputs.close().await?;
|
||||
let part_id = u32::try_from(self.manifest.files.len())
|
||||
.map_err(|_| invalid("too many sample parts"))?;
|
||||
let part = Part::from_groups(part_id, file_length, &groups)?;
|
||||
self.manifest_bytes += serde_json::to_vec(&part).context(SerdeJsonSnafu)?.len()
|
||||
+ usize::from(!self.manifest.files.is_empty());
|
||||
require(
|
||||
self.manifest_bytes <= MANIFEST_LIMIT,
|
||||
"samples manifest exceeds size limit",
|
||||
)?;
|
||||
self.manifest.files.push(part);
|
||||
self.outputs.close(file_size, tail_size).await?;
|
||||
self.position = 0;
|
||||
Ok(())
|
||||
}
|
||||
async fn complete(&mut self) -> Result<ArtifactMetadata> {
|
||||
async fn finish_parts(&mut self) -> Result<()> {
|
||||
require(!self.failed, "sample writer failed previously")?;
|
||||
self.flush_block().await?;
|
||||
self.finish_part().await?;
|
||||
let bytes = serde_json::to_vec(&self.manifest).context(SerdeJsonSnafu)?;
|
||||
require(
|
||||
bytes.len() <= MANIFEST_LIMIT,
|
||||
"samples manifest exceeds limit",
|
||||
)?;
|
||||
let mut file_size = bytes.len() as u64;
|
||||
let mut objects = vec![ArtifactObject {
|
||||
path: self.manifest.path(),
|
||||
file_size,
|
||||
}];
|
||||
for part in &self.manifest.files {
|
||||
objects.push(ArtifactObject {
|
||||
path: self.manifest.part_path(part.part_id),
|
||||
file_size: part.file_size,
|
||||
});
|
||||
self.finish_part().await
|
||||
}
|
||||
|
||||
async fn complete(&mut self) -> Result<ArtifactMetadata> {
|
||||
self.finish_parts().await?;
|
||||
let Destination::Store { outputs, parts } = &mut self.outputs else {
|
||||
return Err(invalid("expected samples object store writer"));
|
||||
};
|
||||
let mut file_size = 0u64;
|
||||
let mut objects = Vec::with_capacity(parts.len());
|
||||
for (index, part) in parts.iter().enumerate() {
|
||||
file_size = file_size
|
||||
.checked_add(part.file_size)
|
||||
.ok_or_else(|| invalid("sample artifact size overflow"))?;
|
||||
objects.push(ArtifactObject {
|
||||
path: narthex_part_path(&self.prefix, index, "samples"),
|
||||
file_size: part.file_size,
|
||||
tail_size: Some(part.tail_size),
|
||||
});
|
||||
}
|
||||
self.outputs.open(self.manifest.path()).await?;
|
||||
self.outputs.write(bytes).await?;
|
||||
self.outputs.close().await?;
|
||||
if let Destination::Store(outputs) = &mut self.outputs {
|
||||
outputs.commit().await;
|
||||
}
|
||||
outputs.commit().await;
|
||||
Ok(ArtifactMetadata {
|
||||
format: ArtifactFormat::ColumnarSamples,
|
||||
generation: self.manifest.generation,
|
||||
@@ -814,7 +906,7 @@ impl SamplesWriter {
|
||||
self.position,
|
||||
self.keys.len() as u64,
|
||||
self.group_blocks,
|
||||
self.manifest.files.len(),
|
||||
self.outputs.part_count(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -823,7 +915,11 @@ impl FormatWriter for SamplesWriter {
|
||||
async fn write(&mut self, batch: &RecordBatch) -> Result<()> {
|
||||
require(!self.failed, "sample writer failed previously")?;
|
||||
self.failed = true;
|
||||
let result = self.write_batch(batch).await;
|
||||
let result = if self.ipc_encoder.is_some() {
|
||||
self.write_ipc_batch(batch).await
|
||||
} else {
|
||||
self.write_batch(batch).await
|
||||
};
|
||||
if result.is_ok() {
|
||||
self.failed = false;
|
||||
}
|
||||
@@ -976,13 +1072,16 @@ mod tests {
|
||||
fn outputs() -> (Destination, ObjectStore) {
|
||||
let store = ObjectStore::new(object_store::services::Memory::default()).unwrap();
|
||||
(
|
||||
Destination::Store(Outputs {
|
||||
store: store.clone(),
|
||||
active: None,
|
||||
paths: Vec::new(),
|
||||
committed: false,
|
||||
upload: None,
|
||||
}),
|
||||
Destination::Store {
|
||||
outputs: Outputs {
|
||||
store: store.clone(),
|
||||
active: None,
|
||||
paths: Vec::new(),
|
||||
committed: false,
|
||||
upload: None,
|
||||
},
|
||||
parts: Default::default(),
|
||||
},
|
||||
store,
|
||||
)
|
||||
}
|
||||
@@ -1004,7 +1103,7 @@ mod tests {
|
||||
buffer.write(&mut outputs, &bytes[split..]).await.unwrap();
|
||||
assert_eq!(buffer.bytes.len(), size % capacity);
|
||||
buffer.flush(&mut outputs).await.unwrap();
|
||||
outputs.close().await.unwrap();
|
||||
outputs.close(0, 0).await.unwrap();
|
||||
assert!(buffer.bytes.is_empty());
|
||||
assert_eq!(store.read(&path).await.unwrap().to_vec(), bytes);
|
||||
}
|
||||
@@ -1043,7 +1142,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
buffer.flush(&mut outputs).await.unwrap();
|
||||
outputs.close().await.unwrap();
|
||||
outputs.close(0, 0).await.unwrap();
|
||||
common_telemetry::info!(
|
||||
"buffered={buffered}, elapsed={:?}, submitted_fragments={}",
|
||||
started.elapsed(),
|
||||
|
||||
+94
-43
@@ -265,14 +265,21 @@ pub struct NarthexPartMeta {
|
||||
pub file_size: u64,
|
||||
}
|
||||
|
||||
/// Sizes used to open a samples part and read its inline metadata.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NarthexSamplePartMeta {
|
||||
/// Total encoded size of the part.
|
||||
pub file_size: u64,
|
||||
/// Encoded size of the metadata range at the end of the part.
|
||||
pub tail_size: u64,
|
||||
}
|
||||
|
||||
/// Narthex samples objects owned by one immutable file ID.
|
||||
/// Common bounds, statistics and sequence semantics remain in [`FileMeta`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NarthexSamplesMeta {
|
||||
/// Encoded size of manifest.json.
|
||||
pub manifest_size: u64,
|
||||
/// Parts in part-ID order, starting at zero.
|
||||
pub parts: SmallVec<[NarthexPartMeta; 1]>,
|
||||
pub parts: SmallVec<[NarthexSamplePartMeta; 1]>,
|
||||
}
|
||||
|
||||
/// Sequence summary of a half-open time window in Unix seconds.
|
||||
@@ -594,15 +601,19 @@ impl FileMeta {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the authoritative object path, using the artifact manifest for narthex files.
|
||||
/// Returns the authoritative object path, using the first part for Narthex samples.
|
||||
pub fn file_path(&self, table_dir: &str, path_type: PathType) -> String {
|
||||
match &self.format {
|
||||
FileFormat::Parquet => location::sst_file_path(table_dir, self.file_id(), path_type),
|
||||
_ => {
|
||||
format => {
|
||||
let region_dir =
|
||||
location::region_dir_from_table_dir(table_dir, self.region_id, path_type);
|
||||
let file_dir = location::narthex_file_dir(®ion_dir, self.file_id);
|
||||
location::narthex_manifest_path(&file_dir)
|
||||
if matches!(format, FileFormat::NarthexSamples(_)) {
|
||||
location::narthex_part_path(&file_dir, 0, "samples")
|
||||
} else {
|
||||
location::narthex_manifest_path(&file_dir)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -613,38 +624,71 @@ impl FileMeta {
|
||||
region_dir: &str,
|
||||
) -> Option<Vec<crate::series_index::artifact::ArtifactObject>> {
|
||||
use crate::series_index::artifact::ArtifactObject;
|
||||
let (manifest, parts, extension) = match &self.format {
|
||||
FileFormat::Parquet => return None,
|
||||
FileFormat::NarthexSamples(meta) => (meta.manifest_size, &meta.parts, "samples"),
|
||||
FileFormat::NarthexSeriesIndex(meta) => (meta.manifest_size, &meta.parts, "series"),
|
||||
let part_object = |dir: &str, extension, id, file_size, tail_size| ArtifactObject {
|
||||
path: location::narthex_part_path(dir, id, extension),
|
||||
file_size,
|
||||
tail_size,
|
||||
};
|
||||
let dir = location::narthex_file_dir(region_dir, self.file_id);
|
||||
let mut objects = Vec::with_capacity(parts.len() + 1);
|
||||
for (id, part) in parts.iter().enumerate() {
|
||||
objects.push(ArtifactObject {
|
||||
path: location::narthex_part_path(&dir, id, extension),
|
||||
file_size: part.file_size,
|
||||
});
|
||||
match &self.format {
|
||||
FileFormat::Parquet => None,
|
||||
FileFormat::NarthexSamples(meta) => {
|
||||
let dir = location::narthex_file_dir(region_dir, self.file_id);
|
||||
Some(
|
||||
meta.parts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, part)| {
|
||||
part_object(&dir, "samples", id, part.file_size, Some(part.tail_size))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
FileFormat::NarthexSeriesIndex(meta) => {
|
||||
let dir = location::narthex_file_dir(region_dir, self.file_id);
|
||||
let mut objects = Vec::with_capacity(meta.parts.len() + 1);
|
||||
objects.extend(
|
||||
meta.parts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, part)| part_object(&dir, "series", id, part.file_size, None)),
|
||||
);
|
||||
objects.push(ArtifactObject {
|
||||
path: location::narthex_manifest_path(&dir),
|
||||
file_size: meta.manifest_size,
|
||||
tail_size: None,
|
||||
});
|
||||
Some(objects)
|
||||
}
|
||||
}
|
||||
objects.push(ArtifactObject {
|
||||
path: location::narthex_manifest_path(&dir),
|
||||
file_size: manifest,
|
||||
});
|
||||
Some(objects)
|
||||
}
|
||||
|
||||
/// Checks that a Narthex inventory describes one complete immutable artifact.
|
||||
pub(crate) fn valid_inventory(&self) -> bool {
|
||||
let (manifest, parts) = match &self.format {
|
||||
let size = match &self.format {
|
||||
FileFormat::Parquet => return true,
|
||||
FileFormat::NarthexSamples(meta) => (meta.manifest_size, &meta.parts),
|
||||
FileFormat::NarthexSeriesIndex(meta) => (meta.manifest_size, &meta.parts),
|
||||
FileFormat::NarthexSamples(meta) => {
|
||||
if meta.parts.is_empty() {
|
||||
return false;
|
||||
}
|
||||
meta.parts.iter().try_fold(0u64, |total, part| {
|
||||
if part.tail_size == 0 || part.tail_size >= part.file_size {
|
||||
return None;
|
||||
}
|
||||
total.checked_add(part.file_size)
|
||||
})
|
||||
}
|
||||
FileFormat::NarthexSeriesIndex(meta) => {
|
||||
if meta.parts.is_empty() {
|
||||
return false;
|
||||
}
|
||||
meta.parts
|
||||
.iter()
|
||||
.try_fold(meta.manifest_size, |total, part| {
|
||||
total.checked_add(part.file_size)
|
||||
})
|
||||
}
|
||||
};
|
||||
!parts.is_empty()
|
||||
&& parts
|
||||
.iter()
|
||||
.try_fold(manifest, |total, part| total.checked_add(part.file_size))
|
||||
== Some(self.file_size)
|
||||
size == Some(self.file_size)
|
||||
}
|
||||
|
||||
/// Returns whether this file's row sequences are trusted in the target region.
|
||||
@@ -1549,10 +1593,15 @@ mod tests {
|
||||
#[test]
|
||||
fn test_narthex_part_paths_follow_inventory_order() {
|
||||
let samples = FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
|
||||
manifest_size: 5,
|
||||
parts: smallvec::smallvec![
|
||||
NarthexPartMeta { file_size: 11 },
|
||||
NarthexPartMeta { file_size: 7 }
|
||||
NarthexSamplePartMeta {
|
||||
file_size: 11,
|
||||
tail_size: 5
|
||||
},
|
||||
NarthexSamplePartMeta {
|
||||
file_size: 7,
|
||||
tail_size: 3
|
||||
},
|
||||
],
|
||||
}));
|
||||
let series = FileFormat::NarthexSeriesIndex(Box::new(NarthexSeriesIndexMeta {
|
||||
@@ -1567,9 +1616,11 @@ mod tests {
|
||||
NarthexPartMeta { file_size: 7 }
|
||||
],
|
||||
}));
|
||||
for (format, extension) in [(samples, "samples"), (series, "series")] {
|
||||
for (format, extension, manifest_size) in
|
||||
[(samples, "samples", None), (series, "series", Some(5))]
|
||||
{
|
||||
let meta = FileMeta {
|
||||
file_size: 23,
|
||||
file_size: 18 + manifest_size.unwrap_or(0),
|
||||
format,
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1580,14 +1631,14 @@ mod tests {
|
||||
.into_iter()
|
||||
.map(|object| (object.path, object.file_size))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
entries,
|
||||
[
|
||||
(format!("{dir}part-0.{extension}"), 11),
|
||||
(format!("{dir}part-1.{extension}"), 7),
|
||||
(format!("{dir}manifest.json"), 5),
|
||||
]
|
||||
);
|
||||
let mut expected = vec![
|
||||
(format!("{dir}part-0.{extension}"), 11),
|
||||
(format!("{dir}part-1.{extension}"), 7),
|
||||
];
|
||||
if let Some(size) = manifest_size {
|
||||
expected.push((format!("{dir}manifest.json"), size));
|
||||
}
|
||||
assert_eq!(entries, expected);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,12 +15,13 @@
|
||||
//! Narthex sample and series-index writers.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BinaryHeap;
|
||||
use std::collections::{BinaryHeap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use datatypes::arrow::array::{Array, BinaryArray, DictionaryArray};
|
||||
use datatypes::arrow::compute::{cast, max, min};
|
||||
use datatypes::arrow::datatypes::{DataType, UInt32Type};
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use futures::stream::BoxStream;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use snafu::ResultExt;
|
||||
@@ -32,6 +33,7 @@ use crate::access_layer::{OperationType, SstInfoArray};
|
||||
use crate::cache::file_cache::{FileType, IndexKey};
|
||||
use crate::cache::write_cache::{NarthexUpload, WriteCacheRef};
|
||||
use crate::error::{ComputeArrowSnafu, InvalidRecordBatchSnafu, Result};
|
||||
use crate::read::FlatSource;
|
||||
use crate::series_index::columnar::reader::ColumnarReader;
|
||||
use crate::series_index::columnar::{ColumnarSeriesFormat, invalid, require};
|
||||
use crate::series_index::format::{FormatWriter, SamplesFormatReader};
|
||||
@@ -39,8 +41,8 @@ use crate::series_index::identity::ExactSeriesKey;
|
||||
use crate::series_index::samples::ColumnarSamplesFormat;
|
||||
use crate::series_index::samples::reader::SamplesReader;
|
||||
use crate::sst::file::{
|
||||
FileFormat, FileHandle, FileMeta, NarthexPartMeta, NarthexSamplesMeta, NarthexSeriesIndexMeta,
|
||||
RegionFileId,
|
||||
FileFormat, FileHandle, FileMeta, NarthexPartMeta, NarthexSamplePartMeta, NarthexSamplesMeta,
|
||||
NarthexSeriesIndexMeta, RegionFileId,
|
||||
};
|
||||
use crate::sst::location;
|
||||
use crate::sst::parquet::SstInfo;
|
||||
@@ -93,6 +95,32 @@ fn count_series(keys: &dyn Array, previous_key: &mut Vec<u8>) -> Result<u64> {
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
const LAYOUT_SAMPLE_ROWS: usize = 4096;
|
||||
const IPC_MAX_POINTS_PER_SERIES: u64 = 8;
|
||||
|
||||
async fn next_samples_batch(
|
||||
source: &mut FlatSource,
|
||||
cancellation: Option<&tokio_util::sync::CancellationToken>,
|
||||
) -> Result<Option<RecordBatch>> {
|
||||
let next = source.next_batch();
|
||||
if let Some(signal) = cancellation {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = signal.cancelled() => crate::error::CompactionCancelledSnafu.fail(),
|
||||
batch = next => batch,
|
||||
}
|
||||
} else {
|
||||
next.await
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_primary_keys(batch: &RecordBatch) -> Result<&dyn Array> {
|
||||
batch
|
||||
.column_by_name("__primary_key")
|
||||
.map(|keys| keys.as_ref())
|
||||
.ok_or_else(|| invalid("narthex samples lack primary key"))
|
||||
}
|
||||
|
||||
/// Reuses the narthex codec and the caller's merged, sequence-normalized source.
|
||||
pub(crate) async fn write_samples(
|
||||
layer: &AccessLayer,
|
||||
@@ -100,6 +128,30 @@ pub(crate) async fn write_samples(
|
||||
guard: Option<Arc<dyn SstWriteGuard>>,
|
||||
cancellation: Option<tokio_util::sync::CancellationToken>,
|
||||
) -> Result<SstInfoArray> {
|
||||
let mut buffered = VecDeque::new();
|
||||
let mut exhausted = false;
|
||||
let mut sampled_rows = 0usize;
|
||||
let mut sampled_series = 0u64;
|
||||
let mut sampled_key = Vec::new();
|
||||
while sampled_rows < LAYOUT_SAMPLE_ROWS {
|
||||
let Some(batch) = next_samples_batch(&mut request.source, cancellation.as_ref()).await?
|
||||
else {
|
||||
exhausted = true;
|
||||
break;
|
||||
};
|
||||
if batch.num_rows() == 0 {
|
||||
continue;
|
||||
}
|
||||
let take = batch.num_rows().min(LAYOUT_SAMPLE_ROWS - sampled_rows);
|
||||
let keys = sample_primary_keys(&batch)?.slice(0, take);
|
||||
sampled_series += count_series(keys.as_ref(), &mut sampled_key)?;
|
||||
sampled_rows += take;
|
||||
buffered.push_back(batch);
|
||||
}
|
||||
if buffered.is_empty() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let ipc_pages = sampled_rows as u64 <= sampled_series * IPC_MAX_POINTS_PER_SERIES;
|
||||
let id = FileId::random();
|
||||
let region_id = request.metadata.region_id;
|
||||
if let Some(guard) = guard {
|
||||
@@ -114,7 +166,10 @@ pub(crate) async fn write_samples(
|
||||
|cache| cache.file_cache().local_store(),
|
||||
);
|
||||
let mut writer = Box::new(crate::series_index::samples::writer::SamplesWriter::new(
|
||||
ColumnarSamplesFormat::default(),
|
||||
ColumnarSamplesFormat {
|
||||
ipc_pages,
|
||||
..Default::default()
|
||||
},
|
||||
request.metadata.clone(),
|
||||
store,
|
||||
&prefix,
|
||||
@@ -139,20 +194,18 @@ pub(crate) async fn write_samples(
|
||||
let timestamp = &request.metadata.time_index_column().column_schema.name;
|
||||
let write_result: Result<()> = async {
|
||||
loop {
|
||||
let next = request.source.next_batch();
|
||||
let batch = if let Some(signal) = &cancellation {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = signal.cancelled() => return crate::error::CompactionCancelledSnafu.fail(),
|
||||
batch = next => batch?,
|
||||
}
|
||||
} else {
|
||||
next.await?
|
||||
let batch = match buffered.pop_front() {
|
||||
Some(batch) => Some(batch),
|
||||
None if exhausted => None,
|
||||
None => next_samples_batch(&mut request.source, cancellation.as_ref()).await?,
|
||||
};
|
||||
let Some(batch) = batch else {
|
||||
break;
|
||||
};
|
||||
|
||||
let Some(batch) = batch else { break };
|
||||
if cancellation
|
||||
.as_ref()
|
||||
.is_some_and(|signal| signal.is_cancelled())
|
||||
{
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
if batch.num_rows() == 0 {
|
||||
continue;
|
||||
}
|
||||
@@ -171,13 +224,7 @@ pub(crate) async fn write_samples(
|
||||
})?;
|
||||
lower = lower.min(min(&values).unwrap_or(lower));
|
||||
upper = upper.max(max(&values).unwrap_or(upper));
|
||||
let keys = batch.column_by_name("__primary_key").ok_or_else(|| {
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: "narthex samples lack primary key".to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
series += count_series(keys.as_ref(), &mut previous_key)?;
|
||||
series += count_series(sample_primary_keys(&batch)?, &mut previous_key)?;
|
||||
rows += batch.num_rows();
|
||||
// Narthex files always retain row sequences; import barriers are applied by readers.
|
||||
writer.write(&batch).await?;
|
||||
@@ -193,13 +240,6 @@ pub(crate) async fn write_samples(
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let artifact = writer.finish().await?;
|
||||
// The samples codec returns its manifest first, then parts in ID order.
|
||||
let (manifest, parts) = artifact.objects.split_first().ok_or_else(|| {
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: "missing Narthex samples manifest",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let unit = request.metadata.time_index_type().unit();
|
||||
let info = SstInfo {
|
||||
file_id: id,
|
||||
@@ -216,13 +256,11 @@ pub(crate) async fn write_samples(
|
||||
file_metadata: None,
|
||||
index_metadata: Default::default(),
|
||||
format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
|
||||
manifest_size: manifest.file_size,
|
||||
parts: parts
|
||||
parts: artifact
|
||||
.objects
|
||||
.iter()
|
||||
.map(|part| NarthexPartMeta {
|
||||
file_size: part.file_size,
|
||||
})
|
||||
.collect(),
|
||||
.map(NarthexSamplePartMeta::try_from)
|
||||
.collect::<Result<_>>()?,
|
||||
})),
|
||||
};
|
||||
Ok(smallvec::smallvec![info])
|
||||
@@ -309,7 +347,14 @@ pub(crate) async fn write_series(
|
||||
)
|
||||
.await?
|
||||
.read(Default::default())?
|
||||
.map_ok(|block| (block.key, block.batch.num_rows() as u64))
|
||||
.map(|block| {
|
||||
let block = block?;
|
||||
let rows = block.num_rows() as u64;
|
||||
let key = block
|
||||
.into_key()
|
||||
.ok_or_else(|| invalid("expected a series maintenance key"))?;
|
||||
Ok((key, rows))
|
||||
})
|
||||
.boxed(),
|
||||
FileFormat::Parquet => {
|
||||
return Err(invalid("expected Narthex series or samples"));
|
||||
|
||||
@@ -418,6 +418,25 @@ async fn prepare_narthex_copy(
|
||||
let source_objects = source
|
||||
.narthex_objects(&layer.build_region_dir(source.region_id))
|
||||
.ok_or_else(|| invalid("expected Narthex copy source"))?;
|
||||
let target_region_dir = layer.build_region_dir(region.region_id);
|
||||
let mut copied = remap_copied_file_meta(source, region.region_id);
|
||||
if matches!(&source.format, FileFormat::NarthexSamples(_)) {
|
||||
// The tail belongs to the immutable file ID, so the entire part can be copied.
|
||||
let targets = copied
|
||||
.narthex_objects(&target_region_dir)
|
||||
.ok_or_else(|| invalid("missing Narthex copy target inventory"))?;
|
||||
let descriptors = source_objects
|
||||
.into_iter()
|
||||
.zip(targets)
|
||||
.map(|(object, target)| FileDescriptor::NarthexObject {
|
||||
source: object.path,
|
||||
target: target.path,
|
||||
size: target.file_size,
|
||||
manifest: None,
|
||||
})
|
||||
.collect();
|
||||
return Ok((copied, descriptors));
|
||||
}
|
||||
let (source_manifest, parts) = source_objects
|
||||
.split_last()
|
||||
.expect("Narthex inventory includes manifest");
|
||||
@@ -438,13 +457,10 @@ async fn prepare_narthex_copy(
|
||||
let bytes = bytes::Bytes::from(
|
||||
serde_json::to_vec(&manifest).map_err(|error| invalid(error.to_string()))?,
|
||||
);
|
||||
let target_region_dir = layer.build_region_dir(region.region_id);
|
||||
let mut copied = remap_copied_file_meta(source, region.region_id);
|
||||
let manifest_size = bytes.len() as u64;
|
||||
match &mut copied.format {
|
||||
FileFormat::NarthexSamples(meta) => meta.manifest_size = manifest_size,
|
||||
FileFormat::NarthexSeriesIndex(meta) => meta.manifest_size = manifest_size,
|
||||
FileFormat::Parquet => return Err(invalid("expected Narthex copy source")),
|
||||
_ => return Err(invalid("expected Narthex series index copy source")),
|
||||
}
|
||||
let targets = copied
|
||||
.narthex_objects(&target_region_dir)
|
||||
|
||||
@@ -23,10 +23,10 @@
|
||||
"sequence": 7,
|
||||
"format": {
|
||||
"narthex_samples": {
|
||||
"manifest_size": 10,
|
||||
"parts": [
|
||||
{
|
||||
"file_size": 20
|
||||
"file_size": 30,
|
||||
"tail_size": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -52,10 +52,10 @@
|
||||
"sequence": 7,
|
||||
"format": {
|
||||
"narthex_samples": {
|
||||
"manifest_size": 10,
|
||||
"parts": [
|
||||
{
|
||||
"file_size": 20
|
||||
"file_size": 30,
|
||||
"tail_size": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
# Mito columnar samples version 1
|
||||
|
||||
This fixture freezes the version-1 sample wire contract in
|
||||
[`mito-samples.md`](../../../../docs/formats/mito-samples.md). It is exercised by
|
||||
the owning Mito Rust test, not SQLness discovery:
|
||||
|
||||
```shell
|
||||
cargo nextest run -p mito2 frozen_v1_samples_fixture_is_rejected
|
||||
```
|
||||
|
||||
`v1-manifest.json` and `v1-part.hex` describe a 397-byte part with raw compression,
|
||||
one leaf/root, and two samples for `(table_id=7, tsid=42)` at timestamp 100 ms.
|
||||
The first row is a put with sequence 9 and Float64 negative zero. The second is a
|
||||
delete with sequence 8 and a null field. Both rows must survive decoding.
|
||||
|
||||
The part was assembled independently of the Rust writer, using explicit
|
||||
little-endian fields and XXH64 with seed zero. Its layout is:
|
||||
|
||||
| Range | Content |
|
||||
| --- | --- |
|
||||
| 0..16 | Header |
|
||||
| 16..32 | Constant-step timestamps: first 100, step 0 |
|
||||
| 32..41 | Delta sequences: first 9, ZigZag delta -1 |
|
||||
| 41..43 | Raw operations: put 1, delete 0 |
|
||||
| 43..53 | Nullable XOR: bitmap mode, validity 0x01, negative-zero bits |
|
||||
| 53..285 | Leaf/root: one block, four column references |
|
||||
| 285..397 | Trailer with root reference and checksum |
|
||||
|
||||
The current reader writes the same wire version as this fixture, so the version
|
||||
number alone does not reject it. The manifest carries no `identity_encoding`
|
||||
discriminator, and the part records only `(table_id, tsid)`, which is a hash: a
|
||||
part whose two series were merged is structurally valid and ordered exactly like a
|
||||
correct one. The test installs these exact bytes and recorded object sizes and
|
||||
asserts that opening them through the samples reader fails on the missing
|
||||
`identity_encoding` discriminator.
|
||||
|
||||
The part bytes above also predate two later version-1 shapes, neither of which is
|
||||
migrated: block descriptors now carry a fixed-size key reference into a separate key
|
||||
area instead of the key bytes, and the trailer records that area (`key_end`) and is
|
||||
120 bytes, not 112. The fixture is still rejected for the same reason — the
|
||||
discriminator is missing — and that rejection happens while opening the manifest,
|
||||
before any part byte is decoded, so the frozen bytes are not a reader for the current
|
||||
part layout and must not be regenerated to look like one.
|
||||
|
||||
Do not regenerate this fixture just to make a reader change pass. Preserve its
|
||||
bytes for future reader compatibility; introduce a separate versioned fixture
|
||||
when the approved format changes. This is a frozen-byte compatibility check,
|
||||
not a cross-binary upgrade/downgrade test.
|
||||
|
||||
The grouped layout test pins a raw frame inline: a four-byte little-endian stored
|
||||
length followed by the three payload bytes `abc`.
|
||||
Run `cargo nextest run -p mito2 raw_key_frame_has_only_length_and_payload`.
|
||||
@@ -1,38 +0,0 @@
|
||||
{
|
||||
"format": "columnar-samples",
|
||||
"version": 1,
|
||||
"region_id": 4294967297,
|
||||
"source_file_id": "11111111-1111-1111-1111-111111111111",
|
||||
"generation": "22222222-2222-2222-2222-222222222222",
|
||||
"timestamp": {
|
||||
"column_id": 3,
|
||||
"name": "ts",
|
||||
"unit": "millisecond"
|
||||
},
|
||||
"fields": [
|
||||
{
|
||||
"column_id": 2,
|
||||
"name": "field_0",
|
||||
"type": "float64",
|
||||
"nullable": true
|
||||
}
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"part_id": 0,
|
||||
"file_size": 397,
|
||||
"num_rows": 2,
|
||||
"num_blocks": 1,
|
||||
"first": {
|
||||
"table_id": 7,
|
||||
"tsid": 42
|
||||
},
|
||||
"last": {
|
||||
"table_id": 7,
|
||||
"tsid": 42
|
||||
},
|
||||
"min_timestamp": 100,
|
||||
"max_timestamp": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
475453414d504c45010000000000000064000000000000000000000000000000
|
||||
0900000000000000010100010100000000000000800000000001000000000000
|
||||
00070000002a0000000000000064000000000000006400000000000000000000
|
||||
0000000000020000000400000001000000030000001000000000000000100000
|
||||
00100000005ec3a3cc10ea641301000000000000000000000002000000000000
|
||||
00200000000000000009000000090000003b1e9c01038b57ca04000000000000
|
||||
0000000000030000000000000029000000000000000200000002000000f1577f
|
||||
bf1d628fdd07000000000000000000000004000000020000002b000000000000
|
||||
000a0000000a0000008e2dc4e1ef3f8b09050000000000000001000000070000
|
||||
002a00000000000000070000002a000000000000006400000000000000640000
|
||||
00000000003500000000000000e8000000e800000077c4ce1b4e0f6c87010000
|
||||
000000000001000000010000008d010000000000003500000000000000475453
|
||||
414d504c45f202e0cce4a9fdb1
|
||||
Reference in New Issue
Block a user