Repository navigation
Import: survive low open-file limits — best-effort raise + FD-budgeted index build - #1591
Conversation
…loor, rebuild raise + 4-order fan-in, observed-limit preflight, cascade cleanup, two-scenario e2e
…based vocab warning, shrink e2e to 12k users
bplatz
left a comment
There was a problem hiding this comment.
Approving. Strong work — the layering (raise what the OS will give → plan within what's left → fail informatively) is the right decomposition, and each layer is independently useful.
The cascade byte-identity argument is genuinely rigorous. I checked the load-bearing claim rather than taking it on faith: consecutive chunks(fan_in) groups, outputs pushed in index order and consumed in that order, KWayMerge tie-breaking by stream index — so the cross-group tie-break order equals flat run order, and the induction to arbitrary depth holds. BucketWriterPool is right in the details people miss: flush-before-evict, O_APPEND on reopen rather than create, last_used stamped before the victim scan but excluded from it because the slot isn't open, and finish() erroring instead of swallowing flush failures in Drop. The re-exec test lowering hard and soft — with the explicit note that leaving hard alone would let the pipeline's own raise undo the constraint and prove nothing — plus the vacuity check, is the part most people skip.
Ran fluree-db-core fd_limit and the full fluree-db-indexer suite locally; all green.
A handful of things flagged inline. The first is an unenforced invariant rather than a live bug — I traced the precondition and it does hold today — but it's cheap to close and the sibling cascade in this same PR already does it the other way. Worth a look to decide which you want to take now.
| let out_path = pass_dir.join(format!("merged_{i:06}.frn")); | ||
| // Spool sources carry no op sideband (`peek_op` is uniformly 1 | ||
| // on the import path), so version-1 intermediates lose nothing. | ||
| let mut inter = StreamingRunFileWriter::create(&out_path, order, false)?; |
There was a problem hiding this comment.
The hierarchical arm discards the op sideband; the flat arm honors it.
Here the group merge does while let Some((record, _op)) = ... and pushes a hardcoded 1. But pump_spot_merge, which both arms feed, does if op == 0 { continue }. So a record with op == 0 is dropped by the flat arm and kept as an assertion by the hierarchical one — and which arm runs is decided by commits.len() > fd_plan.spot_fan_in, i.e. by the machine's FD limit. Same input, different index, silently.
I chased the precondition and it holds today: import.rs:4861 writes op: 1, // assert, so the bulk-import path really is uniformly assert-only and the comment is accurate about the current caller. Not reachable now. Still worth closing:
- The claim is about a caller three crates away with nothing linking them.
SortedCommitMergeReaderV2::peek_opreturnsv1.opstraight from the file, the format round-trips retractions (spool.rs:1951), andspool.rs:1729filtersrecord.op == 1for rdf:type stats — the surrounding code does not assume uniformity. - The pump's own
if op == 0 { continue }is evidence that whoever wrote it didn't assume it either. cascade_runs_to_fan_inin this same PR takes the opposite position on the identical question:let with_op = streams.iter().any(|s| s.header.has_op());. Two cascade implementations, two answers.
Either mirror the sibling's with_op logic, or add debug_assert_eq!(_op, 1) so the precondition is enforced where it's relied on rather than asserted in a comment. Given the byte-identity discipline everywhere else here, this is the one arm pair that's identical only by assumption.
There was a problem hiding this comment.
Great catch — agreed this was the one arm pair that was identical only by assumption, and the two cascades answering the same question differently was the tell. Landed in a21dd0961: the hierarchical arm now writes with-op intermediates and passes the merge's op byte through verbatim, so both arms agree by construction and the pump's op == 0 skip sees the same ops either way — preserve-don't-resolve, same doctrine as cascade_runs_to_fan_in.
One small wrinkle from re-tracing your repro path: it seems SortedCommitMergeReaderV2 doesn't actually override peek_op (only the V1 adapter at spool.rs:690 does), so the V2 path reports a uniform 1 today even where the spool file carries a retraction — which puts the divergence one more step from reachable than the comment suggested, but also means the old hardcoded 1 was silently load-bearing on that non-override. All the more reason to carry the byte through rather than assert about it. The CID-equivalence tests are unchanged and green (the 31- vs 30-byte intermediate format never reaches leaf bytes).
| let fd_raise = fluree_db_core::fd_limit::raise_nofile_soft_to_hard(); | ||
| fluree_db_core::fd_limit::log_raise_outcome(&fd_raise); | ||
| if let Some(limits) = fluree_db_core::fd_limit::nofile_limits() { | ||
| if limits.soft < 96 { |
There was a problem hiding this comment.
This refuses imports that would previously have succeeded. The justification is that 96 "covers the budgeted build's worst phase" — but the worst phase scales with input. A single-chunk import of a small file has no scatter pressure, no SPOT fan-in beyond one reader, and one run file per order; it worked fine at soft=64 before this PR and is now refused outright.
That's a regression for library embedders in constrained containers, and it lands exactly where the rest of this PR already does the right thing — bounded pool, cascade, and an EMFILE error that now preserves raw_os_error and names the observed limit, which was the actual problem to begin with.
Chunk count is known at preflight, so the gate could scale to input shape. Or downgrade to a warning and let the improved exhaustion error carry the diagnosis.
There was a problem hiding this comment.
You're right, and this was the weakest part of the layer-3 story — a fixed floor gates on the worst phase, but the worst phase scales with input, and a single-chunk import at soft=64 that worked yesterday is exactly the kind of regression this PR exists to prevent. a21dd0961 downgrades the refusal to a warning: below 96 it now says small imports may succeed but multi-chunk imports are likely to exhaust the limit, and if exhaustion does happen the EMFILE errors carry the observed limit and remedy as before.
I did consider the chunk-count-aware gate, but the streaming/remote producers only estimate chunk counts at preflight time, so a warning that names the shape of the risk seemed more honest than a gate that guesses. Happy to revisit if we'd rather refuse on the shapes we can count.
| #[cfg(target_os = "macos")] | ||
| let target = hard.min(macos_max_files_per_proc()); | ||
| #[cfg(not(target_os = "macos"))] | ||
| let target = hard; |
There was a problem hiding this comment.
macOS clamps to kern.maxfilesperproc, but this path uses hard verbatim. On a Linux host reporting hard = RLIM_INFINITY, setrlimit fails (the kernel caps at /proc/sys/fs/nr_open) and the raise is abandoned rather than retried at the real ceiling.
It degrades gracefully — Failed → budget planned from the unchanged soft limit — so nothing breaks. But this is exactly the "containers can be arbitrary" case the PR sets out to handle, and one retry at min(hard, nr_open) would make the two platforms symmetric.
There was a problem hiding this comment.
Fixed in a21dd0961 — the raise now clamps to /proc/sys/fs/nr_open on Linux (falling back to the 1,048,576 kernel default if the read fails), symmetric with the macOS kern.maxfilesperproc clamp, so a hard = RLIM_INFINITY container raises to the real ceiling instead of abandoning at Failed.
| if self.soft == u64::MAX { | ||
| return usize::MAX; | ||
| } | ||
| usize::try_from(self.soft.saturating_sub(self.reserve).max(32)).unwrap_or(usize::MAX) |
There was a problem hiding this comment.
The .max(32) floor can exceed soft itself — from_soft(8).available() == 32. Documented, and unreachable through the kernel path thanks to the 96-descriptor preflight, but FLUREE_FD_BUDGET=8 reaches it, and shrinking the plan is precisely what that variable exists for.
A budget that reports more descriptors than its own stated limit is a confusing thing to hand an operator who is debugging an EMFILE. Worth either clamping to soft or logging when the floor is what's binding.
There was a problem hiding this comment.
Agreed — a budget that reports more descriptors than its own stated limit is exactly the wrong thing to hand someone mid-EMFILE-debug. a21dd0961 clamps the floor to min(32, soft), so from_soft(8).available() == 8 now. The per-phase floors in fd_plan can still exceed a degenerate budget; the docs now say explicitly that those are the plan insisting on making progress, with the kernel enforcing reality.
| // A/2 and A. | ||
| spot_fan_in: (a / 2).max(16), | ||
| worker_cap: (a / 8).max(1), | ||
| merge_fan_in_per_order: (a / order_concurrency).saturating_sub(4).max(8), |
There was a problem hiding this comment.
The correctness of the whole merge budget rests on order_concurrency here matching the concurrency actually used, which comes from BuildAllConfig { max_concurrency: config.worker_count } in build_from_commits.rs. I verified they agree today — both derive from the unclamped config.worker_count, and actual concurrency is min(that, order_count) — so the arithmetic is sound.
But it's sound by coincidence of two independently-written expressions in different files, with only prose linking them. If max_concurrency ever gets sized from the core budget instead (which its own doc hints at: "callers size this from the effective import core budget"), each order silently gets a share computed for a different concurrency, and the failure mode is EMFILE on someone else's machine. Deriving both from one expression, or asserting the relationship at the call site, would make it structurally sound rather than coincidentally sound.
There was a problem hiding this comment.
Took the structural version: FdPlan now carries the order_concurrency it divided by, and both BuildAllConfig sites set max_concurrency from that field rather than independently from worker_count — one derivation, so the share arithmetic and the actual concurrency can't drift, and the doc on the field says callers must never size it independently. Effective behavior is unchanged (build_all_indexes still clamps to the buildable order count), and there's a small test pinning that the exposed field equals the divisor across worker/order combinations.
| scratch_dir: &Path, | ||
| ) -> io::Result<Vec<PathBuf>> { | ||
| // fan_in == 1 would make chunks(1) a no-op loop; 2 always terminates. | ||
| let fan_in = fan_in.max(2); |
There was a problem hiding this comment.
Good guard — chunks(1) would loop forever. Worth one line noting it's defense-in-depth: plan_fd_usage already floors merge_fan_in_per_order at 8, so this can only bite a caller passing a hand-built cap. As written a reader has to go find out which of the two floors is authoritative.
There was a problem hiding this comment.
Done in a21dd0961 — the comment now says it's defense-in-depth for a caller passing a hand-built cap, with plan_fd_usage's floor of 8 named as the authoritative one.
…l -> warning, linux nr_open clamp, available() capped at soft, structural order_concurrency, cascade-guard doc
|
Thanks for the close read, @bplatz — especially for actually chasing the tie-break induction and the op-sideband precondition rather than taking the comments' word for it. All six notes landed in |
main moved 114 commits ahead (incl. #1422 iceberg-materialize and #1591 import-fd-budget, both overlapping this PR's materialize domain). Two files conflicted, both in fluree-db-r2rml/src/materialize/: - graph.rs (emit_batch): #1422 refactored the inline per-row emit loop into emit_row / emit_row_terms behind a TmEmitContext; this PR had optimized the same inline loop (MAJOR-4: batched per-POM local_ref_edges fold for constant predicates). Took main's emit_row refactor verbatim — it is the go-forward structure the rest of #1422 depends on, and it is behavior-identical (the per-edge vs batched ref_edges counting yields the same totals). This DROPS MAJOR-4's constant-predicate allocation optimization on the bulk-materialize path; it is tangential to this PR's fused-aggregate QUERY-path core and can be re-applied inside emit_row_terms (a scratch-buffer param) as a follow-up if the materialize bulk-emit path perf warrants it. - mod.rs (pub use graph::{…}): union re-export — canonical_join + subject_sort_key (this PR, reused by the fused query path) plus emit_row + emit_row_terms + TmEmitContext (#1422). Verified on the merged tree: cargo check --all-targets (workspace) = clean; cargo fmt --all --check = clean; cargo clippy --all --all-features --all-targets -- -D warnings = clean; nextest seam crates (fluree-db-r2rml, fluree-db-query, --all-features) = green.
Problem
fluree create --from <large file>dies witherror: index build: index build: Too many open files (os error 24)on any box with a lowRLIMIT_NOFILEsoft limit — including every stock macOS shell (soft limit 256). This is common for me, at least. The workaround isulimit -n 65536before every import.The failure is deterministic, not load-dependent: the workspace had zero rlimit/EMFILE awareness, and the import pipeline has four unbounded descriptor fan-ins that scale with input size (or are flat-out constants larger than the limit):
build_from_commits.rs) — unconditional whenever id-stats +rdf:typeare present, so it could not ever succeed at soft ≤ 256.index_build.rs). Low--memory-budget-mbshrinks chunks and multiplies run files, so FD pressure grows exactly when memory budget shrinks.Fix: three layers, one contract
Layer 1 — claim what the OS will give.
fluree_db_core::fd_limit::raise_nofile_soft_to_hard()best-effort raises soft → hard at CLI and server startup, at import preflight, and on the rebuild path (macOS clamps tokern.maxfilesperproc; unprivileged; never errors). On macOS this alone takes 256 → ~10k and makes the manualulimitautomatic.Layer 2 — plan the build within whatever limit remains. Raising isn't available everywhere (AWS Lambda's hard limit is a fixed 1024; containers can be arbitrary), so the build now plans its fan-in/fan-out inside an
FdBudget(observed soft limit minus a reserve), exactly the wayrun_budget_bytesalready plans memory:fd_plan::plan_fd_usageapportions the budget per phase (phases are strictly sequential, so no runtime permit tracking is needed). Import divides the merge share by its 3 concurrent secondary orders; the remapped-rebuild path divides by its 4.BucketWriterPool); bucket files are created lazily and reopened withO_APPENDon eviction. Lossless because the materialization pass sorts.cascade_runs_to_fan_in) — multi-pass merges of consecutive groups through a new streaming FRN2 writer. Byte-identical to the flat merge: comparators excludet/op,KWayMergetie-breaks by stream index, and consecutive grouping makes the cascade's tie-break order equal the flat order at any depth (full argument in the function docs). Op bytes are carried verbatim so rebuild-path dedup/history resolution still happens exactly once, in the final consumer.g_idin the shared pump because the FRN2 wire format doesn't carry it (see review notes below).Degradation reference (
A = soft − reserve, reserve =clamp(soft/4, 32, 64)):Layer 3 — fail informatively.
EMFILE/ENFILEanywhere in the build now maps to an error carrying the observed limit and remedies (theIndexBuildError→io::Errorwrap preservesraw_os_errorso exhaustion stays recognizable). Import preflight fails in milliseconds — not twenty minutes in — when the observed kernel limit is below 96, and warns below 256.FLUREE_FD_BUDGETshrinks/shapes the plan only; it cannot defeat the preflight.Verification
it_import_low_fd(own[[test]]target — it re-execs itself and lowersRLIMIT_NOFILEhard+soft to 96 in the child, which must not share a process with other tests). Scenario A imports 30k typed subjects from one file (exercises the scatter pool); scenario B imports a 30-file directory with a plan shrunk viaFLUREE_FD_BUDGET=40(30 chunks > SPOT fan-in 24, ≥30 runs/order > merge fan-in 12), so the hierarchical SPOT merge and the cascade both run against the real limit. Both children must produce the same flake count and content fingerprint as unconstrained baselines. Vacuity-checked: neutralizing the budget reproduces the original EMFILE, so the test provably detects the bug it guards.g_idround-trip dropping named-graph class stats into the default graph under the hierarchical SPOT arm (regression test atg_id=5with a live stats collector, mutation-tested); the reserve undercounting the concurrent dictionary upload (measured 15–19 descriptors, reserve floor now 32); the rebuild path lacking a raise and dividing its merge share by the wrong order-concurrency;EMFILEbeing erased by anio::Error::otherwrap; cascade scratch dirs not being reclaimed.Notes for reviewers
FdBudget::unlimited()(u64::MAX sentinel) preserves the exact legacy behavior everywhere a caller doesn't opt in; all existing tests construct configs with it.tper chunk, so records comparing equal under a secondary-order comparator within a chunk are equal in every serialized field (same invariant pre-existing CPU-count-dependent worker counts already leaned on; now documented at the clamp).fluree-db-core/fluree-db-indexersuites,grp_import+grp_index+it_import_low_fd, per-crate clippy (--all-features --all-targets --no-deps -- -D warnings) andcargo fmt --checkall green.