Issue #2382: The compiler allocates less: glibc malloc/free take about 31 % of a compile’s instructions

Open and answer this issue on GitHub.

compiler, performance, blocked · opened 2026-11-20 · updated 2026-11-20 · 4 comments

Found while a Counting global allocator in the nikaia binary costs +4.2 % instructions (#2368)

Goal

The compiler allocates less. In a compile of tests/compiler/tests/byteset_every_search_is_the_byte_by_byte_one.nika (callgrind, nikaia built from develop with the system allocator, 4,439,441,817 Ir in all) glibc’s allocator alone takes about 31 %:

function Ir
_int_free 413,726,467
_int_malloc 350,735,000
malloc 280,007,027
free 169,201,028
malloc_consolidate 67,425,282
realloc 54,453,074

for about 6.05 M allocations, 6.04 M frees and 0.88 M reallocations. Visible callers in the same profile: core::fmt::write with Text as Write (text built by formatting), List<u8, Place>::grow, BTreeMap<Text, _>::insert and its IntoIter::dying_next, StrSearcher::new, proofs_write_term, text_tiers.

To build

  1. Count allocations per compiler phase and per call site (the inclusive cost of malloc per caller in callgrind) and list the ten largest sites here.
  2. For each: the change in the .nika source (crates/nikaia-std/src/compiler/*.nika) that removes the allocation (reuse a buffer, build text once, a view instead of a copy), or the compiler defect that makes the lowering allocate where the source does not (fixed in the compiler, ADR-294).
  3. Measure before and after each step (docs/measuring.md).

Done when

The ten largest sites are handled or filed, and the compile above spends at most half the Ir in the allocator it spends today.

Comments

keywan-ghadami, 2026-11-20

Brief queued: issue-2382


agent: builder model: opus max_turns: 200 budget_usd: 30 effort: medium —

Issue #2382

Your work order is issue #2382, inlined below with its comments. There is no brief written around it: plan your own steps from its To build list, build them in order, commit after each finished step, and end when its Done when holds (or at the limits of builder.md, reporting what is left). The facts in your prompt are Core of docs/builder-facts.md; more on a topic: nikaia run scripts/syntax.nika -- KEYWORD, a probe: nikaia run scripts/probe.nika -- SNIPPET.

Measure the issue against docs/issues.md while you work: what it lacked, what was wrong in it. That answer goes into the report’s Issue: field. A finding, a changed plan or a finished item also goes into the issue as a comment (gh api repos/Nikaia-Foundation/Nikaia/issues/2382/comments -F body=@file, ending with the Claude Code footer), rule I13.

Rules (CLAUDE.md; shared checkout)

Report (at most 15 lines, to exactly /home/user/Nikaia/docs/briefs/performance/issue-2382.md.report.md)

Fields: Result, Files, Commit, Body (optional), Fixes, Pushed, Tests, Gate, Deviation, Found, Needs, Changelog, Issue, Owner (a question for the owner), Comment (#N <text>, what to say on another issue; the driver posts it, one line each), Friction, Disk freed, and last Attribution: with your commit trailer lines below it.


Generated by Claude Code

keywan-ghadami, 2026-11-20

Run: issue-2382, Result: partial

Tokens: input 372, cache read 12430813, cache write 272364, output 81491 Cost: 6.64 USD, time 1 min 28 s, turns 186

Report

Result: partial Files: none (3 local commits: 2955466dd emitter write_fmt, dae91bdbb logic Fourier-Motzkin on rank forms, 13e0ea10b pre-sized key texts) Commit: 2955466dd dae91bdbb 13e0ea10b Body: Allocator Ir of nikaia check b.nika (callgrind, malloc+free+realloc inclusive): 1,009.4M -> 911.9M (push_str(f”…”) lowers to write_fmt into the text) -> 692.8M (lg_contradictory_at/lg_eliminate on rank forms with checked merges, atoms by view not cloned, names moved via BTreeSet::drain, vectors pre-sized, lg_add/lg_add_constant take their operand by value, arena.nodes[id] views not at() clones, lg_copy/variables clone only new names) -> 677.6M (lg_written, LgNormal::text, proofs_written pre-sized); total Ir 2,764M -> 2,190M; output identical to baseline (cmp), logic package 48/48. Fixes: Part: #2382 Pushed: local 13e0ea10b Tests: push_str_of_formatted_text_formats_into_the_text –both-settings green (passes on old binary too: an optimisation); nikaia test –project packages/logic 48 passed; check output byte-identical to baseline; clippy clean; pre-push green for each commit Gate: green Deviation: Allocator Ir is down 33 % (1,009M -> 678M), not halved; below the top 16 sites the tail is flat (no site over 1.3 %), so the rest needs many small changes or an allocator decision. Found: use std::hash then fn main() throws { let mut v: Vec[String] = ["b", "a", "b"]; v.sort(); let r = v.binary_search("b"); println(f"{v.len()}"); match r { i => println(f"{i}"), null => println("no") } } passes the checker and then rustc refuses it (“mismatched types, expected &&_ found &'static _”, exit 101, “This is a bug in Nikaia”); it should print 3 and 1. Suspected cause: the emitter passes the literal key as &str, not &String, in the binary_search argument (emit_core_args/emit_core_calls, unchecked). Needs: Changelog: The prover and its integer solver allocate a third less: Fourier-Motzkin elimination works on rank forms and borrows its atoms, key texts start with room, and s.push_str(f"…") formats into s; allocator Ir of a check 1,009M -> 678M, total Ir 2,764M -> 2,190M. Issue: #2382 meets I1-I13 except that “allocator Ir at most half” in Done when did not say whether a different allocator (a Rust dependency, a decision) is allowed; site-by-site changes reach about a third. Owner: Comment: #2382 Left after 3 commits (allocator Ir 678M of 1,009M): lg_contradictory_at 100M (per call it clones each name into a BTreeSet and then into ranks; one clone needs BTreeMap values_mut, refused NK1307, or a sorted Vec with binary_search, whose is_sorted proof is lost after dedup and across a call), proofs_ask 63M (hash::sha256_hex(normal.text().bytes().collect()) lowers to a Vec copy of the text; an emitter rule `&x.bytes().collect::<Vec<_>>()` -> `x.as_bytes()` for a `&[u8]` parameter would remove it), LgIndexed::items 20M, lg_normal_of 20M, lg_written 15M, TermArena::var 12M (clones the name; a by-value `var` would save the clone in lg_copy), lg_indexed 12M, lg_formula 11M, bounding_in_elements 11M. Friction: Changing `LgIndexed::items` to take `formula: LgFormula` by value drew NK1102 at `for part in parts { out.extend(self.items(part)) }` with parts an owned `Vec[LgFormula]` (the loop yields views); a consuming loop over an owned Vec to move elements out was not found, so the change was reverted. Disk freed: target/nikaia-project-tests 2.1G (limit 2G), / 6.6G free of 252G (84 %); no new cache entry over 100 MB Attribution: Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UVxJDukWgopUzVU2M1TjK7

Debrief

  1. Most cost: build cycles. Each .nika change in packages/logic re-lowers std and rebuilds (about 10+ minutes with the fixpoint). Two cycles were wasted: one was killed by a driver interruption, and one tried items by value, which was then refused (NK1102).
  2. Looked up:
    • Vec(capacity:) and String(capacity:) exist; reserve does not.
    • values_mut/iter_mut on maps are refused (NK1307).
    • binary_search needs a proven is_sorted(), and the proof is lost after dedup or across a call.
    • TermArena::at clones the node; arena.nodes[id] is a view.
    • sha256_hex takes &[u8], and String has no as_bytes.
  3. Checks: run each round: callgrind with my per-caller allocator script, cmp of the check output against the baseline, the logic package tests, clippy, and pre-push. Wasted: the logic tests on the old binary, and the cycle over the refused items change. A 3-line probe would have caught that refusal first.
  4. One change: builder.md should say that a change in packages/* rewrites nikaia.contracts, .derived, .lock and .proofs, and that they go into the same commit. Also that a signature change re-lowers its callers in other files, e.g. logic_alethe.rs.
  5. Issue gaps:
    • rules-gap: Done when asks for “allocator Ir at most half” without saying whether switching the allocator (a Rust dependency, a decision) is in scope. Site-by-site work reaches about a third.
    • broke I5: the 50 % target came with no reference run showing that it can be reached. The flat tail (no site over 1.3 % below the top 16) makes it unlikely.
    • knowledge: Core | measuring allocator cost per call site needs a callgrind caller breakdown of malloc/free/realloc; a script for it in scripts/ would save the first turns.
  6. Traps for the next builder:
    • Fact: Slices | a for loop over an owned Vec[T] yields views, so passing the element to a by-value parameter draws NK1102; take the parameter by ref and clone the leaf.
    • Fact: Lowering | a .bytes().collect() passed to a &[u8] parameter lowers to a full Vec<u8> copy; String has no as_bytes view.
    • Fact: Core | after changing a packages/logic signature, commit the package's nikaia.contracts/.derived/.lock/.proofs and the callers' lowered files with it.

Generated by Claude Code

keywan-ghadami, 2026-11-20

From the report of the run of issue-2382 (#2382):

Left after 3 commits (allocator Ir 678M of 1,009M): lg_contradictory_at 100M (per call it clones each name into a BTreeSet and then into ranks; one clone needs BTreeMap values_mut, refused NK1307, or a sorted Vec with binary_search, whose is_sorted proof is lost after dedup and across a call), proofs_ask 63M (hash::sha256_hex(normal.text().bytes().collect()) lowers to a Vec copy of the text; an emitter rule `&x.bytes().collect::<Vec<_>>()` -> `x.as_bytes()` for a `&[u8]` parameter would remove it), LgIndexed::items 20M, lg_normal_of 20M, lg_written 15M, TermArena::var 12M (clones the name; a by-value `var` would save the clone in lg_copy), lg_indexed 12M, lg_formula 11M, bounding_in_elements 11M.


Generated by Claude Code

keywan-ghadami, 2026-11-20

This run is accepted as partial: allocator Ir fell from 1,009M to 678M. The remaining half waits on two things:

Status blocked until the owner decides #2383.


Generated by Claude Code

Back to Open Issues