Skip to content

Agent/bigint core algorithms#29

Merged
mmacedoeu merged 10 commits intonextfrom
agent/bigint-core-algorithms
Mar 16, 2026
Merged

Agent/bigint core algorithms#29
mmacedoeu merged 10 commits intonextfrom
agent/bigint-core-algorithms

Conversation

@mmacedoeu
Copy link
Contributor

Pull Request Checklist

  • All CI checks pass (green ✓)
  • Lint checks pass (no formatting issues)
  • Security scan passes
  • Tests added/updated for new functionality
  • Documentation updated (if applicable)
  • Commit messages follow Conventional Commits

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • AI-generated work (agent/* branch)

Branch Strategy

This PR follows the CipherOcto branch strategy:

From Branch To Branch Purpose
feat/* next New features
agent/* next AI-generated code
research/* next Experimental work
hotfix/* main Emergency fixes
next main Integration release

Current PR: <!-- source branch --><!-- target branch -->


Description


Related Issues

Closes #(issue)


Testing

  • Unit tests pass
  • Integration tests pass
  • Manual testing performed

Performance Impact

  • No performance impact
  • Performance improved (describe)
  • Performance degraded (describe, justify)

Security Considerations

  • No security implications
  • Security changes (describe)

Additional Notes

RFC-0110 Deterministic BIGINT - Phases 1-3:

Phase 1 - ADD/SUB/CMP:
- BigInt struct with Vec<u64> limbs + sign
- canonicalize(), is_zero(), bit_length()
- magnitude_cmp(), compare() for signed comparison
- bigint_add(), bigint_sub() with overflow checks

Phase 2 - MUL:
- bigint_mul() - schoolbook O(n²) multiplication
- 128-bit intermediate arithmetic
- Post-MUL canonicalization
- Overflow check against MAX_BIGINT_BITS

Phase 3 - DIV/MOD/SHL/SHR:
- bigint_divmod() - binary long division
- bigint_div(), bigint_mod()
- bigint_shl() - left shift with overflow
- bigint_shr() - right shift (arithmetic)

Tests: 17 passing
Clippy: clean
Format: clean
…erification probe

- Added TryFrom implementations for i64/u64/i128/u128 with proper MIN value handling
- Added bigint_to_i128_bytes for i128 round-trip conversion
- Added BigIntEncoding with serialize/deserialize for canonical 24-byte format
- Added BigInt verification probe (56 entries) with SHA-256 Merkle tree
- Added BIGINT_REFERENCE_MERKLE_ROOT constant for verification
- Fixed clippy warnings: manual_div_ceil, needless_borrows
- Fixed entry 52 value (MAX_U64 vs Max 4096-bit)
- Added implementation fixes documentation in source

All 115 tests pass, zero clippy warnings, Merkle root matches reference.
…icalization

Critical fixes:
- limb_sub: Fix borrow propagation using overflowing_sub chain
- limb_mul: Fix carry propagation (replace |= with proper loop)
- bigint_divmod: Replace buggy binary search with Knuth Algorithm D

High severity fixes:
- bigint_shr: Return ZERO for large shifts (not Err)
- bigint_shl: Handle shift == 0 correctly
- Serialization: Fix byte offsets (num_limbs at byte 4)
- Add is_canonical() checks to all arithmetic functions

Lower severity:
- Add BigIntError::OutOfRange variant
- Add debug_assert for non-empty limbs in BigInt::new()
- Narrow #[allow(arithmetic_overflow)] scope in probe.rs

Regression tests: 69 tests added, 2 previously slow division tests
now enabled (Knuth Algorithm D is O(n) not O(quotient)).
Add comprehensive documentation to the BigIntProbeValue enum explaining
when to use each variant. This prevents the bug where Int(MAX_U64)
and Max encode to different bytes in the compact probe format.

Key points:
- Max encodes to ff ff ff ff ff ff ff ff (4096-bit sentinel)
- Int(MAX_U64) encodes to hash-ref bytes (integer operand)
- Trap encodes to de ad de ad de ad de ad (TRAP sentinel)
- Int(TRAP) encodes to hash-ref bytes (integer operand)

The fix log comment is now visible at the variant definition site,
not just in the module docstring.
Critical bug fix: The original i128 cast `q_hat * v[i] as i128` could
overflow when q_hat * v[i] > 2^127 (roughly 1 in 2^64 cases).

Solution: Two-pass approach using pure u128 arithmetic:
1. Pass 1: Compute q_hat * v[] into temporary qv[]
2. Pass 2: Subtract qv[] from u[] with overflow tracking

Also syncs RFC-0110 fixes:
- Probe entry count: 64 → 56
- MUL: pre-check → post-check overflow validation
- FIXED: Entry 1 label (2^64 + 1 → 2^64) - matches Python/Rust reference
- FIXED: Rule 4 DIV iteration count - now correctly states m+1
  where m = dividend.len() - divisor.len()
- FIXED: Removed unnecessary j=0 special case - standard D1 formula
  works with implicit r[-1] = 0
- Updated version to v2.13
- Version: 2.12 → 2.13
- Date: 2026-03-15 → 2026-03-16
bigint.rs:
- Update doc comment to match RFC v2.13: "m+1 outer iterations
  where m = dividend.len() - divisor.len()" instead of "a_norm.limbs.len()"

probe.rs:
- Fix entry 1 description: "2^64 + 1" → "2^64"
- Fix stale python_hashes: entries 52, 54, 55
- Add assert_eq!(mismatches, 0) to fail loudly on future regressions
- Add Display trait implementation for decimal and hex output
- Add LowerHex and UpperHex for {:#x} format
- Add FromStr trait for parsing decimal and hex strings
- Support 0x prefix for hex, -/+ prefix for signed numbers
- Add InvalidString error variant
- Mark slow decimal tests as #[ignore]
All phases complete:
- Phase 1: Primitive conversions (i64, i128, u64, u128)
- Phase 2: String conversions (Display, FromStr, hex support)
- Phase 3: Serialization (BigIntEncoding wire format)
- Phase 4: i128 round-trip conversion
@mmacedoeu mmacedoeu merged commit ee497bb into next Mar 16, 2026
8 of 33 checks passed
@mmacedoeu mmacedoeu deleted the agent/bigint-core-algorithms branch March 16, 2026 14:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant