A chunk figure leaves out the tables its segments index into, because a table is one
allocation however many chunks share it. The operand then billed only the indices, so
tables it kept alive cost nothing: a pool holding room for one table admitted a second
and a third, each arriving from a source whose own reservation was released as it
handed the chunk over. Bill each table once, to the chunk that first references it,
and charge the one slot that remembers it.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Both branches appended tests to vector_match/tests.rs at the same anchor, so keep
both blocks rather than picking a side.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The field is GreptimeDB sample metadata, so the comments now say that instead of
arguing from what Prometheus omits: a FloatHistogram there has no such field, while
its rate and reset evaluation takes start timestamps through a separate channel, and
this crate's native range kernel does not read the field at all.
Comparison filtering and set selection were the two paths that carry the timestamp
without a test. Both keep the payload of the operand they hand back, including the
right side of an or at a point the left side does not cover, and a bool comparison
answers with a float so no histogram reaches the output.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The merged plan validates an input ordering in the arm that reads it, so a
selection over an interleaved input no longer binds at all. Assert that refusal
where it happens instead of asserting a runtime rejection the tree cannot reach,
and keep the map-over-a-selection case: a map above a selection does not shield
the check, because the check looks at the input the selection itself reads.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Resolve the four conflicts by taking the merged narthex side and re-applying this
branch own delta on top of it, since the base this branch grew from carried the
pre-squash commits of the same work.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* feat(promql): execute a bound native tree node by node, over sparse evaluated series
Ports the native runtime onto the sparse evaluated-series API: a chunk is
addressed by a `TimeAxis` that may hold several runs, so a consumer reads
positions through the axis instead of assuming `start + row`.
The driver and both node kinds move to that API:
- `chunk.range().len()` becomes `chunk.series.time.len()`, the compact row
count, in every metric and byte estimate.
- `occupied_runs` walks `time.positions()` with one field cursor, so a chunk
of several runs records each run where it belongs. A run open across a hole
now ends where the hole begins; leaving it open to the last row made two
runs look like one and refused a series that occupies the hole.
- A window keeps the pieces its evaluator decided in a queue: one push can
decide several runs, and reporting only what the push returned stranded the
rest until the next push. Queued pieces are charged by `retained_bytes`, and
the charge is recomputed when one leaves, so a released piece is not held.
- `map_chunk` answers `Option`: an operation that empties every position
(`clamp` with `max < min`) yields no chunk at all, unless the chunk closes
its series -- a closing chunk holding no row is handed over so a consumer
can tell "nothing more here" from "no more input".
`RangeEvaluator::retained_bytes` is restored with the three byte helpers it
reads: a field's buffers, a series' identity and the pending batch's vectors,
all by capacity, and still counted as storage rather than as a peak over a
push.
Tests read absolute positions from the axis (`decided` no longer adds a row
number to a start), and two sparse cases cover what the old reading got wrong:
a `Window -> Map -> Window` chain over a chunk of two runs, and a series that
occupies the hole between another's runs.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(promql): drop the window queue the sparse evaluator never needed
`RangeEvaluator::push` and `push_series` each return `Result<Option<EvaluatedChunk>>`: the
evaluator gathers every run it decided into one chunk and hands back at most one. So
`pending.extend(decided)` inserted at most one chunk and `take_pending` removed it on the spot,
leaving the queue empty after every successful push.
That makes the queue dead weight: a `VecDeque` allocation per productive window, an accounting
term that is always zero, a second drain site in `pull`, and doc comments claiming a problem the
API does not have. The driver's "ask the input again when a window decides nothing" loop was
already the whole story.
Back to returning the evaluator's own answer, and drop `pending`, `take_pending` and
`take_window_output`.
Covers the empty-map protocol this port introduces while it is here: an operation that empties
every position hands on nothing while its series is open, and one empty chunk when it closes. A
non-closing empty chunk would be rejected downstream and a dropped closing one would leave the
series unclosed.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(promql): pin the empty-map output count at one
The test checked that every output was empty and that exactly one closed, which a stray extra
non-closing empty output would also satisfy.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): charge the memory the native evaluator actually retains
Four omissions made the reservation blind to most of what a window over native
histograms keeps, and the existing incremental-equals-recomputed test could not see
any of them because both sides used the same formula.
- `FloatHistogram` owns four heap allocations -- both bucket lists, the custom
bounds, and the span layout -- that `FieldSamples::bytes` never looked at. A
retained 4096-bucket sample is tens of kilobytes against a ledger that saw a
struct header. `heap_bytes` counts them, and both the retained sample slice and
the histograms a row boxes are charged for what they own.
- Queued chunks were estimated as one float per field per row, which is not what a
histogram field holds: it holds indices into a shared `Arc<HistogramBatch>` and
the buffers behind the Arrow arrays. The figure now walks the samples, and counts
a shared table or a shared buffer slice once per pass rather than once per chunk
that references it.
- `history_bytes` included `size_of::<History>()` while the map slot term charged a
`History` per entry as well, so every entry paid two headers. The per-entry figure
now covers only the heap the entry owns.
- The primary key is charged for the allocation its `Buffer` keeps alive rather than
the bytes it shows: a scan slices the key out of a decoded dictionary-values
buffer, so a short key can pin a batch-sized allocation.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): keep the source queue's charge incremental
The queue's reservation was recounted by walking every queued chunk on each
enqueue and each pop. `push_raw` and `push_evaluated` are public and put no bound
on how deep the queue gets, so a caller that queues a whole series before pulling it
paid `N(N+1)/2` chunk visits to hold `N` chunks -- the same shape of defect this
branch fixes in `absorb`.
`QueuedCharge` keeps a reference count and the bytes behind each shared allocation:
a table or buffer is charged when the first queued chunk reaches it and given back
when the last one leaves, so an operation walks the one chunk it names. The count is
per chunk rather than per field, because a pop re-walks the same chunk with the same
dedupe and must remove exactly the references that were added.
A chunk's own struct bytes are counted per chunk (`own_bytes`); only the allocations
behind its fields are counted by address, since a struct has no address to dedupe on.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* perf(promql): append a forward-moving chunk to the emitted history
`absorb` rebuilt the whole stored run array on every non-empty chunk. Legal input
made that quadratic across chunks with no label collision: one series in `K` chunks,
chunk `i` occupying only grid position `2*i`, stores one more run per chunk and moves
`K(K+1)/2` of them -- about five billion for a hundred thousand rows.
A chunk that starts at or past the end of the last stored run only ever adds to the
end, so its runs are appended and the boundary run is joined where it touches. One
that can interleave or reach backwards still takes the full one-pass merge, which can
split a run. Both leave the runs sorted, disjoint and joined, which is what
`Emitted::occupy` looks a position up by.
The test records the chunks through `Emitted::occupy` itself and reads the history
back from it, covering the forward case, the touching boundary, a hole that has to
join both neighbours, and a position before everything stored.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): report a truncated input from a tree with no window
`close` only asked windows whether a series was still open, so a tree of an
input alone, or of a map over one, accepted a final chunk without `is_last` and
handed the consumer a series that never closed. The input node now follows the
series of the chunk it last handed over, and closing such a tree reports the
truncation against it, which is the same refusal a window makes for the input it
reads.
`occupied_runs` read a row the axis names with `expect`, which panics on a
`Series` whose fields are shorter than its axis; the fields are public, so that
chunk is constructible by a caller. It now returns the misalignment as an error
naming the node, the field and both lengths.
The chunk protocol says one series closes once, which reads as one close per
label set. State that it is per input series: a node that rewrites labels can
hand two series over under one label set and both of them close.
Also say in `Emitted`'s doc that the table is one node's own, so a label set
costs its bytes again in every node that keeps one.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): refuse an interleaved input, and close a label set only for its owner
Two series-level identity holes, both reported against `42ea525`.
The truncation flag followed the last chunk handed over, which is the same as
"is a series open" only while at most one series can be open. A tree with no
window still accepted `Interleaved`, and `a` open, `b` closed, end of input then
passed while `a` never closed. Tracking the open set would need an identity that
a raw chunk in bound-label mode does not have (`metric` is `None`, the key holds
it), so the ordering is refused when the state is built instead, for every tree
shape and not only under a window. The flag's doc now says what it means and why
that is the whole answer.
`History` closed on any series' `is_last`, so with `abs` dropping the metric name
a series that contributed nothing could close a label set another series was
still filling: `a{job="x"}` value, `b{job="x"}` empty close, `a{job="x"}`
continuation was refused with "already closed the label set". Contiguous input
hands over exactly that sequence, so it was not an interleaving artefact. A
history now remembers the series that filled it and closes only for that series'
closing chunk; a series that produced nothing under an open set is passed over,
as it already was under a closed one. The owner is charged as part of the entry.
The ordering check also reads every input node rather than only the first: a tree
with two inputs would otherwise have its second declaration read and dropped.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(promql): simplify native execution memory estimates
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): merge rewritten logical series before window evaluation
Accept disjoint closed-source fragments under one output label set. Retain occupancy checks and merge affected window inputs once at EOF using shared typed sample segments. Keep direct input windows and root maps streaming, and release collected fragments on finish or error.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): clarify approximate merge workspace estimate
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): validate series boundaries before collected input merges
Keep each collecting window's open metric and last position so EOF grouping cannot hide reversed runs or identity changes before closing. Preserve source and root-map piece semantics, and test malformed input release, empty closing chunks, and EOF truncation.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(promql): supply the default binary fill in the unimplemented-node fixture
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): merge label groups in first-member order and drop unused accessors
A HashMap iteration order made the merged series order, and the first collision reported, differ between runs; the root chunk stream exposes that order. Also drop len/is_empty, which had no callers and is_empty was always false.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The start-timestamp test was inserted into the middle of another test's doc comment, leaving the earlier test without one.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* feat(datatypes): describe label decoding in the raw series frame schema
A raw series frame written with key-encoded labels carries the primary key
as opaque bytes; only the binding held by the scanner says how to turn
those bytes back into a metric name and labels. A consumer that receives
the frame without that binding cannot decode it, so the schema now
describes its own label layout.
The description is compact JSON under `greptime.series.label_decode`,
carrying a version, the metric name, the primary-key encoding, the ordered
key columns with their physical types, and the logical tags to expose
-- exactly what decoding reads. It is derived from the binding, so there
is one writer, and a reader that does not implement the version it finds
rejects the frame instead of guessing.
`unpack_raw_series` keeps its binding argument and now requires it to
agree with the description the schema declares, so the two cannot drift.
`PrimaryKeyLabelDecoder` reduces both of its inputs to one internal key
layout, so the metadata-backed and description-backed paths share their
validation instead of growing a second decoder.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(datatypes): compare label descriptions by what their order means
The frame's declared label-decode description was compared to the binding's with
plain equality, but the description has one part whose order carries no meaning:
the decoder sorts logical tags by name when it binds them, so the same tags listed
in another order denote the same labels and were being refused.
`same_label_layout` canonicalises exactly that part and leaves `primary_key` in
place, because for a dense key the array position is the encoding position: the same
columns in another order are a different key, not the same key reordered. Both
fields now say which order they mean.
Three checks go with it. The binding stays for a stated reason -- it establishes
identity, the physical region key layout a decoded identity came from -- rather than
because a count of call sites kept it. The post-pack schema comparison in the series
scan could not fire: the leaf already re-derives that schema and compares it, and
every `SeriesSchema` field is covered by the checks between them. And two test
groups re-asserted what the tracked v1_metadata fixture pins case by case.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* feat(promql): decode a raw frame from the frame alone
`unpack_raw_series` took the label mode, the ordering and the caller's binding
along with the stream, so a consumer that received a frame from a peer still
needed a local copy of the binding to read it — the thing the frame's own
description exists to avoid, and the reason the description was freezing a wire
format for nobody.
The stream is now the only input: the field schema, the label mode, the label
decode description and the producer ordering all come from the frame's schema,
and every frame is validated whether or not a caller asked for it. `expected`
stays as an optional check on the schema that is declared — field names and their
order, and no evaluation grid — and supplies nothing to the decoder, so a caller
cannot smuggle in a layout the frame does not declare.
Three call sites compared the caller's binding against the frame and all three
were load-bearing: a peer's response is not trusted to be the region that was
planned, and a native plan's child is an arbitrary execution plan. Those became
`ensure_frame_matches_label_source`, which states what it compares: the label
layout, not the region. Two regions with the same tag ids and names compare equal,
and the doc now says so instead of claiming to establish identity.
A stream with no scan-bound identity reports `NO_BOUND_LABEL_SOURCE` and answers
`label_decode_spec()` instead; every consumer that decides whether to decode reads
the description, so the placeholder never stands in for "these labels are
complete".
The merge contract is the description, not the binding: inputs are compared by
the layout they declare, and a binding that could not be expressed on the wire — a
`RegionMetadata` snapshot — no longer makes the merge stricter than the frames it
merges. `logical_tags` gets one rule rather than two: the writer canonicalizes a
copy, because the caller's binding keeps its own order and the table scan compares
producer tag lists positionally, and readers compare by equality.
The text embeds `ConcreteDataType`'s serde, which `LABEL_DECODE_VERSION` has to
cover. Rather than mirror all 25 datatype variants into a type this module owns, a
frozen fixture records the text of every variant and an exhaustive match makes a
new variant fail to compile until it is recorded. The version policy is written
next to the constant: exact-text comparison across nodes, unknown versions
rejected, any same-version change breaking — with the planning-time fallback
stated as intended and marked not implemented.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(store-api): make every key-encoded raw stream declare its layout
A raw series stream whose chunks carry key-encoded labels had to be decoded
against a scan-bound `RawLabelSource`, and two consumers compensated for
producers that stayed silent by deriving a description from that binding:
`pack_raw_series` and the merge's `declared_layout`. `materialize_raw_labels`
did not compensate, so an unframed producer stream reached it with no
description and a chunk carrying no labels, and failed.
The stream itself is the authority for its chunks. A key-encoded producer
knows its own region metadata and can state the layout it writes, exactly as a
frame states the layout it carries, so the split contract — "a producer
declares its identity, a frame declares its layout" — is replaced by one rule:
a stream whose chunks carry key-encoded labels declares the description, and a
stream whose chunks carry complete labels answers `None`.
mito2's `RawStream` caches the derivation at construction, so the declaration
exists before the first poll and for an empty stream. The trait documentation
states the rule and no longer exempts unframed producers. Both fallbacks are
gone: `pack_raw_series` reads the stream's declaration only, and rejects a
key-encoded stream that declares none rather than packing it as an
explicit-label frame, which would describe chunks carrying no labels as if they
carried all of them. The merge reads the declaration only.
Test fixtures that model key-encoded producers now declare their layout too;
fixtures that carry complete labels keep answering `None`. The new mito2 test
decodes a real produced key through the declared description for both dense and
sparse encodings, and checks the declaration is present before polling even for
an empty stream.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(common-query): let the declaration decide the frame mode alone
`pack_raw_series` rejected a key-encoded stream that declared no description
outright, so a stream that stays silent could not be packed at all. That check
was redundant: the declaration already decides the frame's label mode, and the
first chunk whose labels disagree with it is refused by `RawSeriesChunkCursor`
with "raw chunk label mode does not match frame mode", so no such stream can
pack data either way.
What the check added was an early error for a producer that already breaks the
contract, in exchange for reading the stream's scan binding here — in the one
function whose rule is that the declaration is the only decode input. Drop it,
so pack keeps deciding the mode from the declaration and nothing else.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(store-api): assert the fixture's declared label decode description
The mock prepared source derives a `LabelDecodeSpec` from its label source and
reports it through `RawSeriesStream::label_decode_spec`, but no assertion read
it, so the derivation could drift from the chunks the fixture actually builds.
Check it against the description the fixture's own key columns imply: an
explicit source declares nothing, a primary-key source declares the metric, the
dense encoding, the one key column and its tag.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(promql): let the frame's declaration be the only label authority
Two things still treated a caller-supplied binding as authoritative after the
declaration became the decode input:
- A merged stream forwarded its first input's scan-bound identity, though a
merge is not a region scan and decodes from the declaration alone. It now
reports no bound identity.
- `KeyColumn.tag` repeated an invariant every key column is a tag. The check
moves to the one place a decoder is bound, so a snapshot built without
validation is still rejected instead of silently decoded.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* feat(promql): compile nested expressions instead of fixed query shapes
The native compiler matched three shapes: a bare selector, `range_fn(x[r])`,
and `range_fn(n, x[r])`. Every composition of those kernels was refused, so
`abs(rate(x[5m]))` and `clamp_min(rate(x[5m]), 0)` had no path through it even
though the kernels, the `Map` node and the `Sum` node already existed.
`compile` is now a thin entry over one recursive rule, `compile_expr`: a
parenthesis compiles its inner expression, a vector selector becomes the
instant selection it already was, a call dispatches on its signature, and
anything else is refused naming what was found. Composition follows from that
rule rather than from a list of accepted query shapes -- `abs(rate(x[5m]))` is
a map over whatever its argument compiles to, and
`clamp_min(abs(rate(x[5m])), 0)` is two maps over one window because the inner
call compiles once.
Math functions lower onto the node that already computes them: one `Map`
carrying one `MathOp`, over the node its vector argument compiles to. The
28 names and their parameters are one explicit table, so supporting another is
a decision made in one place; a name outside it is refused as having no native
kernel rather than silently treated as math. `round` without an argument binds
the kernel's documented default.
A scalar parameter is folded from the statement: number literals,
parentheses, unary negation, and arithmetic whose two sides both fold. The
operator goes through `ArithmeticOp::calculate`, the same function the kernels
use, so `%`, `^` and `atan2` keep Prometheus' semantics instead of being
redefined in the compiler -- `(-7) % 3` is `-1`, signed as Go's `math.Mod` is.
A parameter the statement cannot decide, `time()` being the real case, is
refused rather than bound to a value that would be wrong at every point but
one.
`ArithmeticOp::calculate` widens from `pub(crate)` to `pub` for the fold; its
body is unchanged. Nothing else is added: the plan nodes, the kernels and the
tree validation are the ones that were there, and validation still happens
once per statement, at the root.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): match the arithmetic token by its id, not by its text
`arithmetic_op` read the operator through the token's `Display` output. That
is a second source of truth for what an operator is: the id is stable and is
what the rest of the planner matches on (`prom_token_to_binary_expr_builder`),
while the rendered text is a presentation detail. A formatting change would
silently stop `%`, `^` and `atan2` from folding -- not wrong, but quietly
less than it says it does.
Also corrects the doc comment that claimed the parser keeps its token ids to
itself.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): say what the validator compares, and make the fold test bite
The map's doc claimed `NativeTree::validate` compares the map's output grid with
its input's by identity. It compares them by `EvalGrid::spec`, and only an input
node's output is compared by identity, so a map that allocated an equal grid of
its own would validate the same way. The comment says that now, and the two
assertions in the nested-map test compare spec and field names instead of
`Arc::ptr_eq`, which failed a map that allocated an equal grid for no behavioural
reason.
The constant-fold test could not catch what its doc said it guarded: `go_math`'s
modulo is `x % y` and its power agrees with `f64::powf` on `2 ^ 10`, so replacing
the kernel arithmetic with a hand-written match still passed. The power case is
now `1.0000006850274261 ^ 9.80019037e8`, where Go's repeated squaring accumulates
error the standard library's `pow` does not, and where the two disagree above the
last bit. Replacing the fold with `%`/`powf` fails it.
`pi()` and `time()` have no vector to be pointwise over, so the "no arguments"
branch explained them wrongly; without it they fall to "has no native kernel",
which is accurate, and a listed math name called with no argument at all is
covered by the signature's arity check. `math_op` now reads the name first and
returns the vector it found, so both rejections come from one place.
`argument_position` indexes a fixed array: its three callers pass literals, so
there is no fourth position to default to.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): refuse an interleaved scan at the compiler entry
Every accepted shape reads one series to its last chunk before the next, so the ordering
has to be refused before the statement's shape is dispatched on; the check sat in the range
function branch, which let the bare selector and a math function over it compile under
Interleaved. The window branch of NativeTree::validate stays as the backstop for a tree built
another way.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* chore(query): drop the prepared raw-series RPC skeleton
The raw-series preparation RPC was merged into `narthex` for a plan that never
landed: no server or frontend dispatches `greptime.prepare_raw_series.v1`, and the
three `Datanode` methods, `bind_raw_series_query` and the `QueryEngine` trio have no
call sites and no implementors. `PreparedNamedRawSeries` had no user outside them.
The wire envelope never shipped -- no tag contains the commit that added it -- so the
compatibility fixtures go with it. The harness drives `wire/` fixtures from the Rust
tests that own their context conversion rather than from SQLness discovery, and has
no retirement mechanism to record instead.
Left in place: `RawSeriesRequest` and its extension key, `raw_series_frame_ordering`,
`unpack_raw_series` and `RawLabelSource`, all of which the surviving series-frame
path still uses.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* chore(common-query): drop the raw-series request extension transport
The prepared raw-series RPC carried a `RawSeriesRequest` through a
query-context extension, and with that RPC gone (`607de914464`) nothing in
`src/` writes or reads the extension any more. What remains is the binding
the table scan actually uses: `RawSeriesRequest`, `RawSeriesTag`, `bind`,
`validate` and `same_encoding_identity`, unchanged.
Deleted: the extension key, `take_raw_series_request`, and the two
serialization methods that only existed to encode and decode that
transport, plus the wire fixture whose only reader was the test for them.
The fixture never shipped — the commit that introduced it is in no tag.
The tests that covered `validate` are kept, with their rejections now
asserted directly instead of through a JSON round-trip: an unsupported
version, an empty field list, a duplicate field, and a non-field column
id are all still refused. The binding test is untouched, including its
order, identity and `Arc` assertions.
`pub` items in a library crate never trip `dead_code`, so the compiler
could not have found this; the greps above are the evidence.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): bound an instant selection by the memory pool, not a point count
`MAX_INSTANT_MANIPULATE_OUTPUT_POINTS` capped an instant selection at a million
grid points per series. It arrived in a commit whose message was only "cap max
points": no doc, no derivation, no test of the bound itself. It bounded neither
the output (series count is unbounded) nor the payload (a histogram row is
kilobytes), and because the comparison was `>`, exactly a million points passed.
`InstantManipulateExec` — the operator this path actually runs — had no memory
accounting at all, so deleting the count alone would have turned a refusal into
an unbounded allocation. It now registers one reservation per partition and grows
it by the workspace the selection is about to allocate, before it allocates:
the two vectors `select_instants` returns, the copy of the indices `take` reads
with, the output time column, and one row per point per column — where a
histogram column is charged the widest row it holds, because one source row can
be selected by every point of the grid and is copied for each of them. The
reservation is released once the batch is built, since from then on it belongs to
whoever reads it.
The native operators keep their own reservations; `NativeInstantManipulateExec`'s
existing per-point term already covered the same three arrays, and this only says
so where it is computed.
`select_instants` no longer refuses anything: it documents that it allocates 16
bytes per selected point and reserves none of that, which is now every caller's
job. A query over a longer range therefore succeeds when the pool can hold it and
is refused with `ResourcesExhausted` when it cannot, instead of being refused at
a count that says nothing about either.
One bound is gone with the count and is not replaced here: a resolved
`query.memory_pool_size` of zero leaves DataFusion's unbounded pool attached, so
an operator that leaves that option unset has nothing refusing on this path. The
operator doc says so.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(promql): reserve an instant selection for the points it clips to
The workspace estimate charged a series for the whole planned grid, while select_instants clips the range to the series' first and last sample and its lookback. A week-long query at a one-minute step therefore reserved ~413 KB for a series that produces five points, and a small pool refused it before selecting anything. Reserve for the clipped candidate count instead, derived with the same alignment select_instants uses; a series that does span the grid is still charged for it.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* refactor(promql): keep one clipping, shared by the selection and its reservation
The reservation and `manipulate` carried the same clipping arithmetic twice,
with a comment asking the two copies to stay in line. They cannot drift now:
`clipped_range` is the only copy, and both call it. No behaviour change.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The binary kernel adjusted the pool and the metrics once per matched point, per filed row and per merged row, so a million plain float points meant roughly three million reserve calls inside a numeric loop. Reserve at three boundaries instead: the operands as chunks are retained, one figure per phase (pairing, sort, merge) with an estimate over rows/fields/segments/payload, and each result buffer when a block of it is allocated.
Delete the code that modelled another component's allocator: index_column_growth and its shadow index_capacity, BinaryOperand::ends_growth, and the flatten-capacity model in assembly_bytes. Nothing pre-reserves the left-times-right product and no large allocation happens before its reservation.
Tests that pinned the callback sequence or exact small-object arithmetic go; the resource properties stay: a genuinely large input or output is refused, a sparse small result is admitted, and reservations are released on finish, error, truncation and drop.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): state the real reason an instant selection needs no ordering check
`select_instants` reads one series' complete axis, so the executor must
collect a series to its last chunk before evaluating it: a single buffer
closed by `is_last` and keyed by nothing else. That needs each series'
chunks contiguous, which `Contiguous` and `KeyThenTime` both guarantee,
and `Interleaved` never reaches it because `unpack_raw_series` rejects
that ordering at the raw-frame boundary.
The comment said the opposite: that interleaved input was enough because
`select_instants` holds no cross-series state. The conclusion stood, but
the stated reason named a property the executor does not have.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): stop deriving the instant arm's ordering check from another path
The comment justified skipping an ordering check here by pointing at
`unpack_raw_series`, which rejects `Interleaved` at the raw-frame boundary. This
validator never runs through that call, so the rejection was never a premise it
could use, and the conclusion did not follow.
The requirement it was reaching for does exist, one layer down:
`NativeInstantManipulateExec` collects a series to its `is_last` chunk into one
buffer keyed by nothing else, so it needs each series' chunks contiguous. This
validator does not check that. `Instant` has no implementation in the native tree
yet and `try_to_native_execution_plan` has no callers, so the requirement is
unenforced rather than met in advance; it is settled when `Instant` lands.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* feat(promql): refuse an interleaved scan at the compiler entry, and in the validator
The `Instant` validation arm replaced an ordering check with a comment saying no
check was needed. The argument was that `unpack_raw_series` rejects `Interleaved`,
which holds only for the legacy `InstantManipulate` path and says nothing about
this tree. Meanwhile the refusal in `compile` sat after the bare-selector early
return, so `compile(eval_stmt("x"), schema, Interleaved)` returned `Ok` against
`compile`'s own rustdoc, and the same hole was open to every nested shape.
The requirement is real for every shape: a native evaluation reads one series to
its last chunk before the next. The refusal now runs before `compile` dispatches
on the shape, so the bare selector, the range function and its parameterised form
all inherit it, and a shape added later inherits it too.
`NativeNode::validate` keeps a check of its own, for a tree built some other way:
`Instant` and `Window` now share `ensure_not_interleaved` instead of one branch
having the check and the other a comment about it.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): link the validator by the node that has it
`NativeTree` has no `validate`; the method lives on `NativeNode`. Both doc
comments linked the tree, so rustdoc reports an unresolved link and the
published API docs lose the reference.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(promql): assert the control records the scan's ordering
The contiguous control in the interleaved-refusal test only checked that the
bare selector compiled, while its comment said the ordering is recorded. Assert
it on the tree's input instead. Drop the plain range case from the loop, which
the ordering table already compiles under `Interleaved`.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The gather reserved the whole planned grid, while select_instants clips the range to the series' first and last sample and its lookback: a week-long query at a one-minute step reserved ~504 KB for a series that produces five points, and a small pool refused it before gathering. Reserve for the clipped candidate count, derived with the same alignment the kernel uses.
Also pin the start-timestamp semantics the histogram change spread to: last_over_time and first_over_time hand back the sample they selected with its start timestamp, and limitk and limit_ratio keep it on the sample they keep, so a reader downstream can still place a counter reset.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
A window that collects its input answers only once its own input is finished, so ending the input now flushes the deepest ready window and lets the following pull carry its answer up; a binary node computes only when both operands are settled. Previously a binary node computed on an empty operand and marked itself computed, dropping what the window produced afterwards. Also stream the answer instead of collecting it: end_of_input() ends the input, and each pull runs the next stage, so the caller pulls the result and the last None closes the execution.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The raw-series preparation RPC was merged into `narthex` for a plan that never
landed: no server or frontend dispatches `greptime.prepare_raw_series.v1`, and the
three `Datanode` methods, `bind_raw_series_query` and the `QueryEngine` trio have no
call sites and no implementors. `PreparedNamedRawSeries` had no user outside them.
The wire envelope never shipped -- no tag contains the commit that added it -- so the
compatibility fixtures go with it. The harness drives `wire/` fixtures from the Rust
tests that own their context conversion rather than from SQLness discovery, and has
no retirement mechanism to record instead.
Left in place: `RawSeriesRequest` and its extension key, `raw_series_frame_ordering`,
`unpack_raw_series` and `RawLabelSource`, all of which the surviving series-frame
path still uses.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): add a map for src/promql
`src/promql` has no guide of its own, and the two things that cost the most to
learn the hard way are not visible from any one file: which of the two
evaluation paths is live, and what has to line up for a new extension node to
reach a datanode at all.
The map records the module layout, that coupling (substrait payload branch,
physical planner branch, `Commutativity` arm), the native model's reachability,
and the gotchas that fail silently: a missing commutativity arm, a label set
that closes twice under one label, a raw frame decoded with a binding other than
the one it was written with.
It describes mechanisms and where they live, not which branch or PR adds what,
so it stays true as the surrounding work lands.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): correct what the frame schema does and does not say
Two claims in the map were wrong about the code it describes.
The guide said a raw frame's schema metadata explains how to decode the primary
key. It does not: the metadata carries the format keys only — layout, content,
labels, time — and the decoder compares those and the field list, never a label
identity. `unpack_raw_series` still requires the caller's `RawLabelSource`, so
the guide now says to decode with the binding the stream was produced under,
which is the mistake it exists to prevent. A future decode descriptor can be
described here once it is in the base and this text can describe the API that
actually exists.
The raw-scan gap named one way past the partition problem as though it were the
only one. `RegionScanExec::try_to_series_scan` documents the other — finish
partition preparation before converting — so both are stated now, with the
scanner-side override kept as the actual requirement.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): say the storage producer exists and name what is left
The "cannot be planned" bullet listed the scanner-side override as missing,
but mito2 implements `RegionScanner::raw_series_schema` — #9669 landed it, so
the trait's `Ok(None)` default only refuses engines that have not implemented
it. Listing an implemented override as a gap misreads how far the raw path
actually reaches.
Separate the two things: the storage producer is available, and what is missing
is planner wiring plus the partition-preparation order. Merge current narthex in
so the paragraph describes the branch it will land on rather than a stale base.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(promql): hold the batch path to the per-window one on random input
Two comments claimed the opposite of what the code relies on: a batch's spans were
described as absolute indices that survive a release, but a span is recorded against
the retained arrays as they stand, and `advance` drains and shifts them. Nothing
enforces the difference -- the batch is correct only because `evaluate` flushes it
before advancing, so a later change that let a batch outlive one call would return
wrong counter values with no error. Both now say that, and `PendingBatch::spans`
carries the invariant where a reader looks for it.
The batch path had no randomized comparison at all: the differential tests drive a
probe kernel and the function tests cover no counter function, so only fixed cases
exercised it. A new differential test runs rate and increase over 200 seeds of one
to three fields, three series through one evaluator, random chunk splits and mixed
histogram samples, comparing the batch path against the same evaluator with its
batch form removed. Two assertions that could only have failed on a broken helper
are gone, and the counter-reset flag is documented as governing both readers of the
index, not just the per-window one.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(promql): assert the batch is flushed before the sample drain
`PendingBatch.spans` index the retained sample arrays, which `FieldSamples::advance`
drains and shifts. The batch is correct only because `evaluate` flushes it just above
that drain, and nothing enforced the ordering: a future change that let a batch
outlive the call would compute counter values against shifted samples with no error.
The assertion holds on every tested batch path. It is skipped when no batch kernel
is installed, since `pending` is only ever filled on the kernel branch.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): state the flush-before-advance rule once, and assert it plainly
The batch assert could not fail on its `batch.is_none()` disjunct: `accumulate`
is reached only from inside `if let Some(kernel) = self.batch.as_mut()`, and
`batch` is never cleared, so a non-empty `pending` implies a kernel. Drop the
disjunct and name who guarantees the order in the message instead.
The rule that a batch must flush before `advance` was restated in six places.
Keep it on `PendingBatch::spans`, where a reader asks why a span dies with the
batch, and in the assertion message. The other four now state only the
site-specific fact each needs.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* docs(promql): drop the last restatement of flush-before-advance
The rule now lives only on PendingBatch::spans and in the debug_assert message, as the review asked; the comment above the final flush restated it a third time.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
I hereby agree to the terms of the [GreptimeDB
CLA](https://github.com/GreptimeTeam/.github/blob/main/CLA.md).
## Refer to a related PR or issue link (optional)
Narthex operator task NEW-MAP-FN, first part. `histogram_quantiles`
follows separately: its quantile label uses Go's
`FormatOpenMetricsFloat`, which needs the shortest-digit formatting that
#9799 adds for `count_values`.
## What's changed and what's your intention?
Native kernels for four experimental Prometheus v3.15.0 functions.
- `max_of(a, b)` / `min_of(a, b)`: `ScalarFunction::apply` follows Go's
`math.Max` / `math.Min`, which differ from `f64::max` / `f64::min`:
- an infinity of the function's own sign beats NaN;
- NaN beats every other value;
- `+0` is greater than `-0`.
`map_scalar_function` applies it to two time-varying scalars, paired by
absolute grid position. Constant arguments can fold through `apply`.
- `start()` / `end()` / `range()` / `step()`: Prometheus folds these
into number literals before evaluation (`foldQueryContextFunctions`), so
the kernel is `QueryContextFunction::value(start_ms, end_ms, step_ms)`.
- `range()` and `step()` use Go's `Duration.Seconds`, which rounds twice
(whole seconds plus remainder / 1e9) and differs from `ms / 1000` in the
last bit for most values.
- `step()` is 0 when start equals end.
## Tests
Reference values come from promql-compat `narthex-golden-scalarfn`,
built for amd64:
- `math.Max` / `math.Min` over all pairs of ±0, ±1, 2.5, ±Inf and NaN;
- `Duration.Seconds` for 210 millisecond counts, including the
saturation boundary.
A unit test checks that time-varying scalars pair by position and that a
point missing on either side has no result.
## PR Checklist
Please convert it to a draft if some of the following conditions are not
met.
- [x] I have written the necessary rustdoc comments.
- [x] I have added the necessary unit tests and integration tests.
- [ ] This PR requires documentation updates.
- [x] API changes are backward compatible.
- [x] Schema or data changes are backward compatible.
- [ ] This PR needs to be backported to release branches, and I have
added the `backport-<target>` labels (e.g. `backport-v1.3` targets
`release/v1.3`).
I hereby agree to the terms of the [GreptimeDB
CLA](https://github.com/GreptimeTeam/.github/blob/main/CLA.md).
## Refer to a related PR or issue link (optional)
Narthex operator task MAP-LABEL (histogram / mixed same-label-set
merge).
## What's changed and what's your intention?
`grid_series::merge_same_labelset` returned `NotImplemented` as soon as
a member held a native histogram sample. That limited `label_replace` /
`label_join`, the date and native histogram functions, and
`evaluate_histograms` to float output whenever two results shared a
label set.
The merge now handles every sample type. Members of one label set are
still combined by absolute grid position and field. Floats and
histograms keep their type. A field held by two members at one point
fails with the same "vector cannot contain metrics with the same
labelset" error, whatever the sample types, as in Prometheus. Sparse
axes and multi-field series work as before.
### Tests
`merge_keeps_histograms_and_rejects_any_doubled_field` covers:
- two members whose histograms and floats interleave across points and
fields;
- histograms compared field by field after the merge;
- the collision error for float/histogram and histogram/histogram at one
point.
## PR Checklist
Please convert it to a draft if some of the following conditions are not
met.
- [x] I have written the necessary rustdoc comments.
- [x] I have added the necessary unit tests and integration tests.
- [ ] This PR requires documentation updates.
- [x] API changes are backward compatible.
- [x] Schema or data changes are backward compatible.
- [ ] This PR needs to be backported to release branches, and I have
added the `backport-<target>` labels (e.g. `backport-v1.3` targets
`release/v1.3`).
Move vector-vector binary execution onto the simplified native executor: keep one-time logical-series assembly and the actual-candidate regression, drop the deleted byte ledger in favour of the coarse per-chunk reservation, and keep the instant, collecting-window merge, fill and boundary validation from the parent.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Bring the instant selection node onto the simplified native executor: keep the parent's coarse accounting, NodeSpec, collecting-window merge and boundary validation, and re-express the instant gather in that shape.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Keep each collecting window's open metric and last position so EOF grouping cannot hide reversed runs or identity changes before closing. Preserve source and root-map piece semantics, and test malformed input release, empty closing chunks, and EOF truncation.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Accept disjoint closed-source fragments under one output label set. Retain occupancy checks and merge affected window inputs once at EOF using shared typed sample segments. Keep direct input windows and root maps streaming, and release collected fragments on finish or error.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Remove the separate matching prepass and reserve current live workspace at the existing kernel allocation boundaries. Release per-sample and per-field scratch after ownership ends; charge actual retained rows, values, histograms and errors. Unbudgeted public and set callers bypass accounting without another computation path.
Validate with cargo fmt -p promql -- --check; cargo check -p promql --all-targets; cargo nextest run -p promql --retries 0 --no-fail-fast; cargo clippy -p promql --all-targets -- -D warnings. The public nested Binary test also fails on swapped left/right operands and passes after byte-identical restoration.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Drop a redundant complex type annotation flagged by the actual strict clippy run. The collection and literal assertions are unchanged.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Checkpoint the vector-vector runtime and single shared matching kernel. Keep addressed input delivery, whole-input buffering, nested composition and error cleanup together. The existing arithmetic/comparison implementation remains the only computation path.
Local review checkpoint only, not ready for publication: all-targets check passes; the current run has three new fixture failures. Independent review requires current-live workspace resizing, field-local matched storage and kept-value merge budgeting before approval.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The doc on `an_oversized_selection_is_refused_by_the_pool` said the kernel has
no point limit any more. It does on this branch: the limit is removed on its own
branch, which this one does not carry, so the comment described a state that has
not arrived.
What is true here is the order: the estimate now applies to every gather, so the
pool is asked before the kernel is, and the pool's refusal is the one the caller
sees. That is worth saying on its own -- a bound in bytes on the path that
decides the points, rather than a count that says nothing about what they cost --
and it stays true after the limit goes.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Two findings from the review of the instant node.
The gather allocates after the last chunk arrives: the concatenated axis, the
descriptors that read it, the two arrays the selection returns, and the rows the
builder keeps. Nothing asked the pool for any of it, so with one sample selected
by every point of a million-point grid the node took tens of megabytes while its
reservation fell to the buffered chunks' size -- nothing at all, on the chunk
that ends the series. `gather_bytes` now derives a bound from the values in hand
(rows, chunks, segments, fields, points, and the widest histogram row per field,
since one row can be selected by every point), and the reservation grows by it
before the gather runs. It shrinks back on both the success and the error path,
so the workspace never outlives the call.
A selection reads an existing sample, so it has to carry that sample's payload.
`FloatHistogram` had no `start_timestamp` and `push_to` wrote `None`, which lost
it for any histogram that had one: `detect_start_timestamp_reset` reads that
field to spot a counter reset, so a window over this output would mis-detect
resets. The field is now carried through a view and written back; the kernels
that compute a histogram instead of reading one leave it `None`, which is what
they produced before.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
Two series-level identity holes, both reported against `42ea525`.
The truncation flag followed the last chunk handed over, which is the same as
"is a series open" only while at most one series can be open. A tree with no
window still accepted `Interleaved`, and `a` open, `b` closed, end of input then
passed while `a` never closed. Tracking the open set would need an identity that
a raw chunk in bound-label mode does not have (`metric` is `None`, the key holds
it), so the ordering is refused when the state is built instead, for every tree
shape and not only under a window. The flag's doc now says what it means and why
that is the whole answer.
`History` closed on any series' `is_last`, so with `abs` dropping the metric name
a series that contributed nothing could close a label set another series was
still filling: `a{job="x"}` value, `b{job="x"}` empty close, `a{job="x"}`
continuation was refused with "already closed the label set". Contiguous input
hands over exactly that sequence, so it was not an interleaving artefact. A
history now remembers the series that filled it and closes only for that series'
closing chunk; a series that produced nothing under an open set is passed over,
as it already was under a closed one. The owner is charged as part of the entry.
The ordering check also reads every input node rather than only the first: a tree
with two inputs would otherwise have its second declaration read and dropped.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
The three end-to-end sites unpacked every frame as `Contiguous` while the
producer declared `KeyThenTime`, and `SequenceValidator` only checks key order
under the ordering it is given. A producer that declared key-then-time and
emitted keys out of order passed all three. Each site now reads the ordering the
frame declares, asserts it is `KeyThenTime` — so a future producer that quietly
downgrades its declaration fails instead of skipping the check — and unpacks
under it. Reversing two series' key order in the fixture now fails the test;
passing `Contiguous` for the same frames still passes, which is what the old
code did.
The two-phase test asserted key order for an ordering that declares only
`Contiguous`: a reader that stayed contiguous and stopped sorting keys is within
contract and failed the test for it. It now asserts one run per key and that the
two assignments hold the first and last key, which is what `Contiguous` plus the
assignment composition actually promise.
`promql` leaves mito2's dev-dependencies. The storage contract needs only
`pack`/`unpack_raw_series` from `common-query`, which mito2 already depends on;
the cross-region merge composition moves to promql, where it is a stream-level
test rather than a two-region fixture: `merges_two_unpacked_frames_through_the_frame_codec`.
The merge rejection that the two-phase test used to exercise is already covered
by `rejects_unsupported_ordering_and_empty_input_without_polling`, which the
remaining test now cites instead of duplicating.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>