Skip to content

Proof: собрать Arb evaluator из точных входов - #499

Closed
lemone112 wants to merge 14 commits into
mainfrom
agent/v5b2c1-arb-source-build
Closed

lemone112 wants to merge 14 commits into
mainfrom
agent/v5b2c1-arb-source-build

Conversation

@lemone112

@lemone112 lemone112 commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Суть

Строит exact diagnostic Arb evaluator из pinned source-inputs и изолирует BUILD/RUN как отдельный контролируемый путь. Это не proof и не публичный runtime Lab Colors.

Границы

  • source admission и materialization проверяют exact archive coordinates;
  • две offline-сборки из одного pinned OCI manifest должны дать byte-identical static x86_64 ELF;
  • controller владеет one-shot capability, sealed input, cleanup и typed diagnostic observations;
  • runtime ограничен seccomp, rlimits и delegated cgroup v2;
  • receipt, математический verdict и trust claims намеренно отсутствуют;
  • wire-документация теперь различает общий proof codec (u64 blob) и отдельный provenance/source-lock codec (u32 blob).

Проверка

  • Для текущего documentation-only head 9f1f1a7: source-lock suite 13/13 в normal и -O; git diff --check clean.
  • Предыдущий code-head de1a7cf: Arb fast gate 128, protocol/source 41, mutation 50; normal и optimized; compile, shellcheck, actionlint и diff gate были зелёными.
  • Hosted run, остановленный из-за billing до checkout, не засчитывается как product evidence.

Обязательный внешний gate

Этот PR не готов к merge до exact-head проверки на disposable one-job Linux VM:

  • native BUILD, zero skips;
  • cgroup/seccomp/pipeline RUN, zero skips, на binary из BUILD;
  • полного CI на той же одноразовой VM.

Workflow и runner в этом PR не меняются.

@coderabbitai

coderabbitai Bot commented Jul 29, 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: 11 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: 61986e48-d27d-41a1-91c8-edbd7e59ed57

📥 Commits

Reviewing files that changed from the base of the PR and between 8fe2532 and 9f1f1a7.

📒 Files selected for processing (8)
  • .github/workflows/arb.yml
  • proof/region/v1/PROTOCOL.md
  • proof/region/v1/arb/pipeline.py
  • proof/region/v1/arb/tests/gate.py
  • proof/region/v1/arb/tests/test_build_recipe.py
  • proof/region/v1/arb/tests/test_evaluator_source.py
  • proof/region/v1/arb/tests/test_pipeline.py
  • proof/region/v1/region_proof_protocol.py

Walkthrough

Добавлены канонические source locks и admission архивов, самостоятельный Arb evaluator с transcript bytes, Linux sandbox executor, контролируемый Docker BUILD/RUN pipeline, ComparatorManifestV2 и workflow для точного offline-тестирования.

Changes

Канонический офлайн-конвейер Arb Proof V1

Layer / File(s) Summary
Допуск исходников, integrity и snapshots
proof/region/v1/provenance.py, proof/region/v1/arb/origin.py, proof/region/v1/arb/snapshot.py, proof/region/v1/arb/keys/*, proof/region/v1/arb/tests/test_source_lock.py, proof/region/v1/arb/tests/test_origin.py, proof/region/v1/arb/tests/test_snapshot.py
Добавлены source locks, проверка архивов, detached-signature/Git observations и нормализованная материализация исходников.
Генерация и выполнение Arb evaluator
proof/region/v1/arb/evaluator/*, proof/region/v1/arb/build.sh, proof/region/v1/arb/tests/test_evaluator_source.py
Добавлены SSA-генератор, Arb-интервальная арифметика, региональная оценка, wire parser, SHA-256 и CLI-транскрипты с witnesses.
Linux sandbox executor
proof/region/v1/arb/executor.py, proof/region/v1/arb/tests/test_executor.py
Добавлены capability probe, sealed memfd, seccomp, namespaces, cgroup v2, bounded I/O и типизированные execution observations.
Controlled BUILD/RUN pipeline
proof/region/v1/arb/pipeline.py, proof/region/v1/arb/tests/test_pipeline.py, proof/region/v1/arb/build.sh, .github/workflows/arb.yml, .github/actionlint.yaml, proof/region/v1/arb/tests/gate.py, proof/region/v1/arb/tests/native_gate.py, proof/region/v1/arb/tests/runtime_gate.py, proof/region/v1/arb/tests/test_build_recipe.py
Добавлены воспроизводимые Docker builds, FLINT content partitioning, comparator derivation, transcript validation, controlled execution и exact CI gates.
Comparator manifest V2
proof/region/v1/region_proof_protocol.py, proof/region/v1/tests/test_region_proof_protocol.py, proof/region/v1/PROTOCOL.md
Manifest wire identity и content resolution переведены на V2, а transcript, run claim и dual comparison обновлены под новые координаты.

Estimated code review effort: 5 (Critical) | ~120 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.53% 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 Заголовок точно описывает основное изменение: сборку standalone Arb evaluator из закреплённых точных входов.
✨ 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 agent/v5b2c1-arb-source-build

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

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 29, 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.

@lemone112
lemone112 marked this pull request as ready for review July 29, 2026 18:05
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 29, 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.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 57 minutes.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 59 minutes.

@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: 23

🤖 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/arb/build.sh`:
- Around line 101-134: Reduce the dependency test workload in the build sequence
around the GMP, MPFR, and FLINT `make check` commands so the two-hour
`BUILD_TIMEOUT_NS_V1` budget remains viable, preferably by running only targeted
checks for critical modules. Preserve installation and verification coverage,
and document the measured runtime or rationale for the selected test scope in a
nearby comment.

In `@proof/region/v1/arb/evaluator/formula.h`:
- Around line 8-16: Clarify the output-size contract for lc_formula_point in the
header with a brief comment explaining how many Arb elements output must contain
and why it uses arb_ptr, while preserving the existing arb_t declarations for
lc_formula_segment and lc_formula_singleton.

In `@proof/region/v1/arb/evaluator/interval.c`:
- Around line 8-22: Добавьте комментарий к декодированию в блоке с exponent_bits
и significand: зафиксируйте, что шаблоны exponent_bits == 0x7ff отвергаются как
NaN/Infinity, отрицательный ноль (0x8000000000000000) — как недопустимый, а знак
применяется только для ненулевого significand, чтобы каждый принятый шаблон
однозначно задавал ровно один точный dyadic.

In `@proof/region/v1/arb/evaluator/region.c`:
- Around line 159-167: Перенесите проверку минимальной точности в
lc_region_decide перед веткой для knot_count == 1, чтобы precision < 2 всегда
устанавливал LC_DOMAIN_UNPROVEN и завершал функцию до вызова evaluate_singleton.
Сохраните отдельную обработку одноузлового региона для precision >= 2 и
существующую проверку knot_count < 2.

In `@proof/region/v1/arb/evaluator/wire.c`:
- Around line 550-565: Добавьте поясняющий комментарий непосредственно перед
увеличением iterator->range_index в lc_domain_iterator_next: укажите, что
parse_domain гарантирует строго возрастающие непересекающиеся диапазоны и
соответствие суммы их размеров point_count, поэтому переход выполняется только
при наличии следующего диапазона и индекс остаётся в пределах ranges. Не
пересказывайте сам оператор; зафиксируйте именно инвариант, делающий доступ
безопасным.
- Around line 224-231: Replace the manual fixed_one index chain in the wire
evaluator loop with a table of expected field properties aligned with lengths[].
Use that table to determine which fields must be one byte, keeping the existing
reject(&input, LC_WIRE_UNKNOWN_RELEASE) behavior and ensuring the invariant
remains synchronized with the field definitions.

In `@proof/region/v1/arb/executor.py`:
- Around line 503-515: Update ControlledExecutorV1.execute and
NativeLinuxBackendV1.run so each execution performs the probe only once: reuse
the SupportedV1 result obtained by execute, or pass it into run, while
preserving UnsupportedV1 handling and existing result validation. Remove the
redundant probe invocation from the run path.

In `@proof/region/v1/arb/origin.py`:
- Around line 532-546: Update the cleanup logic in the finally block around
child.wait() and os.killpg so SIGKILL is sent only when child is still running.
Preserve the existing wait-and-reap behavior for already terminated children,
and then close the child streams and input_file as before.

In `@proof/region/v1/arb/pipeline.py`:
- Around line 617-619: Replace the locals()-driven field assignment loops in
DiagnosticArbComparatorV1.__init__ (including the corresponding block around the
second location) with explicit object.__setattr__ calls for each dataclass
parameter, matching the established pattern in DiagnosticPipelineObservationV1.
Ensure each field receives its intended constructor argument rather than any
same-named local variable.
- Line 86: Suppress the S108 and S603 findings locally for _BUILD_TMPFS_SPEC_V1
and the corresponding Popen invocation, including a brief justification that the
value is a Docker --tmpfs specification and Popen receives controller-built
argument strings without shell execution. Apply the same targeted suppressions
to the additional affected block around the later Popen usage, without
broadening the lint configuration.
- Around line 2126-2134: В `ControlledPipelineV1.__init__` замените параметр
`executor: object` на параметр с новым именем, например `execution_backend`,
чтобы не затенять модуль `executor`. Объявите для исполнительного backend
отдельный `Protocol` с необходимыми методами `probe` и `execute`, используйте
этот тип в конструкторе и сохраните backend в `_executor`.
- Around line 1188-1192: Упростите инициализацию `_platform_name` в этом
конструкторе: уберите промежуточную переменную `sys_platform` и первое
присвоение, сразу присваивая полю нормализованное значение с сохранением
текущего поведения для Linux и остальных платформ.
- Around line 2259-2279: Создайте публичный слой API verification для проверок,
используемых admission-путём, и перенесите туда обращения к приватным функциям
_result_matches_request, _require_static_x86_64_elf и
_validate_witness_alignment. Обновите pipeline.py, включая показанный блок,
чтобы он вызывал только публичные verification-символы, сохранив существующее
поведение проверок.

In `@proof/region/v1/arb/snapshot.py`:
- Around line 166-170: Replace the snapshot materialization call to the private
provenance._decompress_exact symbol with a public provenance API such as
decompress_locked_tar. Export that API from the provenance module while
preserving the existing bounded-decompression behavior, arguments, and returned
tar bytes used by the snapshot flow.

In `@proof/region/v1/arb/tests/test_build_recipe.py`:
- Around line 29-31: Согласуйте обработку отсутствующего BUILD в тестах
test_recipe_is_offline_static_and_platform_explicit и связанном тесте на
skip-условии: либо уберите skipUnless и сделайте наличие рецепта обязательным,
либо примените то же условие пропуска к чтению BUILD, чтобы при его отсутствии
тест корректно пропускался вместо FileNotFoundError.

In `@proof/region/v1/arb/tests/test_evaluator_source.py`:
- Around line 230-242: Вынесите повторяющиеся вставку пути и импорт символов из
region_proof_protocol в module-level helper или setUpModule, сохранив
единственную вставку REPO/"proof/region/v1" и общий импорт для всех семи
runtime-тестов в test_evaluator_source.py. Обновите тесты, включая
test_generator_is_independent_from_python_protocol_and_controller, чтобы
использовали общий результат загрузки без повторного изменения sys.path и без
ослабления проверки изоляции.
- Around line 38-52: В функции assert_transcript_wire_coordinates замените
getattr(transcript, "decision_bits") и getattr(transcript, "accounting_digest")
прямым доступом к атрибутам transcript.decision_bits и
transcript.accounting_digest; сохраните остальную проверку wire без изменений.

In `@proof/region/v1/arb/tests/test_executor.py`:
- Around line 34-55: Update the needed branch in _static_elf so dynamic_offset
is calculated from the eventual program-header count, including the PT_DYNAMIC
header being appended, instead of assuming two headers. Keep the dynamic payload
immediately after the complete header table so interpreter=True and needed=True
point PT_DYNAMIC at the dynamic data.

In `@proof/region/v1/arb/tests/test_origin.py`:
- Around line 214-223: В тесте вокруг чтения PID-потомка добавьте
bounded-ожидание появления файла, используя тот же временной интервал и
polling-подход, что и последующая проверка завершения процесса, прежде чем
вызывать pid_path.read_text. Сохраните существующее утверждение о принудительном
завершении потомка и явно завершайте тест с диагностикой, если файл так и не
появился.

In `@proof/region/v1/arb/tests/test_pipeline.py`:
- Around line 224-238: Update _transcript so it no longer overwrites
manifest_identity through the hard-coded encoded-byte slice [72:104]. Construct
the transcript through DecisionTranscriptV1.from_decisions using the requested
manifest identity or derive the field offset from the codec’s public encoding
metadata, preserving the test’s intended manifest-identity substitution without
depending on wire layout.
- Around line 570-578: В тесте
test_operator_coordinate_is_the_exact_ordered_formula_contract замените поиск
фиксированной строки b"operators 20" на поиск строки по префиксу b"operators " с
извлечением и проверкой числового счётчика. Сформируйте содержательную ошибку,
если строка операторов отсутствует или имеет некорректный формат, сохранив
последующую перестановку найденных строк.

In `@proof/region/v1/provenance.py`:
- Around line 719-814: Refactor _decompress_exact to share one bounded
decompression loop for the gzip and xz branches, parameterizing only the
decompressor input/feed behavior and continuation predicate. Consolidate the
repeated expected_length overflow, truncated-stream, and final length checks
while preserving each format’s unused_data validation and existing failure
reasons.

In `@proof/region/v1/region_proof_protocol.py`:
- Around line 721-727: Сохраните прежнюю семантику V1: не переименовывайте и не
переинтерпретируйте существующие digest-поля без изменения wire/version domain.
Для новых полей и смыслов выпустите отдельную V2 с новым magic и identity label,
обновив parse(), encode() и identity; также добавьте regression-тест,
подтверждающий, что V1-манифесты не принимаются как V2 и сохраняют прежнюю
интерпретацию.
🪄 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: 31243e84-0d9a-419a-8c0e-f28f9638776b

📥 Commits

Reviewing files that changed from the base of the PR and between ce08323 and acb8355.

📒 Files selected for processing (30)
  • .github/workflows/arb-proof-observation.yml
  • proof/region/v1/PROTOCOL.md
  • proof/region/v1/arb/build.sh
  • proof/region/v1/arb/evaluator/formula.h
  • proof/region/v1/arb/evaluator/formula.py
  • proof/region/v1/arb/evaluator/hash.c
  • proof/region/v1/arb/evaluator/hash.h
  • proof/region/v1/arb/evaluator/interval.c
  • proof/region/v1/arb/evaluator/interval.h
  • proof/region/v1/arb/evaluator/main.c
  • proof/region/v1/arb/evaluator/region.c
  • proof/region/v1/arb/evaluator/region.h
  • proof/region/v1/arb/evaluator/wire.c
  • proof/region/v1/arb/evaluator/wire.h
  • proof/region/v1/arb/executor.py
  • proof/region/v1/arb/keys/gmp.asc
  • proof/region/v1/arb/keys/mpfr.asc
  • proof/region/v1/arb/origin.py
  • proof/region/v1/arb/pipeline.py
  • proof/region/v1/arb/snapshot.py
  • proof/region/v1/arb/tests/test_build_recipe.py
  • proof/region/v1/arb/tests/test_evaluator_source.py
  • proof/region/v1/arb/tests/test_executor.py
  • proof/region/v1/arb/tests/test_origin.py
  • proof/region/v1/arb/tests/test_pipeline.py
  • proof/region/v1/arb/tests/test_snapshot.py
  • proof/region/v1/provenance.py
  • proof/region/v1/region_proof_protocol.py
  • proof/region/v1/tests/test_region_proof_protocol.py
  • proof/region/v1/tests/test_source_lock.py

Comment thread proof/region/v1/arb/build.sh
Comment thread proof/region/v1/arb/evaluator/formula.h
Comment thread proof/region/v1/arb/evaluator/interval.c
Comment thread proof/region/v1/arb/evaluator/region.c
Comment thread proof/region/v1/arb/evaluator/wire.c
Comment thread proof/region/v1/arb/tests/test_origin.py Outdated
Comment thread proof/region/v1/arb/tests/test_pipeline.py Outdated
Comment thread proof/region/v1/arb/tests/test_pipeline.py
Comment thread proof/region/v1/provenance.py
Comment thread proof/region/v1/region_proof_protocol.py
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 36 minutes.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@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: 11

🤖 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 @.github/workflows/arb.yml:
- Around line 79-93: Protect the while loop reading lock.tsv by redirecting
stdin for external commands in its body, especially the archive download and
checksum/validation commands, so they cannot consume remaining input records.
Update the loop around the read of role, url, digest, and length while
preserving the existing three-role processing and final count validation.

In `@proof/region/v1/arb/build.sh`:
- Around line 149-156: Update the PT_INTERP and DT_NEEDED checks around the
readelf invocations so each readelf result is captured and its exit status
validated separately from grep. Fail the build if readelf cannot inspect
arb-evaluator-v1; only perform the corresponding grep assertion when readelf
succeeds, preserving the existing exit-70 errors for detected sections.

In `@proof/region/v1/arb/executor.py`:
- Around line 1595-1675: Сведи последовательность стандартных проб и
повторяющихся проверок guard в одну упорядоченную таблицу дескрипторов и единый
цикл вокруг _probe_operation. Для каждой записи сохрани исходные операцию и
CapabilityReasonV1, а после каждой пробы единообразно обрабатывай failures и
guard.is_current() с возвратом _invalidated_capability_report_v1() или
UnsupportedV1. Сохрани порядок проб и отдельную обработку _probe_sealed_memfd и
проверки cgroup.
- Around line 280-281: Измените аннотацию возвращаемого типа функции
`_request_fail` с `None` на `NoReturn`, добавив необходимый импорт типа.
Сохраните её текущее поведение с безусловным вызовом `ExecutionRequestErrorV1` и
выровняйте контракт с `_source_fail` в `pipeline.py`.
- Around line 2139-2146: В обработке ChildProcessError рядом с наблюдением через
os.waitpid не подменяйте недоступный статус значением 0. Возвращайте
типизированный ObserverFailureV1 либо передавайте его в _classify_process_v1,
сохраняя CompletedV1 только для реально наблюдаемого завершения процесса.

In `@proof/region/v1/arb/origin.py`:
- Around line 321-335: Замените использование locals() в инициализации
AcceptedHistoricalSignatureStatusV1 и связанном участке 772–789 явными ссылками
на соответствующие параметры и поля. Передавайте значения в _digest напрямую по
каждому имени и явно присваивайте поля через object.__setattr__, сохранив
текущий порядок и поведение без зависимости от совпадения имён.

In `@proof/region/v1/arb/snapshot.py`:
- Around line 159-171: The snapshot materialization path decompresses and hashes
the archive twice. Update the flow around provenance.admit_source_archive and
decompress_locked_tar_v1 so the single admission pass returns or accepts and
reuses the already decompressed raw_tar while preserving the existing replay
drift checks and tar extraction behavior.

In `@proof/region/v1/arb/tests/gate.py`:
- Around line 94-99: Update the inventory-drift diagnostic in the print call so
the count/sha256 and expected hash form one concatenated message argument,
avoiding print’s automatic separator and the resulting double space.

In `@proof/region/v1/arb/tests/test_build_recipe.py`:
- Around line 175-186: Update
test_recipe_rejects_ambient_or_incomplete_invocation_before_build to pass a
finite timeout to subprocess.run and close stdin for the build invocation, using
the same established values or pattern as the other subprocess calls in the test
suite.

In `@proof/region/v1/arb/tests/test_origin.py`:
- Around line 342-343: В тесте test_crashed_gpgv_is_a_typed_process_failure
замените имя неиспользуемой переменной expected при распаковке
signed_source_fixture() на имя с префиксом подчёркивания, сохранив admitted без
изменений.

In `@proof/region/v1/arb/tests/test_pipeline.py`:
- Around line 1303-1310: Добавьте проверку переменной окружения
LABCOLORS_ARB_NATIVE_BINARY в условие unittest.skipUnless для теста pipeline,
чтобы при её отсутствии тест пропускался до запуска сборок. Синхронно обновите
строку причины пропуска, используемую EXPECTED_SKIPS в gate.py, сохранив
дословное совпадение текста.
🪄 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: ef637e79-222a-46c7-820f-74ab04a33812

📥 Commits

Reviewing files that changed from the base of the PR and between ce08323 and aedb4e1.

📒 Files selected for processing (34)
  • .github/actionlint.yaml
  • .github/workflows/arb.yml
  • proof/region/v1/PROTOCOL.md
  • proof/region/v1/arb/build.sh
  • proof/region/v1/arb/evaluator/formula.h
  • proof/region/v1/arb/evaluator/formula.py
  • proof/region/v1/arb/evaluator/hash.c
  • proof/region/v1/arb/evaluator/hash.h
  • proof/region/v1/arb/evaluator/interval.c
  • proof/region/v1/arb/evaluator/interval.h
  • proof/region/v1/arb/evaluator/main.c
  • proof/region/v1/arb/evaluator/region.c
  • proof/region/v1/arb/evaluator/region.h
  • proof/region/v1/arb/evaluator/wire.c
  • proof/region/v1/arb/evaluator/wire.h
  • proof/region/v1/arb/executor.py
  • proof/region/v1/arb/keys/gmp.asc
  • proof/region/v1/arb/keys/mpfr.asc
  • proof/region/v1/arb/origin.py
  • proof/region/v1/arb/pipeline.py
  • proof/region/v1/arb/snapshot.py
  • proof/region/v1/arb/tests/gate.py
  • proof/region/v1/arb/tests/native_gate.py
  • proof/region/v1/arb/tests/runtime_gate.py
  • proof/region/v1/arb/tests/test_build_recipe.py
  • proof/region/v1/arb/tests/test_evaluator_source.py
  • proof/region/v1/arb/tests/test_executor.py
  • proof/region/v1/arb/tests/test_origin.py
  • proof/region/v1/arb/tests/test_pipeline.py
  • proof/region/v1/arb/tests/test_snapshot.py
  • proof/region/v1/provenance.py
  • proof/region/v1/region_proof_protocol.py
  • proof/region/v1/tests/test_region_proof_protocol.py
  • proof/region/v1/tests/test_source_lock.py

Comment thread .github/workflows/arb.yml
Comment thread proof/region/v1/arb/build.sh Outdated
Comment thread proof/region/v1/arb/executor.py Outdated
Comment thread proof/region/v1/arb/executor.py
Comment thread proof/region/v1/arb/executor.py
Comment thread proof/region/v1/arb/snapshot.py Outdated
Comment thread proof/region/v1/arb/tests/gate.py
Comment thread proof/region/v1/arb/tests/test_build_recipe.py
Comment thread proof/region/v1/arb/tests/test_origin.py Outdated
Comment thread proof/region/v1/arb/tests/test_pipeline.py
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
proof/region/v1/region_proof_protocol.py (1)

733-756: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Устраните ошибку Ruff F402.

Локальное имя field затеняет импорт из dataclasses; переименуйте переменные обхода.

Исправление
-        for field in fields(self):
-            if field.name != "kind":
-                _require_digest(getattr(self, field.name), "comparator-manifest-v2", field.name)
+        for manifest_field in fields(self):
+            if manifest_field.name != "kind":
+                _require_digest(
+                    getattr(self, manifest_field.name),
+                    "comparator-manifest-v2",
+                    manifest_field.name,
+                )
@@
-            getattr(self, field.name) for field in fields(self) if field.name != "kind"
+            getattr(self, manifest_field.name)
+            for manifest_field in fields(self)
+            if manifest_field.name != "kind"
🤖 Prompt for 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.

In `@proof/region/v1/region_proof_protocol.py` around lines 733 - 756, Устраните
Ruff F402 в методе encode класса ComparatorManifestV2: переименуйте переменную
цикла field в обоих обходах fields(self), включая проверку имени и getattr,
чтобы она не затеняла импорт field из dataclasses.

Source: Linters/SAST tools

🤖 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 @.github/workflows/arb.yml:
- Around line 135-141: Restore the original
kernel.apparmor_restrict_unprivileged_userns value during the existing if:
always() cleanup. In the “delegate one disposable cgroup subtree” step, capture
and persist the value before sudo sysctl changes it, then have cleanup read that
value and restore it with sudo sysctl, including when setup fails. Ensure
cleanup remains best-effort and runs before the runner is released.

In `@proof/region/v1/arb/evaluator/main.c`:
- Around line 234-244: Перенесите объявление массива values из блока после
проверки в начало функции рядом с остальными локальными переменными. Оставьте
его инициализацию значениями lower_text, upper_text и exponent_text
непосредственно перед циклом, сохранив существующий переход goto cleanup.

In `@proof/region/v1/arb/evaluator/region.c`:
- Around line 183-239: Reduce the cognitive complexity of lc_region_decide by
extracting the segment-loop body into a static evaluate_segment(...) helper.
Pass the segment endpoints, intersection/input context, precision, and result
state needed to preserve branch accounting, formula_status, enclosure recording,
and canonical exact_branch selection; have the helper return the
inside/outside/exact aggregate state, while keeping lc_region_decide responsible
for iteration, domain intersection, resource-limit handling, and aggregate
updates.

In `@proof/region/v1/arb/pipeline.py`:
- Around line 2417-2428: Обработайте `_TreeMismatchV1` при вызовах
`_write_exact_file` в цикле материализации workspace и преобразуйте его в
типизированный `BuildRejectedV1`. Расширьте соответствующий внешний `except`
возле обработки `OSError`, `SnapshotErrorV1` и `BuildSourceAdmissionErrorV1`
либо добавьте локальный перехват, чтобы коллизии родительских каталогов не
проходили через `build()`/`execute()` как `RuntimeError`.

In `@proof/region/v1/arb/tests/test_build_recipe.py`:
- Around line 189-202: Update
test_recipe_rejects_ambient_or_incomplete_invocation_before_build to verify
BUILD is executable before invoking subprocess.run, so a missing +x permission
fails with a clear test assertion rather than PermissionError. Preserve the
existing environment-rejection assertions and direct execution flow after this
precondition.

In `@proof/region/v1/arb/tests/test_evaluator_source.py`:
- Around line 38-51: Update generate() and all listed evaluator runtime
subprocess calls to use the same finite timeout and stdin=subprocess.DEVNULL
contract already established in test_pipeline.py and test_build_recipe.py.
Preserve existing command arguments and result handling while ensuring every
generator/evaluator invocation cannot block on stdin or hang indefinitely.

In `@proof/region/v1/arb/tests/test_pipeline.py`:
- Around line 1400-1406: Добавь проверку наличия LABCOLORS_ARB_NATIVE_BINARY в
условие unittest.skipUnless для NativePipelineIntegrationTests, чтобы тест
пропускался при отсутствии переменной окружения вместо KeyError. Обнови
соответствующую запись для этого теста в EXPECTED_SKIPS, синхронизировав
ожидаемую причину или условие пропуска.

---

Outside diff comments:
In `@proof/region/v1/region_proof_protocol.py`:
- Around line 733-756: Устраните Ruff F402 в методе encode класса
ComparatorManifestV2: переименуйте переменную цикла field в обоих обходах
fields(self), включая проверку имени и getattr, чтобы она не затеняла импорт
field из dataclasses.
🪄 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: 0cc71214-2f97-43a2-99cc-936ba5e7e24e

📥 Commits

Reviewing files that changed from the base of the PR and between ce08323 and 8fe2532.

📒 Files selected for processing (34)
  • .github/actionlint.yaml
  • .github/workflows/arb.yml
  • proof/region/v1/PROTOCOL.md
  • proof/region/v1/arb/build.sh
  • proof/region/v1/arb/evaluator/formula.h
  • proof/region/v1/arb/evaluator/formula.py
  • proof/region/v1/arb/evaluator/hash.c
  • proof/region/v1/arb/evaluator/hash.h
  • proof/region/v1/arb/evaluator/interval.c
  • proof/region/v1/arb/evaluator/interval.h
  • proof/region/v1/arb/evaluator/main.c
  • proof/region/v1/arb/evaluator/region.c
  • proof/region/v1/arb/evaluator/region.h
  • proof/region/v1/arb/evaluator/wire.c
  • proof/region/v1/arb/evaluator/wire.h
  • proof/region/v1/arb/executor.py
  • proof/region/v1/arb/keys/gmp.asc
  • proof/region/v1/arb/keys/mpfr.asc
  • proof/region/v1/arb/origin.py
  • proof/region/v1/arb/pipeline.py
  • proof/region/v1/arb/snapshot.py
  • proof/region/v1/arb/tests/gate.py
  • proof/region/v1/arb/tests/native_gate.py
  • proof/region/v1/arb/tests/runtime_gate.py
  • proof/region/v1/arb/tests/test_build_recipe.py
  • proof/region/v1/arb/tests/test_evaluator_source.py
  • proof/region/v1/arb/tests/test_executor.py
  • proof/region/v1/arb/tests/test_origin.py
  • proof/region/v1/arb/tests/test_pipeline.py
  • proof/region/v1/arb/tests/test_snapshot.py
  • proof/region/v1/provenance.py
  • proof/region/v1/region_proof_protocol.py
  • proof/region/v1/tests/test_region_proof_protocol.py
  • proof/region/v1/tests/test_source_lock.py

Comment thread .github/workflows/arb.yml
Comment thread proof/region/v1/arb/evaluator/main.c
Comment thread proof/region/v1/arb/evaluator/region.c
Comment thread proof/region/v1/arb/pipeline.py
Comment thread proof/region/v1/arb/tests/test_build_recipe.py
Comment thread proof/region/v1/arb/tests/test_evaluator_source.py
Comment thread proof/region/v1/arb/tests/test_pipeline.py
@lemone112

Copy link
Copy Markdown
Collaborator Author

Дополнительная outside-diff находка свежего review также закрыта в de1a7cf: локальная переменная обхода ComparatorManifestV2 переименована в manifest_field, устраняя Ruff F402 без изменения wire/API. Проверки exact head: fast gate 128 tests / 12 exact skips в normal и PYTHONOPTIMIZE=2, protocol/source 41/41, mutation 50/50, actionlint, shellcheck, sh -n, py_compile и diff-check — зелёные. Большие C-refactor предложения без поведенческого дефекта сознательно отклонены в inline threads, чтобы второй review-цикл не превратился в бесконечную полировку.

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Fresh exact head 9f1f1a7 is documentation-only. Verify the scoped wire statement against the actual codecs: region_proof_protocol.py uses u64be(length) blob, while provenance/source-lock uses u32be(length) with its documented coordinates. Do not treat unavailable disposable-VM evidence as passed, and do not review workflow or runner infrastructure.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '== checked-out HEAD =='
git rev-parse HEAD
printf '%s\n' '== diff at requested head =='
git diff --check 9f1f1a7^ 9f1f1a7
git diff --unified=80 9f1f1a7^ 9f1f1a7 -- proof/region/v1/PROTOCOL.md

printf '%s\n' '== protocol codec outline =='
ast-grep outline proof/region/v1/region_proof_protocol.py --items all --view expanded
printf '%s\n' '== provenance codec outline =='
ast-grep outline proof/region/v1/provenance.py --items all --view expanded

printf '%s\n' '== length encoding and decoding references =='
rg -n -C 5 -e 'u64be|u32be|blob|length|_Reader|read_u(32|64)|write_u(32|64)' \
  proof/region/v1/region_proof_protocol.py \
  proof/region/v1/provenance.py

printf '%s\n' '== documentation statements related to wire lengths and coordinates =='
rg -n -C 8 -i -e 'wire|u64|u32|length|blob|source lock|source-lock|coordinate' \
  proof/region/v1/PROTOCOL.md

Length of output: 122816


@lemone112 Reviewed exact head 9f1f1a7.

No findings in the scoped documentation change.

The statement matches both codecs:

  • region_proof_protocol.py encodes blob as u64be(length) || bytes and parses its length with u64.
  • provenance.py encodes blob as u32be(length) || bytes and parses its length with u32.
  • The provenance codec also uses u16 and 20-byte OpenPGP/SHA-1 coordinates as documented.

git diff --check passed. I did not review workflow or runner infrastructure. I did not assess disposable-VM evidence and do not treat it as passed.

✅ 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.

@lemone112

Copy link
Copy Markdown
Collaborator Author

Superseded терминальным срезом #514 (Design Freeze M2a): весь объём этого PR — точный source-build Arb evaluator и BUILD-граница — полностью входит в diff #514 (agent/mpfi-m2a-profile → main, head 0e96b037dfb45888e8e95113e85a95a9504d98df), включая все шесть ступеней нативной лестницы отказов и финальный source-bound BUILD→RUN контракт. Дальнейшая работа по этой ветке создаст двойную точку истины в proof-контуре, поэтому этот PR закрывается без merge. Доказательная база в полном объёме приложена к #514: fast gates, mutation truth и native Arb/MPFI BUILD→RUN receipts на disposable-воркере labcolors-ephemeral.

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