From 3f23a7669865bb21d5e3e49a03d018b3a92ec8c1 Mon Sep 17 00:00:00 2001 From: Dotta Date: Thu, 1 Oct 2026 23:47:38 -0500 Subject: [PATCH] ci(runner): add exact snapshot pool comparison Measure four retained B9 snapshots with process-start pool4/16 ABBA, full sealed-output integrity and bounded owned cleanup. Keep diagnostic evidence distinct from native startup qualification. Co-Authored-By: Paperclip --- .github/workflows/docker-runner-check.yml | 77 +++++++++- scripts/ci/pi-intel/snapshot-pool-fixture.mjs | 120 +++++++++++++++ .../pi-intel/snapshot-pool-fixture.test.mjs | 63 ++++++++ scripts/ci/pi-intel/snapshot-pool-inputs.json | 77 ++++++++++ scripts/ci/pi-intel/snapshot_pool.py | 139 ++++++++++++++++++ scripts/ci/pi-intel/test_snapshot_pool.py | 59 ++++++++ 6 files changed, 532 insertions(+), 3 deletions(-) create mode 100644 scripts/ci/pi-intel/snapshot-pool-fixture.mjs create mode 100644 scripts/ci/pi-intel/snapshot-pool-fixture.test.mjs create mode 100644 scripts/ci/pi-intel/snapshot-pool-inputs.json create mode 100644 scripts/ci/pi-intel/snapshot_pool.py create mode 100644 scripts/ci/pi-intel/test_snapshot_pool.py diff --git a/.github/workflows/docker-runner-check.yml b/.github/workflows/docker-runner-check.yml index 58f7a86fcfc..fa5e9e74e41 100644 --- a/.github/workflows/docker-runner-check.yml +++ b/.github/workflows/docker-runner-check.yml @@ -31,6 +31,10 @@ on: description: "Verify frozen Pi 1.0 closed startup and SDK contracts on native Intel macOS (no provider prompts)" type: boolean default: false + diagnose_pi_snapshot_pool: + description: "Measure exact retained B9 snapshots in four process-start pool4/16 ABBA children (diagnostic only)" + type: boolean + default: false diagnose_pi_startup: description: "Instrument one retained B9 profile12 native Intel startup with unchanged deadlines (diagnostic only, no provider prompts)" type: boolean @@ -70,7 +74,7 @@ permissions: {} concurrency: # Different immutable manual sources retain independent evidence; the same # source/mode still supersedes itself. Ordinary PR grouping is unchanged. - group: docker-runner-check-${{ github.event.pull_request.number || github.ref }}-${{ inputs.diagnose_pi_startup && 'pi-startup-diagnostic' || inputs.verify_pi_intel && 'pi-native-intel' || inputs.diagnose_ajv_pack && 'ajv-diagnostic' || inputs.verify_runner && 'runner-verification' || inputs.source_e2e_support_only && 'source-e2e-support' || inputs.source_root_tests_only && 'source-root-tests' || inputs.verify_source && 'verification' || inputs.verify_public_install && 'public-install' || inputs.build_eval_viewer && 'viewer' || 'image' }}${{ github.event_name == 'workflow_dispatch' && inputs.expected_source_sha && format('-{0}', inputs.expected_source_sha) || '' }} + group: docker-runner-check-${{ github.event.pull_request.number || github.ref }}-${{ inputs.diagnose_pi_snapshot_pool && 'pi-snapshot-pool' || inputs.diagnose_pi_startup && 'pi-startup-diagnostic' || inputs.verify_pi_intel && 'pi-native-intel' || inputs.diagnose_ajv_pack && 'ajv-diagnostic' || inputs.verify_runner && 'runner-verification' || inputs.source_e2e_support_only && 'source-e2e-support' || inputs.source_root_tests_only && 'source-root-tests' || inputs.verify_source && 'verification' || inputs.verify_public_install && 'public-install' || inputs.build_eval_viewer && 'viewer' || 'image' }}${{ github.event_name == 'workflow_dispatch' && inputs.expected_source_sha && format('-{0}', inputs.expected_source_sha) || '' }} cancel-in-progress: true jobs: @@ -125,9 +129,10 @@ jobs: SOURCE_E2E_SUPPORT_ONLY: ${{ inputs.source_e2e_support_only }} IMAGE_MODE: ${{ inputs.publish_eval_image || inputs.verify_public_install || inputs.build_eval_viewer }} VERIFY_PI_INTEL: ${{ inputs.verify_pi_intel }} + DIAGNOSE_PI_SNAPSHOT_POOL: ${{ inputs.diagnose_pi_snapshot_pool }} DIAGNOSE_PI_STARTUP: ${{ inputs.diagnose_pi_startup }} DIAGNOSE_AJV: ${{ inputs.diagnose_ajv_pack }} - OTHER_MODE: ${{ inputs.publish_eval_image || inputs.verify_source || inputs.verify_public_install || inputs.build_eval_viewer || inputs.verify_pi_intel || inputs.diagnose_pi_startup || inputs.source_e2e_support_only }} + OTHER_MODE: ${{ inputs.publish_eval_image || inputs.verify_source || inputs.verify_public_install || inputs.build_eval_viewer || inputs.verify_pi_intel || inputs.diagnose_pi_startup || inputs.diagnose_pi_snapshot_pool || inputs.source_e2e_support_only }} run: | set -euo pipefail test "$REPOSITORY" = paperclipai/paperclip @@ -171,6 +176,7 @@ jobs: test "$EXPECTED_LOCK_SHA256" = 5ae57d1ddd475691dac1f1cfbd4836e54f7da1956b47e6e705b218ae3070ae2e fi if [ "$VERIFY_PI_INTEL" = true ]; then + test "$DIAGNOSE_PI_SNAPSHOT_POOL" != true test "$DIAGNOSE_PI_STARTUP" != true test "$VERIFY_RUNNER" != true test "$VERIFY_SOURCE" != true @@ -184,6 +190,20 @@ jobs: test "$(gh api "repos/$REPOSITORY" --jq '.visibility')" = public fi if [ "$DIAGNOSE_PI_STARTUP" = true ]; then + test "$DIAGNOSE_PI_SNAPSHOT_POOL" != true + test "$VERIFY_PI_INTEL" != true + test "$VERIFY_RUNNER" != true + test "$VERIFY_SOURCE" != true + test "$SOURCE_ROOT_TESTS_ONLY" != true + test "$SOURCE_E2E_SUPPORT_ONLY" != true + test "$DIAGNOSE_AJV" != true + test "$IMAGE_MODE" != true + test "$EXPECTED_SOURCE_SHA" = b9e5d6ecdb05ab7244c90976e07c950f8d09b15b + test "$EXPECTED_LOCK_SHA256" = 38338a6867358440c5ab5993eaeb85fb501bc7df65d24acf52fbd63c880ee4ba + test "$(gh api "repos/$REPOSITORY" --jq '.visibility')" = public + fi + if [ "$DIAGNOSE_PI_SNAPSHOT_POOL" = true ]; then + test "$DIAGNOSE_PI_STARTUP" != true test "$VERIFY_PI_INTEL" != true test "$VERIFY_RUNNER" != true test "$VERIFY_SOURCE" != true @@ -307,6 +327,57 @@ jobs: retention-days: 7 if-no-files-found: error + manual_pi_snapshot_pool: + name: Retained B9 native Intel snapshot pool ABBA (not qualification) + if: github.event_name == 'workflow_dispatch' && inputs.diagnose_pi_snapshot_pool + needs: authorize_manual + runs-on: macos-15-intel + timeout-minutes: 25 + permissions: + contents: read + actions: read + steps: + - name: Checkout trusted diagnostic helpers only + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.workflow_sha }} + path: trusted-ci + persist-credentials: false + - name: Download exact failed qualification artifacts + timeout-minutes: 5 + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + gh api repos/paperclipai/paperclip/actions/artifacts/11208570718/zip \ + > "$RUNNER_TEMP/pi-startup-36959948724.zip" + printf '%s %s\n' b82cf6c843006781e2e6d5f0a06e0ff39497ffc457b94a511f8bdda66628aa43 \ + "$RUNNER_TEMP/pi-startup-36959948724.zip" | shasum -a 256 --check + - name: Measure four exact snapshots with pool size fixed before each process starts + timeout-minutes: 18 + run: | + set -euo pipefail + python3 -B trusted-ci/scripts/ci/pi-intel/snapshot_pool.py \ + --archive "$RUNNER_TEMP/pi-startup-36959948724.zip" \ + --output "$GITHUB_WORKSPACE/pi-snapshot-pool-evidence" + - name: Admit complete diagnostic evidence within the storage bound + if: always() + id: diagnostic_evidence + timeout-minutes: 2 + run: | + python3 -B trusted-ci/scripts/ci/pi-intel/admit_diagnostic_evidence.py \ + --evidence "$GITHUB_WORKSPACE/pi-snapshot-pool-evidence" \ + --github-output "$GITHUB_OUTPUT" + - name: Retain original identities, four snapshot measurements and cleanup + if: always() && steps.diagnostic_evidence.outputs.admitted == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: pi-snapshot-pool-${{ github.run_id }} + include-hidden-files: true + path: pi-snapshot-pool-evidence/ + retention-days: 7 + if-no-files-found: error + manual_runner_verify: name: Full offline Runner verification on GitHub-hosted Ubuntu if: github.event_name == 'workflow_dispatch' && inputs.verify_runner @@ -737,7 +808,7 @@ jobs: manual_image: name: Build and verify on EC2 - if: github.event_name == 'workflow_dispatch' && !inputs.verify_runner && !inputs.verify_source && !inputs.diagnose_ajv_pack && !inputs.verify_pi_intel && !inputs.diagnose_pi_startup && !inputs.source_e2e_support_only + if: github.event_name == 'workflow_dispatch' && !inputs.verify_runner && !inputs.verify_source && !inputs.diagnose_ajv_pack && !inputs.verify_pi_intel && !inputs.diagnose_pi_startup && !inputs.diagnose_pi_snapshot_pool && !inputs.source_e2e_support_only needs: authorize_manual runs-on: runs-on/fleet=paperclip-public-pr-x64/env=public-ci timeout-minutes: 90 diff --git a/scripts/ci/pi-intel/snapshot-pool-fixture.mjs b/scripts/ci/pi-intel/snapshot-pool-fixture.mjs new file mode 100644 index 00000000000..f7e9beffca2 --- /dev/null +++ b/scripts/ci/pi-intel/snapshot-pool-fixture.mjs @@ -0,0 +1,120 @@ +// Diagnostic only: import the exact built verifier, never execute its snapshot. +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import { createHash } from 'node:crypto'; +import { join, relative, resolve, dirname } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const sha = bytes => createHash('sha256').update(bytes).digest('hex'); +export function validateEnvironment(env, pool) { + assert.ok(['4', '16'].includes(pool)); + assert.equal(env.UV_THREADPOOL_SIZE, pool); + const expected = ['HOME', 'LANG', 'PATH', 'TMPDIR', 'UV_THREADPOOL_SIZE']; + // macOS adds this scalar even to a replaced OS process environment. Admit + // only the current UID with the default encoding; never filter unknown keys. + if (Object.hasOwn(env, '__CF_USER_TEXT_ENCODING')) { + const match = /^0x([0-9a-f]+):0x0:0x0$/i.exec(env.__CF_USER_TEXT_ENCODING); + assert.ok(match); assert.equal(Number.parseInt(match[1], 16), process.getuid()); + expected.push('__CF_USER_TEXT_ENCODING'); + } + assert.deepEqual(Object.keys(env).sort(), expected.sort()); +} +export function verifySealedSnapshot(value, entries, temporaryRoot) { + const snapshot = value.snapshot; + assert.equal(snapshot.executable, null); + assert.equal(snapshot.roots.length, 1); + const root = snapshot.roots[0]; + assert.equal(dirname(dirname(root)), temporaryRoot); + assert.equal(fs.realpathSync(root), root); + const expected = new Map(entries.map(e => [e.path, { sha256: e.sha256, mode: e.executable ? 0o500 : 0o400, size: e.size }])); + const expectedDirectories = new Set(['']); + for (const entry of entries) { + const parts = entry.path.split('/'); + for (let n = 1; n < parts.length; n++) expectedDirectories.add(parts.slice(0, n).join('/')); + } + for (const name of ['.paperclip-native-entry.cjs', '.paperclip-native-module-guard.cjs']) { + expected.set(name, { sha256: snapshot.digests[join(root, name)], mode: 0o400 }); + } + assert.equal(Object.keys(snapshot.digests).length, expected.size); + const seen = [], seenDirectories = []; + function walk(directory) { + const ds = fs.lstatSync(directory); + assert.ok(ds.isDirectory() && !ds.isSymbolicLink()); + assert.equal(ds.mode & 0o777, 0o500); + seenDirectories.push(relative(root, directory)); + for (const name of fs.readdirSync(directory).sort()) { + const path = join(directory, name), st = fs.lstatSync(path); + assert.ok(!st.isSymbolicLink()); + if (st.isDirectory()) { walk(path); continue; } + const key = relative(root, path), entry = expected.get(key); + assert.ok(entry, `Unexpected snapshot member: ${key}`); + assert.ok(st.isFile()); assert.equal(st.nlink, 1); + assert.equal(st.mode & 0o777, entry.mode); + if (entry.size !== undefined) assert.equal(st.size, entry.size); + assert.equal(snapshot.digests[path], entry.sha256); + assert.equal(sha(fs.readFileSync(path)), entry.sha256); + seen.push(key); + } + } + walk(root); + assert.deepEqual(seen.sort(), [...expected.keys()].sort()); + assert.deepEqual(seenDirectories.sort(), [...expectedDirectories].sort()); + const privateRoot = dirname(root); + assert.deepEqual(fs.readdirSync(privateRoot).sort(), ['distribution', 'manifest.json']); + const manifestStat = fs.lstatSync(snapshot.handoff.path); + assert.equal(snapshot.handoff.path, join(privateRoot, 'manifest.json')); + assert.ok(manifestStat.isFile()); assert.equal(manifestStat.nlink, 1); + assert.equal(manifestStat.mode & 0o777, 0o400); + const handoff = fs.readFileSync(snapshot.handoff.path); + assert.equal(sha(handoff), snapshot.handoff.digest); + assert.deepEqual(JSON.parse(handoff), { roots: [root], executable: null, digests: snapshot.digests }); + assert.equal(sha(value.bootstrap), expected.get('.paperclip-native-entry.cjs').sha256); + const fd = fs.fstatSync(value.commandDirectory.fd), named = fs.lstatSync(root); + assert.equal(fd.dev, named.dev); assert.equal(fd.ino, named.ino); + return { files: seen.length, bytes: entries.reduce((sum, e) => sum + e.size, 0), handoffVerified: true, descriptorIdentityVerified: true }; +} +export async function run(pack, pin, pool, report) { + validateEnvironment(process.env, pool); + assert.equal(process.platform, 'darwin'); assert.equal(process.arch, 'x64'); + assert.equal(process.version, 'v24.21.0'); + const tmp = fs.realpathSync(process.env.TMPDIR); + assert.deepEqual(fs.readdirSync(tmp), []); + const tmpIdentity = fs.lstatSync(tmp); + assert.equal(tmpIdentity.mode & 0o777, 0o700); + const modulePath = join(pack, pin.modulePath); + assert.equal(sha(fs.readFileSync(modulePath)), pin.moduleSha256); + assert.equal(sha(fs.readFileSync(join(pack, pin.closureManifestPath))), pin.closureManifestSha256); + const native = await import(pathToFileURL(modulePath).href); + const input = { distributionRoot: join(pack, pin.distributionPath), manifestPath: join(pack, pin.closureManifestPath), expectedClosureSha256: pin.closureDigest.replace(/^sha256:/, ''), executable: 'node/bin/node', entrypoint: 'pi-entry.cjs', fixedArguments: [] }; + const proof = { schema: 'paperclip.snapshot-pool-copy/v1', isQualification: false, poolRequestedAtProcessStart: Number(pool), actualThreadCountMeasured: false, moduleSha256: pin.moduleSha256, admittedEnvironmentKeys: Object.keys(process.env).sort(), osAddedTextEncoding: process.env.__CF_USER_TEXT_ENCODING ?? null, providerCalls: 0, vendorProcessesStarted: 0, snapshotClosed: false, commandDirectoryClosed: false }; + let snapshot; + try { + const entries = await native.readNativeAcpxDistributionEntries(input); + assert.equal(entries.length, pin.entries); + assert.equal(entries.reduce((sum, e) => sum + e.size, 0), pin.distributionBytes); + const start = process.hrtime.bigint(); + snapshot = await native.createNativeAcpxDistributionSnapshot(input, entries); + proof.snapshotMilliseconds = Number(process.hrtime.bigint() - start) / 1e6; + // Deliberately outside the timed routine; this extra verification is identical in all four children. + proof.sealedOutput = verifySealedSnapshot(snapshot, entries, tmp); + proof.status = 'snapshot_verified_not_executed'; + } finally { + const errors = []; + if (snapshot) { + try { await snapshot.commandDirectory.close(); proof.commandDirectoryClosed = true; } catch (error) { errors.push(error); } + try { await snapshot.snapshot.close(); proof.snapshotClosed = true; } catch (error) { errors.push(error); } + } + try { + const current = fs.lstatSync(tmp); + assert.equal(current.dev, tmpIdentity.dev); assert.equal(current.ino, tmpIdentity.ino); + assert.deepEqual(fs.readdirSync(tmp), []); proof.temporaryRootEmpty = true; + } catch (error) { errors.push(error); } + proof.cleanupErrors = errors.map(error => String(error)); + fs.writeFileSync(report, JSON.stringify(proof, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); + if (errors.length) throw new AggregateError(errors, 'Snapshot cleanup incomplete'); + } +} +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const [pack, pinPath, pool, report] = process.argv.slice(2); + await run(pack, JSON.parse(fs.readFileSync(pinPath)), pool, report); +} diff --git a/scripts/ci/pi-intel/snapshot-pool-fixture.test.mjs b/scripts/ci/pi-intel/snapshot-pool-fixture.test.mjs new file mode 100644 index 00000000000..094a0afca42 --- /dev/null +++ b/scripts/ci/pi-intel/snapshot-pool-fixture.test.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import * as fs from 'node:fs'; +import { createHash } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { validateEnvironment, verifySealedSnapshot } from './snapshot-pool-fixture.mjs'; + +const modulePath = process.env.PI_POOL_TEST_MODULE; +assert.ok(modulePath, 'Explicit retained built-module path is required for this calibration'); +assert.equal(createHash('sha256').update(fs.readFileSync(modulePath)).digest('hex'), '2c321e2a6b356bdd92e19493ee1d848436bdc895e5aa98c4190a0d8658df15df'); +const native = await import(pathToFileURL(modulePath).href); +const sha = bytes => createHash('sha256').update(bytes).digest('hex'); + +test('environment rejects ambient credentials, mismatched or unsupported pools', () => { + const good = { HOME: '/home', LANG: 'C', PATH: '/bin', TMPDIR: '/tmp', UV_THREADPOOL_SIZE: '4' }; + validateEnvironment(good, '4'); + assert.throws(() => validateEnvironment({ ...good, OPENROUTER_API_KEY: 'dummy' }, '4')); + assert.throws(() => validateEnvironment(good, '16')); + assert.throws(() => validateEnvironment({ ...good, UV_THREADPOOL_SIZE: '8' }, '8')); + validateEnvironment({ ...good, __CF_USER_TEXT_ENCODING: `0x${process.getuid().toString(16)}:0x0:0x0` }, '4'); + assert.throws(() => validateEnvironment({ ...good, __CF_USER_TEXT_ENCODING: `0x${(process.getuid() + 1).toString(16)}:0x0:0x0` }, '4')); + assert.throws(() => validateEnvironment({ ...good, __CF_USER_TEXT_ENCODING: 'unknown' }, '4')); +}); + +for (const mutation of ['none', 'changed bytes', 'wrong mode', 'extra file', 'extra directory', 'symbolic link', 'hardlink', 'handoff drift']) { + test(`actual built snapshot calibration: ${mutation}`, async () => { + const source = fs.mkdtempSync(join(tmpdir(), 'pc-pool-calibration-')); + let value; + try { + const entries = [{ path: 'entry.cjs', sha256: sha('entry'), size: 5, executable: false }, { path: 'node', sha256: sha('node'), size: 4, executable: true }]; + fs.writeFileSync(join(source, 'entry.cjs'), 'entry', { mode: 0o600 }); + fs.writeFileSync(join(source, 'node'), 'node', { mode: 0o700 }); + const manifestPath = join(source, 'closure.json'); + fs.writeFileSync(manifestPath, JSON.stringify({ entries })); + const input = { distributionRoot: source, manifestPath, expectedClosureSha256: sha(JSON.stringify(entries)), executable: 'node', entrypoint: 'entry.cjs', fixedArguments: [] }; + value = await native.createNativeAcpxDistributionSnapshot(input, await native.readNativeAcpxDistributionEntries(input)); + const root = value.snapshot.roots[0], target = join(root, 'entry.cjs'); + if (mutation !== 'none') fs.chmodSync(root, 0o700); + if (mutation === 'changed bytes') { fs.chmodSync(target, 0o600); fs.writeFileSync(target, 'wrong'); fs.chmodSync(target, 0o400); } + if (mutation === 'wrong mode') fs.chmodSync(target, 0o600); + if (mutation === 'extra file') fs.writeFileSync(join(root, 'extra'), 'x', { mode: 0o400 }); + if (mutation === 'extra directory') fs.mkdirSync(join(root, 'extra'), { mode: 0o500 }); + if (mutation === 'symbolic link') { fs.unlinkSync(target); fs.symlinkSync(join(source, 'entry.cjs'), target); } + if (mutation === 'hardlink') fs.linkSync(target, join(source, 'linked')); + if (mutation === 'handoff drift') value.snapshot.handoff.digest = '0'.repeat(64); + if (mutation !== 'none') fs.chmodSync(root, 0o500); + if (mutation === 'none') assert.equal(verifySealedSnapshot(value, entries, fs.realpathSync(tmpdir())).files, 4); + else assert.throws(() => verifySealedSnapshot(value, entries, fs.realpathSync(tmpdir()))); + } finally { + if (value) { + await value.commandDirectory.close(); + // The extra empty directory is an intentionally foreign fixture node; + // make it removable without changing the production close function. + const extra = join(value.snapshot.roots[0], 'extra'); + if (fs.existsSync(extra) && fs.lstatSync(extra).isDirectory()) fs.chmodSync(extra, 0o700); + await value.snapshot.close(); + } + fs.rmSync(source, { recursive: true, force: true }); + } + }); +} diff --git a/scripts/ci/pi-intel/snapshot-pool-inputs.json b/scripts/ci/pi-intel/snapshot-pool-inputs.json new file mode 100644 index 00000000000..c4ab140f563 --- /dev/null +++ b/scripts/ci/pi-intel/snapshot-pool-inputs.json @@ -0,0 +1,77 @@ +{ + "schema": "paperclip.native-intel-snapshot-pool-input/v1", + "sourceRevision": "b9e5d6ecdb05ab7244c90976e07c950f8d09b15b", + "resolvedLockSha256": "38338a6867358440c5ab5993eaeb85fb501bc7df65d24acf52fbd63c880ee4ba", + "artifactRunId": "36959948724", + "artifactId": "11208570718", + "artifactWorkflowRevision": "9541eb18789bac35242eeea3e569b77fa90d1818", + "artifactZipBytes": 1076365959, + "artifactZipSha256": "b82cf6c843006781e2e6d5f0a06e0ff39497ffc457b94a511f8bdda66628aa43", + "selectedFiles": { + "receipt.json": { + "bytes": 32763, + "sha256": "47ef1f494c59c1249ac42f08308a2fb83edcb0759890960059cc367ebdf12bf0" + }, + "provider-pack.tar.gz": { + "bytes": 1029214229, + "sha256": "5a550004ca982c49a2d86b3196676f3ce1877b6655ec730d1971b4cec2ba547d" + }, + "provider-pack.json": { + "bytes": 3629, + "sha256": "db5b1d7d825a0533a6506755c6209ccc4d45776c3abbf6c87ff845d1d47e99b2" + }, + "pack-inventory.json": { + "bytes": 10633748, + "sha256": "172f0f4f2319f3716cca656cdeafd03b4f0db652def53101dfbf148850a20eaa" + }, + "paperclip-runnerd": { + "bytes": 32035568, + "sha256": "29d5b0fc2ae2a552b89a107e3777e2c8ee356ebdbb13a14ceab8865e1cea1d45" + }, + "source.tar": { + "bytes": 141742080, + "sha256": "b32d8e32639e6527804fe11bfa1aaefcefa87fca31e9155499e6b9a28f69dbd4" + }, + "source-input-inventory.json": { + "bytes": 1033702, + "sha256": "7c160bb1fc4d049378004d014e398d42dabf12e8a73ec9cdda7679113aaa6949" + }, + "resolved-pnpm-lock.yaml": { + "bytes": 607788, + "sha256": "38338a6867358440c5ab5993eaeb85fb501bc7df65d24acf52fbd63c880ee4ba" + } + }, + "originalSidecarSha256": "7462825f4b82bce8e2a69425eafe4ca8b2c8812df345269c82fb75aa21f3043c", + "originalPackDigest": "sha256:9cf4f88d9fcf63746f7716f773cb8d062544c19e0a78e111e60f659a3596b13f", + "daemonSha256": "29d5b0fc2ae2a552b89a107e3777e2c8ee356ebdbb13a14ceab8865e1cea1d45", + "nodeSha256": "7abcf39bd37ab251015337ff75304d7555f0d8e88c6e0fbf04bce8ce34636f49", + "testPath": "packages/paperclip-runner/test/pi-closed-startup.test.mjs", + "testSha256": "8967cf9c8cd130b68bf9d64abef8cb8d352af00646e2288b341d8c6ae758b47a", + "observerSha256": "1fcf353beb90722f90401a7792a5853bf0807d964a1065e3f55b76a63bc4b4cc", + "profileDigest": "sha256:47306e6d2a9b59e8f9189f725ebb7a0a7f91826044d1739e1a35ab31f228ba1f", + "closureDigest": "sha256:03351f4a250a8db0e79411a9079b43a0ff05f72a2aff41fae17f1fc2de24bd41", + "model": "openrouter/deepseek/deepseek-v4-flash-0731", + "originalFailure": "Original 30s session.open timeout; settled35032ms; runner exit0 and owned cleanup verified;48SDK contracts passed; fresh Rust daemon and complete pack passed.", + "providerCalls": 0, + "timeoutChanges": false, + "archiveBytesMaximum": 268435456, + "retentionDays": 7, + "modulePath": "dist/drivers/acpx/native-distribution-integrity.js", + "moduleSha256": "2c321e2a6b356bdd92e19493ee1d848436bdc895e5aa98c4190a0d8658df15df", + "closureManifestPath": "provider-assets/pi/darwin-x64/native-closure.json", + "closureManifestSha256": "b54c812aa78e072bf9badd0e7e3bf491a948ef5ecef827c40de88be48e2e023b", + "distributionPath": "provider-assets/pi/darwin-x64/runtime", + "pools": [ + 4, + 16, + 16, + 4 + ], + "maximumCopies": 4, + "experimentDeadlineSeconds": 600, + "perCopyDeadlineSeconds": 90, + "cleanupReserveSeconds": 120, + "finalIntegrityReserveSeconds": 60, + "entries": 15671, + "distributionBytes": 538588650 +} diff --git a/scripts/ci/pi-intel/snapshot_pool.py b/scripts/ci/pi-intel/snapshot_pool.py new file mode 100644 index 00000000000..2fd0e6693bb --- /dev/null +++ b/scripts/ci/pi-intel/snapshot_pool.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Four exact-snapshot ABBA measurements; no provider, daemon or qualification.""" +import argparse,datetime,json,os,platform,shutil,signal,stat,subprocess,tempfile,time +from pathlib import Path +from source_guard import require,sha +from native_daemon_reuse import extract_selected +from closed_inventory import closed_tree +from startup_diagnostic import restore_pack,finalize_diagnostic +from diagnostic_lifecycle import DiagnosticChild,DiagnosticInspection +from owned_processes import OwnedProcesses,atomic_json +HERE=Path(__file__).resolve().parent +PIN=json.loads((HERE/'snapshot-pool-inputs.json').read_text()) + +def admit_copy(index,pool,remaining,cancelled,uncertain): + require(not cancelled and not uncertain,'Cancelled or uncertain experiment cannot launch another copy') + require(type(index) is int and 0<=index<4 and pool==[4,16,16,4][index],'Only the exact four-copy ABBA sequence is admitted') + require(remaining>=90+120+60,'Full copy, cleanup and final-integrity windows no longer fit') + +def child_environment(home,tmp,pool): + require(type(pool) is int and pool in (4,16),'Invalid process-start pool request') + return {'PATH':'/usr/bin:/bin:/usr/sbin:/sbin','HOME':str(home),'LANG':'en_US.UTF-8','TMPDIR':str(tmp),'UV_THREADPOOL_SIZE':str(pool)} + +def verify_report(path,pool,pin=PIN): + st=path.lstat();require(stat.S_ISREG(st.st_mode) and st.st_nlink==1 and st.st_size<=16384,'Unsafe copy receipt') + r=json.loads(path.read_text()) + require(r['status']=='snapshot_verified_not_executed' and r['isQualification'] is False and r['poolRequestedAtProcessStart']==pool and r['actualThreadCountMeasured'] is False,'Copy receipt identity/status mismatch') + require(r['moduleSha256']==pin['moduleSha256'] and r['providerCalls']==r['vendorProcessesStarted']==0,'Copy code/execution scope mismatch') + require(all(r[k] is True for k in ['snapshotClosed','commandDirectoryClosed','temporaryRootEmpty']) and r['cleanupErrors']==[],'Copy cleanup incomplete') + require(r['sealedOutput']=={'files':pin['entries']+2,'bytes':pin['distributionBytes'],'handoffVerified':True,'descriptorIdentityVerified':True},'Incomplete sealed snapshot verification') + require(type(r['snapshotMilliseconds']) in (int,float) and 0600: + proof['status']='comparison_failed_no_retry' + raise RuntimeError('Experiment exceeded its 600-second bound; cleanup completed') + if cancelled: + proof['status']='comparison_failed_no_retry' + raise InterruptedError(cancelled+'; owned cleanup completed') + try:assert_complete(proof) + except BaseException: + proof['status']='comparison_failed_no_retry';raise + finally:save() + +if __name__=='__main__': + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--archive',type=Path,required=True);p.add_argument('--output',type=Path,required=True) + raise SystemExit(execute(p.parse_args())) diff --git a/scripts/ci/pi-intel/test_snapshot_pool.py b/scripts/ci/pi-intel/test_snapshot_pool.py new file mode 100644 index 00000000000..f8614c0a5b7 --- /dev/null +++ b/scripts/ci/pi-intel/test_snapshot_pool.py @@ -0,0 +1,59 @@ +import copy,json,tempfile,unittest +from pathlib import Path +from unittest.mock import patch +from snapshot_pool import PIN,admit_copy,child_environment,verify_report,post_integrity,assert_complete +from diagnostic_lifecycle import DiagnosticChild + +class SnapshotPoolTests(unittest.TestCase): + def test_terminal_success_cannot_survive_failed_or_incomplete_finalization(self): + good={'status':'comparison_complete_not_qualification','cleanupUncertain':False,'scratchRemoved':True,'postRunIntegrity':{'complete':True,'passed':True,'checks':{'pack':True},'errors':{}}} + assert_complete(good) + for delta in [{'status':'diagnostic_failed'},{'cleanupUncertain':True},{'scratchRemoved':False},{'postRunIntegrity':{}},{'postRunIntegrity':{'complete':True,'passed':False,'checks':{'pack':False},'errors':{'pack':'changed'}}},{'postRunIntegrity':{'complete':True,'passed':True,'checks':{},'errors':{}}}]: + with self.subTest(delta=delta),self.assertRaises(RuntimeError):assert_complete(good|delta) + def test_exact_four_sequence_and_full_window(self): + for i,p in enumerate([4,16,16,4]):admit_copy(i,p,270,None,False) + for args in [(4,4,600,None,False),(0,16,600,None,False),(0,4,269.9,None,False),(0,4,600,'cancel',False),(0,4,600,None,True)]: + with self.assertRaises(RuntimeError):admit_copy(*args) + def test_only_explicit_noncredential_process_environment(self): + with patch.dict('os.environ',{'OPENROUTER_API_KEY':'must-not-propagate','UV_THREADPOOL_SIZE':'128'}): + e=child_environment('/private/home','/private/tmp',16) + self.assertEqual(e,{'HOME':'/private/home','TMPDIR':'/private/tmp','UV_THREADPOOL_SIZE':'16','LANG':'en_US.UTF-8','PATH':'/usr/bin:/bin:/usr/sbin:/sbin'}) + for bad in [True,0,8,128,'16']: + with self.assertRaises(RuntimeError):child_environment('/home','/tmp',bad) + def receipt(self): + return {'status':'snapshot_verified_not_executed','isQualification':False,'poolRequestedAtProcessStart':4,'actualThreadCountMeasured':False,'moduleSha256':PIN['moduleSha256'],'providerCalls':0,'vendorProcessesStarted':0,'snapshotClosed':True,'commandDirectoryClosed':True,'temporaryRootEmpty':True,'cleanupErrors':[],'sealedOutput':{'files':PIN['entries']+2,'bytes':PIN['distributionBytes'],'handoffVerified':True,'descriptorIdentityVerified':True},'snapshotMilliseconds':125.0} + def test_exact_receipt(self): + with tempfile.TemporaryDirectory() as d: + path=Path(d)/'receipt.json';r=self.receipt();path.write_text(json.dumps(r));self.assertEqual(verify_report(path,4),r) + def test_false_or_incomplete_measurements_rejected(self): + deltas=[{'poolRequestedAtProcessStart':16},{'moduleSha256':'0'*64},{'providerCalls':1},{'snapshotClosed':False},{'commandDirectoryClosed':False},{'temporaryRootEmpty':False},{'cleanupErrors':['error']},{'snapshotMilliseconds':float('nan')},{'snapshotMilliseconds':float('inf')},{'snapshotMilliseconds':0},{'sealedOutput':{}},{'status':'ok'}] + with tempfile.TemporaryDirectory() as d: + path=Path(d)/'receipt.json' + for delta in deltas: + with self.subTest(delta=delta): + path.write_text(json.dumps(self.receipt()|delta)) + with self.assertRaises(RuntimeError):verify_report(path,4) + def test_post_checks_continue_after_pack_failure(self): + calls=[];pin={'selectedFiles':{'one':{'sha256':'1'},'two':{'sha256':'2'}}} + def digest(path):calls.append(path.name);return path.name=='one' and '1' or 'wrong' + with patch('snapshot_pool.closed_tree',side_effect=RuntimeError('pack changed')),patch('snapshot_pool.sha',side_effect=digest):r=post_integrity(Path('/pack'),[],Path('/original'),pin) + self.assertEqual(calls,['one','two']);self.assertEqual(r['checks'],{'pack':False,'one':True,'two':False});self.assertFalse(r['passed']) + def test_before_launch_cancellation_never_calls_factory(self): + owner=type('Owner',(),{})();child=DiagnosticChild(owner);child.cancel('between copies') + with self.assertRaises(RuntimeError):child.execute(lambda:self.fail('cancelled spawn'),90) + self.assertFalse(child.attempted);self.assertFalse(child.uncertain) + def test_during_publication_cancellation_retires_owned_handle(self): + class Process: + pid=123;returncode=0 + def wait(self,timeout):return 0 + class Owner: + stops=0 + def observe(self,pid):child.cancel('during publication') + def stop(self,pid):self.stops+=1;return {'status':'stopped'} + def live(self):return [] + owner=Owner();child=DiagnosticChild(owner) + with self.assertRaises(RuntimeError):child.execute(Process,90) + self.assertTrue(child.retired);self.assertEqual(owner.stops,1) + with self.assertRaises(RuntimeError):child.execute(lambda:self.fail('second spawn'),90) + +if __name__=='__main__':unittest.main()