Repository navigation
feat(p8): condfold — short-circuit condition folding across a complex sibling (supersedes #193 + #194, closes #39 + #56) - #196
Merged
Conversation
… block
Ghidra's ruleBlockOr declines the `A || B` short-circuit fold whenever the
sibling condition block is *complex* (BlockBasic::isComplex: more than two
statements). One spill or address computation parked in front of the second
test is enough, and kuna then emits the second condition as its own block
branching back into the first arm's clause -- a crossing goto where angr
renders one compound condition. On coreutils tr::build_spec_list that is
literally `result_idx = &v10; if (es_match(es,v12,'=')) goto label_40242e;`.
This ports angr Phoenix's MultiStatementExpression relaxation
(_match_acyclic_short_circuit_conditions types a-d, phoenix.py:2688) and
nothing else: a second, narrower disjunct at the single is_complex(orblock)
decline in BOTH structurers (CollapseStructure::rule_block_or and
RegionStructurer::try_block_or -- verbatim copies of each other; implementing
only one would no-op on functions where the other converges). A complex
sibling is accepted when it is a BlockCopy of ONE BlockBasic whose printed
prefix is bounded, branch-free, and comment-free; the prefix then renders
inside the &&/|| operand as a C comma expression, which the printer already
supports (comma_separate).
No p-code moves: new_block_condition re-parents two existing structuring
nodes. The sibling is single-in (an inherited ruleBlockOr precondition), C's
short-circuit rule evaluates the right operand exactly when control used to
fall into the sibling, and the comma operator is a sequence point -- so the
prefix runs on the same paths in the same order. Every added guard is a
rendering-validity or readability guard, not a semantic one:
- BlockCopy-of-one-BlockBasic only (a list/if/condition operand could render
braces or a label inside the parens = invalid C);
- the pre-existing !is_interior_goto_target decline is never relaxed
(emit_block_copy emits the label statement first);
- bounded statement/call count, counted with the printer's own skip rules;
- no non-terminal branch op (angr's own refusal);
- no instruction comment in the block (emit_comment_group is suppressed
under comma_separate, so folding would silently delete it);
- a relaxed fold's node is force-marked complex so rule_block_while_do can
never hoist the comma chain into a while(...) header.
Option `condfold`, default OFF, three-valued: `on` is exact angr parity
(<=5 statements, <=1 call) and `wide` raises only the statement cap to 9 to
absorb kuna's finer printed-statement granularity (argument recovery and
address-tied copy shadows split one AIL statement into several printed ones).
OFF skips the precompute and leaves both disjuncts dead, so output is
byte-identical.
Gates: make test 675/675 PARITY OK; make test-stages 268/268 PARITY OK;
make rust-test green; make check-spec green (strict).
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…nt record Five hand-built-graph unit tests in blockaction/tests.rs covering the gate itself: the upstream decline when the option is off, the fold when the sibling is complex-but-eligible, the refusal of a non-BlockCopy operand, the dead-gate state, and -- the one that matters most -- that a condfold-relaxed BlockCondition reports ITSELF complex despite a trivial left operand, so rule_block_while_do can never hoist the comma chain into a while(...) header. docs/features/condfold/record.json carries the full measurement: the angr-vs-off-vs-on-vs-wide metric table on both vehicles, the PR #53 bonus result on true_ubuntu1804::usage (ifs 9 -> 7 at wide, closing the +2 residual), the 1580-function / 5-binary aggregate sanity sweep (gotos 931 -> 902, ifs 5077 -> 4961, ZERO invalid C, with the gcc -fsyntax-only checker validated against both failure modes this option could produce), the interleaved CPU-time speed delta (-0.21% on, -0.27% wide), and an honest note that the region_structurer mirror is currently unexercised end-to-end because that engine does not converge on any function where the fold applies (verified pre-existing on main's binary). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ngr parity Review finding on PR #193: in `condfold_eligible` the implied-output skip `continue`s BEFORE the `if o.is_call()` test, so a call inlined into the sibling's condition expression is never charged against `MAX_PREFIX_CALLS = 1`. The enforced bound is "at most one call printed as its own comma-chain element", not "at most one call in the rendered operand" -- so the tree's four "<=1 call / exact angr parity" claims were untrue. Measured: 1 of the 46 new call-bearing folded operands renders two calls (`mv -O2 copy_internal` at `wide` renders `cached_umask(...)`, a statement root that is counted, alongside `fchmod(...)`, implied into the test and not counted). Fixed by correcting the documentation, NOT the code. The cap is a readability bound, not a soundness bound -- the fold moves no p-code and the short-circuit + comma sequencing argument is independent of the call count, so the looser count cannot produce wrong C. Reordering the two checks would TIGHTEN the gate and therefore invalidate the PR's measured metric table, aggregate sweep and stage-test witness; that choice is recorded in the PR body as an explicit open decision for the reviewer rather than taken silently here. Corrected in all four places: * kuna_condfold.rs -- module doc guard 1 + the MAX_PREFIX_CALLS doc comment (plus the condfold_eligible decline list and the policy-constant unit test's comment, which carried the same claim) * phases.toml -- the condfold row's summary + use_when * infra/architecture.rs -- the cond_fold field doc * docs/spec/08-structuring.md -- a new paragraph stating the semantics precisely `on` remains exact angr parity on the *statement* threshold (5); only the call-cap parity claim is withdrawn. Also fixes a factual error in the ElementId provenance comment: it named 4112 as `loopbreak`; on `main` 4112 is `switchreturn` and `loopbreakrecovery` is 4092. The comment now also records that `condjoin` (PR #194, developed in parallel) takes 4114 -- both branches had allocated 4113; condfold keeps it. Regenerated the two derived artifacts the phases.toml prose feeds: docs/options.md and tests/fixtures/phase_catalog.json. No code change, so no re-measurement is needed and no behaviour moves. docs/baseline.json untouched. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…icate) PR #193 (`condfold`, proposal #39) and PR #194 (`condjoin`, proposal #56) relax THE IDENTICAL GATE -- the `is_complex(orblock)` decline inside `rule_block_or` and its verbatim twin `try_block_or`. Ship them as ONE option whose admission predicate is the UNION of the two rules. * `condjoin` disappears: no option name, no `cond_join` field, no `kuna_condjoin.rs`, no second spec section. ElementId 4114 is released. Exactly one net new option (76 -> 77). * Rule A (from #193): bounded, branch-free, comment-free printed prefix on a `BlockCopy` of one `BlockBasic`. Closes #39. * Rule B (from #194): statement-shape allowlist, and the only rule that admits a nested `BlockCondition` operand -- which is what a guard CASCADE needs. Closes #56. * Both witnesses kept: `tests/stages/ghangr-condfold.xml` (Rule A) and `tests/stages/ghangr-condfold-newbury.xml` (Rule B, renamed from ghangr-condjoin.xml and rewritten to drive `option condfold`). Four reviewer-found accuracy defects addressed: 1. Rule A's call cap counts statement-root calls only. Decision recorded: KEEP those semantics; constant renamed `MAX_PREFIX_ROOT_CALLS` so the name is the contract, and every doc says so. 2. Rule B's expression-size cap bypass is closed by inheriting #193's `condfolded` force-complex marking (a relaxed result always re-enters the admission check). The residual left-extension case is documented instead of claimed away. 3. The option is NOT a monotone goto reducer; `use_when` and the spec now say so with the measured per-function regressions. 4. A later-produced advisory comment can still be lost; documented. Re-measured on main @ d09f21c (nothing carried over from #193/#194): `on` closes BOTH criteria -- newbury::main 0 gotos / 0 labels, the tr crossing `goto label_40242e` gone with the compound condition present and tr gotos at angr parity (4). Aggregate over 2827 functions / 7 binaries: gotos 2294 -> 2198 (on) -> 2189 (wide), ifs 10492 -> 10135 -> 10108, loc 87959 -> 86713 -> 86567, 0 invalid-C hard stops with a checker validated against label-inside-expression and unbalanced-condition. Gates: make test 675/675 PARITY OK (baseline.json untouched), make test-stages 272/272 PARITY OK, make rust-test green, make check-spec green lenient and --strict, kuna catalog --check OK. Refs #39 #56 #193 #194 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015PVb6KdMKGV5rGEooSGHr4
…t seam - Architecture::cond_fold and ArchContext::cond_fold now document BOTH admission rules, the fixed MAX_PREFIX_ROOT_CALLS intra-doc link, and the two accepted effects (not a monotone goto reducer; a later-produced advisory comment can be lost). - The quoted tr build_spec_list OFF snippet now matches what this main actually emits (&v9 / es_00,v11, not the proposal's &v10 / v12). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015PVb6KdMKGV5rGEooSGHr4
… subsumes the other newbury::main folds entirely under Rule B (five shape folds, zero prefix folds, two of them on a nested BlockCondition Rule A can never accept), and the whole aggregate delta of `wide` over `on` is Rule A folding blocks Rule B declines with 'over MAX_SHAPE_STMTS'. The predicate has to be the union. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015PVb6KdMKGV5rGEooSGHr4
Review round on the consolidation (NEEDS_WORK). Four defects, all in the
option's contract rather than its correctness.
1. Rule B's cap did not bound printed width. MAX_SHAPE_STMTS counts
calc_explicit-*scored* statements, and on this PR's own headline witness
`tr::build_spec_list` a block scored 2 and rendered SEVEN comma elements.
The consequences were exactly what that predicts: the widest emitted comma
operand was 7 at BOTH `on` and `wide`, `on` and `wide` were byte-identical
on all four named targets, and an operator following "try `on` first" got
the option's widest folds at the conservative setting.
Fixed by factoring Rule A's walk into one shared measure,
`kuna_condfold.rs (printed_shape)`, and enforcing it in BOTH rules against
the policy level's cap (5 at `on`, 9 at `wide`). Rule B's shape allowlist
and call cap are untouched -- they are the soundness-relevant half. The
calc_explicit score survives only because the cross-leaf caps are expressed
in it.
Measured effect (7 binaries / 2827 functions, one counter for every column
including the angr panes):
- widest comma operand condfold CREATES: 5 at `on` (its own budget),
7 at `wide`. Was 7 at both.
- newbury::main still closes at `on` (0 gotos / 0 labels), byte-identical
to the pre-fix output.
- tr::build_spec_list now needs `wide` for angr goto parity (4), restoring
#193's original finding; tr.o is byte-identical to `off` at `on`.
- true_ubuntu1804::usage (the #53 bonus, ifs 9 -> 7) now needs `wide`.
- `wide` differentiates itself on 3 of the 4 named targets again.
- aggregate gotos 2294 -> 2219 (`on`) -> 2191 (`wide`); 0 invalid-C hard
stops, 0 functions lost.
2. Stale measurement text. The module docs still listed #193's
`newbury::network_init 3 -> 4` / `lshpack_enc_encode 16 -> 17`, contradicted
by record.json in the same commit; phases.toml and options.md carried the
round-1 numbers, now also stale. Re-measured after (1) and rewritten on
every surface: the regressions are `clientloop.o::process_escapes` 26 -> 28
(both levels) and `true_ubuntu1804::usage` 1 -> 2 (`wide` only).
3. Comment guard restored to #194's breadth. The consolidation had narrowed it
to comment_type::warning; it now declines on ANY buffered comment at a
covered address. Behaviourally equivalent today, but the narrow form rested
on an unstated invariant and the failure mode is a silently deleted comment.
4. Width slack documented honestly. "can render one statement wider than the
nominal budget" is gone from all four surfaces (module docs, architecture.rs,
phases.toml, docs/spec/08-structuring.md). Each now states what the budget
bounds (per-leaf comma-chain width) and what it does not (a Rule-B cascade's
summed width, post-structuring drift, over-counting on unprototyped calls,
the final condition's global width).
Also: KUNA_CONDFOLD_DEBUG=1 now reports both measures on every admit
(`scored N, prints M (budget B)`) and the numbers on every decline;
KUNA_CONDFOLD_DEBUG=ops lists every op printed_shape charges, so a measured
width can be reconciled op by op against the emitted chain -- the reviewer had
to do that by hand.
The Rule-B stage witness `ghangr-condfold-newbury.xml` moves from `on` to
`wide`, and its comment says why: its stub callees are unprototyped, so each
guard block still carries the call's stack-effect ops at structuring time and
measures 6 for an operand that finally emits none. The over-count only ever
declines. That move is itself the two-pass proof of the fix -- under the
pre-review predicate this shape folded at `on`. Assertions unchanged, so the
stages baseline is NOT re-recorded.
Gates: make test 675/675 PARITY OK; make test-stages 272/272 PARITY OK;
make rust-test green (4319 tests, cargo exit 0); make check-spec OK lenient AND
--strict; kuna catalog --check OK; docs/baseline.json diff vs origin/main empty.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015PVb6KdMKGV5rGEooSGHr4
This was referenced Jul 30, 2026
Closed
`condfold`'s admission predicate is the UNION of two rules and `condfold_ok` consults Rule A first, so a sibling both rules accept folds through Rule A. Measured with `KUNA_CONDFOLD_DEBUG=1`, both shipped witnesses did exactly that: `ghangr-condfold-newbury.xml` at `wide` takes 2 `prefix` folds per engine and 0 `shape`, `ghangr-condfold.xml` at `on` takes 1 `prefix`, and the whole stages corpus took ZERO `shape` folds. Deleting Rule B entirely left `make test-stages` green -- a coverage regression against PR #194, which shipped the newbury witness at `on` where Rule A declined all three guards. The shared printed-width budget cannot separate the rules (both enforce it, on the same `printed_shape` measure) and the comment guard declines both. Exactly two properties are Rule B's alone: the nested `BlockCondition` operand, and the call cap -- which, unlike the width budget, does NOT move with the policy level (`MAX_PREFIX_ROOT_CALLS` = 1 at `on` AND at `wide`, against `MAX_SHAPE_CALLS` = 2). New witness `tests/stages/ghangr-condfold-ruleb.xml` (6 assertions, off -> on): a three-guard permission cascade whose middle guard is `su_log(); x = su_euid(); if (x != wu)` -- a void call plus a call whose output the failure arm consumes, so neither is implied and both print as their own comma element. At `on` it traces `admit(shape) ... scored 2, prints 4 (budget 5)` with no `admit(prefix)` line, and folds twice as `shape` in BOTH engines. Acceptance check: with `shape_score` stubbed to always decline, `make test-stages` reports 274/278 and PARITY FAIL on exactly this file's #1..#4; restored, 278/278 PARITY OK. The other two condfold witnesses stay green under the stub. Also in this commit: * `KUNA_CONDFOLD_DEBUG=ops` was off by one. `printed_shape` charged the terminal CBRANCH at its own early `continue`, which skipped the trace, so a block measuring 6 listed 5 ops -- exactly the op-by-op reconciliation the docs advertised. Every `out.stmts` increment now goes through one `charge!`. Verified: the newbury guard block at 0x100060 lists 7 ops and reports `prints 7`; the one at 0x10006b lists 6 and reports `prints 6`. * `data:condfold-newbury #1..#4` said "ON" while the pass runs `wide`. Renamed to say WIDE; the regexes, min/max and verdicts are unchanged. * Seven unit tests that run `printed_shape` / `prefix_eligible` / `shape_score` / `compute_condfold_sets` over REAL hand-built op lists. The existing unit tests only covered the gate against synthetic `CondFoldSets` and never ran the scorers. * `docs/spec/08-structuring.md`, the module docs and all three witness headers now state which rule each witness fires, rather than implying the newbury one isolates Rule B. Gates: `make test` 675/675 PARITY OK; `make test-stages` 278/278 PARITY OK (baseline re-recorded: additive, 272 -> 278, no key dropped, and `docs/baseline.json` untouched); `make rust-test` green; `make check-spec` green lenient and --strict; `kuna catalog --check` OK. No new option (77). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015PVb6KdMKGV5rGEooSGHr4
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.
Supersedes #193 (
condfold, proposal #39) and #194 (condjoin, proposal #56). Closes #39 and #56.Both PRs were green on all four gates, both passed an independent adversarial review with verdict LOOKS_GOOD — and both were the same feature. This ships them as one option, rebased on the final
main(d09f21ce, the six-PR IDA-parity stack), with every number re-measured. Nothing below is carried over from #193 or #194.1. The shared root cause
rule_block_or(p8_structure/blockaction.rs) and its verbatim twintry_block_or(p8_structure/region_structurer.rs) implement Ghidra's short-circuit schema: a 2-out conditionblwhose sibling successororblockis itself a single-in 2-out condition reconverging through a shared clause folds into oneBlockCondition, renderingif (A || B) { clause }.Ghidra additionally requires
orblockto be non-complex —BlockBasic::isComplex(block.cc:2403) is a >2-statement readability budget, where the trailing branch already counts as one. So one spill, one address computation or one extra call parked in front of the second test makes the sibling "complex", the fold is declined, and the crossing edge becomes a goto + label.That is the single gate both PRs relax. They collided hard:
condfoldcondjoinis_complex(orblock)inrule_block_or+try_block_orCollapseStructurefield addedcondfold_blockscondfold_blockswith_condfold_blockswith_condfold_blockscompute_condfold_blockscompute_condfold_blocksThey differed only in the admission predicate and the value surface.
2. What ships
One option:
condfold, valuesoff | on | wide, defaultoff, ElementId 4113, phase P8 / goto-quality, tiertransform,source_decompiler = angr.condjoindisappears entirely — no option name, nocond_joinarchitecture field, nokuna_condjoin.rs, no second spec section. ElementId 4114 is released. Exactly one net new option: 76 → 77, not 78.The admission predicate is the UNION
Every admitted sibling first passes one shared printed-width budget:
kuna_condfold.rs (printed_shape)walks the block with the printer's own skip rules (not_printed, SSA markers, implied outputs, the bareCPUI_BRANCH) and counts what is left — the terminalCBRANCHincluded, because it renders as the comma chain's last element. ≤5 elements aton(angr's own_multistmtexpr_stmt_threshold), ≤9 atwide. The level moves that budget and nothing else.On top of it, a complex sibling is admissible when either rule takes it. They were derived independently against different targets and neither subsumes the other, so they are unioned, not intersected.
Rule A — bounded prefix (from #193, closes #39). The sibling is a
BlockCopyof ONEBlockBasic, within the width budget, branch-free, comment-free, with ≤1 statement-root call. ABlockList/BlockIf/BlockConditionoperand is never taken by this rule — it could render braces, multiple lines, or a label inside the parentheses.Rule B — statement shape (from #194, closes #56). An explicit allowlist on top of the same width budget: every op must be a marker, an op with an output varnode, a void
CALL/CALLIND, aSTORE, or the single terminalCBRANCH.RETURN, a second branch,BRANCHIND,CALLOTHERand no-return calls all decline, as does a comment of any type. ≤2 conservatively-scored statements and ≤2 calls per block — counting every call, unlike Rule A.Rule B additionally admits a nested
BlockConditionoperand, which Rule A never does, and that is the whole reason it cannot be dropped: a guard cascade folds pairwise and then takes the resulting Condition as the next sibling. Both sub-blocks of a nested Condition print underCOMMA_SEPARATE, so every leaf must itself be Rule-B admissible, and the fold site enforces ≤4 condition leaves and ≤4 total scored statements.Rule A is tried first. On
tr_synth.elf::build_spec_listaton,KUNA_CONDFOLD_DEBUG=1traces 4prefixfolds and 3shapefolds per engine — the union genuinely uses both halves, in both engines, on a single function.Neither rule subsumes the other (measured, not asserted)
newbury::mainfolds entirely under Rule B —shapefolds and zeroprefixfolds in each engine, two of them taking a freshly-created nestedBlockConditionas the sibling. Rule A never accepts a nestedBlockCondition, so feat(p8): condfold — short-circuit condition folding across a non-trivial sibling block #193's predicate alone cannot close [PROPOSAL] angr-newburry-main-57ccb1: SUID-guard goto is the SAILR goto-reduction family (large) #56 at any width budget.tr_synth.elfatwidethe trace is dominated byprefixfolds (22–25 per engine against 3–6shape), and the specific witnessprefix: fold BlockId(35v1) with complex BlockId(8v1)is a block Rule B declines withover MAX_SHAPE_STMTS. Rule B admits by shape, and its scored cap of 2 refuses exactly the straight-line prefixes Rule A exists for.Intersecting them, or dropping either, loses a closed proposal.
3. Why this is sound (do not weaken this argument)
The fold is rendering-only.
BlockGraph::new_block_conditionre-parents two existing structuring nodes as the operands of&&/||; it does not move, reorder, duplicate or delete a single p-code op.orblock.size_in() == 1is a pre-existingruleBlockOrprecondition this option never weakens — nothing else reaches the sibling, so its statements cannot execute on a path where the compound condition is not evaluated.orblock.negate_condition_rec, a boolean sense flip on an already-computed condition. It is order-neutral.Proposal #56's worry does not arise. #56 framed the fix as "invert the guard chain by de Morgan and hoist the join", and warned that a wrong inversion emits wrong C because the predicates call
getuid/geteuid/getegid/getgid, which cannot be reordered past one another. The operands are never swapped, only relabelled. No purity analysis is needed, and neither PR needed one. Both original agents and both independent reviewers established this separately.is_complex()itself is unchanged — the relaxation is a disjunct at the two fold sites only, which is why the 675-assertion corpus is untouched.4. Review feedback addressed (round 2 — the NEEDS_WORK verdict on this PR)
The reviewer's verdict: the code is sound and the merge lost nothing, but the option's documented contract was false and its value surface had collapsed. Four defects, all in the contract rather than the correctness.
MAX_SHAPE_STMTScountscalc_explicit-scored statements. On this PR's own headline witness,KUNA_CONDFOLD_DEBUGreportedadmit(shape) BlockId(7v1) @ 0x40242e: 2 statement(s)for a block that renders seven statements plus the branch. Consequences: the widest emitted comma operand was 7 at bothonandwide;onandwidewere byte-identical on all four named targets; and an operator following "tryonfirst" got the option's widest folds at the conservative setting.kuna_condfold.rs (printed_shape), enforced by both rules against the level's cap (5 aton, 9 atwide). Rule B's shape allowlist and call cap are untouched — they are the soundness-relevant half and remain byte-identical to #194. Thecalc_explicitscore survives only because the cross-leaf caps are expressed in it.kuna_condfold.rsstill listed #193'snewbury::network_init 3 → 4andlshpack_enc_encode 16 → 17, contradicted byrecord.jsonin the same commit.phases.toml/options.mdcarried the round-1 numbers, which the Defect-1 fix then made stale too.clientloop.o::process_escapes26 → 28 (both levels) andtrue_ubuntu1804::usage1 → 2 (wideonly).network_initno longer regresses at all.comment_type::warning. Behaviourally equivalent today, but a strictly weaker guard resting on an unstated invariant — and the failure mode is a silently deleted comment.block_carries_commentno longer looks at the type. #194's guard restored. The sweep below was run with the broadened guard: no measurable cost.get_random: scored 2, renders 3)" understated the real slack by ~7×.The direct check that Defect 1 is fixed
Widest comma-expression operand across the 7-binary / 2827-function sweep, counted by a paren-matching walk that distinguishes a comma operator from an argument separator:
on, 7 atwideoffonwideThe 6-element operand at
offandonis the same one, indd::human_readable— it is already there with the option off. Ghidra's ownbb_is_complexbudget has exactly the same score-versus-width slack; refusing to inherit it is what this measure is for.What the budget bounds — and what it does not
Bounds: per admitted leaf, the comma chain
printed_shapemeasures is ≤5 elements atonand ≤9 atwide, counted with the printer's own skip rules.Does not bound, stated rather than glossed:
MAX_JOIN_TOTAL_STMTS) is expressed in the weakcalc_explicitscore. Not tightened: converting it to printed width would declinenewbury::main, whose three leaves print 2–3 elements each.tr::build_spec_listit reads 6–9 across the structuring passes and the operand finally emits 8 elements.widewhile the realnewbury::maincloses aton.Also new:
KUNA_CONDFOLD_DEBUG=1now reports both measures on every admit (scored N, prints M (budget B)) and the numbers on every decline;KUNA_CONDFOLD_DEBUG=opslists every opprinted_shapecharges, so a measured width can be reconciled op by op against the emitted chain. The reviewer had to reconstruct that by hand. (That listing was off by one until round 3 — see §4c.)4b. The round-1 defects (unchanged, restated)
(1) Rule A's call cap counts statement roots only.
prefix_eligible's implied-output skip necessarily runs before theis_calltest — an implied call is not a statement at all. Witness:mv -O2 copy_internalatwiderenders bothcached_umask(...)(counted) andfchmod(...)(not counted). Decision kept: statement-root semantics, with the constant namedMAX_PREFIX_ROOT_CALLSso the name is the contract. It is a readability bound, not a soundness bound; Rule B charges every call op. Still true after round 2 — the width budget bounds comma elements, not how many calls hide inside one.(2) Rule B's cross-leaf caps had a bypass path, closed by inheriting #193's
condfoldedforce-complex marking: every relaxed result reports itself complex, so it always re-enters the admission check. Unit testcondfold_rule_b_enforces_the_total_statement_cap.(3) Not a monotone goto reducer —
use_whensays so in those words. Re-measured (see §5).(4) Comment loss — reproduced on this main:
newbury::mainemits 4WARNINGlines atoffand 3 aton/wide; the lost one is/* WARNING: branchflip: flipped negated guard for linearity ... */. A kuna advisory annotation, never a correctness signal; the emitted C is unaffected.4c. Review feedback addressed (round 3 — the Rule-B coverage gap)
A third review passed the branch on soundness and raised three bounded follow-ups. All three are addressed here.
KUNA_CONDFOLD_DEBUG=1:ghangr-condfold-newbury.xmlatwidetakes 2prefixfolds per engine and 0shape;ghangr-condfold.xmlatontakes 1prefix; the whole stages corpus took zeroshapefolds. Deleting Rule B entirely would have leftmake test-stagesgreen — a genuine coverage regression against #194, which shipped that witness atonwhere Rule A declined all three guard blocks.tests/stages/ghangr-condfold-ruleb.xml(6 assertions,off→on). Both of its folds areshape, in both engines, and the reviewer's suggested route (prototype the callees so the guards measure ≤5) is deliberately not what it uses — see below.KUNA_CONDFOLD_DEBUG=opswas off by one.printed_shapecharged the terminalCBRANCHat its own earlycontinue, which skipped the trace, so a block measuring 6 listed 5 ops — exactly the reconciliation the docs advertised.out.stmtsincrement now goes through onecharge!inprinted_shape, terminalCBRANCHincluded. Verified on the newbury witness: the guard block at0x100060lists 7 ops and reportsprints 7; the one at0x10006blists 6 and reportsprints 6.condfold-newbury #1..#4said "ON" while the pass runswide. Deliberate, to avoid a baseline re-record.WIDE. The four regexes, theirmin/maxand their verdicts are byte-identical; the stages baseline is re-recorded anyway for defect 1.What makes the new witness Rule-B-only
The shared printed-width budget cannot separate the two rules — both enforce it, on the same
printed_shapemeasure — and the comment guard declines both. Prototyping the callees so the guards measure ≤5 is therefore not sufficient: at ≤5 Rule A'sonbudget also admits, and Rule A is tried first. Exactly two properties are Rule B's alone:BlockConditionoperand, which Rule A can never accept; andMAX_PREFIX_ROOT_CALLS= 1 statement-root call atonand atwide, where Rule B allowsMAX_SHAPE_CALLS= 2.The witness exercises both. It is a three-guard permission cascade (
gcc -O2, self-contained bytechunk, local stubs, no relocations) whose middle guard isKUNA_CONDFOLD_DEBUG=1aton:admit(shape) BlockId(3v1) @ 0x10008a: scored 2, prints 4 (budget 5)— and noadmit(prefix)line for that block, because its two statement-root calls are over Rule A's cap. The cascade then folds twice, and the second fold takes the freshly-builtBlockConditionas its sibling:7v1's node kind was confirmed with a throwaway probe printingget_type()at the admit site rather than inferred from the id:orblock BlockId(7v1) type Condition leaves 2, in both engines.3v1istype Copy leaves 1. So the witness covers both of Rule B's exclusive properties in one run.Two-pass delta:
onis enough — the level is not what admits this shape, which is the point.The acceptance check: Rule B stubbed out
shape_scorewas temporarily made to always decline, rebuilt, andmake test-stagesre-run:Restored:
datatests: 278/278 assertions passed/PARITY OK. The four#1..#4failures are the two-pass assertions firing from both directions — with Rule B gone both passes emit the OFF form, so the ON-only token vanishes and the three OFF-only tokens appear twice. Note thatghangr-condfold.xmlandghangr-condfold-newbury.xmlstayed green under the stub, which is the reviewer's finding reproduced verbatim.Unit tests for the scorers themselves
The existing unit tests only covered the gate (
condfold_ok/shape_admits) against syntheticCondFoldSets; the scorers were never run. Seven new tests inkuna_condfold.rsbuild realBlockBasics with live p-code (realtype_op_forflags) and runprinted_shape/prefix_eligible/shape_score/compute_condfold_setsover them — includingtwo_statement_root_calls_are_rule_bs_alone, the unit-scale form of the new witness (prefix_eligiblefalse at both budgets,shape_score=scored 2, printed 4, and the precompute recording the block undershapeand notprefix).5. Fresh metrics (main @
d09f21ce, re-measured after the Defect-1 fix)One counter for every column, angr panes included — loc = non-blank lines including comments; gotos
\bgoto\b; labels^\s*\w+:\s*$; ifs\bif\s*\(; loopswhile|for|do{. Not comparable to #193/#194's tables, which stripped comment lines.Proposal #39 —
tr::build_spec_listtr_synth.elfofftr_synth.elfontr_synth.elfwidetr.oofftr.oontr.owideELF rebuilt per the proposal's recipe:
gcc -no-pie -nostdlib -nostartfiles -static -Wl,-Ttext-segment=0x400000 tr.o stubs.c.#39's crossing goto is gone at
onon the ELF vehicle — OFF hasresult_idx = &v9; if (es_match(es_00,v11,'=')) goto label_40242e;, ON emitsif ((v2) || (result_idx = &v9, es_match(es_00,v11,'=')))and neither the goto norlabel_40242e:survives. Full angr goto parity (4) needswide, on both vehicles;tr.ois byte-identical tooffaton. That restores #193's original and correct finding: the third-term sibling prints 7–8 comma elements, over the angr-parity budget of 5. Atwide:Proposal #56 —
newbury::main(lighttpdserver.c::main)Criterion met at
on, and byte-identical to the pre-fix output — its three guard leaves print 2–3 comma elements each, well inside the angr-parity budget:on==widehere only because the target already closes aton.Bonus — the PR #53 residual,
true_ubuntu1804::usageifs 9 → 7is exactly the +2 residual #53 measured — both!v30 || !strncmp(...)pairs fold into angr's shape, at the cost of +1 goto. It needswide; atonthe output is byte-identical tooff.Which value level does what
onwidenewbury::main(#56)ontr_synth.elf::build_spec_list(#39)tr.o::build_spec_list(#39)offtrue_ubuntu1804::usage(#53)offwidedifferentiates itself on 3 of the 4 named targets again, andonis the conservative setting the docs claim it is: the widest operand it creates is exactly its own budget. Before the fix,onandwidewere byte-identical on all four andonemitted the widest folds.6. Aggregate invalid-C sweep — the hard stop
kuna decompile-all --jsonat off/on/wide over 7 real binaries / 2827 functions; every function whose text changed was syntax-checked by wrapping it in a permissive C TU and runninggcc -fsyntax-only -std=gnu99. Semantic diagnostics a decompiled body always produces in a prelude-only TU are filtered; syntax errors are not.The checker was validated against the two failure modes this option can actually produce, before use:
error: expected ')' before ':' tokenerror: expected ')' before '{' token||&&Functions changed: 83 at
on, 186 atwide. Gotos added/removed: 2 / 77 aton, 3 / 106 atwide. Hard stops: 0. Functions lost: 0.Per-function goto regressions (this is not a monotone goto reducer):
clientloop.o::process_escapestrue_ubuntu1804::usagePer binary (
du,dd,basenc,newbury,true_ubuntu1804,mv -O2,clientloop.o): monotone improvement everywhere, with one inversion —true_ubuntu1804labels 41 (off) / 40 (on) / 41 (wide). Run with the default P8 goto-quality set ON (the real configuration), not ablated, and with the broadened comment guard. Full per-binary table indocs/features/condfold/record.json.7. Speed — within budget, and the noise floor is larger than the effect
Measured interleaved (off/on/wide alternating inside each iteration, so load drift cancels instead of landing in one arm) on child CPU time (user+sys via
os.wait4rusage).scripts.pipeline.timeitruns all-OFF-then-all-ON and is unusable under this box's load — #193 recorded +7.9% / +24.1% / +72.0% for the same measurement on three consecutive runs. Box load average 11–14 from other users' jobs.tr_synth.elf::build_spec_listnewbury::main(run 1)newbury::main(run 2)The measurement does not resolve the option's cost on this box, and is reported that way rather than rounded into a claim. On
newbury::mainthe two independent replicates putonat −5.5% and +5.3% — straddling zero with a 10.8-point spread — while the OFF arm's own sample spread within a single run is −10% to +28% even on CPU time.wideis the more consistent arm at +1.4% / +1.6%. Medians are inside the 5% budget; the noise floor is bigger than the effect. The structural cost is one extra predicate at a decline that already callsbb_is_complex, plus the two-rule precompute (which now also runs theprinted_shapewalk per block).8. decbench — re-checked by ablation, unchanged
The known result is
O2-bash-bash-get_random,ged_before 33.0 → ged_after 36.0(source_nodes: 1,artifact_suspect: true, bucketinherited). The fold absorbsseedrand(), seeded_subshell = v1, v1 = brand()into the guard as a 4-element comma operand while dropping the function's goto 1 → 0: correct and denser, but structurally further from the source CFG, so GED rises.Rather than re-run the scorer (time-boxed), the Defect-1 fix was ablated: a temporary build gated Rule B's new printed-width decline behind an env var, reproducing the pre-review predicate exactly. The ablation was validated first by reproducing the pre-review
tr_synth.elfonoutput byte-for-byte (loc 109 / gotos 4 — i.e. thewideoutput, the very collapse the reviewer reported).Result:
bash::get_randomatonis byte-identical before and after the fix (its guard blocks print 3–4 comma elements, inside the angr-parity budget). The GED regression stands unchanged; no rescore was needed. Also checked:newbury::mainatonis byte-identical before/after;tr.oandtrue_ubuntu1804::usageatondid change — they now matchoffand needwide, which is the intended effect.This is a reason the option stays default-OFF, not something to hide. No DIV is claimed.
docs/decbench/is a regenerable snapshot and is not part of this diff.9. Gates
make testmake test-stagesmake rust-testmake check-spec--strictkuna catalog --checkcatalog OK: documents exactly the registered kuna optionsgit diff origin/main...HEAD -- docs/baseline.jsondocs/baseline-stages.jsonre-recorded (the sanctioned re-record,kuna test --datatests --datatests-dir tests/stages --save-baseline). The change is additive and tightening: 272 → 278 keys, the 6 newcondfold-rulebassertions plus the 4condfold-newburyrenames (same regexes, samemin/max, same verdicts). No key was dropped.Three stage witnesses
tests/stages/ghangr-condfold.xml— Rule A, 7 assertions, levelon, unchanged by this round. Two-pass: OFF = the crossing goto + label, ON = one compound condition carrying the sibling prefix as a 3-element comma expression.KUNA_CONDFOLD_DEBUG=1confirmsprefixfires in both engines.tests/stages/ghangr-condfold-newbury.xml— the guard-cascade shape witness, 4 assertions, movedon→widein round 2 (assertions untouched then; renamed in round 3 so they sayWIDErather thanON). Its stub callees are unprototyped and get no frame recovery, so each guard block still carries the call's stack-effect ops when structuring runs andprinted_shapemeasures 6 for an operand that finally emits none. The over-count only ever declines — so this vehicle needswidewhile the realnewbury::main(prototyped libc calls, 3 measured elements per guard) closes aton. The move is itself the two-pass proof of the Defect-1 fix: under the pre-review predicate this shape folded atonbecause Rule B had no width cap. It folds through Rule A atwideand does not isolate Rule B — stated in the XML's own header rather than implied away.tests/stages/ghangr-condfold-ruleb.xml— Rule B isolated, 6 assertions, levelon(new in round 3). A three-guard cascade whose middle guard holds two statement-root calls, so Rule A refuses it at every level; both folds trace asshapein both engines, and the second takes a nestedBlockConditionas its sibling. Verified by stubbing Rule B out:make test-stagesfails (§4c).All three ASCII-only (the stage-XML parser is ASCII-only, and a literal
--inside an XML comment is a bare "syntax error" too).Wiring
phases.tomlrow (every field, incl.tier+symptoms) ·p0_knowledge/options.rs·Architecture::cond_fold+apply_mode+ parser + theArchSeamcopy (ctx.cond_fold = self.cond_fold— verified present; a per-function flag not copied into the seam is silently ignored) ·kuna_phases/tests.rs(settable 77, tiers 16/37/24, JSON rows 76, suppressed-live-value list) ·catalog_bytecompat.rs+ a regenerated byte-exactphase_catalog.json(the prose changed) ·tests/stages/kuna-catalog.xml(#6 30→31, #7 19→20) ·kuna-base/src/xml.rscorpus count 164 → 167 ·docs/options.mdregenerated · one merged spec section indocs/spec/08-structuring.md.10. What this does NOT close
calc_explicitscore. Converting that cap to printed width would declinenewbury::main, so it is documented rather than tightened.ghangr-condfold-newbury.xmlis the reproducible case (itsfhas no frame, so every guard block still carries the CALL'sINT_ADD/STORE/LOAD). The newghangr-condfold-ruleb.xmlgivesfa real frame, which is why it measures at the emitted width and closes aton.phases.toml, not claimed away.newbury::mainloses onebranchflipadvisory aton.type_b/type_d(with-else) short-circuit arms. kuna matches all four only through Ghidra'sruleBlockOrtopology; graphs those checks reject remain unfolded.build_spec_list. Still incomplete; a separate, larger opportunity. (Both engines are exercised by this option — that gap from feat(p8): condfold — short-circuit condition folding across a non-trivial sibling block #193 is closed.)Refs #39, #56, #193, #194. Full evidence, including all three review rounds and every per-binary number:
docs/features/condfold/record.json.