Skip to content

feat(p8): condjoin — condition-based join restructuring (guard inversion) to remove a forward goto into a shared body - #194

Closed
mahaloz wants to merge 3 commits into
mainfrom
feat/condjoin
Closed

mahaloz wants to merge 3 commits into
mainfrom
feat/condjoin

Conversation

@mahaloz

@mahaloz mahaloz commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Implements proposal #56 (newburry-main-57ccb1). Target: lighttpd server.c::main, angr corpus binary newbury (that on-disk spelling; the proposal title says "newburry") at 0x40f696.

Ships as option condjoin on|off, default-OFF.

The gap

kuna emitted 1 goto / 1 label where angr emits 0 / 0 — numerically identical to the proposal-era column, i.e. zero improvement on this function since #56 was filed, despite the whole SAILR family landing in between.

if (getuid() != 0) {
   v2 = geteuid();
   if (v2 == getuid()) {
     v2 = getegid();
     if (v2 == getgid()) goto label_f6ec;      // forward goto INTO the sibling arm
   }
   v2 = -1; fputs("Are you nuts ...", stderr);
} else {
label_f6ec:
   setlocale(2,"C"); tzset(); do { /* server loop */ } while (...);
}

Root cause — and why the proposal's framing made it look larger than it is

The four blocks are a textbook ruleBlockOr cascade:

B0 @f69a: getuid();            test; je f6ec   -> {BODY, B1}
B1 @f6b0: geteuid(); getuid(); cmp; je f6dc    -> {B2, B3}
B2 @f6dc: getegid(); getgid(); cmp; jne f6c0   -> {B3, BODY}
B3 @f6c0: r = -1; fputs(...)   -> RET      (in-degree 2: B1, B2)
BODY @f6ec: the server loop    -> RET      (in-degree 2: B0, B2)

Every gate of CollapseStructure::rule_block_or holds for (B1,B2) and then for (B0, B1||B2) — 2-out, no goto-outs, non-switch, orblock single-in, not an interior goto target, no back edge, shared clause block — except one: is_complex(orblock). Funcdata::bb_is_complex (Ghidra BlockBasic::isComplex) calls a block complex once its statement count exceeds 2, counting the branch as one and each call as one; B1/B2 hold two calls each, so both score 3. That decline is what leaves BODY with two predecessors and forces one in-edge to be virtualized.

The proposal classified this LARGE ("invert the guard chain by de Morgan and hoist the join") and warned that a wrong inversion emits wrong C because the predicates are calls that cannot be reordered. Neither holds:

  • No hand-rolled inversion is needed. negate_condition_rec + new_block_condition already perform the de Morgan orientation and merge the join edge, and ruleBlockIfElse then hoists the join.
  • No reordering is possible, so no purity analysis is needed (see below).

Also worth recording: the region structurer bails on this function ([rs] STUCK: 25 components remain (round 88), then STUCK: 7), so the C actually comes from CollapseStructure, not region_structurer.rs. Confirmed independently by --option regionstructure off producing byte-identical output.

What the option does

It relaxes that one gate — in both engines, since region_structurer::try_block_or carries the identical predicate. New module p8_structure/kuna_condjoin.rs (ELEM 4113) precomputes, over the live bblocks op lists, the set of complex blocks that are nonetheless safe to absorb; CollapseStructure::condjoin_admits / RegionStructurer::condjoin_admits consult it beside is_complex.

isComplex is a readability budget, not a correctness gate: PrintC::emit_block_condition already sets modifiers::COMMA_SEPARATE on a folded condition's right operand, and emit_basic_block_ops under that modifier walks every op and emits them comma-separated with the semicolon suppressed. Ghidra itself exercises that path for the one-extra-statement case its threshold admits. This is the same escape hatch angr has: when _is_single_statement_block is false, phoenix._match_acyclic_short_circuit_conditions_type_{a,b,c,d} wrap the operand in a MultiStatementExpression instead of declining (MultiStmtExprMode, multistmtexpr_stmt_threshold). kuna's COMMA_SEPARATE is MultiStatementExpression.

Result on the target:

if ((getuid() != 0) && ((v2 = geteuid(), v2 != getuid() || (v2 = getegid(), v2 != getgid())))) {
  v2 = -1;
  fputs("Are you nuts ? Don't apply a SUID bit to this binary\n",dat_5f140);
} else {
  setlocale(2,"C"); tzset(); do { /* server loop */ } while (dat_5f278 != 0);
}
return v2;

Soundness

S1 — no reordering, and this is structural, not a check. new_block_condition only relabels two blocks that are already sequenced bl -> orblock in the CFG as the left and right operands of a &&/||. C's &&/|| short-circuit strictly left to right and the comma operator sequences strictly left to right, so the emitted expression evaluates bl's statements and condition and then, only if the short circuit does not cut, orblock's — byte-for-byte the CFG's own order and conditionality. getuid()/geteuid()/getegid()/getgid() are therefore safe without any purity analysis: none of them is ever hoisted, sunk, duplicated, or made unconditional. The only synthesized operation is negate_condition_rec, an order-neutral boolean sense flip.

S2 — expression-shaped ops only. Every op must be a marker (printer skips it), an op with an output, a void CALL/CALLIND, a STORE, or the single terminal CBRANCH. A RETURN, a second branch, a BRANCHIND, a CALLOTHER (userop rendering can be multi-line) or any no-return call declines the block.

S3 — statement budget. At most 2 scored statements and 2 calls per clause block. Scoring uses the same Varnode::calc_explicit approximation bb_is_complex uses and never reads Varnode::isExplicit — structuring runs before ActionMarkExplicit, so the flags are not yet meaningful.

S4 — expression-size caps. At most 4 condition leaves and 4 scored statements in the folded condition (collapse_conditions is an unbounded fixpoint loop). Every leaf of a compound operand must itself be admissible, because a nested BlockCondition emits both sub-blocks under COMMA_SEPARATE.

S5 — no comment loss. emit_basic_block_ops skips emit_comment_group entirely under COMMA_SEPARATE, so a clause block carrying a comment is declined outright rather than silently dropping e.g. a "WARNING: Subroutine does not return" annotation.

S6 — no label loss. Guaranteed by the pre-existing gates (size_in() == 1, !is_interior_goto_target()), asserted in the module docs.

S7 — option off is byte-identical. With cond_join false the admissible set is never computed, condjoin_admits is unconditionally false, and every gate is the verbatim upstream is_complex verdict.

Declining is always correct — the fold does not happen and today's goto+label output stands.

Measurement

Target metric table (scripts.pipeline.compare.metrics; angr column from the proposal branch's angr-vs-kuna.txt, angr 9.2.213)

metric angr kuna condjoin off kuna condjoin on
loc 206 138 131
gotos 0 1 0
labels 0 1 0
ifs 20 16 14
loops 6 6 6
ternaries 1 1 1
switches 0 0 0

Success criterion (0 gotos / 0 labels with the option on, valid compilable-shaped C, make test unchanged with it off) — met.

Speed

python3 -m scripts.pipeline.timeit --repeat 5: off 527.27 ms, on 518.37 ms, delta -1.69% (budget 5%). Within budget.

Aggregate sanity sweep (the hard stop)

kuna decompile-all --json OFF vs ON over 5 binaries under binaries/tests/x86_64/ (cat, dirname, basenc, dd, du), 1367 functions; every changed body syntax-checked with gcc -fsyntax-only against a permissive prelude, flagging any body that parses OFF but not ON.

OFF ON
functions decompiled 1367 1367
gotos 638 620
labels 379 369
loc 34675 34415
comma operands in conditions 173 214

0 invalid C, 0 crashes, 0 functions lost, 0 goto regressions. 68 functions changed.

decbench (bounded)

scripts.decbench.mine --select 28 completed; of the 28 mined cases exactly one is touched by condjoin: O2-bash-bash-get_random, goto 1 -> 0. Rescored under the decbench venv:

ged_before 33.0 -> ged_after 36.0   (delta +3.0, worse)

Reported honestly: the fold absorbs seedrand(); seeded_subshell = v1; v1 = brand() into the guard as a comma operand — correct and denser, but structurally further from the source CFG, so GED penalises it (the mine also tagged this case artifact-suspect, source_nodes = 1). This is exactly the presentation trade-off that keeps the option default-OFF; no DIV is claimed.

Gates

gate result
make test PARITY OK 675/675
make test-stages PARITY OK 265/265
make rust-test green
make check-spec green (lenient and --strict)
kuna catalog --check catalog OK

No baseline was re-pinned except docs/baseline-stages.json, which the new stage test requires.

What is in the PR

  • p8_structure/kuna_condjoin.rs — the admissibility scorer + caps + KUNA_CONDJOIN_DEBUG=1 trace (which engine took each fold, and why a block was declined).
  • The relaxed gate in blockaction.rs (rule_block_or) and region_structurer.rs (try_block_or), plus is_condfoldable / cond_leaf_count / cond_stmt_count in both.
  • Funcdata::has_pending_comment_at — the in-pipeline comment lookup S5 needs (the ArchContext seam cannot see the console CommentDatabase).
  • Full option wiring: phases.toml row, p0_knowledge/options.rs, both Architecture structs including the build_arch_handle copy, and all the hard-coded catalog counts (kuna_phases/tests.rs 76 -> 77, catalog_bytecompat.rs + regenerated fixture, tests/stages/kuna-catalog.xml Render unknown types as real C types (realtypes, DIV-6) #6 30 -> 31 and Fix test stages #7 19 -> 20, kuna-base/src/xml.rs corpus count 164 -> 165). Regenerated docs/options.md.
  • Two-pass stage test tests/stages/ghangr-condjoin.xml (ASCII-only), self-contained gcc -O2 witness: OFF asserts the goto + its label, ON asserts the inverted compound guard.
  • Spec prose in docs/spec/08-structuring.md under both §8.1 and §8.2.
  • docs/features/condjoin/{record.json,angr-vs-kuna.txt}.

What this PR does NOT close

  • Default-ON. Not attempted, and the decbench signal argues against it: the one mined case it touches loses GED even while losing its goto. A flip would need its own ablation + DIV row.
  • The remaining loc/if gap to angr on this function (131 vs 206 loc, 14 vs 20 ifs) is unrelated to the goto and untouched here.
  • Statement-scoring exactness. The pre-ActionMarkExplicit approximation is Ghidra's own and is inexact in both directions — bash get_random scores 2 and renders 3 statements in its comma operand. That is readability slack, never a correctness one (COMMA_SEPARATE emits every op regardless); the module and spec now say so rather than claiming the score over-counts. Making it exact would mean moving the scoring after ActionMarkExplicit, which structuring's position in universal_sched does not currently allow.
  • The branchflip interaction is cosmetic and unresolved: with the fold taken, ActionBranchFlip no longer fires on the target guard, so its /* WARNING: branchflip: ... */ note disappears from the output. Not a comment loss through COMMA_SEPARATE (S5 covers that) — the pass simply has nothing to flip.

Closes #56.

mahaloz and others added 2 commits July 29, 2026 17:10
… a forward goto into a shared body

Closes proposal #56 (lighttpd server.c::main, angr corpus `newbury` @0x40f696).

kuna emitted 1 goto / 1 label where angr emits 0 / 0 on a short-circuit
permission-guard cascade whose arms reconverge on a shared body. Every gate of
CollapseStructure::ruleBlockOr holds for that cascade except one:
BlockBasic::isComplex, which declines a clause block once its statement count
exceeds 2 (two calls plus the branch is 3). Declining forces one of the two
edges into the shared body to be virtualized into a goto + label.

That predicate is a readability budget, not a correctness gate: the printer
already renders a folded BlockCondition's second operand under
modifiers::COMMA_SEPARATE, walking every op and emitting them comma-separated
with the semicolon suppressed. This is exactly the escape hatch angr's Phoenix
structurer has (MultiStatementExpression, gated by MultiStmtExprMode).

`option condjoin on` (default-OFF) relaxes that one gate in BOTH engines
(CollapseStructure and the region structurer) under strict preconditions:
expression-shaped ops only (no RETURN, second branch, BRANCHIND, CALLOTHER or
no-return call), at most 2 conservatively-scored printed statements and 2 calls
per clause block, at most 4 condition leaves and 4 total statements in the
folded condition, and an outright decline when a clause block carries a comment
(the COMMA_SEPARATE path skips emitCommentGroup).

The fold performs no reordering, so predicates that call functions need no
purity analysis: new_block_condition only relabels two already-sequenced blocks
as the operands of a && / ||, and C's short-circuit and comma operators both
sequence strictly left to right.

newbury::main with the option on: 1 goto / 1 label -> 0 / 0, 138 -> 131 loc.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
* docs/features/condjoin/{record.json,angr-vs-kuna.txt} — the metric table
  (angr / kuna-off / kuna-on), the timeit speed delta (-1.69%), the aggregate
  invalid-C sweep (5 binaries / 1367 functions: 0 invalid C, 0 crashes, 0 goto
  regressions, gotos 638 -> 620), and the bounded decbench comparison.

* KUNA_CONDJOIN_DEBUG=1 now also traces which engine took each relaxed fold, so
  both the CollapseStructure and the region-structurer half have a named
  witness (newbury::main and bash O2 get_random respectively).

* Corrected the module and spec claim that the pre-ActionMarkExplicit statement
  scoring "over-counts". It is Ghidra's own approximation and is inexact in
  both directions: bash get_random scores 2 and renders 3. That is readability
  slack, not a correctness one (COMMA_SEPARATE emits every op either way), but
  the docs should not overclaim.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mahaloz

mahaloz commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

Approved!

…ld, PR #193)

`feat/condfold` (PR #193) and this branch were developed in parallel in
isolated worktrees and both allocated ElementId 4113 -- on `main` the highest
allocated id is 4112 (`switchreturn`), so 4113 was genuinely free and both
took it.

Resolution: `condfold` keeps 4113, `condjoin` moves to 4114. The provenance
comment now records both allocations so the next feature does not repeat the
collision, and the stage test's header comment is updated to match.

Note this is a convention fix, not a functional one: `IdRegistry` is keyed by
element *name*, not by numeric id (`main` already carries a pre-existing 4110
duplicate between `iteregion` and `returndup`), so the duplicate could not have
misbehaved at runtime. No behaviour change: `condjoin` is still default-off and
no gate logic is touched.

Gates: make rust-test green; make test-stages PARITY OK (265/265);
make check-spec OK (lenient + strict); `kuna catalog --check` OK.
docs/baseline.json untouched.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mahaloz

mahaloz commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

Merge-order note — #193 (condfold) and #194 (condjoin) collide on the option count

These two PRs were developed in parallel in isolated worktrees, so neither saw the other. They are independent — different modules, different options, no shared logic — and either merge order works. But they touch the same hard-coded counters, so:

Whichever merges SECOND must rebase on main and bump every settable-option count assertion 77 → 78, then re-record docs/baseline-stages.json.

Both PRs currently move the count 76 → 77. Merging the first is a no-op for the second's diff; merging the second without the bump fails make rust-test and make test-stages loudly (this is self-announcing, not silent), so nothing can slip through — this note just saves the rediscovery.

Exact files the second merge must touch

File What to change
decompiler/crates/kuna-decomp/src/p0_knowledge/kuna_phases/tests.rs fn settable_count_is_77 → _78; kuna_num_settables() and SETTABLE_TABLE.len() assertions 77 → 78; fn tier_counts_are_16_core_37_transform_24_analysis → ..._38_transform... and its (16, 37, 24) → (16, 38, 24) (both options are tier = "transform"); json.matches("},\n").count() 76 → 77
decompiler/crates/kuna-decomp/tests/catalog_bytecompat.rs fn fixture_has_all_77_settables → _78; the "option": / "tier": / "symptoms": count assertions 77 → 78
decompiler/crates/kuna-decomp/tests/fixtures/phase_catalog.json Regenerate — it is a byte-exact fixture, not a count. Procedure is in the catalog_bytecompat.rs module doc: printf 'openfile write /tmp/cap.json\nphase catalog\nclosefile\nquit\n' | decompiler/target/release/decomp_dbg -s "$PWD/specs" then copy over the fixture
tests/stages/kuna-catalog.xml KUNA-CATALOG #6 ("source_decompiler": "angr") min/max="31" → 32 and add the other option's name to the test name list; KUNA-CATALOG #7 ("change_kind": "structure-recovery") min/max="20" → 21 and likewise
decompiler/crates/kuna-base/src/xml.rs The datatest corpus file count assert_eq!(count, 165, "corpus file count drifted") → 166 (both PRs add one tests/stages/*.xml), and extend the explanatory comment
docs/options.md Generated — decompiler/target/release/kuna catalog --markdown > docs/options.md
docs/baseline-stages.json Re-record: kuna test --datatests --datatests-dir tests/stages --save-baseline docs/baseline-stages.json (sanctioned — a stage test was added)

#194-only extra: kuna_phases/tests.rs also renames option_values_live_value_present_for_28_suppressed_for_39 → _40. condfold does not touch that test, so if #194 is the second merge it becomes _41; if #194 merges first, #193's rebase leaves it at _40.

docs/baseline.json (the 675-assertion datatest corpus) is not touched by either PR and must not be re-pinned by the rebase.

ElementId — already deconflicted

Both branches originally allocated ElementId 4113 (main's highest is 4112 = switchreturn). That is now resolved on the branches, so the reviewer merging either one does not need to act:

The provenance comments on both branches now record the other's allocation, and #193's comment additionally corrects a factual error (it named 4112 as loopbreak; on main 4112 is switchreturn and loopbreakrecovery is 4092).

Nothing else in either diff overlaps.

mahaloz added a commit that referenced this pull request Jul 29, 2026
…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]>
mahaloz added a commit that referenced this pull request Jul 30, 2026
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
@mahaloz

mahaloz commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #196 — consolidated with #193 into one option

Closing in favour of #196, which carries this work forward in full. Nothing here is discarded, and the newbury::main criterion this PR set is met there.

Why

This PR and #193 (condfold, proposal #39) turned out to be the same feature, discovered twice. Both relax the identical gate — the is_complex(orblock) decline inside CollapseStructure::rule_block_or and its verbatim twin try_block_or in the region structurer — rooted in Ghidra's BlockBasic::isComplex >2-statement readability budget. They collided textually too: both added a CollapseStructure field named condfold_blocks, both added a builder named with_condfold_blocks, this branch's entry point was even named compute_condfold_blocks, and both bumped the option count 76 → 77.

Two catalog entries relaxing one gate cuts against the option surface being the product, so they ship as one: condfold off|on|wide, ElementId 4113. The condjoin name and ElementId 4114 are released.

What survived into #196

Everything, and it is load-bearing:

  • shape_score (Rule B) is this PR's score_condfold_block, byte-identical. An independent reviewer checked every decline is present: size_out()!=2, non-CBRANCH tail, interior flow-break (RETURN / second branch), CALLOTHER, no-return call, MAX_SHAPE_CALLS, void op that is neither call nor STORE, MAX_SHAPE_STMTS, comment.
  • is_shape_foldable / cond_leaf_count / cond_stmt_count / shape_admits are this PR's is_condfoldable / … / condjoin_admits verbatim, in both engines.
  • The stage witness was renamed, not duplicated — ghangr-condfold-newbury.xml's bytechunk is md5-identical to ghangr-condjoin.xml's, all 4 assertions preserved.
  • newbury::main reaches 0 gotos / 0 labels at on, matching angr, byte-identical before and after the consolidation.
  • Your soundness argument is preserved verbatim and independently re-confirmed: negate_condition_rec on a Condition is de Morgan and never swaps operands, so proposal [PROPOSAL] angr-newburry-main-57ccb1: SUID-guard goto is the SAILR goto-reduction family (large) #56's worry that getuid/geteuid predicates cannot be reordered genuinely does not arise, and no purity analysis is needed.

It was also measured — not assumed — that Rule B is necessary: newbury::main folds under five shape folds and zero prefix folds (two of them on a nested BlockCondition, which Rule A can never accept). #193's predicate alone could not have closed proposal #56 at any cap.

What got fixed on the way

The decbench result you reported honestly — bash::get_random ged 33.0 → 36.0, source_nodes: 1, artifact-suspect — was re-checked and stands unchanged. It remains a reason the option ships default-off.

All measurements were re-taken against main @ d09f21ce; the six-PR IDA-parity stack landed in between and changes emitted C, so every number in this PR is stale.

Branch feat/condjoin is left in place for reference.

@mahaloz mahaloz closed this Jul 30, 2026
mahaloz added a commit that referenced this pull request Jul 30, 2026
`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 added a commit that referenced this pull request Jul 30, 2026
… sibling (supersedes #193 + #194, closes #39 + #56) (#196)

* feat(p8): condfold -- short-circuit fold across a non-trivial sibling 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]>

* test(p8): condfold gate unit tests + docs/features/condfold measurement 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]>

* docs(p8): condfold's call cap counts statement-root calls only, not angr 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]>

* feat(p8): consolidate condfold + condjoin into one option (union predicate)

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

* docs(p8): describe the union predicate at the Architecture/ArchContext 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

* docs(condfold): record the measured proof that neither admission rule 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

* fix(p8): give condfold ONE printed-width budget shared by both rules

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

* test(p8): isolate condfold's Rule B with a witness Rule A cannot take

`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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@mahaloz
mahaloz deleted the feat/condjoin branch August 9, 2026 02:45
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