Skip to content

feat(p8): condfold — short-circuit condition folding across a complex sibling (supersedes #193 + #194, closes #39 + #56) - #196

Merged
mahaloz merged 9 commits into
mainfrom
feat/condfold-unified
Jul 30, 2026
Merged

mahaloz merged 9 commits into
mainfrom
feat/condfold-unified

Conversation

@mahaloz

@mahaloz mahaloz commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

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 twin try_block_or (p8_structure/region_structurer.rs) implement Ghidra's short-circuit schema: a 2-out condition bl whose sibling successor orblock is itself a single-in 2-out condition reconverging through a shared clause folds into one BlockCondition, rendering if (A || B) { clause }.

Ghidra additionally requires orblock to 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:

#193 condfold #194 condjoin
gate touched is_complex(orblock) in rule_block_or + try_block_or the same
CollapseStructure field added condfold_blocks condfold_blocks
builder added with_condfold_blocks with_condfold_blocks
module entry point compute_condfold_blocks compute_condfold_blocks
option count bump 76 → 77 76 → 77

They differed only in the admission predicate and the value surface.

2. What ships

One option: condfold, values off | on | wide, default off, ElementId 4113, phase P8 / goto-quality, tier transform, source_decompiler = angr.

condjoin disappears entirely — no option name, no cond_join architecture field, no kuna_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 bare CPUI_BRANCH) and counts what is left — the terminal CBRANCH included, because it renders as the comma chain's last element. ≤5 elements at on (angr's own _multistmtexpr_stmt_threshold), ≤9 at wide. 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 BlockCopy of ONE BlockBasic, within the width budget, branch-free, comment-free, with ≤1 statement-root call. A BlockList/BlockIf/BlockCondition operand 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, a STORE, or the single terminal CBRANCH. RETURN, a second branch, BRANCHIND, CALLOTHER and 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 BlockCondition operand, 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 under COMMA_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_list at on, KUNA_CONDFOLD_DEBUG=1 traces 4 prefix folds and 3 shape folds per engine — the union genuinely uses both halves, in both engines, on a single function.

Neither rule subsumes the other (measured, not asserted)

The round-1 argument for Rule A's necessity — "the whole wide-over-on delta is Rule A, because Rule B's caps do not move between levels" — no longer holds: the shared width budget now moves for both rules. It is replaced by the per-target traces above.

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_condition re-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() == 1 is a pre-existing ruleBlockOr precondition this option never weakens — nothing else reaches the sibling, so its statements cannot execute on a path where the compound condition is not evaluated.
  • C's short-circuit rule evaluates the right operand exactly when control used to fall into orblock.
  • The comma operator is a sequence point, so the absorbed statements still run before the test, in order.
  • The only synthesized operation is 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.

# defect what changed
1 Rule B's cap did not bound printed width. MAX_SHAPE_STMTS counts calc_explicit-scored statements. On this PR's own headline witness, KUNA_CONDFOLD_DEBUG reported admit(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 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. Rule A's walk factored into one shared measure, kuna_condfold.rs (printed_shape), enforced by both rules against the 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 and remain byte-identical to #194. The calc_explicit score survives only because the cross-leaf caps are expressed in it.
2 Stale measurement text. kuna_condfold.rs still listed #193's newbury::network_init 3 → 4 and lshpack_enc_encode 16 → 17, contradicted by record.json in the same commit. phases.toml / options.md carried the round-1 numbers, which the Defect-1 fix then made stale too. Re-measured after the fix and rewritten on every surface. The regressions are now clientloop.o::process_escapes 26 → 28 (both levels) and true_ubuntu1804::usage 1 → 2 (wide only). network_init no longer regresses at all.
3 The comment guard was silently narrowed vs #194. #194 declined on any buffered comment at a covered address; the consolidation filtered to 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_comment no longer looks at the type. #194's guard restored. The sweep below was run with the broadened guard: no measurable cost.
4 The width slack was documented dishonestly — "can render one statement wider than the nominal budget (bash get_random: scored 2, renders 3)" understated the real slack by ~7×. That sentence is gone from all four surfaces. Each now states exactly what the enforced budget bounds and what it does not (below).

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:

widest operand condfold creates widest operand anywhere in the emitted C
before this fix 7 at on, 7 at wide 7 / 7
off — 6
on 5 (exactly its own budget) 6
wide 7 (of a 9 budget) 7

The 6-element operand at off and on is the same one, in dd::human_readable — it is already there with the option off. Ghidra's own bb_is_complex budget 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_shape measures is ≤5 elements at on and ≤9 at wide, counted with the printer's own skip rules.

Does not bound, stated rather than glossed:

  • A Rule-B cascade's summed width. It is a per-leaf bound; the only cross-leaf cap (MAX_JOIN_TOTAL_STMTS) is expressed in the weak calc_explicit score. Not tightened: converting it to printed width would decline newbury::main, whose three leaves print 2–3 elements each.
  • Post-structuring drift. The measure is taken on the op list as it stands at structuring time. On tr::build_spec_list it reads 6–9 across the structuring passes and the operand finally emits 8 elements.
  • Over-counting on unprototyped calls. Where a call's stack-effect ops are still live at structuring time (no prototype, no frame recovery), the measure over-counts. Over-counting only ever declines a fold, so the error is in the safe direction — but it is why the Rule-B stage witness needs wide while the real newbury::main closes at on.
  • The final condition's global width — unchanged from round 1: a purely upstream-legal fold (both operands non-complex) can still extend a cascade on the left without consulting any condfold cap, exactly as it can with the option off.

Also new: 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 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 the is_call test — an implied call is not a statement at all. Witness: mv -O2 copy_internal at wide renders both cached_umask(...) (counted) and fchmod(...) (not counted). Decision kept: statement-root semantics, with the constant named MAX_PREFIX_ROOT_CALLS so 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 condfolded force-complex marking: every relaxed result reports itself complex, so it always re-enters the admission check. Unit test condfold_rule_b_enforces_the_total_statement_cap.

(3) Not a monotone goto reducer — use_when says so in those words. Re-measured (see §5).

(4) Comment loss — reproduced on this main: newbury::main emits 4 WARNING lines at off and 3 at on/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.

# defect what changed
1 No regression test exercised Rule B. Measured with KUNA_CONDFOLD_DEBUG=1: ghangr-condfold-newbury.xml at wide takes 2 prefix folds per engine and 0 shape; ghangr-condfold.xml at on takes 1 prefix; the whole stages corpus took zero shape folds. Deleting Rule B entirely would have left make test-stages green — a genuine coverage regression against #194, which shipped that witness at on where Rule A declined all three guard blocks. New witness tests/stages/ghangr-condfold-ruleb.xml (6 assertions, off → on). Both of its folds are shape, 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.
2 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 reconciliation the docs advertised. Every out.stmts increment now goes through one charge! in printed_shape, terminal CBRANCH included. Verified on the newbury witness: the guard block at 0x100060 lists 7 ops and reports prints 7; the one at 0x10006b lists 6 and reports prints 6.
3 condfold-newbury #1..#4 said "ON" while the pass runs wide. Deliberate, to avoid a baseline re-record. Renamed to say WIDE. The four regexes, their min/max and 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_shape measure — and the comment guard declines both. Prototyping the callees so the guards measure ≤5 is therefore not sufficient: at ≤5 Rule A's on budget also admits, and Rule A is tried first. Exactly two properties are Rule B's alone:

  1. the nested BlockCondition operand, which Rule A can never accept; and
  2. the call cap, which does not move with the policy level — Rule A charges at most MAX_PREFIX_ROOT_CALLS = 1 statement-root call at on and at wide, where Rule B allows MAX_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 is

su_log();                 /* a void call: its own comma element      */
x = su_euid();            /* an output the FAILURE ARM consumes, so it is
                             neither implied nor in-block-only: it prints */
if (x != wu) ...

KUNA_CONDFOLD_DEBUG=1 at on: admit(shape) BlockId(3v1) @ 0x10008a: scored 2, prints 4 (budget 5) — and no admit(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-built BlockCondition as its sibling:

[condfold] region_structurer/shape: fold BlockId(2v1) with complex BlockId(3v1)
[condfold] region_structurer/shape: fold BlockId(2v1) with complex BlockId(7v1)
[condfold] CollapseStructure/shape: fold BlockId(2v1) with complex BlockId(3v1)
[condfold] CollapseStructure/shape: fold BlockId(2v1) with complex BlockId(7v1)

7v1's node kind was confirmed with a throwaway probe printing get_type() at the admit site rather than inferred from the id: orblock BlockId(7v1) type Condition leaves 2, in both engines. 3v1 is type Copy leaves 1. So the witness covers both of Rule B's exclusive properties in one run.

Two-pass delta:

/* off */  if (su_uid() != 0) {
             su_log();
             v1 = su_euid();
             if ((v1 != a1) || (su_egid() != a2)) { su_warn(v1); return 0xffffffff; }
           }
/* on  */  if ((su_uid() != 0) && ((su_log(), v1 = su_euid(), v1 != a1 || (su_egid() != a2)))) {
             su_warn(v1); return 0xffffffff;
           }

on is enough — the level is not what admits this shape, which is the point.

The acceptance check: Rule B stubbed out

shape_score was temporarily made to always decline, rebuilt, and make test-stages re-run:

datatests: 274/278 assertions passed
FAILURES:
  [data] condfold-ruleb #1: ON, the whole three-guard cascade folds into ONE short-circuit condition ...
  [data] condfold-ruleb #2: OFF, the fold is declined and the sibling's void call stays a statement of its own ...
  [data] condfold-ruleb #3: OFF, so does the second statement-root call ...
  [data] condfold-ruleb #4: OFF, the declined cascade nests the last two guards inside the first one's arm ...
exit: 4

=== baseline parity ===
REGRESSED (4): ...
PARITY FAIL
make: *** [Makefile:51: test-stages] Error 1

Restored: datatests: 278/278 assertions passed / PARITY OK. The four #1..#4 failures 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 that ghangr-condfold.xml and ghangr-condfold-newbury.xml stayed 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 synthetic CondFoldSets; the scorers were never run. Seven new tests in kuna_condfold.rs build real BlockBasics with live p-code (real type_op_for flags) and run printed_shape / prefix_eligible / shape_score / compute_condfold_sets over them — including two_statement_root_calls_are_rule_bs_alone, the unit-scale form of the new witness (prefix_eligible false at both budgets, shape_score = scored 2, printed 4, and the precompute recording the block under shape and not prefix).

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*\(; loops while|for|do{. Not comparable to #193/#194's tables, which stripped comment lines.

Proposal #39 — tr::build_spec_list

loc gotos labels ifs loops
angr 9.2.213 122 4 3 15 3
tr_synth.elf off 117 7 4 16 3
tr_synth.elf on 114 6 3 15 3
tr_synth.elf wide 109 4 2 14 3
tr.o off 114 6 3 15 3
tr.o on 114 6 3 15 3
tr.o wide 110 4 2 14 3

ELF 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 on on the ELF vehicle — OFF has result_idx = &v9; if (es_match(es_00,v11,'=')) goto label_40242e;, ON emits if ((v2) || (result_idx = &v9, es_match(es_00,v11,'='))) and neither the goto nor label_40242e: survives. Full angr goto parity (4) needs wide, on both vehicles; tr.o is byte-identical to off at on. That restores #193's original and correct finding: the third-term sibling prints 7–8 comma elements, over the angr-parity budget of 5. At wide:

if (((v2) || (result_idx = &v9, es_match(es_00,v11,'='))) &&
    (pre_bracket_char = *(char *)(v1 + i), result_idx = &v9, v4 = v9, v11 = v9,
     v2 = find_closing_delim(es,start_idx,pre_bracket_char,result_idx), v9 = v4, v9 = v9, v2)) {

Proposal #56 — newbury::main (lighttpd server.c::main)

loc gotos labels ifs loops
angr 9.2.213 205 0 0 20 7
off 138 1 1 16 8
on 131 0 0 14 8
wide 131 0 0 14 8

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:

if ((getuid() != 0) && ((v2 = geteuid(), v2 != getuid() || (v2 = getegid(), v2 != getgid())))) {

on == wide here only because the target already closes at on.

Bonus — the PR #53 residual, true_ubuntu1804::usage

loc gotos labels ifs
off 107 1 1 9
on 107 1 1 9
wide 103 2 2 7

ifs 9 → 7 is exactly the +2 residual #53 measured — both !v30 || !strncmp(...) pairs fold into angr's shape, at the cost of +1 goto. It needs wide; at on the output is byte-identical to off.

Which value level does what

target on wide
newbury::main (#56) closes it (0/0) identical to on
tr_synth.elf::build_spec_list (#39) crossing goto gone, 6 gotos angr parity, 4 gotos
tr.o::build_spec_list (#39) identical to off angr parity, 4 gotos
true_ubuntu1804::usage (#53) identical to off ifs 9 → 7

wide differentiates itself on 3 of the 4 named targets again, and on is the conservative setting the docs claim it is: the widest operand it creates is exactly its own budget. Before the fix, on and wide were byte-identical on all four and on emitted the widest folds.

6. Aggregate invalid-C sweep — the hard stop

kuna decompile-all --json at 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 running gcc -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:

probe expected result
label inside an expression reject REJECTED — error: expected ')' before ':' token
unbalanced condition reject REJECTED — error: expected ')' before '{' token
clean comma fold accept ACCEPTED
loc gotos labels ifs || &&
off 87959 2294 1408 10492 941 1820
on 87088 2219 1385 10255 1029 1970
wide 86637 2191 1371 10126 1050 2079

Functions changed: 83 at on, 186 at wide. Gotos added/removed: 2 / 77 at on, 3 / 106 at wide. Hard stops: 0. Functions lost: 0.

Per-function goto regressions (this is not a monotone goto reducer):

function off on wide
clientloop.o::process_escapes 26 28 28
true_ubuntu1804::usage 1 1 2

Per binary (du, dd, basenc, newbury, true_ubuntu1804, mv -O2, clientloop.o): monotone improvement everywhere, with one inversion — true_ubuntu1804 labels 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 in docs/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.wait4 rusage). scripts.pipeline.timeit runs 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.

target n off on wide
tr_synth.elf::build_spec_list 21 318.25 ms 318.90 ms (+0.20%) 322.95 ms (+1.48%)
newbury::main (run 1) 15 4159.11 ms 3930.78 ms (−5.49%) 4216.48 ms (+1.38%)
newbury::main (run 2) 15 4047.57 ms 4262.98 ms (+5.32%) 4110.39 ms (+1.55%)

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::main the two independent replicates put on at −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. wide is 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 calls bb_is_complex, plus the two-rule precompute (which now also runs the printed_shape walk 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, bucket inherited). The fold absorbs seedrand(), 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.elf on output byte-for-byte (loc 109 / gotos 4 — i.e. the wide output, the very collapse the reviewer reported).

Result: bash::get_random at on is 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::main at on is byte-identical before/after; tr.o and true_ubuntu1804::usage at on did change — they now match off and need wide, 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

gate result
make test 675/675 PARITY OK
make test-stages 278/278 PARITY OK
make rust-test green — cargo exit 0, 4326 tests across 291 suites (4319 + the 7 new scorer tests)
make check-spec green, lenient and --strict
kuna catalog --check catalog OK: documents exactly the registered kuna options
git diff origin/main...HEAD -- docs/baseline.json empty — never re-pinned

docs/baseline-stages.json re-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 new condfold-ruleb assertions plus the 4 condfold-newbury renames (same regexes, same min/max, same verdicts). No key was dropped.

Three stage witnesses

  • tests/stages/ghangr-condfold.xml — Rule A, 7 assertions, level on, 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=1 confirms prefix fires in both engines.
  • tests/stages/ghangr-condfold-newbury.xml — the guard-cascade shape witness, 4 assertions, moved on → wide in round 2 (assertions untouched then; renamed in round 3 so they say WIDE rather than ON). 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 and printed_shape measures 6 for an operand that finally emits none. The over-count only ever declines — so this vehicle needs wide while the real newbury::main (prototyped libc calls, 3 measured elements per guard) closes at on. The move is itself the two-pass proof of the Defect-1 fix: under the pre-review predicate this shape folded at on because Rule B had no width cap. It folds through Rule A at wide and 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, level on (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 as shape in both engines, and the second takes a nested BlockCondition as its sibling. Verified by stubbing Rule B out: make test-stages fails (§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.toml row (every field, incl. tier + symptoms) · p0_knowledge/options.rs · Architecture::cond_fold + apply_mode + parser + the ArchSeam copy (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-exact phase_catalog.json (the prose changed) · tests/stages/kuna-catalog.xml (#6 30→31, #7 19→20) · kuna-base/src/xml.rs corpus count 164 → 167 · docs/options.md regenerated · one merged spec section in docs/spec/08-structuring.md.

10. What this does NOT close

  • Default-ON. Needs its own 0/675 ablation and a DIV row. The 2827-function sweep is supporting evidence, not the ablation — and the decbench regression plus the comment-loss effect are both presentation arguments for staying opt-in.
  • The width budget is a per-leaf bound. A Rule-B cascade of up to 4 leaves has no bound on their summed printed width, because the only cross-leaf cap is expressed in the weak calc_explicit score. Converting that cap to printed width would decline newbury::main, so it is documented rather than tightened.
  • The width measure over-counts on unprototyped calls (stack-effect ops still live at structuring time). Safe direction — it only declines — but it makes the option needlessly conservative on such code. ghangr-condfold-newbury.xml is the reproducible case (its f has no frame, so every guard block still carries the CALL's INT_ADD/STORE/LOAD). The new ghangr-condfold-ruleb.xml gives f a real frame, which is why it measures at the emitted width and closes at on.
  • Rule B's cross-leaf caps are not a global bound on the folded condition's width — a purely upstream-legal fold can extend a cascade on the left without consulting them. Documented in the spec and phases.toml, not claimed away.
  • A comment produced by a pass that runs after structuring can still be dropped. newbury::main loses one branchflip advisory at on.
  • angr's type_b/type_d (with-else) short-circuit arms. kuna matches all four only through Ghidra's ruleBlockOr topology; graphs those checks reject remain unfolded.
  • Region-structurer convergence on 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.

mahaloz and others added 8 commits July 29, 2026 17:03
… 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
`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
@mahaloz
mahaloz merged commit a6984b3 into main Jul 30, 2026
7 checks passed
@mahaloz
mahaloz deleted the feat/condfold-unified branch July 30, 2026 22:47
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.

1 participant