Repository navigation
perf(ingest,staging,query): single-hop ingest, parallel Parquet conversion, certified-bounds TopK, and filter-first staging scans - #193
Merged
Conversation
…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>
…d interior time/count pushdown
…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>
…istency, and staging two-phase filter
…ck, cancellation, and empty-batch merge
… 'f519901e' into t3/investigate-ingest-performance
… float eq pruning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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)src/event/format/json.rs,src/utils/json/strict.rs,src/handlers/http/ingest.rs): builds ArrowRecordBatches directly from JSON bytes off the HTTP worker thread, eliminating intermediate map/value hops.LogSourcefast 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.src/parseable/streams/push_queue.rs,src/parseable/staging/writer.rs): moves Arrow IPC encoding and eviction drops offwriter.lock().src/parseable/streams.rs,src/parseable/staging/reader.rs): pipelines IPC decoding and Parquet writing with bounded merged reverse-reader buffers.FieldStatsAccumulator& bounded thread pool (src/storage/field_stats.rs): eliminates per-row allocations duringpstatsaccumulation.hard_linkfast path (src/storage/localfs.rs): links completed multipart uploads atomically on LocalFS instead of copying file payloads.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)src/query/stream_schema_provider.rs,src/catalog/column.rs,src/catalog/manifest.rs):reverse(&batch)on unlimited in-memory staging scans and omits emptyUnionExecchildren.METADATA_CACHEper closed manifest on standaloneMode::Alllive queries while keeping active minute manifests uncached.StatsProvenance(complete_row_groups,exact_min_max,timestamp_unit) and generalExacttime-bound pushdown + interior/boundary file split (ExactTimeFilterPlan).Statistics(num_rows,null_count, certified min/max; withholding float min/max from DataFusionStatisticsto prevent[7.0, NaN]literal substitution, while permitting sound non-NaN equality manifest pruning only).src/query/ordered_topk.rs,src/query/mod.rs):ProgressiveTopKRule+ProgressiveTopKExecfor any supported column, ASC/DESC,NULLS FIRST/LAST, andLIMIT/OFFSET(<= 1,000), ordering unbounded staging + certified-bound Parquet files best-first and pruning uncompetitive files unopened.has_prunable_unit()(falls back to stock parallelSortExecwhenever no unit can be pruned, e.g. identical file bounds or all-nullableNULLS FIRST), DataFusionMemoryPoolreservations, and fresh per-execution dynamic filters.src/parseable/staging/reader.rs,src/parseable/staging/disk_source.rs):src/parseable/streams/log_clustering.rs,src/storage/field_stats.rs,docs/log-severity-clustering.md):P_LOG_SEVERITY_CLUSTER_COLUMN,Noneby default) cooperativerayon::joinpipelined clustering with actual-byte 64/128 MiB caps, sticky sequential fallback, and bounded (16 MiB) inlineFieldStatsAccumulator.Query Evaluation Results (Release Build
c56936d8vs Baseline236290de)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
ProgressiveTopKExecisolation checks, wide 52-column evolved schemas, float NaN/NULL/tie edges, NDJSON streaming, andpstatsparity) with zero correctness regressions:236290de) p50c56936d8) p50SELECT count(*) FROM prod_logs2.5×–6.6×across windows)SELECT count(user_id), count(*) FROM prod_logsnull_countfold; 0 false folds on filtered/DISTINCTORDER BY p_timestamp DESC LIMIT 100ProgressiveTopKExecprunes 2/3 files (7.8×–9.9×fewer bytes scanned)ORDER BY p_timestamp DESC LIMIT 1000ProgressiveTopKExecORDER BY p_timestamp DESC LIMIT 4600SortExec(fetch > 1,000)ORDER BY app ASC, seq ASC LIMIT 100SortExec(has_prunable_unit == false)ORDER BY app ASC, seq ASC LIMIT 10000SortExecWHERE seq = 999999999(absent Float64 eq)SELECT *TopK /ILIKETopK−0.3%..+0.4%at 100%)Verification
cargo fmt --check: cleanP_BUILD_NO_UI=1 cargo test --lib: 2,066 passed, 0 failed, 25 ignoredP_BUILD_NO_UI=1 cargo test --test staging_api_compat: 1 passed, 0 failedP_BUILD_NO_UI=1 cargo test --bin parseable jemalloc_conf_tests: 1 passed, 0 failedP_BUILD_NO_UI=1 cargo clippy --lib --bins --tests: 0 new warnings across all touched filesOpen in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.