Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
f6c7dbf
Proof: вынести общую BUILD-границу
lemone112 Aug 1, 2026
2e415d3
Proof: изолировать CID cleanup и lifecycle
lemone112 Aug 1, 2026
f34fa37
Proof: укрепить transport boundary и receipt trust
lemone112 Aug 1, 2026
6600223
Proof: preserve stream ownership during cleanup
lemone112 Aug 1, 2026
1b3ffbf
Test: always reap hostile observer fixture
lemone112 Aug 1, 2026
08e0243
Test: register observer cleanup before fixture setup
lemone112 Aug 1, 2026
c010af9
Build: типизировать невалидный public input
lemone112 Aug 1, 2026
9e10df2
Proof: сохранить Arb binding и total probe
lemone112 Aug 1, 2026
f465413
Proof: totalize native cleanup failure
lemone112 Aug 1, 2026
ba538b0
Test: уточнить fixed-arity boundary
lemone112 Aug 1, 2026
f645d75
Proof: totalize native build observations
lemone112 Aug 1, 2026
284ee16
Proof: retain native cleanup evidence
lemone112 Aug 1, 2026
33dfded
Proof: зафиксировать BUILD binding на capability
lemone112 Aug 1, 2026
f23c627
Proof: seal V2 build identity review fixes
lemone112 Aug 1, 2026
78a174e
Merge remote-tracking branch 'origin/agent/mpfi-source' into agent/bu…
lemone112 Aug 1, 2026
13e4fbf
Docs: уточнить CID-root boundary
lemone112 Aug 1, 2026
8327636
Test: закрепить безопасный native fallback
lemone112 Aug 1, 2026
f77acc9
Proof: make Arb build environment entrypoint structural
lemone112 Aug 2, 2026
29c7b5c
Proof: bind split build recipes to the right coordinates
lemone112 Aug 2, 2026
1268d4d
Proof: independently replay every comparator coordinate
lemone112 Aug 2, 2026
8998ada
Proof: expose the comparator replay boundary
lemone112 Aug 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 63 additions & 9 deletions proof/region/v1/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ MPFI source closure ещё не является provenance исполнения
receipt, cross-path dependency overlap и diversity не представлены admitted
типом; structural coordinates не восполняют это отсутствие.

## Wire и identity
## Бинарный формат и идентичность

Для wire-artifact-ов из `region_proof_protocol.py` все целые беззнаковые и
записаны big-endian как `u8`, `u32be` или `u64be`; `digest` — ровно 32
Expand Down Expand Up @@ -155,7 +155,7 @@ Arb controller связывает его с наблюдёнными BUILD/RUN
границы доверия; receipt не заявляет отсутствие ambient inputs за пределами этой
границы. Альтернативный JSON/TOML definition запрещён протоколом.

## Source lock и integrity observations
## Фиксация источников и наблюдения целостности

`SourceReleaseLockV1` фиксирует bytes и структурный состав архива. Поле
`.integrity` содержит один `SourceIntegrityPolicyV1`; это точная граница
Expand Down Expand Up @@ -195,7 +195,7 @@ Lab Colors фиксирует exact HTTPS URL, длину и SHA-256 получ
`MpfiSourceLockV1` использует те же единичные GMP/MPFR source declarations, что
и Arb, однако имеет отдельную aggregate identity и отдельный typed admission.

## Diagnostic execution boundary
## Диагностическая граница исполнения

`proof/region/v1/executor.py` — общий для enclosure engines leaf без импорта
Arb/MPFI, formula или comparator semantics. Он же единолично кодирует
Expand Down Expand Up @@ -234,7 +234,60 @@ observation. Право на Arb receipt получает не executor, а от
`SourceBoundArbControllerV1`, который владеет всей цепью BUILD → RUN и не
принимает backend, capability либо diagnostic observation от вызывающего.

## Source-bound Arb replay
## Общая граница BUILD

`proof/region/v1/build/input.py` принимает уже нормализованные lane entries,
кодирует один канонический USTAR и владеет точными input bytes. Он не
импортирует и не перепроверяет source capability: это ответственность
потребляющего lane. `SealedInputV1` структурно неизменяем, связывает
целостность байтов с opaque caller digest и не утверждает recipe либо engine
semantics. Resource bounds передаёт lane: общий encoder не вводит собственный
fixture-specific cap.

`proof/region/v1/build/transport.py` владеет immutable Docker policy,
одноразовым probe→build lease, bounded stdin/stdout observation, cleanup и
двумя свежими попытками. Доказательные координаты разделены по причинам:

1. transport policy identity связывает все поля точной policy;
2. native command contract identity связывает один типизированный grammar для
probe, build и cleanup и один immutable child-launch context
(environment, cwd, umask, stdio topology, FD и session behavior); фактический argv и
Popen kwargs строятся только этими значениями;
3. daemon observation identity связывает только два raw probe stdout;
4. Docker capability identity связывает policy, command contract и exact CLI
path, daemon observation и наблюдённые host uid/gid.

`BuildSessionV1` и каждый `DockerBuildRequestV1` сохраняют только ту же
capability, те же input bytes и output cap. Request не содержит host path,
CID file или имя контейнера: native adapter сам создаёт свежий приватный CID
path. Native cleanup поддерживается только в fresh one-job VM workflow Arb:
другой субъект с тем же effective UID либо Docker-daemon authority там не
сосуществует. Права `0700` закрывают лишь cross-UID pathname access и не
аутентифицируют same-UID writer. В этой объявленной operational boundary для
cleanup допускается только полный ID, который Docker записал в CID path; перед
`rm --force <id>` adapter сверяет, что `docker container inspect` вернул тот же
ID. Имя контейнера и fallback-координата в cleanup не участвуют. Вне этой
границы CID path не является доказательством ownership. Чужая либо не
полученная текущим probe capability отвергается до process spawn; ambient
path/user повторно не считываются. Разрешение принадлежит создавшему process:
fork и конкурентное повторное использование отвергаются до блокировки. После
возврата Popen handle `BaseException` до повторного выброса исходного
interruption запускает детерминированные попытки остановить и reap CLI, закрыть
streams и очистить допущенный container. Во время самого Popen construction
handle может ещё отсутствовать: тогда возможна только best-effort попытка CID
cleanup, без ложного заявления о reap CLI. `TwoBuildObservationV1` хранит обе успешные попытки и только
классифицирует их байты как identical или different, не называя пару
универсальным доказательством воспроизводимости. При отказе после создания
валидной session сохраняется весь уже завершённый causal prefix. Context-free
contract violation, обнаруженный до создания session (например, невалидная
session или сбой создания приватного CID-root через `mkdtemp`), может вернуть `BuildRejectedV1` без
`session` и `completed_processes`.
Transport не знает formula, ELF, comparator или
source provenance: lane отдельно перепроверяет semantic input binding перед
каждым process и передаёт output admission. Arb объявляет собственную exact
policy; MPFI обязан объявить другую, а не заимствовать Arb semantics.

Comment on lines +237 to +289

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Раздел точно описывает код build/input.py и build/transport.py: caller-owned limits, четыре разделённые identity, one-shot lease, две попытки и сохранение causal prefix.

Одно уточнение по пункту про causal prefix. В ControlledBuildTransportV1._build_once отказ при невалидной сессии или при сбое tempfile.TemporaryDirectory возвращает BuildRejectedV1(attempt, CONTRACT_VIOLATION) без session и без completed_processes. Формулировка «при отказе сохраняется весь уже завершённый causal prefix» здесь не выполняется. Добавьте оговорку про context-free contract violation, чтобы документ не заявлял больше, чем даёт код.

🤖 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/PROTOCOL.md` around lines 234 - 265, Уточните абзац о
сохранении causal prefix в разделе «Общая граница BUILD»: добавьте оговорку, что
context-free contract violations, возникающие при невалидной сессии или сбое
создания TemporaryDirectory в ControlledBuildTransportV1._build_once, могут
возвращать BuildRejectedV1 без session и completed_processes. Не изменяйте
остальные гарантии документа.

## Воспроизведение Arb, связанное с источником

`SourceBoundArbControllerV1` сначала повторно парсит source lock и job,
повторно допускает exact owned archive/build-input bytes и строит из regular
Expand All @@ -244,7 +297,8 @@ object дважды передаётся через bounded stdin; каждый
bounded tmpfs, а executable возвращает через stdout. Semantic host bind mounts,
host output path и повторное открытие результата отсутствуют. Эта граница
доказывает точный controller-observed byte stream, а не непрерывность inode
между host и Docker daemon; сам daemon остаётся явно доверенным V1 input.
между host и Docker daemon. Raw daemon observation входит в capability, но сам
daemon остаётся явно доверенным input объявленной границы.

Успешный replay хранится одним token-closed
`ContentResolvedEvaluatorReplayV1`, который повторно выводит три причинные
Expand All @@ -253,9 +307,9 @@ identity без зеркальных промежуточных dataclass:
1. source identity связывает lock, три admitted archive closures, build inputs
и formula support. Job сюда не входит: одинаковый evaluator build не меняет
source identity от конкретного RUN;
2. build identity связывает source identity, versioned transport/isolation
policy, trust boundary, pinned OCI toolchain, один sealed bundle object, два
exact transfer и два byte-identical executable stdout. Comparator verifier
2. build identity связывает source identity, versioned Docker capability,
pipeline policy, trust boundary, один sealed bundle object, два exact
transfer и два byte-identical executable stdout. Comparator verifier
строит свежий canonical manifest из SHA-256 retained preimage bytes и
сверяет все его поля и identity с build observation; это проверка retained
причинных данных, а не заявление о независимом втором выводе preimages;
Expand Down Expand Up @@ -489,7 +543,7 @@ release не содержит. Family mint
manifest: единственный range `[0, 2^24)` и point count `2^24`. Совпадение
только point count или reduced-domain candidate этот gate не проходят.

## Ошибки admission
## Ошибки допуска

`ProtocolReasonV1` — закрытая сумма:

Expand Down
156 changes: 156 additions & 0 deletions proof/region/v1/arb/build-inner.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
#!/bin/sh
# Internal Arb recipe. The source-bound transport dispatches this file only
# after establishing its clean child environment; it is not a standalone API.
set -eu

if [ "$#" -ne 0 ]; then
printf '%s\n' 'arb build takes no arguments' >&2
exit 64
fi

umask 022

readonly inputs=/build/snapshot/inputs
readonly workspace=/build/snapshot/workspace
readonly build=/build/work

require_regular() {
if [ ! -f "$1" ] || [ -L "$1" ]; then
printf 'missing regular build input: %s\n' "$1" >&2
exit 66
fi
}

require_directory() {
if [ ! -d "$1" ] || [ -L "$1" ]; then
printf 'missing normalized source directory: %s\n' "$1" >&2
exit 66
fi
}

require_empty_directory() {
if [ ! -d "$1" ] || [ -L "$1" ]; then
printf 'missing build directory: %s\n' "$1" >&2
exit 66
fi
if [ -n "$(find "$1" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
printf 'build directory is not empty: %s\n' "$1" >&2
exit 65
fi
}

require_directory "$inputs/gmp-6.3.0"
require_directory "$inputs/mpfr-4.2.2"
require_directory "$inputs/flint-3.6.0"
require_regular "$inputs/formula.generated.c"
printf '%s %s\n' \
'9958f20c8ca598625db0593a45f8f8bc79e4b2f22b53263b6c32d78a5e1d2693' \
"$inputs/formula.generated.c" \
| /usr/bin/sha256sum --check --strict -
for source in main.c wire.c hash.c interval.c region.c; do
require_regular "$workspace/proof/region/v1/arb/evaluator/$source"
done
require_regular "$workspace/proof/region/v1/arb/evaluator/formula.h"
for header in wire.h hash.h interval.h region.h; do
require_regular "$workspace/proof/region/v1/arb/evaluator/$header"
done
require_empty_directory "$build"

/usr/bin/mkdir "$build/prefix" "$build/gmp" "$build/mpfr" "$build/flint" "$build/tmp"

# GCC 15 changed its implicit dialect to GNU C23, where GMP 6.3.0's locked
# no-prototype configure probes have different semantics. GNU C17 is the last
# default those probes targeted; changing it requires a source/toolchain slice
# and a fresh live build, not reliance on a compiler's moving default.
readonly common_cflags='-O2 -g0 -fno-ident -fno-fast-math -ffp-contract=off -fno-lto -std=gnu17 -march=x86-64 -mtune=generic -ffile-prefix-map=/build=. -fdebug-prefix-map=/build=.'
readonly common_ldflags='-Wl,--build-id=none -fno-lto'
readonly prefix="$build/prefix"

cd "$build/gmp"
ABI=64 CC=/usr/local/bin/gcc CFLAGS="$common_cflags" LDFLAGS="$common_ldflags" \
"$inputs/gmp-6.3.0/configure" \
--build=x86_64-pc-linux-gnu \
--host=x86_64-pc-linux-gnu \
--prefix="$prefix" \
--disable-shared \
--enable-static \
--disable-assembly \
--disable-cxx
/usr/bin/make -j1
/usr/bin/make check -j1
/usr/bin/make install

cd "$build/mpfr"
CC=/usr/local/bin/gcc CFLAGS="$common_cflags" LDFLAGS="$common_ldflags" \
"$inputs/mpfr-4.2.2/configure" \
--build=x86_64-pc-linux-gnu \
--host=x86_64-pc-linux-gnu \
--prefix="$prefix" \
--with-gmp="$prefix" \
--disable-shared \
--enable-static \
--enable-formally-proven-code
/usr/bin/make -j1
/usr/bin/make check -j1
/usr/bin/make install

cd "$build/flint"
CC=/usr/local/bin/gcc CFLAGS="$common_cflags" LDFLAGS="$common_ldflags" \
"$inputs/flint-3.6.0/configure" \
--build=x86_64-pc-linux-gnu \
--host=x86_64-pc-linux-gnu \
--prefix="$prefix" \
--with-gmp="$prefix" \
--with-mpfr="$prefix" \
--disable-shared \
--enable-static \
--disable-assembly \
--disable-lto \
--enable-assert
/usr/bin/make -j1
/usr/bin/make check -j1
/usr/bin/make install

cd "$workspace/proof/region/v1/arb/evaluator"
/usr/local/bin/gcc \
-O2 -g0 -fno-ident -fno-fast-math -ffp-contract=off -fno-lto \
-march=x86-64 -mtune=generic \
-ffile-prefix-map=/build=. -fdebug-prefix-map=/build=. \
-std=c17 -Wall -Wextra -Werror -pedantic \
-I. -I"$prefix/include" \
main.c wire.c hash.c interval.c region.c "$inputs/formula.generated.c" \
-static -Wl,--build-id=none -fno-lto \
"$prefix/lib/libflint.a" "$prefix/lib/libmpfr.a" "$prefix/lib/libgmp.a" \
-lm -lpthread \
-o "$build/arb-evaluator-v1"

if ! /usr/bin/readelf -l "$build/arb-evaluator-v1" > "$build/program-headers"; then
printf '%s\n' 'cannot inspect evaluator program headers' >&2
exit 70
fi
if /usr/bin/grep -q INTERP "$build/program-headers"; then
printf '%s\n' 'evaluator unexpectedly contains PT_INTERP' >&2
exit 70
else
grep_status=$?
if [ "$grep_status" -ne 1 ]; then
printf '%s\n' 'cannot search evaluator program headers' >&2
exit 70
fi
fi
if ! /usr/bin/readelf -d "$build/arb-evaluator-v1" > "$build/dynamic-section"; then
printf '%s\n' 'cannot inspect evaluator dynamic section' >&2
exit 70
fi
if /usr/bin/grep -q NEEDED "$build/dynamic-section"; then
printf '%s\n' 'evaluator unexpectedly contains DT_NEEDED' >&2
exit 70
else
grep_status=$?
if [ "$grep_status" -ne 1 ]; then
printf '%s\n' 'cannot search evaluator dynamic section' >&2
exit 70
fi
fi

/usr/bin/sha256sum "$build/arb-evaluator-v1"
Loading
Loading