mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
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 <noreply@paperclip.ing>
This commit is contained in:
1 parent
2c5a21762e
commit
3f23a76698
6 files changed
+532
-3
No files matched your search
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 0<r['snapshotMilliseconds']<90000,'Invalid copy duration')
|
||||
return r
|
||||
|
||||
def post_integrity(pack,inventory,original,pin):
|
||||
checks={};errors={}
|
||||
actions={'pack':lambda:closed_tree(pack)==inventory}
|
||||
for name,row in pin['selectedFiles'].items():actions[name]=lambda name=name,row=row:sha(original/name)==row['sha256']
|
||||
for name,check in actions.items():
|
||||
try:require(check(),'Identity mismatch: '+name);checks[name]=True
|
||||
except BaseException as error:checks[name]=False;errors[name]=repr(error)
|
||||
return {'complete':True,'passed':not errors,'checks':checks,'errors':errors}
|
||||
|
||||
def assert_complete(proof):
|
||||
integrity=proof.get('postRunIntegrity',{})
|
||||
require(proof.get('status')=='comparison_complete_not_qualification' and proof.get('cleanupUncertain') is False and proof.get('scratchRemoved') is True and integrity.get('complete') is True and integrity.get('passed') is True and not integrity.get('errors') and integrity.get('checks') and all(v is True for v in integrity['checks'].values()),'Comparison finalization did not establish complete integrity and owned cleanup')
|
||||
|
||||
def execute(args):
|
||||
out=args.output.resolve();out.mkdir(mode=0o700,parents=True,exist_ok=False)
|
||||
scratch=Path(tempfile.mkdtemp(prefix='pc-snapshot-pool-',dir='/private/tmp'));scratch.chmod(0o700)
|
||||
initial=scratch.stat();identity=(initial.st_dev,initial.st_ino,initial.st_uid)
|
||||
proof={'schema':'paperclip.native-intel-snapshot-pool/v1','status':'preparing','sourceRevision':PIN['sourceRevision'],'runId':os.environ['GITHUB_RUN_ID'],'trustedWorkflowRevision':os.environ['GITHUB_WORKFLOW_SHA'],'startedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'isQualification':False,'providerCalls':0,'runtimePromptsSubmitted':0,'vendorProcessesStarted':0,'nativeRecompiled':False,'dependencyInstallExecuted':False,'sourceOrPackModified':False,'actualThreadCountMeasured':False,'poolBinding':'Explicit UV_THREADPOOL_SIZE in each Node child environment before OS process start','cacheLimitation':'Full archive admission reads all bytes before ABBA. Four sequential samples measure this host and warm-cache order only, not canonical cold startup or end-to-end qualification.','helpers':{p.name:sha(p) for p in HERE.iterdir() if p.is_file()},'copies':[],'cleanupUncertain':False,'scratchRemoved':False}
|
||||
active=None;cancelled=None;pack=None;inventory=None;original=None;experiment_started=None
|
||||
def save():atomic_json(out/'receipt.json',proof)
|
||||
def cancel(sig,_):
|
||||
nonlocal cancelled
|
||||
cancelled='signal '+str(sig)
|
||||
if active is not None:active.cancel(cancelled)
|
||||
signal.signal(signal.SIGTERM,cancel);signal.signal(signal.SIGINT,cancel)
|
||||
save()
|
||||
try:
|
||||
require(platform.system()=='Darwin' and platform.machine()=='x86_64','Native Intel required')
|
||||
env={'PATH':'/usr/bin:/bin:/usr/sbin:/sbin','LANG':'en_US.UTF-8'}
|
||||
for flag in ['sysctl.proc_translated','hw.optional.arm64']:
|
||||
r=subprocess.run(['/usr/sbin/sysctl','-in',flag],capture_output=True,text=True,env=env,timeout=10)
|
||||
require(r.stdout.strip() in ('','0'),'Rosetta/ARM rejected');proof[flag]={'value':r.stdout.strip(),'exitCode':r.returncode}
|
||||
hardware=subprocess.run(['/usr/sbin/sysctl','hw.machine','machdep.cpu.vendor','machdep.cpu.brand_string'],capture_output=True,text=True,env=env,timeout=10)
|
||||
require(hardware.returncode==0 and 'GenuineIntel' in hardware.stdout and 'x86_64' in hardware.stdout,'Intel identity missing');(out/'hardware.log').write_text(hardware.stdout)
|
||||
require(not cancelled,'Cancelled before artifact preparation')
|
||||
original=extract_selected(args.archive,scratch/'original-artifact',PIN)
|
||||
original_receipt=json.loads((original/'receipt.json').read_text())
|
||||
require(all(original_receipt[k]==PIN[v] for k,v in [('sourceRevision','sourceRevision'),('runId','artifactRunId'),('trustedWorkflowRevision','artifactWorkflowRevision')]),'Original source/workflow/run mismatch')
|
||||
require(original_receipt['status']=='failed_no_retry' and original_receipt['cleanupUncertain'] is False,'Original failure/cleanup provenance mismatch')
|
||||
refs=out/'original-reference';refs.mkdir(mode=0o700)
|
||||
for name in ['receipt.json','provider-pack.json','pack-inventory.json','source-input-inventory.json','resolved-pnpm-lock.yaml']:shutil.copy2(original/name,refs/name)
|
||||
atomic_json(out/'original-input-pins.json',PIN)
|
||||
inventory=json.loads((original/'pack-inventory.json').read_text());pack=restore_pack(original/'provider-pack.tar.gz',scratch/'unpacked',inventory)
|
||||
node=pack/'node_modules/node/bin/node'
|
||||
for path,digest in [(node,PIN['nodeSha256']),(pack/PIN['modulePath'],PIN['moduleSha256']),(pack/PIN['closureManifestPath'],PIN['closureManifestSha256'])]:require(sha(path)==digest,'Exact executable/module/closure mismatch')
|
||||
for name in ['snapshot-pool-fixture.mjs','snapshot-pool-inputs.json']:shutil.copy2(HERE/name,out/name)
|
||||
shutil.copy2(pack/PIN['modulePath'],out/'native-distribution-integrity.js')
|
||||
require(PIN['pools']==[4,16,16,4] and PIN['maximumCopies']==4 and PIN['experimentDeadlineSeconds']==600 and PIN['perCopyDeadlineSeconds']==90 and PIN['cleanupReserveSeconds']==120 and PIN['finalIntegrityReserveSeconds']==60,'Experiment bounds changed')
|
||||
experiment_started=time.monotonic();deadline=experiment_started+600
|
||||
proof.update(status='measuring',experimentStartedAt=datetime.datetime.now(datetime.timezone.utc).isoformat());save()
|
||||
for index,pool in enumerate(PIN['pools']):
|
||||
admit_copy(index,pool,deadline-time.monotonic(),cancelled,proof['cleanupUncertain'])
|
||||
copy_root=scratch/('copy-'+str(index));copy_root.mkdir(mode=0o700)
|
||||
home=copy_root/'home';home.mkdir(mode=0o700);tmp=copy_root/'tmp';tmp.mkdir(mode=0o700)
|
||||
report=out/('copy-'+str(index)+'.json');log=out/('copy-'+str(index)+'.log')
|
||||
owner=OwnedProcesses(out/('copy-'+str(index)+'-processes.json'),scratch,pack,pack/'dist/cli/acpx-runtime-sidecar.cjs')
|
||||
active=DiagnosticChild(owner);inspection=DiagnosticInspection(owner,active);owner.table=inspection.table;owner.argv=inspection.argv
|
||||
if cancelled:active.cancel(cancelled)
|
||||
row={'index':index,'pool':pool,'outerDeadlineSeconds':90,'startedAt':datetime.datetime.now(datetime.timezone.utc).isoformat()};proof['copies'].append(row);save()
|
||||
def spawn():
|
||||
# Recheck after publishing the new lifecycle; a cancellation before this
|
||||
# exact boundary cannot escape through the previous child's gate.
|
||||
if cancelled:active.cancel(cancelled);raise InterruptedError(cancelled)
|
||||
admit_copy(index,pool,deadline-time.monotonic(),cancelled,proof['cleanupUncertain'])
|
||||
return subprocess.Popen([str(node),str(HERE/'snapshot-pool-fixture.mjs'),str(pack),str(HERE/'snapshot-pool-inputs.json'),str(pool),str(report)],env=child_environment(home,tmp,pool),cwd=pack,stdout=output,stderr=output,start_new_session=True)
|
||||
with log.open('xb') as output:result=active.execute(spawn,90)
|
||||
row.update(exitCode=result,logSha256=sha(log),finishedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),shutdown=owner.stop_result)
|
||||
proof['cleanupUncertain']=active.uncertain;save()
|
||||
require(result==0,'Snapshot child failed; no later copy will launch')
|
||||
row['measurement']=verify_report(report,pool);row['reportSha256']=sha(report);save()
|
||||
require(not cancelled,'Experiment cancelled before completion')
|
||||
proof.update(status='comparison_complete_not_qualification',meansMilliseconds={str(p):sum(r['measurement']['snapshotMilliseconds'] for r in proof['copies'] if r['pool']==p)/2 for p in [4,16]})
|
||||
return 0
|
||||
except BaseException as error:
|
||||
proof.update(status='comparison_failed_no_retry',errorType=type(error).__name__,error=str(error));raise
|
||||
finally:
|
||||
def post():
|
||||
if pack is None:return {'complete':False,'passed':False,'reason':'pack preparation incomplete'}
|
||||
return post_integrity(pack,inventory,original,PIN)
|
||||
def retain():
|
||||
proof['finishedAt']=datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
if experiment_started is not None:proof['experimentThroughIntegritySeconds']=time.monotonic()-experiment_started
|
||||
def remove():
|
||||
st=scratch.lstat();require(stat.S_ISDIR(st.st_mode) and (st.st_dev,st.st_ino,st.st_uid)==identity,'Scratch identity changed')
|
||||
# A forcibly retired copy may leave sealed 0500 snapshot directories. Only
|
||||
# this owned scratch is made removable, after retirement and integrity audit.
|
||||
for root,dirs,_ in os.walk(scratch,followlinks=False):
|
||||
require(not Path(root).is_symlink(),'Scratch directory replaced by link');os.chmod(root,0o700,follow_symlinks=False)
|
||||
shutil.rmtree(scratch)
|
||||
try:
|
||||
finalize_diagnostic(proof,active,post,retain,remove)
|
||||
if experiment_started is not None:
|
||||
proof['experimentIncludingCleanupSeconds']=time.monotonic()-experiment_started
|
||||
if proof['experimentIncludingCleanupSeconds']>600:
|
||||
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()))
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user