Skip to content

Import: survive low open-file limits — best-effort raise + FD-budgeted index build - #1591

Merged
aaj3f merged 12 commits into
mainfrom
fix/import-fd-budget
Aug 7, 2026
Merged

aaj3f merged 12 commits into
mainfrom
fix/import-fd-budget

Conversation

@aaj3f

@aaj3f aaj3f commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

fluree create --from <large file> dies with error: index build: index build: Too many open files (os error 24) on any box with a low RLIMIT_NOFILE soft limit — including every stock macOS shell (soft limit 256). This is common for me, at least. The workaround is ulimit -n 65536 before 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):

  1. Class-membership scatter opened exactly 256 partition writers up front (build_from_commits.rs) — unconditional whenever id-stats + rdf:type are present, so it could not ever succeed at soft ≤ 256.
  2. Secondary-order k-way merge opened every run file of an order simultaneously, × up to 3 orders concurrently (index_build.rs). Low --memory-budget-mb shrinks chunks and multiplies run files, so FD pressure grows exactly when memory budget shrinks.
  3. SPOT merge held one descriptor per commit chunk for the whole merge.
  4. Dictionary merge (found while testing this PR, pre-existing): subject/string/language vocab merges run concurrently at ~5 descriptors per chunk — the first wall multi-chunk imports actually hit, before the index build even starts.

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 to kern.maxfilesperproc; unprivileged; never errors). On macOS this alone takes 256 → ~10k and makes the manual ulimit automatic.

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 way run_budget_bytes already plans memory:

  • fd_plan::plan_fd_usage apportions 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.
  • Scatter: the 256 logical buckets now write through a bounded LRU pool of append-mode handles (BucketWriterPool); bucket files are created lazily and reopened with O_APPEND on eviction. Lossless because the materialization pass sorts.
  • Secondary merges: run counts above the cap are first reduced by a lossless cascaded merge (cascade_runs_to_fan_in) — multi-pass merges of consecutive groups through a new streaming FRN2 writer. Byte-identical to the flat merge: comparators exclude t/op, KWayMerge tie-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.
  • SPOT: chunk counts above the cap take a hierarchical arm — group-merge chunks into globally-remapped intermediates, then final-merge those. Same byte-identity argument; the flat arm is untouched and remains the common case. Records are re-stamped with the build's g_id in the shared pump because the FRN2 wire format doesn't carry it (see review notes below).
  • Dictionary merges: serialized (subject → string → language) when the budget can't cover their concurrent peak, cutting per-chunk cost from ~5 descriptors to ~2.

Degradation reference (A = soft − reserve, reserve = clamp(soft/4, 32, 64)):

soft A scatter pool SPOT fan-in run-gen workers merge fan-in/order
96 64 56 32 8 17
256 (raise failed) 192 184 96 24 60
1024 (Lambda) 960 256 480 120 316
10240 (raised macOS) 10176 256 5088 1272 3388

Layer 3 — fail informatively. EMFILE/ENFILE anywhere in the build now maps to an error carrying the observed limit and remedies (the IndexBuildError → io::Error wrap preserves raw_os_error so 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_BUDGET shrinks/shapes the plan only; it cannot defeat the preflight.

Verification

  • End-to-end under a real kernel limit: it_import_low_fd (own [[test]] target — it re-execs itself and lowers RLIMIT_NOFILE hard+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 via FLUREE_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.
  • Byte identity: cascade-vs-flat and hierarchical-vs-flat builds assert equal content-addressed leaf/branch/sidecar CIDs (with and without op sidebands, import and rebuild consumer paths); the streaming writer is byte-compared against the slice writers; the scatter pool at size 4 is compared against the unbounded scatter.
  • Adversarial review (three independent passes) found and this PR fixes: the FRN2 g_id round-trip dropping named-graph class stats into the default graph under the hierarchical SPOT arm (regression test at g_id=5 with 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; EMFILE being erased by an io::Error::other wrap; 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.
  • The worker-count clamp can change run-file boundaries; that is unobservable in output because bulk import assigns one t per 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).
  • Gates: full fluree-db-core/fluree-db-indexer suites, grp_import + grp_index + it_import_low_fd, per-crate clippy (--all-features --all-targets --no-deps -- -D warnings) and cargo fmt --check all green.

@aaj3f
aaj3f requested review from bplatz and zonotope August 5, 2026 17:02

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_op returns v1.op straight from the file, the format round-trips retractions (spool.rs:1951), and spool.rs:1729 filters record.op == 1 for 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_in in 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread fluree-db-core/src/fd_limit.rs Outdated
if self.soft == u64::MAX {
return usize::MAX;
}
usize::try_from(self.soft.saturating_sub(self.reserve).max(32)).unwrap_or(usize::MAX)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@aaj3f

aaj3f commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

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 a21dd0961: op bytes now pass through the hierarchical SPOT intermediates verbatim (the two cascades finally agree on the question), the preflight refusal is a warning (your single-chunk-at-soft-64 regression case was right), the Linux raise clamps to nr_open, available() can no longer report more than its own limit, order_concurrency is now a plan field both BuildAllConfig sites consume, and the cascade guard comment names which floor is authoritative. Full gates re-run green (core/indexer suites, grp_import, the low-fd e2e, clippy -D warnings, fmt).

@aaj3f
aaj3f merged commit a1f485b into main Aug 7, 2026
15 checks passed
@aaj3f
aaj3f deleted the fix/import-fd-budget branch August 7, 2026 13:31
aaj3f added a commit that referenced this pull request Aug 10, 2026
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.
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.

2 participants