Skip to content

feat(u4): add embedded cap clamp - #140

Merged
RobinLinus merged 3 commits into
solving-bitcoin:mainfrom
brenorb:feat/u4-clamp
Sep 28, 2026
Merged

RobinLinus merged 3 commits into
solving-bitcoin:mainfrom
brenorb:feat/u4-clamp

Conversation

@brenorb

@brenorb brenorb commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Summary\n- add a range-checked u4 batch primitive that saturates each nibble to an embedded public cap\n- use bottom-to-top OP_ROLL scheduling so the capped outputs preserve original order and surrounding state\n- document the intentional information loss, canonical-byte boundary, catalog record, comparison, and exact metrics\n\n## Evidence\n- focused unit tests: cargo test --locked arithmetic::u4::clamp::tests --lib\n- exact metric fixture: cargo test --locked --test primitive_metrics u4_clamp_metrics_are_current -- --exact\n- knowledge validation: python3 tools/kb.py validate\n- formatting, JSON, and diff checks pass\n- representative 16-nibble fragment: 298 script bytes, 33 witness bytes, 18 strict peak stack items, 221 static non-push opcodes\n- execution class remains unclassified; no Bitcoin Core consensus or relay-policy validation is claimed\n\nThe full repository test suite was skipped intentionally.

Copy link
Copy Markdown
Contributor

Review: changes required before merge.

The vector result reverses the documented input order. The loop consumes the bottom input first using OP_ROLL, then restores staged results in reverse order. On input [1,2,3] bottom-to-top, the threshold(2), equality(1), trichotomy(2), and clamp(2) cases fail their documented ordered output checks and succeed with the reversed expected vectors. Preserve the documented order and add asymmetric input/output vectors, including preserved main/alt-stack state.

Evidence: locally-reproduced against the proposed implementation; local fragment execution only, deployment unclassified. This is not Bitcoin Core or complete-spend validation. Run the affected module tests and focused metric check after the fix.

Reviewed commit: fbaa771fcd4cd6c07947e6d6663a7a02e9ca7ebe.

@brenorb

brenorb commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

Updated in commit ba5b56c and pushed to feat/u4-clamp.

  • Fixed the root ordering bug by processing the top input first and retaining alt-stack restoration, so documented vector order and preserved main/alt-stack state are correct.
  • Added asymmetric ordering regressions, malformed-input checks at every position, and permissive-profile tests showing that non-minimal aliases below or at the cap are preserved while above-cap values normalize to the embedded cap.
  • Added exact 998-item and preserved-state stack-boundary coverage; generation still rejects 999.
  • Refreshed metrics and docs: 270 bytes, 206 static non-push opcodes, 18-item peak, 16 canonical witness items.

Checks passed: focused clamp tests, all 34 non-ignored primitive_metrics tests, cargo fmt --all -- --check, python3 tools/kb.py validate, and git diff --cached --check.

Copy link
Copy Markdown
Contributor

Review of ba5b56c45cde1cdb013fa092288cd43f1f6071ae:

Processing the top input before altstack staging addresses the previously reversed output schedule. Preserve asymmetric ordering and the exact preserved-state stack frontier when rebasing; run the clamp library/metric checks and KB validation.

Current integration conflicts: knowledge/catalog.json, knowledge/comparisons/arithmetic.md, knowledge/primitives/index.md, src/arithmetic/u4/README.md, src/arithmetic/u4/mod.rs, tests/primitive_metrics.rs. These must be resolved and the integrated result validated before merging.

Validation scope: source/diff and existing CI review; no new full-repository or field-arithmetic test run was requested.

brenorb and others added 2 commits September 27, 2026 21:14
Resolve the six integration conflicts Robin listed (catalog, arithmetic
comparison, primitive index, u4 README, u4 mod.rs, primitive_metrics) as a
union: every origin/main record, row, module, and metric test is kept
unchanged, and the clamp record/row/module/metric is added once. The
merged tree differs from origin/main by exactly the PR's original diff.

Catalog: 101 main records / 256 configurations plus the clamp record and
its configuration = 102 / 257, no duplicate ids, main records byte-equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add two regressions requested in review:

- keeps_asymmetric_witness_order_with_preserved_state: twelve distinct
  runtime witness nibbles under cap 9 with two distinct preserved main and
  two distinct alt items; the full final stack must match the documented
  order. The original bottom-first OP_ROLL schedule returns the exact
  reversed output vector and fails this test.
- preserved_state_stack_frontier_is_exact: for batches 1, 16, 997, 998,
  exactly `998 - nibble_count` preserved items (main, alt, or split)
  succeed with a 1,000-item combined peak and intact state; one more item
  fails with StackSize. Raising U4_CLAMP_MAX_BATCH by one fails it.

Consistency fixes: the catalog configuration still quoted the pre-fix
script_bytes of 298 (the reversed ROLL schedule) while per_use and the
README metric are 270; set it to 270. Measure the previously unchecked
u4_clamp_16_witness_items marker (16) and add an explicit
u4_clamp_16_hints marker (0). Metric values are otherwise unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@RobinLinus
RobinLinus merged commit dee38b2 into solving-bitcoin:main Sep 28, 2026
3 checks passed
@brenorb

brenorb commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 48d45b542a64920b484f4db91a19e3d0bb188896 (follow-up) on top of merge commit 0305d20dd9ac5e941080f5ea5386acf423dce0cd, which merges origin/main at e9d5a66b6391eccee64f72cc5af590bc14ed550c into feat/u4-clamp. I kept the ordering fix from ba5b56c (top input processed first, then staged on the alt stack) unchanged.

  • Integration conflicts. A trial git merge --no-ff origin/main conflicted in exactly the six files you listed: knowledge/catalog.json, knowledge/comparisons/arithmetic.md, knowledge/primitives/index.md, src/arithmetic/u4/README.md, src/arithmetic/u4/mod.rs and tests/primitive_metrics.rs. I resolved each one as a union: main's content is kept unchanged and the clamp entry is added once.

    • Catalog: main has 101 records and 256 configurations. The PR side has 56 and 162. The merged file has 102 and 257. Both sides are subsets of the merged file, there are no duplicate record or configuration ids, and every main record is equal to its main version. I inserted the clamp record as text so main's hand-formatted lines stay byte-identical.
    • mod.rs now lists centered and clamp in alphabetical order.
    • primitive_metrics.rs is main's file plus u4_clamp_metrics_are_current, placed before u4_xor_reduce_metrics_are_current.
    • README, comparison and index rows are main's rows plus the clamp row, which stays in its original position after parity. In the u4 README list the LSB bullet keeps main's wording about canonical encoding.
    • Check: at the merge commit, git diff origin/main touches the same 8 files and 405 added lines as the original PR diff, with the same added lines in each file. No conflict markers remain.
  • Asymmetric ordering is preserved. New test keeps_asymmetric_witness_order_with_preserved_state:

    • It uses twelve distinct runtime witness nibbles [11,0,9,3,15,1,10,4,8,2,14,5] with cap 9, two distinct preserved main-stack items (99, 100) and two distinct alt-stack items (77, 78).
    • It compares the whole final stack in the strict tapscript harness, and first asserts that the expected output vector differs from its reverse.
    • The existing ordered tests (clamps_all_nibbles_to_an_embedded_cap_in_order and preserves_surrounding_main_and_alt_stack_items) are kept.
  • Mutant (a): the original bottom-first {index} OP_ROLL schedule from fbaa771, applied temporarily to the generator. The new test fails with clamp outputs or preserved state out of documented order:

    • got [[99],[100],[5],[9],[2],[8],[4],[9],[1],[9],[3],[9],[],[9],[78],[77]]
    • expected [[99],[100],[9],[],[9],[3],[9],[1],[9],[4],[8],[2],[9],[5],[78],[77]]

    That is exactly the reversed output vector, with the preserved state intact. Three existing tests also fail under this mutant: the in-order test, the surrounding-state test, and the non-minimal-alias position test (left: [0], right: [1, 0]). The frontier test still passes, as expected, because the schedule does not change the stack peak. The mutant was reverted.

  • The preserved-state stack frontier is exact. New test preserved_state_stack_frontier_is_exact:

    • It runs batches 1, 16, 997 and 998 (U4_CLAMP_MAX_BATCH).
    • With exactly 998 - nibble_count preserved items on the main stack, on the alt stack, or split between them, it succeeds with a combined main-plus-alt peak of exactly 1,000 and leaves preserved state intact. One more preserved item in each of those three placements fails with ExecError::StackSize.
    • Batches of 16 or fewer use the policy-compiled fragment bytes. The larger batches bypass the optimizer with the module's existing compile_boundary helper. In both cases alt-stack staging is added as raw bytes around the compiled fragment.
  • Mutant (b): U4_CLAMP_MAX_BATCH = 1_000 - 1. The frontier test fails with frontier failed: nibbles=1, main=998, alt=0 … Error: StackSize. The existing rejects_invalid_nibbles_and_generation_bounds test also fails (998-item clamp failed … Error: StackSize). The mutant was reverted.

  • Consistency fixes in the follow-up commit.

    • The catalog configuration still quoted script_bytes: 298, left over from the reversed ROLL schedule in fbaa771, while per_use_script_bytes and the README metric are 270. I set it to 270. kb.py validate had not caught this because 270 appears in another numeric field.
    • The README marker u4_clamp_16_witness_items was not measured; u4_clamp_16_metrics_are_current now checks it (16).
    • I added an explicit u4_clamp_16_hints = 0 marker.
    • I listed the two new tests in the catalog, set the record's as_of to 2026-09-27, and documented the ordering and frontier evidence, plus zero-hint composition under the 1,000-item limit, in knowledge/primitives/u4-clamp.md.
  • Metrics are unchanged; nothing was refreshed. The 16-nibble, cap-4 fixture measures:

    • 270 policy-produced fragment bytes
    • 33 serialized witness bytes
    • 16 canonical data items and 0 hint items
    • an 18-item combined stack peak (nibble_count + 2)
    • 206 static non-push opcodes

Validation, run on the committed HEAD 48d45b5 with a clean tree, CARGO_PROFILE_{DEV,TEST}_OPT_LEVEL=1:

  • cargo test --locked --lib arithmetic::u4::clamp: 7 passed
  • cargo test --locked --test primitive_metrics u4_clamp_metrics_are_current -- --exact: 1 passed
  • cargo test --locked --lib arithmetic::u4::: 146 passed
  • python3 tools/kb.py validate: valid, 102 records / 257 configurations
  • python3 -m unittest discover -s tools -p 'test_*.py': 45 passed
  • cargo fmt --all -- --check and git diff --check origin/main HEAD: clean
  • cargo test --locked --no-run: the crate and all test targets compile

No field-arithmetic tests and no full-repository test run.

Evidence is locally-reproduced: fragment execution in the local tapscript-context executor with the 1,000-item stack limit enforced. Deployment stays unclassified. No Bitcoin Core consensus or relay-policy validation is claimed.

This head was subsequently integrated into main by #244.

@brenorb
brenorb deleted the feat/u4-clamp branch October 28, 2026 02:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants