Prepare verified laboratory 6 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 470d9d6f1e
commit 7d56e52fd0
335 changed files with 31206 additions and 72 deletions
+19
View File
@@ -0,0 +1,19 @@
export type BrowserPrimaryFailure={error:unknown};
export type BrowserLifecyclePorts<C,R>={acquire():Promise<C>;run(context:C):Promise<R>;close(context:C):Promise<void>;reportResult(result:R|undefined,primary?:BrowserPrimaryFailure):Promise<void>;reportSecondaryFailure(kind:'report'|'close',error:unknown):Promise<void>};
// Local adaptation of the sibling acquire/run/close contract. Result reporting
// occurs after close, so a failing writer cannot extend the browser lifetime.
export function createBrowserLifecycle<C,R>(ports:BrowserLifecyclePorts<C,R>){
if(!ports||[ports.acquire,ports.run,ports.close,ports.reportResult,ports.reportSecondaryFailure].some(port=>typeof port!=='function'))throw Error('BROWSER_LIFECYCLE_PORTS_REQUIRED');
const secondary=async(kind:'report'|'close',error:unknown)=>{try{await ports.reportSecondaryFailure(kind,error)}catch{/* Secondary reporting never replaces an owned primary failure. */}};
return async()=>{
let result:R|undefined,primary:unknown,cleanup:unknown,failed=false,cleanupFailed=false;
const context=await ports.acquire();
try{try{result=await ports.run(context)}catch(error){primary=error;failed=true}}
finally{try{await ports.close(context)}catch(error){cleanup=error;cleanupFailed=true}}
if(cleanupFailed)await secondary('close',cleanup);
try{await ports.reportResult(result,failed?{error:primary}:undefined)}catch(error){await secondary('report',error);if(!failed&&!cleanupFailed){primary=error;failed=true}}
if(failed)throw primary;
if(cleanupFailed)throw cleanup;
return result as R;
};
}
+5
View File
@@ -0,0 +1,5 @@
export type GrafanaCredentialPorts={read():Promise<string|undefined>;generate():string;archive(value:string):Promise<void>;publish(value:string):Promise<void>};
export function createGrafanaCredentialBootstrap(ports:GrafanaCredentialPorts){
if(['read','generate','archive','publish'].some(key=>typeof ports?.[key]!=='function'))throw new Error('All Grafana credential ports required');
return async()=>{const existing=await ports.read(),value=existing??ports.generate();if(!/^[!-~]{16,128}$/.test(value))throw new Error('Invalid Grafana owner credential');await ports.archive(value);if(existing===undefined)await ports.publish(value);};
}
+13
View File
@@ -0,0 +1,13 @@
export function dashboardMatches(actual:any,expected:any):boolean{
const panels=actual?.dashboard?.panels,configured=expected?.panels;
if(typeof expected?.uid!=='string'||actual?.dashboard?.uid!==expected.uid||!Array.isArray(panels)||!Array.isArray(configured)||!configured.length||panels.length!==configured.length)return false;
const valid=(p:any)=>Number.isSafeInteger(p?.id)&&p.id>0&&typeof p.title==='string'&&p.title.length>0;
if(!configured.every(valid)||!panels.every(valid))return false;
const wanted=new Map(configured.map(p=>[p.id,p.title]));
return wanted.size===configured.length&&new Set(panels.map(p=>p.id)).size===panels.length&&panels.every(p=>wanted.get(p.id)===p.title);
}
export function rulesMatch(actual:any,expected:string[]):boolean{
if(!Array.isArray(actual)||!Array.isArray(expected)||!expected.length||actual.length!==expected.length||!expected.every(v=>typeof v==='string'&&v.length>0))return false;
const wanted=new Set(expected),got=new Set(actual.map(row=>row?.uid));
return wanted.size===expected.length&&got.size===actual.length&&[...got].every(uid=>wanted.has(uid));
}
+5
View File
@@ -0,0 +1,5 @@
// Native13.3.1 rejects1s groups and accepts10s. Public-tag setting_unified_alerting.go is reference only; the reported deployed commit differs.
export function validateGrafanaRuleIntervals(groups:readonly {interval:string}[],baseSeconds:number):void{
if(!Number.isSafeInteger(baseSeconds)||baseSeconds<=0||!Array.isArray(groups)||!groups.length)throw new Error('Native Grafana scheduler contract missing');
for(const group of groups){const m=/^(\d+)(s|m)$/.exec(group.interval??''),seconds=m?Number(m[1])*(m[2]==='m'?60:1):NaN;if(!Number.isSafeInteger(seconds)||seconds<baseSeconds||seconds%baseSeconds!==0)throw new Error('Grafana rule group interval must be a positive native scheduler multiple');}
}
+12
View File
@@ -0,0 +1,12 @@
export type IncidentSample={at:string;phase:string;rules:{name:string;state:string}[]};
export type AcceptedFact={id:string;status:string;accepted_at:string;first_ready_at:string;ready_seconds:number};
export function readyIncidentObserved(samples:IncidentSample[],facts:AcceptedFact[],ids:string[],stoppedAt:string,restoredAt:string){
const stop=Date.parse(stoppedAt),restart=Date.parse(restoredAt),expected=new Set(ids);
if(!Number.isFinite(stop)||!Number.isFinite(restart)||restart<stop||!expected.size||expected.size!==ids.length||facts.length!==expected.size||new Set(facts.map(f=>f.id)).size!==facts.length)return false;
let firstAccepted=Infinity,lastReady=-Infinity;
for(const f of facts){const accepted=Date.parse(f.accepted_at),ready=Date.parse(f.first_ready_at);if(!expected.has(f.id)||f.status!=='ready'||!Number.isFinite(accepted)||!Number.isFinite(ready)||accepted<stop||accepted>restart||ready<accepted||!Number.isFinite(f.ready_seconds)||f.ready_seconds<=10)return false;firstAccepted=Math.min(firstAccepted,accepted);lastReady=Math.max(lastReady,ready);}
// A process restart does not make its accepted backlog ready. Bound the readback by
// actual immutable job facts plus the configured cohort/evaluation/export budgets.
return samples.some(s=>{const at=Date.parse(s.at);return Number.isFinite(at)&&at>=firstAccepted+10000&&at<=lastReady+44000&&['worker_stopped','worker_recovery'].includes(s.phase)&&s.rules.some(r=>r.name==='MessengerReadyErrorBudgetBurn'&&r.state==='Alerting');});
}
export function drained(values:number[]){return values.length>0&&values.every(v=>Number.isFinite(v)&&v===0);}
+48
View File
@@ -0,0 +1,48 @@
export type AccountResponse = { status: number; chunks: AsyncIterable<Uint8Array> };
export type AccountRequest = { captureId: string; path: string; method: string; body?: unknown; auth: string };
export type AccountCapture = { captureId: string; raw: Uint8Array; status: number | null; outcome: string; complete: boolean };
export type AccountHTTPPorts = {
request(input: AccountRequest): Promise<AccountResponse>;
capture(input: AccountCapture): Promise<void>;
};
export class AccountHTTPError extends Error {
constructor(readonly stage: string, readonly captureFailed = false) {
super('Account HTTP outcome: ' + stage + (captureFailed ? '; private capture failed' : ''));
}
}
export function createAccountHTTP(ports: AccountHTTPPorts, maxBytes: number) {
if (!ports?.request || !ports?.capture || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 1_048_576) throw new Error('Invalid account HTTP ports or bound');
return async (input: AccountRequest) => {
const chunks: Uint8Array[] = [];
let size = 0, status: number | null = null, stage = 'network_uncertain';
const joined = () => {
const raw = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) { raw.set(chunk, offset); offset += chunk.length; }
return raw;
};
try {
const response = await ports.request(input);
status = response.status;
stage = 'body_uncertain';
for await (const chunk of response.chunks) {
const available = Math.min(chunk.length, maxBytes - size);
if (available > 0) { chunks.push(chunk.slice(0, available)); size += available; }
if (available < chunk.length) { stage = 'size_exceeded'; throw new AccountHTTPError(stage); }
}
} catch {
let captureFailed = false;
try { await ports.capture({ captureId: input.captureId, raw: joined(), status, outcome: stage, complete: false }); }
catch { captureFailed = true; }
// No retry: the remote POST may already have created the account.
throw new AccountHTTPError(stage, captureFailed);
}
const raw = joined();
try { await ports.capture({ captureId: input.captureId, raw, status, outcome: 'response_complete', complete: true }); }
catch { throw new AccountHTTPError('capture_failed', true); }
let body: unknown;
try { body = size ? JSON.parse(new TextDecoder().decode(raw)) : null; }
catch { throw new AccountHTTPError('invalid_json'); }
return { status: status!, body: body as any };
};
}
+35
View File
@@ -0,0 +1,35 @@
export type AccountKey = 'ingest' | 'query';
export type Account = { email: string; token: string };
export type Intent = { email: string; rawFile: string; captureId: string };
export type Capability = { role: string; searchHTTP: number; searchHasRows: boolean; ingestHTTP: number; adminRotateHTTP: number };
export type CreateResult = { status: number | null; body: any };
export type BootstrapPorts = {
readIndex(): Promise<Record<AccountKey, Account> | undefined>;
readAccount(key: AccountKey): Promise<Account | undefined>;
readIntent(key: AccountKey): Promise<Intent | undefined>;
makeIntent(key: AccountKey): Intent;
claimIntent(key: AccountKey, intent: Intent): Promise<void>;
readCaptured(intent: Intent): Promise<CreateResult | undefined>;
create(key: AccountKey, intent: Intent): Promise<CreateResult>;
saveAccount(key: AccountKey, account: Account): Promise<void>;
verify(key: AccountKey, account: Account): Promise<Capability>;
publishIndex(accounts: Record<AccountKey, Account>): Promise<void>;
publishDerived(accounts: Record<AccountKey, Account>): Promise<void>;
};
export const accountEmail = (key: AccountKey) => 'vp6-' + key + '@lab.invalid';
function candidate(key:AccountKey,response:CreateResult):Account{if(![200,null].includes(response.status)||response.body?.code!==200||response.body?.user!==accountEmail(key)||typeof response.body?.token!=="string"||!/^[A-Za-z0-9_-]{16,256}$/.test(response.body.token))throw new Error("Captured native account response is not recoverable; no POST retry");return{email:response.body.user,token:response.body.token};}
function validateAccount(key:AccountKey,account:Account){if(account?.email!==accountEmail(key)||typeof account?.token!=="string"||!/^[A-Za-z0-9_-]{16,256}$/.test(account.token))throw new Error("Private account checkpoint invalid; no POST retry");}
export function createAccountBootstrap(ports:BootstrapPorts){
const names:(keyof BootstrapPorts)[]=["readIndex","readAccount","readIntent","makeIntent","claimIntent","readCaptured","create","saveAccount","verify","publishIndex","publishDerived"];if(names.some(name=>typeof ports?.[name]!=="function"))throw new Error("All bootstrap ports are required");
return async()=>{const previous=await ports.readIndex(),accounts={} as Record<AccountKey,Account>,proofs=[];
for(const key of ["ingest","query"] as const){let account=await ports.readAccount(key)??previous?.[key];
if(!account){const retained=await ports.readIntent(key);if(retained){if(retained.email!==accountEmail(key))throw new Error("Private account intent identity mismatch");const captured=await ports.readCaptured(retained);if(!captured)throw new Error("Uncertain account creation retained; inspect captured bytes, never repeat POST automatically");account=candidate(key,captured);}else{const intent=ports.makeIntent(key);if(intent.email!==accountEmail(key))throw new Error("New account intent identity mismatch");await ports.claimIntent(key,intent);const created=await ports.create(key,intent);if(created.status!==200)throw new Error("Native account create was not accepted; retained intent prevents automatic retry");account=candidate(key,created);}}
validateAccount(key,account);
// A received credential is durable before the next create, including when its live probe fails.
await ports.saveAccount(key,account);
const proof=await ports.verify(key,account);if(proof.role!=="service_account"||proof.searchHTTP!==200||!proof.searchHasRows||proof.ingestHTTP!==200||proof.adminRotateHTTP!==403)throw new Error("Native account capability verification failed; derived credentials/start are not published");
accounts[key]=account;proofs.push({principal:key,...proof});
}
await ports.publishIndex(accounts);await ports.publishDerived(accounts);return{accounts,proofs};
};
}
+7
View File
@@ -0,0 +1,7 @@
export type FaultPorts<L,T>={acquire():Promise<L>;exercise(lease:L):Promise<T>;restore(lease:L):Promise<void>};
export class OwnedFaultFailure extends Error{constructor(readonly primary:unknown,readonly cleanup:unknown){super('Owned fault execution or restoration failed');}}
// Ownership acquisition is read-only; every mutation belongs in exercise so restoration is already registered.
export function createOwnedFaultRunner<L,T>(ports:FaultPorts<L,T>){
if(!ports?.acquire||!ports?.exercise||!ports?.restore)throw new Error('All owned-fault ports required');
return async()=>{const lease=await ports.acquire();let result:T|undefined,primary:unknown,cleanup:unknown,failed=false,cleanupFailed=false;try{result=await ports.exercise(lease)}catch(error){primary=error;failed=true}try{await ports.restore(lease)}catch(error){cleanup=error;cleanupFailed=true}if(failed||cleanupFailed)throw new OwnedFaultFailure(primary,cleanup);return result as T;};
}