Skip to content

Commit cf94179

Browse files
author
Odysseus
committed
Temporary hosted reference pool measurement; correct classification and product SDK identity
1 parent 951dd3b commit cf94179

12 files changed

Lines changed: 556 additions & 10 deletions

File tree

‎.diagnostic/SHA256SUMS‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
a862b173a5ee8244c341816ccac26d3a08c739b8ea96cfbec0fedf71e48ef3e0 .diagnostic/fixture_admit.py
2+
0ef0d3c375af704c0404043d87e72226e3f280605efc3ccff9c40654e3593a2c .diagnostic/hosted.py
3+
f2135159332a1eaea9c396a3eb66127675c351b7c194e767bcd8d12e2111d65b .diagnostic/overlay.json
4+
499c4d1fa6700843d3115e8917c52d1cdbf4a9faa1ea7953368f1d9b8c2b4b87 .diagnostic/recorder.py
5+
e296ab610dd897920c6bf68d7d22c7079258bd0aab629e4ad6b4bf1ce56fdbcb .diagnostic/sample.sh
6+
47157466996f2a34b304bfce718c99a9ba698513f05fb8b51f2335e50b28b699 .diagnostic/source-inventory.json
7+
2b5daf239c3ce961928cb13ffc2f79f4dec4ba6e308faecbcbb4d742f869d5f4 .github/workflows/diag-3129.yml
8+
d62e73496e16e6703d6bd4e4665f103bb5772dbc4d1a7914e493e1446257f991 packages/ui-sdk/src/server/native-reference-pool-helper.ts
9+
02a48254f5b839c9e9ab40178c6cf863a89e92461749954c2944d16a2365d5d6 packages/ui-sdk/src/server/native-reference-pool.ts
10+
7ee8d9836b5c71604716314669624df928481b73bba067a58793b0406b12ca8c scripts/native-proof/reference-pool-fixture.py
11+
ebc8262cefc761c8dbb9434b93f5ef8ef0b153a42e0b884845ed306ab5e1c42a scripts/native-proof/reference-pool.native.ts

‎.diagnostic/fixture_admit.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""Derived fixture prerequisites only; no raw host/process/environment dumps."""
2+
mi = pathlib.Path('/proc/self/mountinfo').read_text().splitlines()
3+
def mounted_at(path):
4+
rows = [row for row in mi if row.split()[4] == path]
5+
assert len(rows) == 1, 'DIAGNOSTIC_MOUNT_IDENTITY'
6+
left, right = rows[0].split(' - ')
7+
assert right.split()[0] == 'btrfs', 'DIAGNOSTIC_NOT_BTRFS'
8+
assert {'nosuid', 'nodev'}.issubset(set(left.split()[5].split(','))), 'DIAGNOSTIC_MOUNT_FLAGS'
9+
return right.split()[2].split(',')
10+
assert os.uname().release == '7.0.0-1017-azure', 'DIAGNOSTIC_ACTUAL_KERNEL'
11+
assert os.getuid() == 0 and os.getgid() == 0, 'DIAGNOSTIC_FIXTURE_UID'
12+
pool_options, store_options = mounted_at('/reference-pool'), mounted_at('/brain-fixture')
13+
assert 'discard=async' in pool_options, 'DIAGNOSTIC_POOL_DISCARD'
14+
assert not any(value.startswith('discard') for value in store_options), 'DIAGNOSTIC_STORE_DISCARD'
15+
status = pathlib.Path('/proc/self/status').read_text()
16+
derived = {key: value.strip() for key, value in (row.split(':',1) for row in status.splitlines() if ':' in row)}
17+
cap = int(derived['CapEff'],16)
18+
expected = sum(1 << bit for bit in [21, 27, 1, 3, 0, 5, 7, 6, 31])
19+
assert all(int(derived[key],16)==expected for key in ['CapEff','CapPrm','CapBnd']), 'DIAGNOSTIC_CAPS'
20+
assert int(derived['CapInh'],16)==int(derived['CapAmb'],16)==0, 'DIAGNOSTIC_AMBIENT_CAPS'
21+
assert derived['NoNewPrivs']=='1' and derived['Seccomp']=='2', 'DIAGNOSTIC_RESTRICTIONS'
22+
profile = pathlib.Path('/proc/self/attr/current').read_text().strip()
23+
assert profile == 'brain-kit-native-proof (enforce)', 'DIAGNOSTIC_APPARMOR'
24+
interfaces = [row.split(':')[0].strip() for row in pathlib.Path('/proc/net/dev').read_text().splitlines()[2:]]
25+
assert interfaces == ['lo'], 'DIAGNOSTIC_NETWORK'
26+
fsid = subprocess.check_output(['btrfs', 'filesystem', 'show', '--raw', str(POOL)]).decode().split('uuid: ')[1].split()[0]
27+
sysbase = pathlib.Path('/sys/fs/btrfs') / fsid
28+
assert (sysbase/'qgroups/mode').read_text().strip() == 'squota', 'DIAGNOSTIC_SQUOTA'
29+
assert (sysbase/'qgroups/inconsistent').read_text().strip() == '0', 'DIAGNOSTIC_QUOTA_INCONSISTENT'
30+
assert (sysbase/'quota_override').read_text().strip() == '0', 'DIAGNOSTIC_QUOTA_OVERRIDE'
31+
features = sorted(item.name for item in (sysbase/'features').iterdir())
32+
assert 'simple_quota' in features, 'DIAGNOSTIC_SIMPLE_QUOTA'
33+
record('diagnostic-admitted', kernel=os.uname().release, disposition='SAME_KERNEL_MEASUREMENT',
34+
uid=os.getuid(), gid=os.getgid(), capEff=hex(cap), apparmor=profile, networkLoopbackOnly=True,
35+
restrictions={key:derived[key] for key in ['CapInh','CapPrm','CapEff','CapBnd','CapAmb','NoNewPrivs','Seccomp']},
36+
poolOptions=pool_options, storeOptions=store_options, features=features, tracefs='TRACEFS_NOT_REQUESTED')

‎.diagnostic/hosted.py‎

Lines changed: 317 additions & 0 deletions
Large diffs are not rendered by default.

‎.diagnostic/overlay.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"files": [
3+
".diagnostic/SHA256SUMS",
4+
".diagnostic/fixture_admit.py",
5+
".diagnostic/hosted.py",
6+
".diagnostic/overlay.json",
7+
".diagnostic/recorder.py",
8+
".diagnostic/sample.sh",
9+
".diagnostic/source-inventory.json",
10+
".github/workflows/diag-3129.yml",
11+
"packages/ui-sdk/src/server/native-reference-pool-helper.ts",
12+
"packages/ui-sdk/src/server/native-reference-pool.ts",
13+
"scripts/native-proof/reference-pool-fixture.py",
14+
"scripts/native-proof/reference-pool.native.ts"
15+
],
16+
"matrixJobs": 4,
17+
"maximumFullScripts": 16,
18+
"maximumPerJob": 4,
19+
"temporaryBranch": "diag/3129-hosted-reference-pool"
20+
}

‎.diagnostic/recorder.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""Temporary compact observation measurement; no writes between paired reads."""
2+
import fcntl as _trace_fcntl
3+
import json, os, sys, time, uuid
4+
5+
TRACE_LIMIT = 8 * 1024 * 1024
6+
ARM = "/proof/diagnostic-arm.json"
7+
TRACE = "/proof/diagnostic-trace"
8+
9+
def differences(before, after, path=""):
10+
if isinstance(before, dict) and isinstance(after, dict):
11+
result = []
12+
for key in sorted(set(before) | set(after)):
13+
child = path+"."+key if path else key
14+
if key not in before or key not in after:
15+
result.append({"path": child, "before_present": key in before, "after_present": key in after,
16+
"before": before.get(key), "after": after.get(key)})
17+
else:
18+
result.extend(differences(before[key], after[key], child))
19+
return result
20+
return [] if before == after else [{"path": path, "before": before, "after": after}]
21+
22+
class Recorder:
23+
def __init__(self, original, context):
24+
self.original, self.context = original, context
25+
self.items, self.sync_start, self.sync_done = [], None, None
26+
self.arm = None
27+
if os.path.exists(ARM):
28+
with open(ARM, encoding="utf8") as source:
29+
value = json.load(source)
30+
if context and value["worktreeId"] == context.get("from"):
31+
self.arm = value
32+
def snapshot(self, *args):
33+
began = {"wall_ns": time.time_ns(), "mono_ns": time.monotonic_ns()}
34+
value = self.original(*args)
35+
ended = {"wall_ns": time.time_ns(), "mono_ns": time.monotonic_ns()}
36+
if len(self.items) >= 8:
37+
raise RuntimeError("DIAGNOSTIC_SNAPSHOT_BOUND")
38+
self.items.append({"began": began, "ended": ended, "value": value})
39+
return value
40+
def finish(self, ns):
41+
stable = self.items[-2]["value"] == self.items[-1]["value"] if len(self.items) >= 2 else None
42+
row = {"version": 1, "observation_id": uuid.uuid4().hex,
43+
"synthetic": ns.get("_diag_synthetic", False), "armed": self.arm is not None,
44+
"operation": self.context or {"operation": None, "id": None, "from": None},
45+
"reads": ns.get("reads"), "stable": stable, "fsid": ns["fsid"],
46+
"sync_start_ns": self.sync_start, "sync_done_ns": self.sync_done,
47+
"finished_mono_ns": time.monotonic_ns(), "finished_wall_ns": time.time_ns(),
48+
"exception": str(sys.exc_info()[1]) if sys.exc_info()[0] else None}
49+
# Stable two-read unarmed observations are summaries. Every unequal pair and every armed pair is retained.
50+
if self.arm is not None or not stable or ns.get("reads", 0) > 2:
51+
pairs = []
52+
for offset in range(0, len(self.items)-1, 2):
53+
a, b = self.items[offset:offset+2]
54+
delta = differences(a["value"], b["value"])
55+
pairs.append({"index": offset//2+1, "first_began": a["began"], "first_ended": a["ended"],
56+
"second_began": b["began"], "second_ended": b["ended"],
57+
"equal": not delta, "first_difference": delta[0]["path"] if delta else None,
58+
"differences": delta, "first_dropping": a["value"]["dropping"],
59+
"second_dropping": b["value"]["dropping"],
60+
"first_subvolumes_count": len(a["value"]["subvolumes"]),
61+
"second_subvolumes_count": len(b["value"]["subvolumes"])})
62+
row["pairs"] = pairs
63+
if self.arm is not None:
64+
row.update(arm=self.arm, pool=ns["pool"], helper_pid=os.getpid())
65+
data = (json.dumps(row, sort_keys=True, separators=(",", ":"))+"\n").encode()
66+
os.makedirs(TRACE, mode=0o755, exist_ok=True)
67+
fd = os.open(os.path.join(TRACE, "observations.jsonl"), os.O_WRONLY|os.O_CREAT|os.O_APPEND|os.O_NOFOLLOW, 0o644)
68+
try:
69+
_trace_fcntl.flock(fd, _trace_fcntl.LOCK_EX)
70+
if os.fstat(fd).st_size+len(data) > TRACE_LIMIT:
71+
raise RuntimeError("DIAGNOSTIC_TRACE_BUDGET")
72+
remaining = memoryview(data)
73+
while remaining:
74+
written = os.write(fd, remaining)
75+
if written <= 0:
76+
raise RuntimeError("DIAGNOSTIC_SHORT_WRITE")
77+
remaining = remaining[written:]
78+
os.fchmod(fd, 0o644); os.chmod(TRACE, 0o755)
79+
os.fsync(fd)
80+
finally:
81+
os.close(fd)
82+
83+
_diag_context = json.loads(sys.argv[5]) if len(sys.argv) > 5 else None
84+
_diag = Recorder(snapshot, _diag_context)
85+
snapshot = _diag.snapshot

‎.diagnostic/sample.sh‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
[ "${DIAG_SAMPLES:-}" = 4 ] || { echo 'SETUP_MISMATCH sample_bound' >&2; exit 1; }
4+
# Fixed maximum; every non-clean outcome stops this shard. Independent shards finish separately.
5+
for index in 1 2 3 4; do
6+
python3 .diagnostic/hosted.py invoke "$index" || exit "$?"
7+
done

‎.diagnostic/source-inventory.json‎

Lines changed: 1 addition & 0 deletions
Large diffs are not rendered by default.

‎.github/workflows/diag-3129.yml‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
name: Temporary reference-pool measurements 3129 (never merge)
2+
on:
3+
push:
4+
branches: [diag/3129-hosted-reference-pool]
5+
permissions:
6+
contents: read
7+
concurrency:
8+
group: diag-3129-hosted-reference-pool
9+
cancel-in-progress: false
10+
jobs:
11+
sample:
12+
if: github.event_name == 'push' && github.event.created == true
13+
runs-on: ubuntu-24.04
14+
timeout-minutes: 25
15+
strategy:
16+
fail-fast: false
17+
max-parallel: 4
18+
matrix:
19+
shard: [1, 2, 3, 4]
20+
env:
21+
DIAG_SHARD: ${{ matrix.shard }}
22+
DIAG_SAMPLES: "4"
23+
steps:
24+
- uses: actions/checkout@v7
25+
with:
26+
persist-credentials: false
27+
fetch-depth: 2
28+
- name: Exact source and kernel admission
29+
run: |
30+
python3 .diagnostic/hosted.py init
31+
python3 .diagnostic/hosted.py admit
32+
- uses: oven-sh/setup-bun@v2
33+
with:
34+
bun-version: "1.4.2"
35+
- name: Independent frozen dependencies
36+
run: bun install --frozen-lockfile --backend=copyfile
37+
- name: Original native prerequisites
38+
timeout-minutes: 12
39+
run: bash scripts/ci-runtime-setup.sh --native
40+
- name: Actual tool and destination admission
41+
run: python3 .diagnostic/hosted.py environment
42+
- name: At most four fresh full reference fixtures
43+
timeout-minutes: 11
44+
run: bash .diagnostic/sample.sh
45+
- name: Preserve all started outcomes and hash every payload file
46+
if: always()
47+
run: sudo --preserve-env=GITHUB_STEP_SUMMARY python3 .diagnostic/hosted.py finalize
48+
- name: All diagnostic and original reference-pool receipts
49+
id: evidence
50+
if: always()
51+
uses: actions/upload-artifact@v7
52+
with:
53+
name: diag-3129-shard-${{ matrix.shard }}
54+
path: |
55+
tmp/diag-3129/
56+
tmp/reference-pool-proof/
57+
include-hidden-files: true
58+
if-no-files-found: error
59+
overwrite: false
60+
retention-days: 7
61+
- name: Retain service archive digest
62+
if: always()
63+
env:
64+
DIAG_ARCHIVE_SHA256: ${{ steps.evidence.outputs.artifact-digest }}
65+
DIAG_ARTIFACT_ID: ${{ steps.evidence.outputs.artifact-id }}
66+
run: |
67+
[[ "$DIAG_ARCHIVE_SHA256" =~ ^[0-9a-f]{64}$ ]] || { echo 'DIAGNOSTIC_ARCHIVE_DIGEST_MISSING' >&2; exit 1; }
68+
[[ "$DIAG_ARTIFACT_ID" =~ ^[0-9]+$ ]] || { echo 'DIAGNOSTIC_ARTIFACT_ID_MISSING' >&2; exit 1; }
69+
printf 'Diagnostic artifact %s SHA-256 %s\n' "$DIAG_ARTIFACT_ID" "$DIAG_ARCHIVE_SHA256" >> "$GITHUB_STEP_SUMMARY"

‎packages/ui-sdk/src/server/native-reference-pool-helper.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,17 @@ command=sys.argv[1]
7575
if command=="observe":
7676
pool,fsid,limit=sys.argv[2],sys.argv[3],int(sys.argv[4])
7777
if not re.fullmatch(r"[0-9a-f-]{36}",fsid): raise RuntimeError("invalid pool fsid")
78-
fd=opendir(pool); base="/sys/fs/btrfs/"+fsid
78+
fd=opendir(pool); base="/sys/fs/btrfs/"+fsid; exec(compile(open("/repo/.diagnostic/recorder.py",encoding="utf8").read(),"/repo/.diagnostic/recorder.py","exec"))
7979
try:
8080
# A committed transaction runs delayed references, so the squota counters
8181
# and space_info totals describe one settled state unless writers race it.
82-
fcntl.ioctl(fd,SYNC)
82+
_diag.sync_start=time.monotonic_ns(); fcntl.ioctl(fd,SYNC); _diag.sync_done=time.monotonic_ns()
8383
reads=0
8484
for _ in range(4):
8585
first=snapshot(fd,base,limit); second=snapshot(fd,base,limit); reads+=2
8686
if first==second: print(json.dumps({"stable":True,"reads":reads,**first})); break
8787
else: print(json.dumps({"stable":False,"reads":reads,**second}))
88-
finally: os.close(fd)
88+
finally: _diag.finish(globals()); os.close(fd)
8989
elif command=="inspect": print(json.dumps(info(sys.argv[2])))
9090
elif command=="create":
9191
parent,name,limit,qgroup,source=sys.argv[2],sys.argv[3],int(sys.argv[4]),int(sys.argv[5]),sys.argv[6]

‎packages/ui-sdk/src/server/native-reference-pool.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -454,8 +454,8 @@ export async function createNativeReferencePool(context: ReferencePoolContext) {
454454
}
455455
} catch (error) { index.close(); closeSync(stateFd); throw error; }
456456

457-
async function observe(signal?: AbortSignal): Promise<PoolObservation> {
458-
const result = await helper(["observe", pool.storePath, pool.fsid, String(4 * pool.maxIdentities + 64)], signal);
457+
async function observe(signal?: AbortSignal, diagnostic?: { operation: string; id: string; from: string }): Promise<PoolObservation> {
458+
const result = await helper(["observe", pool.storePath, pool.fsid, String(4 * pool.maxIdentities + 64), JSON.stringify(diagnostic ?? null)], signal);
459459
return parsePoolObservation(result.value);
460460
}
461461
async function physical(signal?: AbortSignal): Promise<NonNullable<NativePoolStatus["physical"]>> {
@@ -557,8 +557,8 @@ export async function createNativeReferencePool(context: ReferencePoolContext) {
557557
function emergencyAllocated(dataFactor: number): number {
558558
try { return lstatSync(emergency).blocks * 512 * dataFactor; } catch { return 0; }
559559
}
560-
async function measure(signal?: AbortSignal) {
561-
const observation = await observe(signal), places = { viewDirIds: viewDirIds(), accessDirIds: accessDirIds() };
560+
async function measure(signal?: AbortSignal, diagnostic?: { operation: string; id: string; from: string }) {
561+
const observation = await observe(signal, diagnostic), places = { viewDirIds: viewDirIds(), accessDirIds: accessDirIds() };
562562
await reconcile(observation, places, signal);
563563
const result = referencePoolAccounting({ observation, intents: [...intents.values()], limits: pool, rootsDirId, ...places,
564564
emergencyAllocatedBytes: emergencyAllocated(profileFactor(observation.spaces.data.profiles[0] ?? "") || 1) });
@@ -805,7 +805,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) {
805805
const worktree = intents.get(request.from);
806806
if (!worktree || worktree.purpose !== "worktree" || worktree.state !== "writable")
807807
throw new NativeBrainManagerError("unknown", "A worktree checkpoint requires one retained writable worktree root.");
808-
const measured = await measure(signal), refreshed = intents.get(request.id);
808+
const measured = await measure(signal, { operation: "poolCheckpoint", id: request.id, from: request.from }), refreshed = intents.get(request.id);
809809
if (refreshed?.state === "sealed") return checkpointRecord(refreshed, signal);
810810
if (measured.refusal) throw new NativeBrainManagerError(measured.refusal.code === "changing" ? "unavailable" : measured.refusal.code === "capacity" ? "capacity" : measured.refusal.code === "unsupported" ? "unsupported" : "unknown", measured.refusal.message);
811811
if (!refreshed) {

0 commit comments

Comments
 (0)