Skip to content

perf(ingest,staging,query): single-hop ingest, parallel Parquet conversion, certified-bounds TopK, and filter-first staging scans - #193

Merged
VibeSWE merged 29 commits into
mainfrom
t3/investigate-ingest-performance
Dec 1, 2026
Merged

VibeSWE merged 29 commits into
mainfrom
t3/investigate-ingest-performance

Conversation

@VibeSWE

@VibeSWE VibeSWE commented Dec 1, 2026 •

Copy link
Copy Markdown

Summary

Implements general-purpose ingestion, conversion, staging-scan, and query-planning performance improvements across 28 commits (origin/main..c56936d8) while preserving exact query semantics, fail-closed safety invariants, and strict memory bounds.

Ingest, Staging & Parquet Conversion (origin/main..236290de)

  1. Single-hop flat JSON → Arrow ingestion (src/event/format/json.rs, src/utils/json/strict.rs, src/handlers/http/ingest.rs): builds Arrow RecordBatches directly from JSON bytes off the HTTP worker thread, eliminating intermediate map/value hops.
  2. Single-snapshot stream admission & zero-clone LogSource fast path (src/parseable/streams.rs, src/handlers/http/modal/utils/ingest_utils.rs): consolidates schema/stream admission checks per batch and removes redundant clones on the ingest hot path.
  3. Async push queue, pre-encoded group writes & off-lock cache drops (src/parseable/streams/push_queue.rs, src/parseable/staging/writer.rs): moves Arrow IPC encoding and eviction drops off writer.lock().
  4. Parallel pipelined log Parquet conversion (src/parseable/streams.rs, src/parseable/staging/reader.rs): pipelines IPC decoding and Parquet writing with bounded merged reverse-reader buffers.
  5. Zero-allocation FieldStatsAccumulator & bounded thread pool (src/storage/field_stats.rs): eliminates per-row allocations during pstats accumulation.
  6. Zero-copy LocalFS hard_link fast path (src/storage/localfs.rs): links completed multipart uploads atomically on LocalFS instead of copying file payloads.
  7. Parallelized, projected & count-optimized disk-backed staging scans (src/parseable/staging/disk_source.rs, src/query/stream_schema_provider.rs): projects columns and parallelizes disk-staged Arrow IPC scans with exact row-count fast paths.

General-Purpose Query Engine & Clustered Conversion (236290de..c56936d8)

  1. Live-window planning, manifest provenance & O(1) metadata counts (src/query/stream_schema_provider.rs, src/catalog/column.rs, src/catalog/manifest.rs):
    • Skips unnecessary reverse(&batch) on unlimited in-memory staging scans and omits empty UnionExec children.
    • Shares METADATA_CACHE per closed manifest on standalone Mode::All live queries while keeping active minute manifests uncached.
    • Adds manifest StatsProvenance (complete_row_groups, exact_min_max, timestamp_unit) and general Exact time-bound pushdown + interior/boundary file split (ExactTimeFilterPlan).
    • Publishes certified exact per-file and table-level Statistics (num_rows, null_count, certified min/max; withholding float min/max from DataFusion Statistics to prevent [7.0, NaN] literal substitution, while permitting sound non-NaN equality manifest pruning only).
  2. Certified-bounds progressive TopK execution (src/query/ordered_topk.rs, src/query/mod.rs):
    • General ProgressiveTopKRule + ProgressiveTopKExec for any supported column, ASC/DESC, NULLS FIRST/LAST, and LIMIT/OFFSET (<= 1,000), ordering unbounded staging + certified-bound Parquet files best-first and pruning uncompetitive files unopened.
    • Guarded by has_prunable_unit() (falls back to stock parallel SortExec whenever no unit can be pruned, e.g. identical file bounds or all-nullable NULLS FIRST), DataFusion MemoryPool reservations, and fresh per-execution dynamic filters.
  3. Filter-first two-phase staging disk IPC reader (src/parseable/staging/reader.rs, src/parseable/staging/disk_source.rs):
    • Decodes predicate columns first from disk-staged Arrow IPC batches and skips payload decompression on zero-match batches.
    • Guarded by shared 64 MiB / 16 MiB message budgets, FlatBuffer bounds validation, non-throwing predicate & narrowed-nullability checks, cancellation checks, and automatic adaptive fallback to single-phase decoding after 4 consecutive matching batches.
  4. Parallel pipelined clustered log conversion & inline field stats (src/parseable/streams/log_clustering.rs, src/storage/field_stats.rs, docs/log-severity-clustering.md):
    • Opt-in (P_LOG_SEVERITY_CLUSTER_COLUMN, None by default) cooperative rayon::join pipelined clustering with actual-byte 64/128 MiB caps, sticky sequential fallback, and bounded (16 MiB) inline FieldStatsAccumulator.

Query Evaluation Results (Release Build c56936d8 vs Baseline 236290de)

Evaluated across 20 diverse SQL query families (100+ queries, 855 mid-minute/millisecond boundary fuzz queries, 200-query 8-way concurrency bursts, 48-query concurrent ProgressiveTopKExec isolation checks, wide 52-column evolved schemas, float NaN/NULL/tie edges, NDJSON streaming, and pstats parity) with zero correctness regressions:

Workload Baseline (236290de) p50 Optimized (c56936d8) p50 Speedup Notes
SELECT count(*) FROM prod_logs 6.16 ms 1.43 ms 4.31× O(1) metadata fold (2.5×–6.6× across windows)
SELECT count(user_id), count(*) FROM prod_logs 6.28 ms 1.70 ms 3.70× Exact null_count fold; 0 false folds on filtered/DISTINCT
ORDER BY p_timestamp DESC LIMIT 100 5.98 ms 3.57 ms 1.67× ProgressiveTopKExec prunes 2/3 files (7.8×–9.9× fewer bytes scanned)
ORDER BY p_timestamp DESC LIMIT 1000 7.38 ms 4.59 ms 1.61× ProgressiveTopKExec
ORDER BY p_timestamp DESC LIMIT 4600 11.11 ms 8.89 ms 1.25× Stock SortExec (fetch > 1,000)
ORDER BY app ASC, seq ASC LIMIT 100 5.85 ms 5.03 ms 1.16× Stock SortExec (has_prunable_unit == false)
ORDER BY app ASC, seq ASC LIMIT 10000 16.92 ms 15.01 ms 1.13× Stock SortExec
WHERE seq = 999999999 (absent Float64 eq) 1.36 ms 1.31 ms 1.03× Sound non-NaN equality manifest pruning
Wide 52-col SELECT * TopK / ILIKE TopK — −45% to −57% 1.8×–2.3× Pruned unopened wide Parquet files
8-way concurrent repeated queries (200 queries) — −48% p95 1.55× QPS 200/200 deterministic; 0 errors
Live staging selectivity sweep (0%–20% / 82%–100%) — −4%..−20% / neutral 1.04×–1.25× Adaptive single-phase fallback verified (−0.3%..+0.4% at 100%)

Verification

  • cargo fmt --check: clean
  • P_BUILD_NO_UI=1 cargo test --lib: 2,066 passed, 0 failed, 25 ignored
  • P_BUILD_NO_UI=1 cargo test --test staging_api_compat: 1 passed, 0 failed
  • P_BUILD_NO_UI=1 cargo test --bin parseable jemalloc_conf_tests: 1 passed, 0 failed
  • P_BUILD_NO_UI=1 cargo clippy --lib --bins --tests: 0 new warnings across all touched files

Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

VibeSWE and others added 29 commits November 30, 2026 11:35
…ache drops

Ingestion stalled below CPU saturation because callers of a busy stream
parked their Rayon threads behind one leader that concatenated, compressed
and flushed for all of them, and because rollover and budget eviction freed
gigabytes of cached batches while holding the writer lock.

Push queue
- Add `Stream::push_async`: callers await admission and the write instead of
  blocking a thread; turns run on a blocking-pool drainer. `Stream::push`
  keeps its signature and behaviour for blocking callers.
- One FIFO admission line serves both kinds of caller, still bounded by
  MAX_JOBS and MAX_BYTES. A waiting async job sits in the line itself and is
  admitted by whichever thread makes room, so admission never depends on a
  task being polled. A cancelled waiter takes its job back out of the line.
- Replace the `lifecycle` RwLock with `PushQueue::pause`: a flush closes
  admission and waits for the admitted pushes, without any push holding a
  lock guard across an await.

Staging writes
- `push` encodes and compresses large dictionary-free batches on the
  caller's thread (`PreEncodedBatch`); the writer copies the bytes. Reordered
  columns, dictionary schemas and mismatched schemas fall back to encoding
  under the lock.
- A turn's batches are written under one hold of the writer lock and each
  touched file is flushed once (`Writer::push_group`). A batch is acknowledged
  only after the flush that covers it; a failed append or flush retires the
  writer and fails every batch still staged in it, keeping the previously
  acknowledged prefix queryable.
- Large batches are no longer concatenated in the queue. Small batches, where
  message framing dominates, are still combined.
- DiskWriter buffer raised from 8 KiB to 256 KiB.
- `P_STAGING_IPC_COMPRESSION=lz4|zstd` (default lz4) selects the codec of
  compressed messages; readers need no change because each message names its
  own codec.

Memory
- Rollover, budget eviction, `evict_staging_memory` and writer retirement move
  cached batches into a `DeferredDrop` that the caller drops after releasing
  the writer lock and its queue turn. Their bytes leave the staging budget at
  the move, so accounting stays exact; sets of 8 MiB or more are freed by a
  dedicated thread.
- Name `background_thread:true` in the compiled-in jemalloc configuration and
  assert it in `jemalloc_conf_tests`. The `background_threads` crate feature
  already made it jemalloc's built-in default, so this pins the setting
  rather than changing it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… 'a16ec8f4' into t3/investigate-ingest-performance
POST /api/v1/ingest parsed the whole body into a serde_json::Value on the
actix worker, validated it, and then had Arrow's JSON decoder copy every
row onto its tape before building the columns.

- The handler takes the body as bytes and parses it on the rayon pool
  (bodies up to 4 KiB are parsed inline, which is cheaper than the hop).
  A request the Json<StrictValue> extractor refused is still refused
  before anything else, with the extractor's response; the route caps the
  body with a PayloadConfig of the same limit.
- A body of flat rows whose keys are all existing scalar fields of the
  stream is built into its record batch straight from the bytes, in one
  pass and without a Value (try_parse_flat_json_bytes_to_recordbatch,
  over the new strict flat-row parser in utils::json::strict). It only
  takes bodies for which the general path yields the same batch, origin
  size and flatten budget charge; every other body, and every body that
  is rejected, goes through the general path unchanged.
- decode_rows builds scalar columns directly from the values and leaves
  everything else, and every batch that does not decode, to Arrow.
- value_compatible_with_type asks Arrow for the timestamp first and skips
  the chrono parsers for the canonical shapes Arrow accepted.

Release microbenchmark, 2,000 rows / 650 KB: 4.9 ms through Value and
Arrow's decoder, 4.1 ms through Value and the direct builders, 1.2 ms
from bytes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Regular log streams were converted from staged Arrow to Parquet by one
thread: an ArrowWriter fed batch by batch. A hot stream took about as
long to convert a minute of data as the minute lasts.

Log conversion now runs as a pipeline on LOG_CONVERSION_THREADPOOL:

- Row groups are cut from the merged reader's batches by row count
  (row_group_size) and by Arrow data bytes (row_group_bytes), without
  copying or reordering rows, and encoded with ArrowRowGroupWriterFactory:
  the columns of a row group in parallel, and up to
  LOG_ROW_GROUP_ENCODE_IN_FLIGHT (default 2) row groups at once.
- While one wave of row groups is encoded, the previous wave is appended
  to the file in order and the next one is read. The steps are joined on
  the pool, never passed over blocking channels, so a pool whose every
  thread is converting a stream cannot deadlock.
- The decoded batches of a wave are reversed in parallel; they are then
  adapted and counted for field statistics one by one in source order.
- The pipeline is installed on the conversion pool whatever thread calls
  it, so none of its work lands on the global Rayon pool or the ingest
  pool.

With row groups cut by row count the file is byte for byte what the
sequential writer produced. The byte limit is now counted in Arrow data
bytes of the rows, not in the Parquet writer's encoded-size estimate.

Also:

- A part whose writer closed without error and reports rows is no longer
  reopened to validate its footer. Empty outputs are still checked and
  removed as before.
- The Parquet part file is written through a 256 KiB buffer; the 32 MiB
  writeback hint flushes that buffer first and is otherwise unchanged.
- Staged Arrow files are scanned for message boundaries through a 64 KiB
  buffer instead of four system calls per message, and decoded through a
  256 KiB buffer.
- utils::arrow::reverse uses 32-bit take indices, shares the columns of
  batches with at most one row, and reverses the columns of larger
  batches in parallel when, and only when, its caller is already on a
  Rayon pool.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…e field stats

Clustered log conversion (P_LOG_SEVERITY_CLUSTER_COLUMN) ran the
sequential clustered writer off the conversion pool and returned no
artifacts, so dataset field stats re-read every clustered Parquet file.

Clustered files are now written by the same cooperative rayon::join
pipeline as unclustered log conversion, on LOG_CONVERSION_THREADPOOL:
row groups are cut at exactly row_group_size rows by LogRowGroupSource
(byte cap off, so membership is unchanged), clustered with the stable
(cluster ASC NULLS LAST, time DESC NULLS LAST) permutation, and each
column is gathered and encoded in parallel in the 8,192-row batches the
sequential writer hands ArrowWriter, so pages and bytes are identical.
Per-column encoded-size estimates replay ArrowWriter's row/byte split
rules; a group it would split is re-encoded by an exact emulator.

Memory: groups estimated above the 128 MiB parallel ceiling (wide
schema churn) or files with content-defined chunking use the sequential
writer; above 64 MiB waves hold one group; a wave whose decoded rows
exceed 64 MiB is encoded before the next one is read.

FieldStatsAccumulator is fed every finished batch in source order on
both paths and the populated WrittenParquetArtifacts (stats and footer
metadata) are returned. Default (clustering off) behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add ProgressiveTopKRule/ProgressiveTopKExec (src/query/ordered_topk.rs).
The rule replaces `SortPreservingMergeExec(fetch) -> SortExec(TopK)` or a
single-partition `SortExec(fetch)` (fetch <= 10,000) whose primary key is
a plain column, when the input is a UnionExec and/or file scan behind
Filter/Projection/Coalesce/Repartition/Cooperative nodes.

Each union input (and each file, when every PartitionedFile carries its own
statistics) becomes a unit. Bounds come only from Precision::Exact min/max
statistics of a file scan; row order is never trusted. Unbounded units run
first, then bounded units best-bound first under a 1, 2, target_partitions
partition budget. Once `fetch` rows are held, a unit whose exact max (DESC)
or min (ASC) is strictly beyond the fetch-th key, and that provably holds no
NULL keys under NULLS FIRST, is never started (or is aborted). Each unit runs
DataFusion's own TopK; results merge into at most `fetch` rows. The original
TopK dynamic filter pushed into the scans is driven from the global
threshold. Dropping the stream aborts every unit task.

Registered in Query::create_session_state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… '891033da' into t3/investigate-ingest-performance
Address the Astra 6.2 review of the progressive certified-bounds TopK:

- Never split a file scan with a pushed-down limit into per-file units
  (each copy would re-apply the limit).
- Keep uncertified files of a split scan in at most
  min(target_partitions, original group count) size-balanced groups.
- Count every unit, unbounded ones included, against one shared
  target_partitions budget of running partitions.
- Reserve held TopK rows and merge buffers in the query memory pool.
- Build per-file units from a file-less template config (linear planning)
  and prune pending bounded units only when the threshold changes, by
  popping the prunable suffix of the best-first queue.
- Require a no-NULL certificate on every byte-range piece of a file.
- Give each execution fresh unit state (reset scan work queues) and its
  own dynamic filter, rebound into the Parquet scans and marked complete
  when the run ends.
- Let bounded units use spare budget once unbounded units have run for
  OVERLAP_DELAY; thresholds from completed units already prune safely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Address Astra 6.2 Review B findings on parallel log clustering (Q3):

- P0-2: clustered row groups stop taking rows at 128 MiB of Arrow data
  (CLUSTER_ROW_GROUP_MAX_BYTES), counted per decoded batch identically in
  the parallel source and the sequential fallback, so both writers cut the
  same groups. Groups of ordinary rows are unchanged and byte-identical.
  Each row group now reports the bytes its finished rows actually retain
  (allocations deduplicated, so IPC-shared buffers count once); once one
  exceeds 64 MiB the rest of the file is read, encoded and appended one
  group at a time with no read-ahead or overlap.
- P0-3/P1-6: FieldStatsAccumulator tracks retained value bytes and
  approximate mode. Inline clustered stats are dropped immediately when they
  exceed MAX_INLINE_FIELD_STATS_BYTES (16 MiB) or become approximate, and
  the upload path rereads the file. The staged stats cache refuses entries
  over 16 MiB and evicts oldest entries beyond 64 MiB total.
- P1-5: after the first byte-limit split, later row groups go straight to
  the split-aware encoder (sticky), and row-limit splits are predicted
  without encoding twice.
- P2: docs narrow the row-group time-pruning claim and describe the
  64 MiB / 128 MiB actual-byte thresholds and stats dropping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… 'f519901e' into t3/investigate-ingest-performance
@VibeSWE
VibeSWE merged commit 7e40406 into main Dec 1, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant