Skip to content

Proof: independent semantic verifier replays engine transcripts and seals receipts (V5b2c) - #521

Merged
lemone112 merged 6 commits into
mainfrom
v5b2c-semantic-verifier
Aug 4, 2026
Merged

Proof: independent semantic verifier replays engine transcripts and seals receipts (V5b2c)#521
lemone112 merged 6 commits into
mainfrom
v5b2c-semantic-verifier

Conversation

@lemone112

@lemone112 lemone112 commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Срез

Третий независимый верификатор региона: stdlib-only Python-пакет proof/region/v1/semantic/, который самостоятельно replay'ит один engine transcript и запечатывает SemanticVerificationReceiptV1 либо возвращает типизированный отказ. Узел correctness-цепи из #228: semantic verifier → DualProofReceiptV1 (V5b2d) → full-domain materialisation.

Что внутри

  • ssa.py — строгий повторный разбор committed ASCII SSA spec собственным reader'ом (release-pinned digest), без доверия engine-парсеру.
  • intervalmath.py — строгая интервальная арифметика на exact dyadic Fraction: ряды с рациональными хвостами (atanh/atan), Лагранж для exp, редукция против рациональных огораживаний ln 2 и π (формула Мэчина), outward-округление на dyadic сетку. Адаптивные остатки: ряд останавливается, когда строгая граница хвоста достигает guard-цели; подъём точки 9.65 s → 0.028 s.
  • region.py / replay.py — повторный вывод решений региона (INSIDE/OUTSIDE/BOUNDARY_UNPROVEN/RESOURCE_LIMIT_REACHED), exact-zero trace replay и accounting digest по общим wire-грамматикам.
  • verifier.py + receipt.py — sealed receipt (module-owned token), закрытая сумма причин отказа, binding-проверки до replay.

Принятые решения

  • Binding run claim: run допускается только по совпадению job/comparator/transcript координат. binary_identity/invocation_identity/platform_identity — заявленные execution coordinates; их причинность source → build → executable доказывает source-bound controller, верификатор не дублирует anchor (совместимо с production RunClaimV1.for_transcript, где передаётся binary_sha256 ≠ manifest.build_identity).
  • Доменные guard'ы: root3/log неразрешимы на отрицательных и пересекающих ноль интервалах, pow_nn доказывает точный ноль только при строго положительной экспоненте, exp неразрешим за пределами V1 reduction range — по грамматикам операторов и паритету с обоими двигателями (DOMAIN_UNPROVEN → BoundaryUnproven).
  • Sign-строгость: пересекающий ноль аргумент sign уводит точку в BoundaryUnproven — сознательное ужесточение относительно продолжения engine с hull [-1, 1].
  • Diversity держится AST-контрактом (запрет импортов arb//mpfi//evaluator paths); неиспользуемая причина diversity_violation удалена из закрытой суммы.

Доказательства

  • RED b654824: hostile-replay контракт, 5 тестов падали на заглушке.
  • GREEN: 56 тестов OK локально (test_region_proof_protocol, test_semantic_replay + positive-path full-domain receipt, test_semantic_receipt, test_semantic_diversity, test_semantic_intervalmath — рациональные окна вокруг 20-значных истин для каждого трансцендентного огораживания), compileall чист.
  • Независимый code review: 2 soundness-находки (pow_nn, root3) и 2 robustness-находки (point_count drift, exp overflow) воспроизведены исполнением и закрыты регрессионными тестами в c93d15f.
  • Все огораживания кросс-проверены против mpmath dps=200 (локально, до коммита).

Гейты

CI (ci-worker pinned) + CodeRabbit на head. PROTOCOL.md дополнен секцией semantic verification.

Summary by CodeRabbit

  • Новые возможности

    • Добавлена независимая семантическая проверка транскриптов с точным воспроизведением вычислений.
    • Реализована интервальная арифметика с контролем диапазонов, точности и недопустимых операций.
    • Добавлены запечатанные квитанции успешной проверки и структурированные причины отклонения.
    • Усилены проверки каноничности, привязок, свидетелей, ресурсов и учёта вычислений.
  • Тесты

    • Добавлены проверки математической точности, граничных случаев, целостности квитанций и защиты от некорректных транскриптов.

Claude Code added 4 commits August 4, 2026 07:39
Third verifier re-parses the immutable formula bytes with its own strict reader (ssa.py), re-derives every decision through rigorous interval arithmetic (intervalmath.py) and the driver rules (region.py), and replays the claimed transcript decision by decision (replay.py). A clean replay seals SemanticVerificationReceiptV1; any mismatch, witness defect or accounting drift rejects with a closed rejection reason before or during replay.

Run binding: the verifier admits a run only when its job, comparator and transcript coordinates match the verified objects. binary_identity, invocation_identity and platform_identity stay declared execution coordinates - their source->build->executable causality belongs to the source-bound controller and the semantic verifier never re-declares that anchor.

Interval arithmetic keeps exact rational endpoints and gains adaptive Taylor remainders: series stop as soon as a rigorous tail bound clears the guard target, ln(2)/pi enclosures are cached, and odd-power partial sums evaluate through one integer Horner pass. Point lift drops from 9.65 s to 0.028 s; every enclosure was cross-checked against mpmath dps=200 truth values.

Gates: 17 semantic tests including a positive full-domain replay that seals a receipt, protocol suite 39 OK, compileall clean.
pow_nn no longer proves exact zero when the exponent crosses zero, and root3 enforces its nonnegative domain grammar, matching both engines' DOMAIN_UNPROVEN fallback. exp rejects arguments beyond the V1 reduction range and bounds its branch loop, so hostile binary64 inputs terminate in typed rejection instead of overflow or runaway reduction. verify_transcript rejects transcripts whose point count drifts from the bound domain before replay.

Diversity stays enforced by the AST boundary test; the unused diversity_violation rejection reason leaves the closed sum. PROTOCOL.md documents the operator domain guards and the deliberate sign strictness. New regression tests: point-count drift, operator domain contracts, and rational-window soundness checks pinning every transcendental enclosure around 20-digit truth values. Gates: 56 tests OK, compileall clean.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 42 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5dbc0cb2-d618-415a-84a1-9d5e595a2a8c

📥 Commits

Reviewing files that changed from the base of the PR and between 45c8b15 and a91c944.

📒 Files selected for processing (3)
  • proof/region/v1/region_proof_protocol.py
  • proof/region/v1/tests/test_semantic_diversity.py
  • proof/region/v1/tests/test_semantic_replay.py

Walkthrough

Добавлена независимая stdlib-only semantic verification boundary для V1 transcript-ов. Она разбирает SSA, выполняет точный replay region decisions, проверяет witness-ы и accounting, затем создаёт sealed receipt или typed rejection.

Changes

Semantic verification V1

Layer / File(s) Summary
Контракт проверки и receipt
proof/region/v1/PROTOCOL.md, proof/region/v1/region_proof_protocol.py, proof/region/v1/semantic/receipt.py, proof/region/v1/semantic/verifier.py, proof/region/v1/semantic/__init__.py, proof/region/v1/tests/test_semantic_receipt.py
Протокол определяет digest-грамматики, admission rules, binding-проверки, SemanticVerificationReceiptV1 и SemanticVerificationRejectedV1. Receipt создаётся только через _seal после успешной проверки.
SSA-разбор и интервальная арифметика
proof/region/v1/semantic/ssa.py, proof/region/v1/semantic/intervalmath.py, proof/region/v1/tests/test_semantic_intervalmath.py
Добавлены канонический parser и typed SSA evaluator на Fraction. Интервальные функции проверяют области определения и возвращают UnresolvedError для нерешаемых случаев.
Воспроизведение region decisions
proof/region/v1/semantic/region.py
Добавлены точные структуры Region, RGB-преобразование и обработка singleton- и segment-регионов с контролем precision и resource budget.
Point replay и accounting
proof/region/v1/semantic/replay.py, proof/region/v1/tests/test_semantic_replay.py
SemanticReplay распределяет ordinal-prefix grant, проходит precision ladder и формирует exact-zero и accounting digest. Тесты покрывают ошибочные binding-и и успешный replay.
Проверка transcript и witness-ов
proof/region/v1/semantic/verifier.py, proof/region/v1/tests/test_semantic_diversity.py
verify_transcript сверяет решения, witness-ы, resource scope и accounting digest. Статические тесты проверяют независимость verifier boundary и запрет вырожденных receipt-конструкторов.

Estimated code review effort: 5 (Critical) | ~120 минут

Sequence Diagram(s)

sequenceDiagram
  participant Transcript
  participant verify_transcript
  participant SemanticReplay
  participant SSA_EvaluationContext
  participant SemanticVerificationReceiptV1
  Transcript->>verify_transcript: submit job, comparator, run, transcript
  verify_transcript->>SemanticReplay: initialize canonical replay
  SemanticReplay->>SSA_EvaluationContext: parse formula and evaluate region programs
  SSA_EvaluationContext-->>SemanticReplay: point decision and resource result
  SemanticReplay-->>verify_transcript: replay result and accounting record
  verify_transcript->>SemanticVerificationReceiptV1: seal after all checks pass
  SemanticVerificationReceiptV1-->>verify_transcript: receipt or typed rejection
Loading

Possibly related PRs

  • Labpics-Team/lab-colors#494 — добавляет contextual region definitions, которые semantic replay преобразует и проверяет.
  • Labpics-Team/lab-colors#497 — предоставляет V1 protocol types для jobs, comparator manifests, transcripts и witnesses.
  • Labpics-Team/lab-colors#498 — определяет RunClaimV1, к которому привязываются replay и verification receipt.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.28% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно описывает основное изменение: независимый verifier воспроизводит engine-транскрипты и создаёт receipts.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch v5b2c-semantic-verifier

Comment @coderabbitai help to get the list of available commands.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 29

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@proof/region/v1/PROTOCOL.md`:
- Around line 733-742: Исправьте опечатку в описании доменных guard’ов
операторов: замените латинскую букву `t` в начале слова «tочный» на
кириллическую «т», чтобы получилось «точный».

In `@proof/region/v1/semantic/__init__.py`:
- Around line 8-20: Замените абсолютные импорты в пакете semantic на
относительные, сохранив импорт символов из receipt, rejected-типов и
verify_transcript из verifier при импорте как proof.region.v1.semantic. Также
отсортируйте элементы __all__ в порядке, требуемом RUF022.

In `@proof/region/v1/semantic/intervalmath.py`:
- Around line 506-526: Ограничьте перебор в _reduce_quadrant, чтобы большие
аргументы не приводили к неограниченным вычислениям: введите явный
типизированный отказ при превышении допустимого числа кандидатов или величины
value и корректно распространите его через пути sin и cos. Зафиксируйте
выбранный предел и поведение отказа в PROTOCOL.md рядом с ограничением reduction
range для exp; не используйте panic или приблизительный fallback.
- Around line 529-574: Remove the remainder-out-of-range fallback branches from
sin and cos; do not return Interval(-1, 1). Let _reduce_quadrant’s invariant
stand, and preserve the existing lo > hi checks to report missing quadrant
coverage through UnresolvedError.

In `@proof/region/v1/semantic/receipt.py`:
- Around line 69-81: Prevent subclassing of SemanticVerificationReceiptV1 by
enforcing sealed-type inheritance restrictions in addition to the _RECEIPT_TOKEN
check. Ensure any attempted subclass definition is rejected, so only
verify_transcript can create receipts with the inherited binds, encode, and
identity behavior.
- Around line 112-181: Add a regression test that compares
resolved_decision_digest_v1(...) with candidate.claim.decision_digest when both
use identical decision_bits, matching the domain and field ordering used by
compare_dual_transcripts and PROTOCOL.md. Keep the implementations tested
independently while asserting their digest outputs are equal.

In `@proof/region/v1/semantic/region.py`:
- Around line 164-174: Добавьте проверку пустого `region.knots` в начале
соответствующего пути перед обращением к `region.knots[0]` и `region.knots[-1]`,
возвращая типизированный отказ `DecisionResult` вместо допуска `IndexError`;
сохраните существующую обработку одиночного узла через `_evaluate_singleton` и
последующую логику для регионов с узлами.
- Around line 247-252: Переместите распаковку `outputs["jp"]`, `outputs["ap"]` и
`outputs["bp"]` в защищённый блок вокруг вызова `ssa.evaluate` в проверке
point-программы. Обработайте отсутствующие выходы так же, как
`intervalmath.UnresolvedError` и `SemanticFormulaError`, возвращая
типизированный `DecisionResult(BOUNDARY_UNPROVEN, 0, False, 0)` вместо
распространения `KeyError`.
- Around line 41-43: Export a public `dyadic_to_fraction` helper from the
protocol module and replace all three `protocol._dyadic` usages in
`Region.from_definition` and its surrounding logic with that API. Also remove
the unnecessary quotes from the `-> "Region"` return annotation, leaving it as
`-> Region` under postponed annotations.
- Around line 193-229: Update the grant-exhaustion check in the surrounding
segment-processing loop to use a greater-than-or-equal comparison, so consumed
budgets at or beyond grant immediately return RESOURCE_LIMIT_REACHED. Preserve
the existing DecisionResult values and subsequent processing for budgets that
remain available.
- Around line 19-22: Замените локальные числовые коды INSIDE, OUTSIDE,
BOUNDARY_UNPROVEN и RESOURCE_LIMIT_REACHED ссылками на соответствующие члены
protocol.DecisionV1, сохранив доступные имена для verifier.py и тестов.
Убедитесь, что значения вычисляются из канонического перечисления при загрузке
модуля, чтобы несовпадение с DecisionV1 сразу приводило к ошибке.
- Around line 109-112: Обновите путь `_predicate_decision` → `decide` →
`evaluate_rgb` и внешний цикл `verify_transcript`, чтобы ошибки
`SemanticFormulaError` и отсутствующая программа (`KeyError`) не выходили через
публичную границу проверки. Перехватите их вместе с существующими
`intervalmath.UnresolvedError` и `replay.ReplayIntegrityError`, сохранив typed
rejection вместо panic для программ `singleton` и `segment`.
- Around line 40-54: Перед семантическим replay в verify_transcript зафиксируйте
исходный ProofJobV1 через protocol.snapshot_proof_job_v1 и используйте
полученный snapshot дальше. Обработайте IndexError и ProtocolErrorV1 при
построении Region через from_definition как типизированный отказ, сохранив
текущий путь успешной проверки.

In `@proof/region/v1/semantic/replay.py`:
- Around line 129-138: Обновите создание PointReplay в данном участке так, чтобы
все восемь аргументов передавались по именам полей, включая consumed,
point_grant, resource_scope и exact_branch. Сохраните существующее соответствие
каждого значения одноимённому полю и не меняйте остальную логику.
- Around line 89-91: Замените материализацию `job.domain.iter_ordinals()` в
инициализации `self._ordinals` на ленивый итератор, сохранив последовательное
чтение ординалов в `next_point`. Уберите логику, предполагающую наличие кортежа
или произвольный доступ по индексу, но сохраните существующее поведение курсора
и обработки исчерпания домена.
- Around line 141-147: Добавьте аннотацию возврата -> None к
ReplayIntegrityError.__init__ и переместите объявление ReplayIntegrityError выше
SemanticReplay, чтобы исключение было объявлено до его использования в
next_point; остальное поведение класса сохраните.
- Around line 109-111: Validate that budget.precision_ladder is non-empty in the
relevant __init__ method before verify_transcript can access ladder[0], and
reject an empty ladder with the established typed validation error. Preserve
normal initialization and verification behavior for non-empty ladders, including
the existing final_precision setup.
- Around line 50-61: Update accounting_prefix_v1 to handle unsupported
ComparatorKindV1 values explicitly instead of allowing
ACCOUNTING_DOMAINS_V1[kind] to raise KeyError. Raise the repository’s
established typed validation/error type with a clear unsupported-comparator
message, so verify_transcript receives a typed failure at its public boundary.
- Around line 39-70: Добавьте независимый тестовый вектор для digest,
формируемого через accounting_prefix_v1 и account_record: зафиксируйте engine
transcript bytes и ожидаемый digest, затем сравните их с результатом
replay-реализации. Не ограничивайтесь test_replayed_transcript_seals_a_receipt,
поскольку он использует те же функции; проверьте соответствие доменов, порядка
полей и ширин 4/4/8/1.

In `@proof/region/v1/semantic/ssa.py`:
- Around line 199-212: Согласуйте ветку проверки оператора eq в проверке
семантики с ограничениями _evaluate_node: разрешайте сравнение только одинаковых
дискретных типов, исключив real и decode_table. Сохраните требование ровно двух
аргументов и одинаковости их типов, чтобы неподдерживаемые сравнения отклонялись
при разборе через SemanticFormulaError.
- Around line 360-392: Вынесите создание значений литералов из горячего пути:
добавьте кеш декодированных `Interval` в `SemanticFormula`, рассчитанный один
раз для `self.formula.literals`, и в `evaluate` используйте его вместо
повторного вызова `binary64_to_fraction` и `intervalmath.exact`. Сохраните
текущее сопоставление имён литералов и их значений.

In `@proof/region/v1/semantic/verifier.py`:
- Around line 42-48: Update verify_transcript’s canonical object validation to
return a SemanticVerificationRejectedV1 with a new INVALID_INPUT reason instead
of raising TypeError, ensuring every noncanonical argument remains within the
VerificationResultV1 result path.

In `@proof/region/v1/tests/test_semantic_diversity.py`:
- Around line 21-37: Strengthen the independence scan by updating
SEMANTIC_SOURCES to recurse with rglob, and revise _imported_roots() to inspect
every import-path component, including names in relative ImportFrom nodes with
no module. Extend the AST checks to reject dynamic imports through both
__import__ and importlib.import_module, then add negative tests covering nested
modules, relative executor imports, qualified proof.region.v1.executor imports,
and both dynamic-import forms.

In `@proof/region/v1/tests/test_semantic_intervalmath.py`:
- Around line 124-168: Добавьте в OperatorDomainContractTests тесты для
публичного ratio0, проверив особое поведение 0/0 и отклонение нулевого либо
неопределённо знакового делителя, а также тесты для sin и cos с аргументом за
пределами допустимого диапазона редукции, ожидающие UnresolvedError. Используйте
существующие helper call, CAP и стили проверок класса.

In `@proof/region/v1/tests/test_semantic_replay.py`:
- Around line 223-287: Расширьте тестовый модуль фикстурой транскрипта,
созданного реальным semantic replay engine, вместо построения decisions,
witnesses и accounting через те же функции, которые проверяет verify_transcript.
В test_replayed_transcript_seals_a_receipt используйте эту engine-produced
fixture с run_claim и подтвердите выдачу SemanticVerificationReceiptV1 и
корректную привязку к job, comparator, run и transcript; формат фикстуры должен
явно содержать engine-generated decisions, witnesses и accounting digest.
- Around line 205-216: Update the packed-decision byte length in the
DecisionTranscriptV1 fixture construction to round drifted_count up for four
decisions per byte, preserving the declared count even when it is not divisible
by four. Keep the existing byte-fill pattern and drift-count setup unchanged.
- Around line 229-273: Update the test loop around decisions and witnesses to
assert that the fixture produces each witness-producing outcome: exact-boundary
INSIDE, BOUNDARY_UNPROVEN, and RESOURCE_LIMIT_REACHED, before constructing the
transcript. Replace the untyped witnesses list with a union of
ExactZeroSignalTraceV1, BoundaryUnprovenWitnessV1, and ResourceLimitWitnessV1.
- Around line 138-145: Update test_saturate_all_inside_transcript_fails_replay
to assert the specific expected result.reason for saturation-induced replay
failure, matching the explicit reason checks used by the neighboring tests,
rather than only checking SemanticVerificationRejectedV1.
- Around line 121-136: Update
test_two_identical_wrong_transcripts_both_fail_replay to assert that both
rejected results have a reason other than FOREIGN_BINDING, while preserving the
existing checks for deterministic rejection and matching ordinals.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4fa8b195-d912-44a5-b06d-f6c6d896d7fe

📥 Commits

Reviewing files that changed from the base of the PR and between be009ce and c93d15f.

📒 Files selected for processing (12)
  • proof/region/v1/PROTOCOL.md
  • proof/region/v1/semantic/__init__.py
  • proof/region/v1/semantic/intervalmath.py
  • proof/region/v1/semantic/receipt.py
  • proof/region/v1/semantic/region.py
  • proof/region/v1/semantic/replay.py
  • proof/region/v1/semantic/ssa.py
  • proof/region/v1/semantic/verifier.py
  • proof/region/v1/tests/test_semantic_diversity.py
  • proof/region/v1/tests/test_semantic_intervalmath.py
  • proof/region/v1/tests/test_semantic_receipt.py
  • proof/region/v1/tests/test_semantic_replay.py

Comment thread proof/region/v1/PROTOCOL.md
Comment thread proof/region/v1/semantic/__init__.py Outdated
Comment thread proof/region/v1/semantic/intervalmath.py
Comment thread proof/region/v1/semantic/intervalmath.py
Comment thread proof/region/v1/semantic/receipt.py
Comment thread proof/region/v1/tests/test_semantic_replay.py
Comment thread proof/region/v1/tests/test_semantic_replay.py
Comment thread proof/region/v1/tests/test_semantic_replay.py
Comment thread proof/region/v1/tests/test_semantic_replay.py
Comment thread proof/region/v1/tests/test_semantic_replay.py
- intervalmath: sin/cos unresolved beyond the 2^12 V1 reduction range; drop the unreachable hull fallbacks

- region: bind outcome codes to DecisionV1, typed empty-knot rejection, widen predicate catch, guarded output unpack, >= grant check, public dyadic_field_v1

- replay: ReplayIntegrityError moved above its raiser, empty ladder + unknown kind + exhausted ordinals are typed errors, streaming ordinals, keyword PointReplay

- verifier: noncanonical inputs reject as invalid_input instead of raising; init/loop catches cover IndexError, ProtocolErrorV1 and ReplayIntegrityError

- receipt: INVALID_INPUT reason, final type guard

- ssa: eq admits discrete operands only at parse; literal environment cached once per formula

- semantic/__init__: relative imports, sorted __all__

- PROTOCOL.md: typo fix, sin/cos guard rule, invalid_input + final documented

- tests: hardened diversity checker with synthetic negative cases, dual admission digest parity, independent accounting vector, ratio0/sin/cos domain tests, tighter rejection assertions
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@proof/region/v1/region_proof_protocol.py`:
- Around line 265-268: Обновите public-функцию dyadic_field_v1, чтобы до вызова
_dyadic она проверяла, что bits имеет тип bytes, и для любого другого входа
возвращала ProtocolErrorV1 через существующий механизм _fail вместо передачи
значения в len. Сохраните текущую обработку корректных bytes без изменений.

In `@proof/region/v1/tests/test_semantic_diversity.py`:
- Around line 33-41: Update the Import handling in the AST root-collection logic
to add every component of alias.name, not only the first component, while
preserving the existing ImportFrom behavior. Extend the relevant
semantic-diversity test with a negative case for `import
proof.region.v1.executor`, ensuring this dependency is rejected and the
verifier’s independence check covers the AST import path.

In `@proof/region/v1/tests/test_semantic_replay.py`:
- Around line 343-364: Добавьте в тест рядом с существующим вектором ARB
независимую проверку для ComparatorKindV1.MPFI: создайте MPFI-компаратор,
вручную соберите ожидаемый SHA-256 с MPFI domain identity и теми же полями
записей, затем сравните его с digest, полученным через accounting_prefix_v1 и
account_record. Не переиспользуйте ожидаемый digest или внутренний результат
accounting_prefix_v1 для вычисления эталона.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 35714452-d03d-48a5-937d-48a8ae84e847

📥 Commits

Reviewing files that changed from the base of the PR and between c93d15f and 45c8b15.

📒 Files selected for processing (13)
  • proof/region/v1/PROTOCOL.md
  • proof/region/v1/region_proof_protocol.py
  • proof/region/v1/semantic/__init__.py
  • proof/region/v1/semantic/intervalmath.py
  • proof/region/v1/semantic/receipt.py
  • proof/region/v1/semantic/region.py
  • proof/region/v1/semantic/replay.py
  • proof/region/v1/semantic/ssa.py
  • proof/region/v1/semantic/verifier.py
  • proof/region/v1/tests/test_semantic_diversity.py
  • proof/region/v1/tests/test_semantic_intervalmath.py
  • proof/region/v1/tests/test_semantic_receipt.py
  • proof/region/v1/tests/test_semantic_replay.py

Comment thread proof/region/v1/region_proof_protocol.py
Comment thread proof/region/v1/tests/test_semantic_diversity.py
Comment thread proof/region/v1/tests/test_semantic_replay.py
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