forked from mtusi2026/mtusi2026lab6
Prepare verified laboratory 6 implementation and evidence
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
# Native account HTTP capture cases
|
||||
|
||||
The production provisioner uses a separate HTTP factory with mandatory request/capture ports. Tests invoke this actual factory with explicit fakes; they never invoke the live entrypoint. The legacy extraction retains parse-before-capture until RED is reproduced; the following implementation changes only the capture boundary.
|
||||
|
||||
| Situation | Example | Expected observable behavior | Level |
|
||||
|---|---|---|---|
|
||||
| Invalid JSON after accepted POST | 200 with a partial one-time token JSON | Raw bytes captured before decoding fails; no retry | Factory with explicit ports |
|
||||
| Body read error | One token-prefix chunk then a reader error | Available partial bytes and uncertain outcome captured, one request | Factory with explicit ports |
|
||||
| Response cap | Six available bytes with four-byte cap | First four bytes captured with size-exceeded outcome, no unbounded buffer | Factory with explicit ports |
|
||||
| Network uncertainty | Request rejects before response | Empty response capture with null status and network-uncertain outcome, no retry | Factory with explicit ports |
|
||||
| Valid response | 200 with known synthetic token | Raw capture exists before parsed token is returned | Factory with explicit ports |
|
||||
|
||||
The preliminary extraction probe is not a native account-creation incident. Raw wire responses stay in exclusive0600 files under an already claimed private0700 operation directory. Metadata is secondary to raw capture; error reporting preserves the primary uncertainty if capture fails. Never automatically repeat an uncertain account POST.
|
||||
|
||||
## Bootstrap continuation cases (recorded before the correction)
|
||||
|
||||
The production caller now invokes `createAccountBootstrap` with all ports required. Legacy RED is8 failures/1 positive control; corrected workflow9 tests/24 expectations. Combined HTTP/workflow suite14 tests/46 expectations. The immutable legacy source and RED output remain evidence, not active imports.
|
||||
|
||||
| Bootstrap state | Expected observation |
|
||||
|---|---|
|
||||
| Ingest received, query create fails | Ingest checkpoint already present; no derived publication |
|
||||
| One checkpoint survives | Resume does not repeat that account POST |
|
||||
| Intent plus valid captured native response | Recover token and reverify without repeating POST |
|
||||
| Intent without recoverable response | Fail closed; zero automatic POST retries |
|
||||
| Saved token search401, ingest503, admin401 | Reject startup before derived credentials/successful continuation |
|
||||
| Healthy first bootstrap | Persist ingest before query create; publish only after both verified |
|
||||
| Healthy saved pair | Reverify both, zero account create calls |
|
||||
|
||||
The first native verification performs owned identity_probe ingestion before its exact-event search, so no preexisting application stream is required. The current native existing-pair readback proves the production wiring; fresh-volume runtime remains a separate final acceptance gate.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Native Grafana acceptance cases
|
||||
|
||||
The owner approved at most600000000 new network bytes on omarchy for pinned Grafana13.3.1 and existing OpenObserve plugin1.0.1. Historical113-file/native-only receipts remain immutable. These cases precede browser/fault implementation; failures are retained rather than reclassified by HTTP status alone.
|
||||
|
||||
| Situation or input | Example | Observable expected result | Level |
|
||||
|---|---|---|---|
|
||||
| Authorized dependency identity/budget | Pinned native image manifest and plugin SHA | Exact size/SHA/platform/version, total fetched bytes≤600MB, no other images/browser/model downloads | Native operation |
|
||||
| First-user initialization | Existing own password file, empty Grafana user DB | Actual13.3.1 initializer/policy checked, encrypted private roundtrip before first start, no credential printed | Native operation |
|
||||
| Initial startup convergence | SQLite migrations before HTTP bind | Wait bounded convergence; distinguish running/migrating from failed/OOM; preserve actual failed readiness outcome | Integration |
|
||||
| Intended owner context | Native login with own encrypted-owner credential | Login200 and actual admin principal, cookies only in isolated browser memory; anonymous stars403 is retained separately, roles/publicness unchanged | Browser |
|
||||
| Real datasource/provisioning | Metrics UIDprometheus and plugin UIDopenobserve | Both loaded and query actual own retained data through Grafana gateway; all mandatory panels imported | Integration and browser |
|
||||
| Required dashboard signals | Actual retained upload workload window |18 panels query real data, finite active percentiles, actual request/job labels, queue/DB/worker/process values; idle NoData remains explicit | Browser and data readback |
|
||||
| Canonical trace | Retained actual42-span upload trace | Actual waterfall renders correct span count, nanosecond→millisecond units/durations and41 parent relations, API/publisher/worker/S3/DB visible | Browser and native frame |
|
||||
| Correlation/navigation | API and worker logs for same trace and HTTP request_id | Structured logs visible; log→trace and trace→log navigate to the same actual trace with preserved time bounds | Browser |
|
||||
| Actual response bound | Bounded own query whose result exceeds1MiB | Native Grafana proxy rejects/truncates with explicit failure rather than silently treating incomplete output as full data; ordinary positive query still succeeds | Integration |
|
||||
| Worker stopped | Own worker stopped while a unique valid upload is accepted | API stays usable; queue age increases, actual queue/readiness alerts fire; restore worker drains backlog and alerts becomeNormal | Fault integration |
|
||||
| Database slowed | Own bounded SQL table lock plus steady business requests | postgres.query error/latency and HTTP5xx distinguish DB failure from handler delay; actual high-error/burn alert transitions; restore releases lock andNormal returns | Fault integration |
|
||||
| Short spike versus sustained failure | Brief DB lock, then longer DB lock under same bounded rate | Record duration/detection/recovery, false positives and expected multiwindow/for filtering, not substituted vector rules | Controlled experiment |
|
||||
| Fresh volume path | New isolated project/ports/volumes with checked source/config | Complete bootstrap/provisioning/core+Grafana/smoke works with empty storage; old volumes untouched and receipts distinctly attributed | Integration |
|
||||
| Final compatibility/source | Exact final files and original contracts | Required upstream/source checks pass; backend95 remains byte-identical, independent review and self-contained package checks precede full completion claim | Source and artifact |
|
||||
|
||||
Operational failures include bad digest/size, lost partial download, password-policy rejection, migration timeout, plugin load/provisioning/auth failure, empty/NaN result during a known positive workload, dropped trace parents, incorrect duration or link window, response overflow, alert evaluationError/NoData, fault cleanup failure and empty-volume bootstrap failure. No external notification delivery is required or performed. Tests use only owned resources and synthetic data; browser and fault workers inherit low-priority background.slice. This is correctness testing, not a benchmark.
|
||||
|
||||
The measured browser proxy returned2097625 bytes despite the1MiB setting, while the plugin SDK backend rejected the same2MiB result. Public tag and deployed image report different commits, so an applicable additional native frontend limit remains unknown. The approved minimal fallback is a bounded recognized Content-Length contract at the existing HAProxy gateway, not a universal streaming/decompression counter. Before changing it, native cases cover normal small/exact1048576/cap+1, encoded responses, Transfer-Encoding/chunked, EOF-delimited bodies, invalid/overflow/leading-zero Content-Length, duplicate/conflicting fields, and actual metadata/search/Prom queries. Native HTTP parser refusal is recorded separately from the ACL's static response code. Raw identical Content-Length normalization is reported explicitly if the native parser canonicalizes it; it is never called proof of rejecting every raw duplicate.
|
||||
# Native histogram compatibility delta
|
||||
|
||||
The original8-file response-boundary snapshot remains immutable. A later actual-browser query omitted `query.size`; native OpenObserve1.1.2 accepts missing/0 as full aggregation. This delta permits absent size and native integer0..1000 without rewriting requests. Negative/oversize values remain gateway-denied; fractional/string/null/object inputs fail closed. Native9-case comparison is retained in evidence/grafana/histogram-native-red.json and histogram-native-green.json. Size is a requested query parameter, not a hard returned-row or byte limit; window, body, response, engine and resource budgets remain active.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import {resolve} from 'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),base='http://127.0.0.1:28206';
|
||||
if(Bun.argv.includes('--dry-run')){console.log('Valid isolated two-replica acceptance; no reads or writes');process.exit(0)}
|
||||
function compose(...args:string[]){const r=Bun.spawnSync([resolve(root,'scripts/compose.sh'),...args],{cwd:root,stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw new Error('isolated compose failed');return new TextDecoder().decode(r.stdout).trim()}
|
||||
let transientRetries=0;
|
||||
async function call(path:string,method='GET',body?:unknown,token?:string,auth?:string){const key=crypto.randomUUID(),encoded=body===undefined?undefined:JSON.stringify(body),retryable=method==='GET'||method==='POST'&&path.endsWith('/messages'),deadline=performance.now()+8000;for(;;){try{const r=await fetch(base+path,{method,headers:{'Content-Type':'application/json','Idempotency-Key':key,...(token?{Authorization:'Bearer '+token}:{}),...(auth?{Authorization:auth}:{})},body:encoded,signal:AbortSignal.timeout(1000)});const b=await r.json();if(!r.ok){if(r.status<500||!retryable)throw {fatal:true,status:r.status};throw new Error('transient HTTP failure')};return{body:b,instance:r.headers.get('X-Instance-Id')}}catch(e){if((e as any)?.fatal||!retryable||performance.now()>=deadline)throw new Error('acceptance request failed after bounded retry');transientRetries++;await Bun.sleep(100)}}}
|
||||
|
||||
async function ready(){const ids=new Set();for(let i=0;i<150;i++){try{const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1000)});await r.arrayBuffer();if(r.ok)ids.add(r.headers.get('X-Instance-Id'));if(ids.size===2)return}catch{}await Bun.sleep(150)}throw new Error('two API instances did not recover')}
|
||||
compose('up','-d','api');await ready();const username='rep_'+crypto.randomUUID().slice(0,8),password=crypto.randomUUID();await call('/api/v1/users','POST',{username,display_name:'Synthetic replica acceptance',password});const session=(await call('/api/v1/auth/sessions','POST',undefined,undefined,'Basic '+btoa(username+':'+password))).body;const token=session.token;const chat=(await call('/api/v1/chats','POST',{title:'Owned both-replica fixture',member_ids:[session.user.id]},token)).body;
|
||||
const ids=compose('ps','-q','api').split('\n');if(ids.length!==2)throw new Error('expected two isolated replicas');const results=[];const confirmed=[];
|
||||
for(const id of ids){const retryStart=transientRetries;try{const inspected=Bun.spawnSync(['docker','inspect',id,'--format','{{index .Config.Labels "com.docker.compose.project"}}|{{.Config.Hostname}}'],{stdout:'pipe'});const [project]=new TextDecoder().decode(inspected.stdout).trim().split('|');const alias=new TextDecoder().decode(Bun.spawnSync(['docker','exec',id,'cat','/tmp/messenger-instance-id'],{stdout:'pipe'}).stdout).trim();if(project!=='mtuci-vp6-medvedev'||!alias)throw new Error('wrong resource ownership');const before=(await call('/api/v1/chats/'+chat.id+'/messages','POST',{text:'before-'+id},token)).body;confirmed.push(before.id);
|
||||
const stop=Bun.spawnSync(['docker','stop','--time','8',id],{stdout:'pipe',stderr:'pipe'});if(stop.exitCode!==0)throw new Error('owned replica stop failed');const started=performance.now();let surviving='';for(let i=0;i<100;i++){try{const response=await call('/api/v1/users/me','GET',undefined,token);if(response.instance===alias)throw new Error('stopped replica served response');surviving=response.instance??'';break}catch{}await Bun.sleep(100)}if(!surviving)throw new Error('surviving replica unavailable');const written=(await call('/api/v1/chats/'+chat.id+'/messages','POST',{text:'during-'+id},token)).body;confirmed.push(written.id);const history=(await call('/api/v1/chats/'+chat.id+'/messages?limit=100','GET',undefined,token)).body.items;if(new Set(history.map((m:any)=>m.text)).size!==history.length)throw new Error('uncertain write retry created duplicate messages');if(!confirmed.every(x=>history.some((m:any)=>m.id===x)))throw new Error('confirmed message missing');results.push({stopped_instance:alias,surviving_instance:surviving,session_preserved:true,confirmed_messages:confirmed.length,transient_retries:transientRetries-retryStart,recovery_observed_ms:Math.round(performance.now()-started)});
|
||||
}finally{compose('up','-d','api');await ready()}}
|
||||
const result={checked_at:new Date().toISOString(),results};await Bun.write(resolve(root,'evidence/both-replicas.json'),JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result));
|
||||
@@ -0,0 +1,17 @@
|
||||
import{test,expect}from'bun:test';import{createBrowserLifecycle}from'../scripts/lib/browser-lifecycle';
|
||||
function fixture(flags:{setup?:string;primary?:unknown;report?:boolean;close?:boolean;secondaryReport?:boolean;acquire?:boolean}={}){
|
||||
const primary=Object.hasOwn(flags,'primary')?flags.primary:new Error(flags.setup??'WORK'),reportError=new Error('RESULT_WRITE'),closeError=new Error('CLOSE'),resource={id:'synthetic-browser'},events:string[]=[],secondary:{kind:string;error:unknown}[]=[];let closes=0,acquires=0;
|
||||
const run=createBrowserLifecycle({acquire:async()=>{acquires++;if(flags.acquire)throw primary;return resource},run:async received=>{expect(received).toBe(resource);events.push('run');if(flags.setup||Object.hasOwn(flags,'primary'))throw primary;return 17},close:async received=>{expect(received).toBe(resource);closes++;events.push('close');if(flags.close)throw closeError},reportResult:async(result,failure)=>{events.push('report');if(flags.report)throw reportError;if(flags.setup||Object.hasOwn(flags,'primary'))expect(failure?.error).toBe(primary);else expect(result).toBe(17)},reportSecondaryFailure:async(kind,error)=>{secondary.push({kind,error});if(flags.secondaryReport)throw Error('SECONDARY_REPORT')}});
|
||||
return{run,primary,reportError,closeError,events,secondary,closes:()=>closes,acquires:()=>acquires};
|
||||
}
|
||||
async function captured(run:()=>Promise<unknown>){try{return{threw:false,value:await run(),error:undefined}}catch(error){return{threw:true,value:undefined,error}}}
|
||||
test('context setup rejection closes the acquired owned browser',async()=>{const f=fixture({setup:'newContext'}),result=await captured(f.run);expect(f.closes()).toBe(1);expect(result.error).toBe(f.primary)});
|
||||
test('page setup rejection closes the acquired owned browser',async()=>{const f=fixture({setup:'newPage'}),result=await captured(f.run);expect(f.closes()).toBe(1);expect(result.error).toBe(f.primary)});
|
||||
test('result-write rejection still closes and remains the primary failure',async()=>{const f=fixture({report:true}),result=await captured(f.run);expect(f.closes()).toBe(1);expect(result.error).toBe(f.reportError)});
|
||||
test('work failure survives simultaneous result-write failure',async()=>{const primary=new Error('ORIGINAL'),f=fixture({primary,report:true}),result=await captured(f.run);expect(result.error).toBe(primary);expect(f.closes()).toBe(1);expect(f.secondary).toEqual([{kind:'report',error:f.reportError}])});
|
||||
test('primary failure survives close and secondary-reporter failures',async()=>{const primary=new Error('ORIGINAL'),f=fixture({primary,close:true,secondaryReport:true}),result=await captured(f.run);expect(result.error).toBe(primary);expect(f.closes()).toBe(1);expect(f.secondary).toEqual([{kind:'close',error:f.closeError}])});
|
||||
test('close failure after success remains a separately reported failure',async()=>{const f=fixture({close:true}),result=await captured(f.run);expect(result.error).toBe(f.closeError);expect(f.closes()).toBe(1);expect(f.secondary).toEqual([{kind:'close',error:f.closeError}])});
|
||||
test('acquisition failure does not close a nonexistent browser',async()=>{const f=fixture({acquire:true}),result=await captured(f.run);expect(result.error).toBe(f.primary);expect(f.closes()).toBe(0)});
|
||||
test('missing required ports fail before acquisition',()=>{expect(()=>createBrowserLifecycle({}as any)).toThrow('BROWSER_LIFECYCLE_PORTS_REQUIRED')});
|
||||
test('thrown undefined is preserved when cleanup also fails',async()=>{const f=fixture({primary:undefined,close:true}),result=await captured(f.run);expect(result.threw).toBe(true);expect(result.error).toBeUndefined();expect(f.closes()).toBe(1);expect(f.secondary).toEqual([{kind:'close',error:f.closeError}])});
|
||||
test('successful work closes before reporting and returns its value',async()=>{const f=fixture();expect(await f.run()).toBe(17);expect(f.closes()).toBe(1);expect(f.events).toEqual(['run','close','report']);expect(f.secondary).toEqual([])});
|
||||
@@ -0,0 +1,6 @@
|
||||
import {mkdir,readFile,writeFile} from 'node:fs/promises';import {resolve} from 'node:path';
|
||||
const root=resolve(import.meta.dir,'..');const output=resolve(root,'.local/collector-config-check-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const dummy=resolve(output,'dummy-auth.yaml');await writeFile(dummy,'Basic Zml4dHVyZTpub3QtYS1jcmVkZW50aWFs\n',{flag:'wx',mode:0o644});
|
||||
const old=process.argv[2];if(!old||!resolve(old).startsWith(root+'/.local/history/'))throw new Error('preserved historical Collector config path required');
|
||||
const image='docker.io/library/mtuci-vp6-collector-cache:0.163.2';const inspect=Bun.spawnSync(['docker','image','inspect',image,'--format','{{.Id}}'],{stdout:'pipe',stderr:'pipe'});if(inspect.exitCode!==0||new TextDecoder().decode(inspect.stdout).trim()!=='sha256:a65df9129a5b3f99ee4434c5e53aee1965ff0129eda6a2da75ea917165b7fa6b')throw new Error('cached Collector identity mismatch');
|
||||
const cases=[];for(const [name,path,expected] of [['historical-storage-red',old,1],['openobserve-native-green',resolve(root,'config/otel-collector.yaml'),0]] as const){const bytes=await readFile(path);const readable=resolve(output,name+'.yaml');await writeFile(readable,bytes,{flag:'wx',mode:0o644});const run=Bun.spawnSync(['docker','run','--pull=never','--rm','--network','none','--read-only','-v',readable+':/etc/otelcol.yaml:ro','-v',dummy+':/run/secrets/openobserve_ingest_auth:ro',image,'validate','--config=/etc/otelcol.yaml'],{stdout:'pipe',stderr:'pipe'});await writeFile(resolve(output,name+'.log'),Buffer.concat([run.stdout,run.stderr]),{flag:'wx',mode:0o600});const actual=run.exitCode;const intendedFailure=name==='historical-storage-red'?new TextDecoder().decode(run.stderr).includes('prometheus'):true;cases.push({name,sourceHash:new Bun.CryptoHasher('sha256').update(bytes).digest('hex'),exitCode:actual,expectedSuccess:expected===0,intendedFailure,pass:(actual===0)===(expected===0)&&intendedFailure});}
|
||||
await writeFile(resolve(output,'RESULT.json'),JSON.stringify({checkedAt:new Date().toISOString(),image,cases},null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({cases,receipt:resolve(output,'RESULT.json')}));if(cases.some(c=>!c.pass))process.exitCode=1;
|
||||
@@ -0,0 +1,25 @@
|
||||
import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';import{createBrowserLifecycle}from'../scripts/lib/browser-lifecycle';
|
||||
const args=process.argv.slice(2);if(args.some(a=>/^--(?:only|filter|debug|skip)/.test(a)))throw Error('Partial/debug filters are forbidden for final browser acceptance');if(args.includes('--check')){console.log('Three-scenario native browser acceptance validated without credentials or launch');process.exit(0)}
|
||||
if(process.platform!=='linux'||!args.includes('--run-native'))throw Error('Explicit native browser acceptance required');const root=resolve(import.meta.dir,'..'),retryPath=resolve(args[args.indexOf('--retry-evidence')+1]??'');if(args.indexOf('--retry-evidence')<0||!retryPath.startsWith(root+'/'))throw Error('Explicit owned successful retry evidence required');
|
||||
const fixture=await Bun.file(resolve(root,'evidence/openobserve/native-signals-sa.json')).json(),retry=await Bun.file(retryPath).json();if(!retry.passed||!/^([a-f0-9]{32})$/.test(retry.traceId))throw Error('Verified same-job retry evidence missing');
|
||||
const out=resolve(root,'.local/grafana-browser-'+crypto.randomUUID());await mkdir(out,{mode:0o700});const modulePath='/home/rey/.bun/install/cache/playwright-core@1.63.0@@@1/index.mjs',{chromium}=await import(modulePath);
|
||||
const expected=['canonical-log-to-trace','canonical-trace-to-logs','retry-trace-render'],executed:string[]=[],consoleRecords:any[]=[],networkErrors:any[]=[],navigationEvents:any[]=[],wires:any[]=[],tasks:Promise<void>[]=[];let stage='browser-launch',failure:string|undefined,wireSequence=0,ownedHistoryPath='',closeAttemptedAt:string|undefined,closedAt:string|undefined;const secondaryFailures:{kind:'report'|'close'}[]=[];
|
||||
const rangeFor=(spans:any[])=>({from:new Date(Number(spans.reduce((m:bigint,s:any)=>BigInt(s.startTimeNs??s.start_ns)<m?BigInt(s.startTimeNs??s.start_ns):m,2n**100n)/1000000n)-1000).toISOString(),to:new Date(Number(spans.reduce((m:bigint,s:any)=>BigInt(s.endTimeNs??s.end_ns)>m?BigInt(s.endTimeNs??s.end_ns):m,0n)/1000000n)+1000).toISOString()});
|
||||
function explore(query:any,range:any){return'http://127.0.0.1:28306/explore?schemaVersion=1&panes='+encodeURIComponent(JSON.stringify({qa:{datasource:'openobserve',queries:[{refId:'A',organization:'default',stream:'messenger',...query}],range}}))+'&orgId=1'}
|
||||
async function capture(response:any){const id=++wireSequence,status=response.status(),contentType=response.headers()['content-type']??'',query=response.request().postDataJSON()?.query,raw=await response.body();await writeFile(resolve(out,'wire-'+id+'.private'),raw,{flag:'wx',mode:0o600});if(raw.length>1048576)throw Error('Actual browser query response bound');let body:any;try{body=JSON.parse(raw.toString())}catch{}const row={id,status,contentType,query,hits:body?.hits?.length,path:new URL(response.url()).pathname};wires.push(row);return{...row,body};}
|
||||
|
||||
try{await createBrowserLifecycle({
|
||||
acquire:async()=>chromium.launch({executablePath:'/usr/bin/chromium',headless:true,args:['--no-sandbox','--disable-dev-shm-usage','--disable-background-networking']}),
|
||||
run:async browser=>{stage='browser-context';const context=await browser.newContext({viewport:{width:1600,height:1100},colorScheme:'dark'});stage='browser-page';const page=await context.newPage();
|
||||
function searchResponse(type:string,predicate:(q:any)=>boolean){return page.waitForResponse((r:any)=>{if(!r.url().includes('_search'))return false;const url=new URL(r.url()),query=r.request().postDataJSON()?.query;return url.searchParams.get('type')===type&&predicate(query)},{timeout:45000})}
|
||||
stage='owner-login';const password=(await readFile(resolve(root,'.local/grafana_password'),'utf8')).trim();if((await context.request.post('http://127.0.0.1:28306/login',{data:{user:'admin',password}})).status()!==200)throw Error('Owner login failed');const principal=await context.request.get('http://127.0.0.1:28306/api/user'),owner=await principal.json();if(principal.status()!==200||owner.login!=='admin'||owner.isGrafanaAdmin!==true)throw Error('Intended owner principal not verified');ownedHistoryPath='/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:'+owner.uid;
|
||||
page.on('console',(m:any)=>{if(['error','warning'].includes(m.type()))consoleRecords.push({stage,type:m.type(),failedResource:m.text().startsWith('Failed to load resource:'),messageSHA256:new Bun.CryptoHasher('sha256').update(m.text()).digest('hex')})});page.on('pageerror',()=>networkErrors.push({stage,kind:'pageerror'}));page.on('requestfailed',(r:any)=>{const at=new Date().toISOString();const reason=r.failure()?.errorText??'unknown',known=['net::ERR_ABORTED','net::ERR_FAILED','net::ERR_CONNECTION_REFUSED','net::ERR_CONNECTION_RESET','net::ERR_TIMED_OUT'].includes(reason);networkErrors.push({at,stage,kind:'requestfailed',path:new URL(r.url()).pathname,resourceType:r.resourceType(),reason:known?reason:'withheld',reasonSHA256:new Bun.CryptoHasher('sha256').update(reason).digest('hex')})});page.on('response',(r:any)=>{const path=new URL(r.url()).pathname;if(r.status()>=400){const error:any={stage,kind:'http',path,status:r.status(),expectedOptionalState:path===ownedHistoryPath&&r.status()===404};networkErrors.push(error);const captureId=++wireSequence;tasks.push((async()=>{const raw=await r.body();error.bytes=raw.length;error.contentType=r.headers()['content-type'];if(raw.length>1048576){error.captureLimit=true;return}await writeFile(resolve(out,'http-error-'+captureId+'.private'),raw,{flag:'wx',mode:0o600})})().catch(()=>{error.captureFailed=true}));}});
|
||||
stage='canonical-logs';const traceId=fixture.traceId,query={queryType:'logs',streamType:'logs',query:'SELECT * FROM "messenger" WHERE "trace_id"=\''+traceId+'\' ORDER BY "_timestamp" ASC LIMIT 100',sqlMode:true,displayMode:'logs'},canonicalLogs=searchResponse('logs',q=>q?.sql?.startsWith('SELECT *')&&q.sql.includes(traceId));navigationEvents.push({at:new Date().toISOString(),kind:'intentional-goto',stage});await page.goto(explore(query,rangeFor(fixture.spans)),{waitUntil:'domcontentloaded',timeout:60000});const initial=await capture(await canonicalLogs);if(initial.status!==200||initial.body?.hits?.length!==3)throw Error('Canonical three correlated logs missing');await page.waitForFunction(()=>document.body.innerText.includes('http.request')&&document.body.innerText.includes('worker.job'),undefined,{timeout:30000});await page.getByText('http.request',{exact:true}).click();const requestId=fixture.correlatedLogs.find((l:any)=>l.requestId)?.requestId;if(!requestId)throw Error('Original HTTP request_id fixture missing');await page.waitForFunction((id:string)=>document.body.innerText.includes(id),requestId,{timeout:15000});
|
||||
stage='canonical-log-to-trace';const traceWire=searchResponse('traces',q=>q?.sql?.includes(traceId));navigationEvents.push({at:new Date().toISOString(),kind:'intentional-ui-link',stage});await page.getByRole('link',{name:'View trace '+traceId,exact:true}).click();const trace=await capture(await traceWire),ids=new Set(trace.body?.hits?.map((s:any)=>s.span_id)),wanted=new Set(fixture.spans.map((s:any)=>s.spanId));if(trace.status!==200||ids.size!==42||wanted.size!==42||[...wanted].some(id=>!ids.has(id))||trace.body.hits.filter((s:any)=>ids.has(s.reference_parent_span_id)).length!==41)throw Error('Canonical browser trace IDs/parents mismatch');await page.waitForFunction(()=>/42\s+spans/i.test(document.body.innerText),undefined,{timeout:30000});const worker=page.getByText('attachment.process (1.15s)',{exact:true}).first();await worker.scrollIntoViewIfNeeded();await page.screenshot({path:resolve(out,'canonical-worker-tree.png')});executed.push(stage);
|
||||
stage='canonical-trace-to-logs';await worker.click();const logsWire=searchResponse('logs',q=>q?.sql?.startsWith('SELECT *')&&q.sql.includes(traceId));navigationEvents.push({at:new Date().toISOString(),kind:'intentional-ui-link',stage});await page.getByRole('link',{name:'View logs for trace '+traceId,exact:true}).click();const returned=await capture(await logsWire),workerSpan=trace.body.hits.find((s:any)=>s.operation_name==='attachment.process');if(returned.status!==200||returned.body?.hits?.length!==1||returned.body.hits[0].event!=='worker.job'||returned.body.hits[0].span_id!==workerSpan.span_id||returned.body.hits[0].trace_id!==traceId||returned.body.hits[0]._timestamp<returned.query.start_time||returned.body.hits[0]._timestamp>returned.query.end_time)throw Error('Selected-span log navigation mismatch');await page.getByText('worker.job',{exact:true}).last().click();await page.waitForFunction(()=>document.body.innerText.includes('Total: 1'),undefined,{timeout:15000});await page.screenshot({path:resolve(out,'canonical-returned-log.png')});executed.push(stage);
|
||||
stage='retry-trace-render';const retryWire=searchResponse('traces',q=>q?.sql?.includes(retry.traceId));navigationEvents.push({at:new Date().toISOString(),kind:'intentional-goto',stage});await page.goto(explore({queryType:'trace_id',streamType:'traces',traceId:retry.traceId,sqlMode:false,displayMode:'trace'},rangeFor(retry.spans)),{waitUntil:'domcontentloaded',timeout:60000});const actualRetry=await capture(await retryWire),retryIDs=new Set(actualRetry.body?.hits?.map((s:any)=>s.span_id));if(actualRetry.status!==200||retryIDs.size!==retry.spanCount||retry.spans.some((s:any)=>!retryIDs.has(s.span_id)))throw Error('Actual browser retry trace differs from same-job proof');await page.waitForFunction((count:number)=>new RegExp(count+'\\s+spans','i').test(document.body.innerText),retry.spanCount,{timeout:30000});const processes=page.getByText(/^attachment.process \(/);if(await processes.count()!==2)throw Error('Two real consumer attempts not rendered');await processes.first().scrollIntoViewIfNeeded();await page.screenshot({path:resolve(out,'retry-two-attempts.png')});await page.getByText(/^s3.get \(/).first().scrollIntoViewIfNeeded();await page.screenshot({path:resolve(out,'retry-storage-child.png')});executed.push(stage);
|
||||
},
|
||||
close:async browser=>{closeAttemptedAt=new Date().toISOString();navigationEvents.push({at:closeAttemptedAt,kind:'intentional-browser-close',stage});await browser.close();closedAt=new Date().toISOString();},
|
||||
reportSecondaryFailure:async kind=>{secondaryFailures.push({kind});await writeFile(resolve(out,'SECONDARY-'+kind+'.json'),JSON.stringify({at:new Date().toISOString(),stage,kind})+'\n',{flag:'wx',mode:0o600});},
|
||||
reportResult:async(_result,primary)=>{failure=primary?(primary.error instanceof Error?primary.error.message:'Browser acceptance failed'):undefined;await Promise.all(tasks);const allowed404=networkErrors.filter(e=>e.expectedOptionalState).length,unexpectedNetwork=networkErrors.filter(e=>!e.expectedOptionalState),unexpectedConsole=consoleRecords.filter(e=>e.type==='warning'||!e.failedResource).length+Math.max(0,consoleRecords.filter(e=>e.type==='error'&&e.failedResource).length-allowed404),complete=expected.length===executed.length&&expected.every((name,i)=>executed[i]===name),cleanupFailed=secondaryFailures.some(e=>e.kind==='close');const result={checkedAt:new Date().toISOString(),scope:'three actual authenticated Chromium UI scenarios, no filters or manually reconstructed reverse link',expectedScenarios:expected,executedScenarios:executed,complete,stage,failure,primaryFailurePresent:primary!==undefined,cleanupFailed,secondaryFailures,canonicalTraceId:fixture.traceId,retryTraceId:retry.traceId,wires,rawConsoleRecords:consoleRecords,rawNetworkErrors:networkErrors,navigationEvents,expectedOptional404Count:allowed404,unexpectedConsoleErrors:unexpectedConsole,unexpectedNetworkErrors:unexpectedNetwork.length,passed:complete&&!primary&&!cleanupFailed&&!unexpectedConsole&&!unexpectedNetwork.length,out};await writeFile(resolve(out,'TEARDOWN.json'),JSON.stringify({closeAttemptedAt,closedAt,navigationEvents,cleanupFailed})+'\n',{flag:'wx',mode:0o600});await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({out,stage,failure,executedScenarios:executed,unexpectedConsoleErrors:unexpectedConsole,unexpectedNetworkErrors:unexpectedNetwork.length,cleanupFailed,passed:result.passed}));if(!result.passed)process.exitCode=1;}
|
||||
})();}catch(error){process.exitCode=1;failure??=error instanceof Error?error.message:'Browser acceptance failed';try{console.log(JSON.stringify({out,stage,failure,closeAttemptedAt,closedAt,secondaryFailures,passed:false}))}catch{/* A broken reporter cannot replace the preserved primary or prevent close. */}}
|
||||
@@ -0,0 +1,5 @@
|
||||
import{test,expect}from'bun:test';import{createGrafanaCredentialBootstrap}from'../scripts/lib/grafana-credential';
|
||||
const value='Aa1!synthetic-fixture-credential';
|
||||
test('archives and verifies a new owner credential before publishing the runtime file',async()=>{const order:string[]=[];await createGrafanaCredentialBootstrap({read:async()=>undefined,generate:()=>value,archive:async v=>{expect(v).toBe(value);order.push('archive')},publish:async()=>{order.push('publish')}})();expect(order).toEqual(['archive','publish'])});
|
||||
test('does not publish a credential when encrypted archival fails',async()=>{let published=0;await expect(createGrafanaCredentialBootstrap({read:async()=>undefined,generate:()=>value,archive:async()=>{throw Error('archive failed')},publish:async()=>{published++}})()).rejects.toThrow();expect(published).toBe(0)});
|
||||
test('preserves the existing owner and archives it without rotating or rewriting',async()=>{let generated=0,published=0,archived='';await createGrafanaCredentialBootstrap({read:async()=>value,generate:()=>{generated++;return value},archive:async v=>{archived=v},publish:async()=>{published++}})();expect(archived).toBe(value);expect(generated).toBe(0);expect(published).toBe(0)});
|
||||
@@ -0,0 +1,6 @@
|
||||
import{resolve}from'node:path';import{mkdir,writeFile}from'node:fs/promises';import{readyIncidentObserved,drained}from'../scripts/lib/incident-readback';
|
||||
const root=resolve(import.meta.dir,'..'),source=resolve(process.argv[2]??'');if(!source.startsWith(root+'/.local/grafana-incidents-'))throw new Error('Explicit captured owned incident directory required');
|
||||
const names=['RESULT.json','VALIDATIONS.json','snapshots.json','requests.json','attachment-facts.json','events.jsonl'];const bytes=await Promise.all(names.map(name=>Bun.file(resolve(source,name)).arrayBuffer()));const hashes=Object.fromEntries(names.map((name,i)=>[name,new Bun.CryptoHasher('sha256').update(bytes[i]).digest('hex')]));const [original,validation,samples,requests,facts]=bytes.slice(0,5).map(b=>JSON.parse(new TextDecoder().decode(b)));const events=new TextDecoder().decode(bytes[5]).trim().split('\n').map(s=>JSON.parse(s));const stopped=events.find(e=>e.kind==='owned-worker-stopped'),restored=events.find(e=>e.kind==='owned-worker-restored');const ids=requests.filter(r=>r.kind==='upload'&&r.status===202).map(r=>r.attachmentId);const passed=readyIncidentObserved(samples,facts,ids,stopped?.at??'',restored?.at??'')&&drained(validation.metric.B.values)&&Object.entries(validation.validations).every(([k,v])=>k==='readyBurnAlerting'||v===true)&&original.cleanupFailure===undefined;
|
||||
const changes=samples.filter((s,i)=>i===0||JSON.stringify(s.rules.map(r=>[r.name,r.state]))!==JSON.stringify(samples[i-1].rules.map(r=>[r.name,r.state]))).map(s=>({at:s.at,phase:s.phase,rules:s.rules.map(r=>({name:r.name,state:r.state}))}));
|
||||
const receipt={checkedAt:new Date().toISOString(),scope:'bounded readback of the SAME captured native incident; original command remains FAIL; no repeated fault or changed thresholds',source,hashes,originalCommandPassed:original.passed,originalFailure:original.primaryFailure,originalCleanupFailure:original.cleanupFailure??null,correctedReadyBurnObserved:passed,acceptedJobs:ids.length,readyJobs:facts.filter(f=>f.status==='ready').length,readySeconds:{min:Math.min(...facts.map(f=>f.ready_seconds)),max:Math.max(...facts.map(f=>f.ready_seconds))},workerStoppedAt:stopped.at,workerProcessStartedAt:restored.at,lastBusinessReadyAt:new Date(Math.max(...facts.map(f=>Date.parse(f.first_ready_at)))).toISOString(),causalWindowBudgetSeconds:{initialReadiness:10,cohort:30,evaluation:10,export:2,observation:2},metric:validation.metric,changes,passed};
|
||||
const out=resolve(root,'.local/grafana-incident-readback-'+crypto.randomUUID());await mkdir(out,{mode:0o700});await writeFile(resolve(out,'RESULT.json'),JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({out,passed,originalCommandPassed:original.passed,acceptedJobs:ids.length,readySeconds:receipt.readySeconds}));if(!passed)process.exitCode=1;
|
||||
@@ -0,0 +1,9 @@
|
||||
import{resolve}from'node:path';import{mkdir,readFile,writeFile}from'node:fs/promises';
|
||||
if(process.argv.includes('--check')){console.log('Captured incident trace reader validated without credential reads or network');process.exit(0)}
|
||||
const root=resolve(import.meta.dir,'..'),source=resolve(process.argv[2]??'');if(process.platform!=='linux'||!source.startsWith(root+'/.local/grafana-incidents-'))throw new Error('Explicit native captured incident directory required');
|
||||
const requests=await Bun.file(resolve(source,'requests.json')).json(),request=requests.find(r=>r.phase==='db_sustained_degradation'&&r.status>=500&&r.status<600&&/^[a-f0-9-]{36}$/.test(r.requestId??''));if(!request)throw new Error('Captured actual application5xx UUID missing');
|
||||
const out=resolve(root,'.local/grafana-incident-traces-'+crypto.randomUUID());await mkdir(out,{mode:0o700});const password=(await readFile(resolve(root,'.local/grafana_password'),'utf8')).trim(),auth='Basic '+Buffer.from('admin:'+password).toString('base64'),start=Date.parse(request.at)-5000,end=Date.parse(request.at)+15000;
|
||||
async function query(type:string,sql:string,label:string){const response=await fetch('http://127.0.0.1:28306/api/datasources/proxy/uid/openobserve/api/default/_search?type='+type,{method:'POST',headers:{Authorization:auth,'Content-Type':'application/json'},body:JSON.stringify({query:{sql,start_time:start*1000,end_time:end*1000,size:100}}),signal:AbortSignal.timeout(15000)});const parts:Uint8Array[]=[];let count=0;for await(const part of response.body??[]){count+=part.length;if(count>1048576)throw new Error('Readback response limit');parts.push(part)}const raw=Buffer.concat(parts);await writeFile(resolve(out,label+'.private.json'),raw,{flag:'wx',mode:0o600});if(response.status!==200)throw new Error('Incident readback HTTP'+response.status);const body=JSON.parse(raw.toString());if(!Array.isArray(body.hits))throw new Error('Native hit schema missing');return body.hits;}
|
||||
const logs=await query('logs','SELECT trace_id, span_id, request_id, event, service_name FROM "messenger" WHERE request_id=\''+request.requestId+'\' LIMIT 10','logs');if(logs.length!==1||!/^[a-f0-9]{32}$/.test(logs[0].trace_id))throw new Error('Captured request did not correlate to one HTTP log');const traceId=logs[0].trace_id;
|
||||
const spans=await query('traces','SELECT trace_id, span_id, reference_parent_span_id, operation_name, service_name, span_status, start_time, end_time, duration FROM "messenger" WHERE trace_id=\''+traceId+'\' LIMIT 100','spans');const normalized=spans.map(s=>({traceId:s.trace_id,spanId:s.span_id,parentSpanId:s.reference_parent_span_id,operation:s.operation_name,service:s.service_name,status:s.span_status,durationMs:Number(s.duration)/1000}));const databaseFailure=normalized.some(s=>s.operation==='postgres.query'&&s.status==='ERROR'&&s.durationMs>=900),apiFailure=normalized.some(s=>s.operation?.startsWith('GET ')&&s.status==='ERROR');
|
||||
const result={checkedAt:new Date().toISOString(),scope:'read-only correlation of SAME captured actual app5xx, without a new producer or fault',source,request,logs,traceId,spans:normalized,databaseFailure,apiFailure,passed:databaseFailure&&apiFailure};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({out,traceId,spans:spans.length,databaseFailure,apiFailure,passed:result.passed}));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,44 @@
|
||||
import {mkdir,readFile,writeFile,appendFile} from 'node:fs/promises';
|
||||
import {resolve} from 'node:path';
|
||||
import{writeFileSync}from'node:fs';
|
||||
import{createAccountHTTP}from'../scripts/lib/openobserve-account-http';
|
||||
if(process.argv.includes('--check')){const cfg:any=Bun.YAML.parse(await Bun.file(resolve(import.meta.dir,'../config/grafana/provisioning/alerting/rules.yaml')).text());if(cfg.groups?.length!==1||cfg.groups[0].interval!=='10s')throw new Error('Expected native scheduler configuration');console.log('Validated native incident entrypoint and immutable rule configuration; no secrets, Docker or API operations');process.exit(0);}
|
||||
import {createOwnedFaultRunner,OwnedFaultFailure} from '../scripts/lib/owned-fault';
|
||||
import{readyIncidentObserved,drained}from'../scripts/lib/incident-readback';
|
||||
if(process.platform!=='linux'||!process.argv.includes('--run-native'))throw new Error('Explicit native owned-stand incident invocation required');
|
||||
const root=resolve(import.meta.dir,'..'),out=resolve(root,'.local/grafana-incidents-'+crypto.randomUUID()),project='mtuci-vp6-medvedev';
|
||||
await mkdir(out,{mode:0o700});await writeFile(resolve(out,'CLAIM.json'),JSON.stringify({claimedAt:new Date().toISOString(),project,scope:'own synthetic native Grafana SLO experiment; bounded worker and PostgreSQL faults',root})+'\n',{flag:'wx',mode:0o600});await writeFile(resolve(out,'events.jsonl'),'',{flag:'wx',mode:0o600});
|
||||
const started=performance.now(),requests:any[]=[],snapshots:any[]=[],phases:any[]=[],attachments:string[]=[],commands:any[]=[],events:any[]=[];
|
||||
const ruleNames=['MessengerHighErrorRate','MessengerFastErrorBudgetBurn','MessengerQueueLag','MessengerReadyErrorBudgetBurn','MessengerDatabaseObserverUnavailable'];
|
||||
let phase='setup',sessionToken='',chatId='',monitorSequence=0,commandSequence=0;
|
||||
const admin=(await readFile(resolve(root,'.local/grafana_password'),'utf8')).trim(),adminAuth='Basic '+Buffer.from('admin:'+admin).toString('base64'),image=await readFile(resolve(root,'tests/fixtures/sample.png'));
|
||||
async function event(kind:string,data:Record<string,unknown>={}){const record={at:new Date().toISOString(),elapsedMs:Math.round(performance.now()-started),phase,kind,...data};events.push(record);await appendFile(resolve(out,'events.jsonl'),JSON.stringify(record)+'\n');console.log(JSON.stringify(record));}
|
||||
function command(args:string[],label:string){const r=Bun.spawnSync(args,{cwd:root,stdout:'pipe',stderr:'pipe'});const number=++commandSequence;try{writeFileSync(resolve(out,'command-'+number+'.stderr.private'),r.stderr,{flag:'wx',mode:0o600})}catch{/* Secondary diagnostics cannot replace the owned command outcome. */}commands.push({number,label,exitCode:r.exitCode});if(r.exitCode!==0)throw new Error('Owned command failed at '+label);return new TextDecoder().decode(r.stdout).trim();}
|
||||
function owned(service:string,id?:string){const target=id??project+'-'+service+'-1',raw=command(['docker','inspect',target],'inspect-'+service),c=JSON.parse(raw)[0];if(c.Config.Labels['com.docker.compose.project']!==project||c.Config.Labels['com.docker.compose.service']!==service||c.Config.Labels['com.docker.compose.project.working_dir']!==root)throw new Error('Owned component guard failed');return c;}
|
||||
owned('postgres');owned('worker');owned('grafana');
|
||||
async function gf(path:string,body?:unknown){const response=await fetch('http://127.0.0.1:28306'+path,{method:body?'POST':'GET',headers:{Authorization:adminAuth,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(12000)});const raw=await response.text();if(raw.length>2_097_152)throw new Error('Grafana response budget');if(response.status!==200)throw new Error('Grafana observation HTTP'+response.status);return JSON.parse(raw);}
|
||||
async function sample(){const raw=await gf('/api/prometheus/grafana/api/v1/rules');await writeFile(resolve(out,'states-'+String(++monitorSequence).padStart(4,'0')+'.private.json'),JSON.stringify(raw),{flag:'wx',mode:0o600});const rows=(raw?.data?.groups??[]).flatMap((g:any)=>g.rules.map((r:any)=>({name:r.name,health:r.health,nativeRuleState:r.state,instances:(r.alerts??[]).map((a:any)=>({state:a.state,activeAt:a.activeAt})),interval:g.interval}))).filter((r:any)=>ruleNames.includes(r.name));if(raw.status!=='success'||rows.length!==5)throw new Error('Actual Grafana rule set missing');for(const row of rows){if(!['ok','nodata','err','unknown'].includes(row.health)||row.instances.some((a:any)=>!['Normal','Pending','Alerting','NoData','Error','Recovering'].includes(a.state)))throw new Error('Unknown native alert enum');row.state=row.instances.some((a:any)=>a.state==='Alerting')?'Alerting':row.instances.some((a:any)=>a.state==='Pending')?'Pending':row.instances.some((a:any)=>a.state==='NoData')?'NoData':row.instances.some((a:any)=>a.state==='Error')?'Error':row.instances.length?'Normal':'Initializing';}
|
||||
let healthHTTP=0;try{const h=await fetch('http://127.0.0.1:28206/health/ready',{signal:AbortSignal.timeout(1500)});healthHTTP=h.status;await h.arrayBuffer();}catch{}
|
||||
const record={at:new Date().toISOString(),elapsedMs:Math.round(performance.now()-started),phase,healthHTTP,rules:rows};snapshots.push(record);return record;}
|
||||
const identity=process.env.VP6_SECRET_IDENTITY_FILE;if(!identity||!identity.startsWith(root+'/.local/')||!identity.endsWith('/identity.agekey'))throw new Error('Explicit owned private encryption identity is required');
|
||||
async function seal(name:string,bytes:Uint8Array){const r=Bun.spawnSync(['/home/rey/.local/bin/age','--encrypt','-i',identity!],{stdin:bytes,stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw new Error('Private capture encryption failed');await writeFile(resolve(out,name+'.age'),r.stdout,{flag:'wx',mode:0o600});}
|
||||
let apiSequence=0;const correlations=new Map<string,{status:number,requestId:string|null}>();
|
||||
const apiHTTP=createAccountHTTP({request:async input=>{const binary=input.body instanceof Uint8Array;const r=await fetch('http://127.0.0.1:28206'+input.path,{method:input.method,headers:{'Content-Type':binary?'image/png':'application/json',...(input.auth?{Authorization:input.auth}:{})},body:input.body===undefined?undefined:binary?input.body as Uint8Array<ArrayBuffer>:JSON.stringify(input.body),signal:AbortSignal.timeout(6000)});const id=r.headers.get('X-Request-Id');correlations.set(input.captureId,{status:r.status,requestId:/^[a-f0-9-]{36}$/.test(id??'')?id:null});return{status:r.status,chunks:r.body??(async function*(){})()};},capture:async capture=>{await seal(capture.captureId,capture.raw);try{await writeFile(resolve(out,capture.captureId+'.meta.json'),JSON.stringify({status:capture.status,outcome:capture.outcome,complete:capture.complete,bytes:capture.raw.length})+'\n',{flag:'wx',mode:0o600})}catch{/* Raw encrypted capture is primary. */}}},1048576);
|
||||
async function api(path:string,method='GET',body?:unknown,authorization?:string){const captureId='api-response-'+String(++apiSequence).padStart(5,'0');try{const r=await apiHTTP({captureId,path,method,body,auth:authorization??(sessionToken?'Bearer '+sessionToken:'')});return{status:r.status,body:r.body,requestId:correlations.get(captureId)?.requestId??null};}catch{const wire=correlations.get(captureId);return{status:wire?.status??0,body:undefined,requestId:wire?.requestId??null};}}
|
||||
async function traffic(upload=false){const at=new Date().toISOString(),begin=performance.now();let status=0,requestId:string|null=null,attachmentId:string|undefined;try{if(upload){const r=await api('/api/v1/chats/'+chatId+'/attachments?filename=owned-slo.png','POST',image);status=r.status;requestId=r.requestId;const body=r.body;if(status===202){attachmentId=body.id;if(!/^[a-f0-9-]{36}$/.test(attachmentId??''))throw new Error('Accepted attachment identity missing');attachments.push(attachmentId!);}}else{const r=await api('/api/v1/chats/'+chatId+'/messages?limit=1');status=r.status;requestId=r.requestId;}}catch{}requests.push({phase,kind:upload?'upload':'business',at,elapsedMs:Math.round(performance.now()-begin),status,requestId,attachmentId});}
|
||||
async function observe(name:string,durationMs:number,uploadForMs=0){phase=name;const begin=performance.now(),startAt=new Date().toISOString(),pending=new Set<Promise<void>>();const launch=(upload:boolean)=>{if(pending.size>=4)return;const job=traffic(upload);pending.add(job);job.finally(()=>pending.delete(job));};const business=setInterval(()=>launch(false),500),uploads=uploadForMs?setInterval(()=>{if(performance.now()-begin<uploadForMs)launch(true)},1000):undefined;await event('phase-start',{durationMs,uploadForMs});let signature='';try{while(performance.now()-begin<durationMs){const observation=await sample(),next=observation.rules.map((r:any)=>r.name+'='+r.state+'/'+r.health).join('|');if(next!==signature){signature=next;await event('native-alert-states',{rules:observation.rules.map((r:any)=>({name:r.name,state:r.state,health:r.health})),healthHTTP:observation.healthHTTP});}await Bun.sleep(1000);}}finally{clearInterval(business);if(uploads)clearInterval(uploads);await Promise.allSettled(pending);}const record={name,startAt,endAt:new Date().toISOString(),startElapsedMs:Math.round(begin-started),durationMs:Math.round(performance.now()-begin)};phases.push(record);await event('phase-end',{durationMs:record.durationMs});return record;}
|
||||
function psql(sql:string,label:string){return command(['docker','exec','-i',project+'-postgres-1','psql','-X','-U','messenger','-d','messenger','-Atq','-v','ON_ERROR_STOP=1','-c',sql],label);}
|
||||
function lease(service:'worker'|'postgres',kind:string){const c=owned(service),tag='vp6_fault_'+crypto.randomUUID().replaceAll('-','');return{service,kind,id:c.Id,image:c.Image,tag,holder:undefined as ReturnType<typeof Bun.spawn>|undefined};}
|
||||
async function saveLease(value:any){await writeFile(resolve(out,'lease-'+value.tag+'.json'),JSON.stringify({service:value.service,kind:value.kind,id:value.id,image:value.image,tag:value.tag,root,project})+'\n',{flag:'wx',mode:0o600});return value;}
|
||||
async function dbLock(name:string,duration:number){phase=name+'_control';return createOwnedFaultRunner({acquire:async()=>saveLease(lease('postgres','messages-table-lock')),exercise:async l=>{const sql='BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(90); COMMIT;';l.holder=Bun.spawn(['docker','exec','-i','-e','PGAPPNAME='+l.tag,l.id,'psql','-X','-U','messenger','-d','messenger','-Atq','-v','ON_ERROR_STOP=1'],{stdin:'pipe',stdout:'pipe',stderr:'pipe'});l.holder.stdin.write(sql);l.holder.stdin.end();let acquired=false;for(let attempt=0;attempt<50;attempt++){const count=psql("SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a USING(pid) WHERE a.application_name='"+l.tag+"' AND l.relation='messages'::regclass AND l.mode='AccessExclusiveLock' AND l.granted;",'own-lock-ready');if(count==='1'){acquired=true;break;}await Bun.sleep(100);}if(!acquired)throw new Error('Owned table lock did not acquire');await event('owned-db-lock-acquired',{tag:l.tag});return observe(name,duration);},restore:async l=>{const c=owned('postgres',l.id);if(c.Image!==l.image)throw new Error('Database restore image guard');const result=psql("SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE application_name='"+l.tag+"' AND datname='messenger' AND pid<>pg_backend_pid();",'cancel-only-own-lock');if(l.holder){const exit=await l.holder.exited;await writeFile(resolve(out,l.tag+'-stdout.private'),new Uint8Array(await new Response(l.holder.stdout).arrayBuffer()),{flag:'wx',mode:0o600});await writeFile(resolve(out,l.tag+'-stderr.private'),new Uint8Array(await new Response(l.holder.stderr).arrayBuffer()),{flag:'wx',mode:0o600});await event('owned-db-lock-released',{cancelled:result==='t',holderExit:exit});}}})();}
|
||||
async function metricProof(){const expressions=['sum(http_requests{status_class="5xx"}) or vector(0)','max(queue_depth and (timestamp(queue_depth)>time()-10))','max(queue_oldest_age_seconds and (timestamp(queue_oldest_age_seconds)>time()-10))'];const body=await gf('/api/ds/query',{queries:expressions.map((expr,i)=>({refId:String.fromCharCode(65+i),datasource:{uid:'prometheus',type:'prometheus'},expr,instant:true,range:false,intervalMs:2000,maxDataPoints:1000})),from:String(Date.now()-60000),to:String(Date.now())});await writeFile(resolve(out,'metric-proof.private.json'),JSON.stringify(body),{flag:'wx',mode:0o600});return Object.fromEntries(Object.entries(body.results??{}).map(([key,value]:[string,any])=>[key,{error:!!value.error,values:(value.frames??[]).flatMap((f:any)=>f.schema.fields.flatMap((field:any,i:number)=>field.type==='number'?f.data.values[i].filter((v:any)=>typeof v==='number'&&Number.isFinite(v)):[]))}]));}
|
||||
let primaryFailure:string|undefined,cleanupFailure:string|undefined;
|
||||
try{const username='slo_'+crypto.randomUUID().slice(0,8),password='Aa1!'+crypto.randomUUID();await seal('fixture-auth-input',Buffer.from(JSON.stringify({username,password})));const user=await api('/api/v1/users','POST',{username,display_name:'Owned SLO experiment',password});if(user.status!==201)throw new Error('Synthetic fixture registration failed');const login=await api('/api/v1/auth/sessions','POST',undefined,'Basic '+Buffer.from(username+':'+password).toString('base64'));if(login.status!==201||typeof login.body?.token!=='string')throw new Error('Synthetic fixture login failed');sessionToken=login.body.token;const chat=await api('/api/v1/chats','POST',{title:'Owned bounded SLO experiment',member_ids:[login.body.user.id]});if(chat.status!==201)throw new Error('Synthetic fixture chat creation failed');chatId=chat.body.id;
|
||||
await observe('healthy_baseline',40000);const baseline=snapshots.at(-1);if(!baseline.rules.every((r:any)=>r.state==='Normal'&&r.health==='ok'))throw new Error('Native Grafana baseline is not all Normal');
|
||||
await dbLock('db_short_spike',3000);await observe('db_short_recovery',35000);
|
||||
await dbLock('db_sustained_degradation',40000);await observe('db_sustained_recovery',45000);
|
||||
await createOwnedFaultRunner({acquire:async()=>saveLease(lease('worker','worker-stop')),exercise:async l=>{owned('worker',l.id);command(['docker','stop','--time','8',l.id],'stop-only-own-worker');await event('owned-worker-stopped',{container:l.id});return observe('worker_stopped',45000,35000);},restore:async l=>{const c=owned('worker',l.id);if(c.Image!==l.image)throw new Error('Worker restore image guard');if(!c.State.Running)command(['docker','start',l.id],'start-only-owned-worker');await event('owned-worker-restored');}})();
|
||||
await observe('worker_recovery',80000);
|
||||
const metric=await metricProof();const facts=attachments.length?JSON.parse(psql("SELECT COALESCE(jsonb_agg(jsonb_build_object('id',id,'status',status,'accepted_at',accepted_at,'first_ready_at',first_ready_at,'ready_seconds',EXTRACT(EPOCH FROM(first_ready_at-accepted_at)))),'[]'::jsonb)::text FROM attachments WHERE id IN ("+attachments.map(id=>"'"+id+"'").join(',')+");",'own-attachment-facts')):[];await writeFile(resolve(out,'attachment-facts.json'),JSON.stringify(facts,null,2)+'\n',{flag:'wx',mode:0o600});const at=(phase:string,name:string,state:string)=>snapshots.filter(s=>s.phase===phase&&s.rules.some((r:any)=>r.name===name&&r.state===state));const validations={baselineNormal:true,dbHighErrorAlerting:at('db_sustained_degradation','MessengerHighErrorRate','Alerting').length>0,dbBurnAlerting:at('db_sustained_degradation','MessengerFastErrorBudgetBurn','Alerting').length>0,dbRecoveredNormal:snapshots.filter(s=>s.phase==='db_sustained_recovery').at(-1)?.rules.filter((r:any)=>r.name.includes('Error')).every((r:any)=>r.state==='Normal'),queueAlerting:at('worker_stopped','MessengerQueueLag','Alerting').length>0,readyBurnAlerting:readyIncidentObserved(snapshots,facts,attachments,events.find(e=>e.kind==='owned-worker-stopped')?.at??'',events.find(e=>e.kind==='owned-worker-restored')?.at??''),workerRecoveredNormal:snapshots.at(-1)?.rules.every((r:any)=>r.state==='Normal'&&r.health==='ok'),acceptedUploads:attachments.length>0,allAcceptedReady:facts.length===attachments.length&&facts.every((f:any)=>f.status==='ready'),app5xxObserved:requests.some(r=>r.phase==='db_sustained_degradation'&&r.status>=500&&/^[a-f0-9-]{36}$/.test(r.requestId??'')),dbPingRemainedHealthy:snapshots.filter(s=>s.phase==='db_sustained_degradation').every(s=>s.healthHTTP===200),native5xxMetric:(metric.A?.values??[]).some((v:number)=>v>0),queueDrained:drained(metric.B?.values??[])};await writeFile(resolve(out,'VALIDATIONS.json'),JSON.stringify({checkedAt:new Date().toISOString(),validations,metric},null,2)+'\n',{flag:'wx',mode:0o600});if(Object.values(validations).some(v=>v!==true))throw new Error('One or more mandatory native incident observations missing');
|
||||
}catch(error){primaryFailure=error instanceof OwnedFaultFailure?'Owned fault failed; separate primary/cleanup retained':error instanceof Error?error.message:'native incident failed';if(error instanceof OwnedFaultFailure)await writeFile(resolve(out,'FAULT-ERROR.json'),JSON.stringify({primaryPresent:error.primary!==undefined,cleanupPresent:error.cleanup!==undefined})+'\n',{flag:'wx',mode:0o600});}finally{if(sessionToken){try{const revoked=await api('/api/v1/auth/sessions/current','DELETE');if(revoked.status!==204)cleanupFailure='Synthetic session revocation failed';}catch{cleanupFailure='Synthetic session revocation unavailable';}}}
|
||||
await writeFile(resolve(out,'requests.json'),JSON.stringify(requests,null,2)+'\n',{flag:'wx',mode:0o600});await writeFile(resolve(out,'snapshots.json'),JSON.stringify(snapshots,null,2)+'\n',{flag:'wx',mode:0o600});const summary={checkedAt:new Date().toISOString(),project,scope:'real native Grafana rules and ordinary business workload; correctness/fault experiment, not performance benchmark',phases,requests:requests.length,acceptedUploads:attachments.length,primaryFailure,cleanupFailure,retainedSyntheticData:'Owned user/chat/attachments retained intentionally for course trace/metric defense; session revoked; no plaintext password/token/cookie persisted; encrypted private captures retained',passed:!primaryFailure&&!cleanupFailure,out};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(summary,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify(summary));if(!summary.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,2 @@
|
||||
import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),out=resolve(root,'.local/native-histogram-'+crypto.randomUUID());await mkdir(out,{mode:0o700});const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64');const query={sql:'SELECT histogram("_timestamp") AS zo_sql_key, count(*) AS zo_sql_num FROM "messenger" WHERE "trace_id"=\'33513303fdb8cdefbd4ff24c8394f3d3\' GROUP BY zo_sql_key ORDER BY zo_sql_key',start_time:1794784790000000,end_time:1794784794000000,from:0,sql_mode:'full'};const cases=[{id:'missing',query,valid:true},{id:'zero',query:{...query,size:0},valid:true},{id:'one',query:{...query,size:1},valid:true},{id:'negative',query:{...query,size:-1},valid:false},{id:'fraction',query:{...query,size:1.5},valid:false},{id:'string',query:{...query,size:'1'},valid:false},{id:'null',query:{...query,size:null},valid:false},{id:'too-large',query:{...query,size:1001},valid:false},{id:'object',query:{...query,size:{}},valid:false}];const results=[];for(const c of cases)for(const [stage,port]of[['native-consumer',28406],['gateway',28906]] as const){const r=await fetch('http://127.0.0.1:'+port+'/api/default/_search?type=logs',{method:'POST',headers:{Authorization:auth,'Content-Type':'application/json'},body:JSON.stringify({query:c.query}),signal:AbortSignal.timeout(10000)}),raw=await r.text();if(raw.length>1048576)throw new Error('Native histogram response bound');await writeFile(resolve(out,stage+'-'+c.id+'.private'),raw,{flag:'wx',mode:0o600});let b:any;try{b=JSON.parse(raw)}catch{}const rows=b?.hits??[],count=rows.reduce((s:number,row:any)=>s+Number(row.zo_sql_num??0),0);results.push({id:c.id,stage,http:r.status,contentType:r.headers.get('content-type'),rows:rows.length,count,validCase:c.valid,pass:stage==='native-consumer'?null:c.valid?r.status===200&&rows.length>0&&count>0:r.status>=400});}const result={checkedAt:new Date().toISOString(),scope:'exact actual browser supplementary histogram SQL/shape, native consumer compared to query gateway; no query rewriting',actualProducerMissingSize:true,query,results,passed:results.filter(r=>r.stage==='gateway').every(r=>r.pass),out};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(out,'RESULT.json'),passed:result.passed,results}));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,24 @@
|
||||
import{mkdir,readFile,writeFile}from'node:fs/promises';
|
||||
import{resolve}from'node:path';
|
||||
import{dashboardMatches,rulesMatch}from'../scripts/lib/grafana-provisioning';
|
||||
if(process.argv.includes('--check')){console.log('Grafana metadata acceptance validated without credentials or network');process.exit(0)}
|
||||
if(process.platform!=='linux')throw Error('Run native Grafana acceptance on the owned Linux host');
|
||||
const root=resolve(import.meta.dir,'..'),out=resolve(root,'.local/grafana-native-'+crypto.randomUUID());
|
||||
const expectedDashboard=await Bun.file(resolve(root,'config/grafana/dashboards/messenger.json')).json();
|
||||
const alertConfig:any=Bun.YAML.parse(await Bun.file(resolve(root,'config/grafana/provisioning/alerting/rules.yaml')).text());
|
||||
const expectedRules=(alertConfig.groups??[]).flatMap((g:any)=>(g.rules??[]).map((r:any)=>r.uid));
|
||||
await mkdir(out,{mode:0o700});
|
||||
const password=(await readFile(resolve(root,'.local/grafana_password'),'utf8')).trim(),auth='Basic '+Buffer.from('admin:'+password).toString('base64'),checks=[];
|
||||
for(const[name,path]of[['server','/api/health'],['metrics-source','/api/datasources/uid/prometheus/health'],['plugin-source','/api/datasources/uid/openobserve/health'],['provisioned-dashboard','/api/dashboards/uid/messenger'],['rules','/api/v1/provisioning/alert-rules']]){
|
||||
let response:Response|undefined;
|
||||
for(let attempt=0;attempt<60;attempt++){try{response=await fetch('http://127.0.0.1:28306'+path,{headers:{Authorization:auth},signal:AbortSignal.timeout(5000)});break}catch{await Bun.sleep(500)}}
|
||||
if(!response)throw Error('Native Grafana unavailable at '+name);
|
||||
const parts:Uint8Array[]=[];let length=0;
|
||||
for await(const part of response.body??[]){length+=part.length;if(length>2097152)throw Error('Grafana metadata response bound');parts.push(part)}
|
||||
const raw=Buffer.concat(parts);await writeFile(resolve(out,name+'.private.json'),raw,{flag:'wx',mode:0o600});
|
||||
let body:any;try{body=JSON.parse(raw.toString())}catch{}
|
||||
const contentMatches=name==='server'?body?.version==='13.3.1'&&body.database==='ok':name.endsWith('source')?body?.status==='OK':name==='provisioned-dashboard'?dashboardMatches(body,expectedDashboard):rulesMatch(body,expectedRules);
|
||||
checks.push({name,http:response.status,...(name==='server'?{version:body?.version,database:body?.database}:{}),...(name.endsWith('source')?{status:body?.status}:{}),...(name==='provisioned-dashboard'?{uid:body?.dashboard?.uid,panels:body?.dashboard?.panels?.length}:{}),...(name==='rules'?{count:Array.isArray(body)?body.length:null,uids:Array.isArray(body)?body.map(r=>r.uid):[]}:{}),contentMatches,pass:response.status===200&&contentMatches});
|
||||
}
|
||||
const result={checkedAt:new Date().toISOString(),checks,expectedDashboardUID:expectedDashboard.uid,expectedPanelIDs:expectedDashboard.panels.map((p:any)=>p.id),expectedRuleUIDs:expectedRules,passed:checks.every(c=>c.pass),out};
|
||||
await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify(result));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,5 @@
|
||||
import{test,expect}from'bun:test';import{dashboardMatches,rulesMatch}from'../scripts/lib/grafana-provisioning';
|
||||
const expected={uid:'messenger',panels:[{id:1,title:'RPS'},{id:2,title:'API p95'}]};
|
||||
test('accepts the actual configured dashboard and exact rule UID set',()=>{expect(dashboardMatches({dashboard:expected},expected)).toBe(true);expect(rulesMatch([{uid:'b'},{uid:'a'}],['a','b'])).toBe(true)});
|
||||
test('rejects empty or mismatched dashboard payload despite successful HTTP status',()=>{expect(dashboardMatches({},expected)).toBe(false);expect(dashboardMatches({dashboard:{uid:'other',panels:expected.panels}},expected)).toBe(false);expect(dashboardMatches({dashboard:{...expected,panels:[]}},expected)).toBe(false);expect(dashboardMatches({dashboard:{...expected,panels:[expected.panels[0],expected.panels[0]]}},expected)).toBe(false);expect(dashboardMatches({dashboard:{...expected,panels:[expected.panels[0],{id:2,title:'Wrong signal'}]}},expected)).toBe(false)});
|
||||
test('rejects absent, duplicated or wrong rule UIDs even when counts match',()=>{expect(rulesMatch([],['a','b'])).toBe(false);expect(rulesMatch([{uid:'a'},{uid:'a'}],['a','b'])).toBe(false);expect(rulesMatch([{uid:'a'},{uid:'c'}],['a','b'])).toBe(false);expect(rulesMatch([],[])).toBe(false)});
|
||||
@@ -0,0 +1,13 @@
|
||||
import{createServer}from'node:net';import{gzipSync}from'node:zlib';import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
if(process.platform!=='linux'||!process.argv.includes('--run-native'))throw new Error('Explicit native Linux fixture invocation required; no live command executed');
|
||||
const root=resolve(import.meta.dir,'..'),out=resolve(root,'.local/response-boundary-'+crypto.randomUUID()),claim=crypto.randomUUID();await mkdir(out,{mode:0o700});await writeFile(resolve(out,'CLAIM.json'),JSON.stringify({claim,kind:'temporary native HAProxy response framing test; synthetic upstream only'})+'\n',{flag:'wx',mode:0o600});
|
||||
const run=(args:string[])=>Bun.spawnSync(args,{stdout:'pipe',stderr:'pipe'}),own=run(['docker','inspect','mtuci-vp6-medvedev-observe-query-1']);if(own.exitCode!==0)throw new Error('Own gateway missing');const gateway=JSON.parse(new TextDecoder().decode(own.stdout))[0];if(gateway.Config.Labels['com.docker.compose.project']!=='mtuci-vp6-medvedev')throw new Error('Own gateway identity mismatch');const image=gateway.Image,source=await readFile(resolve(root,'config/openobserve-query.cfg'),'utf8');let cfg=source.replace('bind :5082','bind 127.0.0.1:29506').replace(/ server own openobserve:5080[^\n]*/,' server synthetic 127.0.0.1:29606');if(cfg===source||cfg.includes('server own openobserve:5080'))throw new Error('Fixture must not address real upstream');
|
||||
cfg=cfg.replace(' http-response return',' http-response set-header X-VP6-Observed-Length %[res.fhdr(Content-Length)]\n http-response set-header X-VP6-Observed-Length-Count %[res.fhdr_cnt(Content-Length)]\n http-response return');
|
||||
const configPath=resolve(out,'fixture.cfg'),usersPath=resolve(out,'users.cfg');await writeFile(configPath,cfg,{flag:'wx',mode:0o644});await writeFile(usersPath,'userlist query_users\n user fixture insecure-password fixture-only\n',{flag:'wx',mode:0o644});
|
||||
const small=Buffer.from('{"ok":true}'),sized=(n:number)=>Buffer.from('{"v":"'+'x'.repeat(n-8)+'"}');if(sized(1048576).length!==1048576)throw new Error('Fixture byte oracle invalid');
|
||||
const cases=[{id:'small',body:small,headers:['Content-Length: '+small.length],expected:[200]}, {id:'exact-cap',body:sized(1048576),headers:['Content-Length: 1048576'],expected:[200]}, {id:'cap-plus-one',body:sized(1048577),headers:['Content-Length: 1048577'],expected:[502]}, {id:'gzip',body:gzipSync(small),headers:['Content-Length: '+gzipSync(small).length,'Content-Encoding: gzip'],expected:[502]}, {id:'encoding-identity',body:small,headers:['Content-Length: '+small.length,'Content-Encoding: identity'],expected:[502]}, {id:'empty-encoding',body:small,headers:['Content-Length: '+small.length,'Content-Encoding:'],expected:[502]}, {id:'chunked',body:Buffer.from(small.length.toString(16)+'\r\n'+small+'\r\n0\r\n\r\n'),headers:['Transfer-Encoding: chunked'],expected:[502]}, {id:'eof-delimited',body:small,headers:[],expected:[502]}, {id:'duplicate-equal',body:small,headers:['Content-Length: '+small.length,'Content-Length: '+small.length],expected:[200,502],normalizationInformational:true}, {id:'duplicate-conflicting',body:small,headers:['Content-Length: '+small.length,'Content-Length: '+(small.length+1)],expected:[502]}, {id:'leading-zero',body:small,headers:['Content-Length: 000'+small.length],expected:[200,502],normalizationInformational:true}, {id:'invalid-length',body:small,headers:['Content-Length: abc'],expected:[502]}, {id:'length-overflow',body:small,headers:['Content-Length: 999999999999999999999999999999999999'],expected:[502]}, {id:'negative-length',body:small,headers:['Content-Length: -1'],expected:[502]}];
|
||||
const originRequests:any[]=[];const server=createServer(socket=>{let request='';socket.on('data',chunk=>{request+=chunk.toString();if(!request.includes('\r\n\r\n'))return;socket.removeAllListeners('data');const id=/fixture=([a-z0-9-]+)/.exec(request)?.[1],c=cases.find(c=>c.id===id)??cases[0];originRequests.push({id:c.id,acceptEncodingIdentity:/\r\naccept-encoding:\s*identity\r\n/i.test(request)});socket.end(Buffer.concat([Buffer.from('HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/json\r\n'+c.headers.join('\r\n')+'\r\n\r\n'),c.body]));});socket.on('error',()=>{});});await new Promise<void>((ok,fail)=>{server.once('error',fail);server.listen(29606,'127.0.0.1',ok);});let id='',primaryFailure:string|undefined,cleanup='not-started';const results:any[]=[];
|
||||
try{const launched=run(['docker','run','--detach','--rm','--pull=never','--network','host','--read-only','--cap-drop','ALL','--user','10001:10001','--label','mtuci.task=vp6-response-boundary','--label','mtuci.claim='+claim,'-v',configPath+':/fixture.cfg:ro','-v',usersPath+':/users.cfg:ro','--entrypoint','haproxy',image,'-W','-db','-f','/fixture.cfg','-f','/users.cfg']);await writeFile(resolve(out,'launch-stderr.private'),launched.stderr,{flag:'wx',mode:0o600});if(launched.exitCode!==0)throw new Error('Fixture container launch failed');id=new TextDecoder().decode(launched.stdout).trim();if(!/^[a-f0-9]{64}$/.test(id))throw new Error('Owned fixture launch identity absent');for(let attempt=0;attempt<50;attempt++){try{const r=await fetch('http://127.0.0.1:29506/api/default/streams?fixture=small',{headers:{Authorization:'Basic Zml4dHVyZTpmaXh0dXJlLW9ubHk='},signal:AbortSignal.timeout(1000)});await r.arrayBuffer();if(r.status===200)break;}catch{}if(attempt===49)throw new Error('Fixture readiness failed');await Bun.sleep(100);}
|
||||
for(const c of cases){const response=await fetch('http://127.0.0.1:29506/api/default/streams?fixture='+c.id,{headers:{Authorization:'Basic Zml4dHVyZTpmaXh0dXJlLW9ubHk=','Accept-Encoding':'gzip'},signal:AbortSignal.timeout(5000)});const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.length>1048576)throw new Error('Fixture forwarded bytes exceed boundary');let body:any;try{body=JSON.parse(new TextDecoder().decode(bytes))}catch{}const marker=body?.error==='query_response_boundary';const observedLength=response.headers.get('x-vp6-observed-length'),observedCount=response.headers.get('x-vp6-observed-length-count');const pass=(response.status!==200||observedLength===String(c.body.length)&&observedCount==='1')&&c.expected.includes(response.status)&&(response.status!==200||bytes.length===c.body.length)&&originRequests.filter(o=>o.id===c.id).every(o=>o.acceptEncodingIdentity);results.push({id:c.id,status:response.status,bytes:bytes.length,observedLength,observedCount,rawContentLengthFields:c.headers.filter(h=>h.toLowerCase().startsWith('content-length:')),expected:c.expected,aclMarker:marker,classification:response.status===200?(c.normalizationInformational?'accepted-native-normalized-bounded':'accepted-bounded'):marker?'response-acl':'native-http-rejected-without-acl-marker',normalizationInformational:c.normalizationInformational??false,pass});}}
|
||||
catch(error){primaryFailure=error instanceof Error?error.message:'fixture failed';}finally{if(id){const check=run(['docker','inspect',id]);if(check.exitCode===0){const c=JSON.parse(new TextDecoder().decode(check.stdout))[0];if(c.Id!==id||c.Image!==image||c.Config.Labels['mtuci.claim']!==claim)cleanup='ownership-mismatch';else{const log=run(['docker','logs',id]);await writeFile(resolve(out,'haproxy.private.log'),Buffer.concat([log.stdout,log.stderr]),{flag:'wx',mode:0o600});const stop=run(['docker','stop','--time','3',id]);cleanup=stop.exitCode===0?'stopped':'stop-failed';}}else cleanup='already-absent';}server.close();}
|
||||
const receipt={checkedAt:new Date().toISOString(),configSHA256:new Bun.CryptoHasher('sha256').update(source).digest('hex'),scope:'native HAProxy recognized Content-Length boundary; temporary synthetic raw HTTP upstream, no application mutation',image,results,originRequests,primaryFailure,cleanup,passed:!primaryFailure&&results.length===cases.length&&results.every(r=>r.pass)&&cleanup==='stopped'};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(out,'RESULT.json'),...receipt}));if(!receipt.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,10 @@
|
||||
import{resolve}from'node:path';import{mkdir,readFile,writeFile}from'node:fs/promises';
|
||||
if(process.argv.includes('--check')){console.log('Same-job retry telemetry reader validated without credentials or network');process.exit(0)}const root=resolve(import.meta.dir,'..'),source=resolve(process.argv[2]??'');if(process.platform!=='linux'||!source.startsWith(root+'/.local/grafana-retry-'))throw Error('Explicit owned native retry receipt required');const original=await Bun.file(resolve(source,'RESULT.json')).json();if(!original.passed||!/^[a-f0-9]{32}$/.test(original.traceId))throw Error('Successful owned retry operation receipt missing');
|
||||
const traceId=original.traceId,start=Date.parse(original.observations.find((o:any)=>o.kind==='accepted').at)-5000,end=Date.parse(original.observations.find((o:any)=>o.kind==='same-job-ready').at)+10000,out=resolve(root,'.local/grafana-retry-readback-'+crypto.randomUUID());await mkdir(out,{mode:0o700});const password=(await readFile(resolve(root,'.local/grafana_password'),'utf8')).trim(),auth='Basic '+Buffer.from('admin:'+password).toString('base64');let sequence=0;
|
||||
async function request(path:string,body:unknown){const r=await fetch('http://127.0.0.1:28306'+path,{method:'POST',headers:{Authorization:auth,'Content-Type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(15000)});const chunks:Uint8Array[]=[];let bytes=0;for await(const chunk of r.body??[]){bytes+=chunk.length;if(bytes>1048576)throw Error('Retry query response limit');chunks.push(chunk)}const raw=Buffer.concat(chunks);await writeFile(resolve(out,'response-'+(++sequence)+'.private.json'),raw,{flag:'wx',mode:0o600});if(r.status!==200)throw Error('Retry readback HTTP'+r.status);return JSON.parse(raw.toString())}
|
||||
async function search(type:string,sql:string){return(await request('/api/datasources/proxy/uid/openobserve/api/default/_search?type='+type,{query:{sql,start_time:start*1000,end_time:end*1000,size:100}})).hits}
|
||||
let rows:any[]=[],logs:any[]=[];for(let attempt=0;attempt<20;attempt++){rows=await search('traces','SELECT trace_id, span_id, reference_parent_span_id, operation_name, service_name, span_status, status_code, duration, CAST(start_time AS VARCHAR) AS start_ns, CAST(end_time AS VARCHAR) AS end_ns FROM "messenger" WHERE trace_id=\''+traceId+'\' ORDER BY start_time LIMIT 100');logs=await search('logs','SELECT trace_id, span_id, event, outcome, request_id, service_name FROM "messenger" WHERE trace_id=\''+traceId+'\' ORDER BY _timestamp LIMIT 100');if(logs.some(r=>r.event==='worker.job'&&r.outcome==='retry')&&logs.some(r=>r.event==='worker.job'&&r.outcome==='ready'))break;await Bun.sleep(1000)}
|
||||
const publishers=rows.filter(r=>r.operation_name==='attachment.publish'),consumers=rows.filter(r=>r.operation_name==='attachment.process'),publisherIDs=new Set(publishers.map(r=>r.span_id)),allIDs=new Set(rows.map(r=>r.span_id)),rootSpan=original.observations.find((o:any)=>o.kind==='accepted').traceparent.split('-')[2];
|
||||
const metrics=await request('/api/ds/query',{queries:['retry','ready'].map((outcome,i)=>({refId:i?'B':'A',datasource:{uid:'prometheus',type:'prometheus'},expr:'sum(jobs_processed{job_type="attachment.process.v1",outcome="'+outcome+'"})',instant:true,range:false,intervalMs:2000,maxDataPoints:1000})),from:String(start),to:String(end)}),metricValues=Object.fromEntries(Object.entries(metrics.results??{}).map(([key,result]:[string,any])=>[key,(result.frames??[]).flatMap((f:any)=>f.schema.fields.flatMap((field:any,i:number)=>field.type==='number'?f.data.values[i]:[])).filter((v:any)=>typeof v==='number'&&Number.isFinite(v))]));
|
||||
const validations={sameTrace:rows.length>0&&rows.every(r=>r.trace_id===traceId)&&logs.every(r=>r.trace_id===traceId),apiRoot:rows.some(r=>r.span_id===rootSpan&&r.service_name==='messenger-api'),multiplePublishAndProcess:publishers.length>=2&&consumers.length>=2,producerParents:publishers.every(r=>r.reference_parent_span_id===rootSpan),consumerParents:consumers.every(r=>publisherIDs.has(r.reference_parent_span_id)),errorStorageChild:rows.some(r=>r.operation_name==='s3.get'&&r.span_status==='ERROR'&&allIDs.has(r.reference_parent_span_id)),retryAndReadyLogs:['retry','ready'].every(outcome=>logs.some(r=>r.event==='worker.job'&&r.outcome===outcome)),retryMetric:metricValues.A?.some((v:number)=>v>=1)===true,readyMetric:metricValues.B?.some((v:number)=>v>=1)===true};
|
||||
const result={checkedAt:new Date().toISOString(),scope:'native Grafana query of same accepted job retry; no second producer/fault',source,attachmentId:original.attachmentId,traceId,window:{startMicroseconds:start*1000,endMicroseconds:end*1000},spanCount:rows.length,parentRelations:rows.filter(r=>allIDs.has(r.reference_parent_span_id)).length,spans:rows,logs,metrics:metricValues,validations,passed:Object.values(validations).every(v=>v===true),out};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({out,traceId,spanCount:rows.length,publishers:publishers.length,consumers:consumers.length,validations,passed:result.passed}));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,15 @@
|
||||
import{resolve}from'node:path';import{mkdir,readFile,writeFile}from'node:fs/promises';import{createOwnedFaultRunner,OwnedFaultFailure}from'../scripts/lib/owned-fault';import{createAccountHTTP}from'../scripts/lib/openobserve-account-http';
|
||||
if(process.argv.includes('--check')){console.log('Scoped synthetic retry entrypoint validated without credentials, Docker or mutation');process.exit(0)}if(process.platform!=='linux'||!process.argv.includes('--run-native'))throw Error('Explicit native owned retry operation required');
|
||||
const root=resolve(import.meta.dir,'..'),project='mtuci-vp6-medvedev',out=resolve(root,'.local/grafana-retry-'+crypto.randomUUID());await mkdir(out,{mode:0o700});await writeFile(resolve(out,'CLAIM.json'),JSON.stringify({root,project,checkedAt:new Date().toISOString(),scope:'one synthetic accepted job; reversible missing staging object; no DB/queue incident repeat'})+'\n',{flag:'wx',mode:0o600});let stage='ownership',failure:string|undefined,failureStage:string|undefined,cleanupFailure:string|undefined,token='',sequence=0,attachmentId='',traceId='';const observations:any[]=[];
|
||||
function command(args:string[]){const r=Bun.spawnSync(args,{cwd:root,stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw Error('Owned command failed at '+stage);return new TextDecoder().decode(r.stdout).trim()}
|
||||
function owned(service:string,id?:string){const c=JSON.parse(command(['docker','inspect',id??project+'-'+service+'-1']))[0];if(c.Config.Labels['com.docker.compose.project']!==project||c.Config.Labels['com.docker.compose.project.working_dir']!==root||c.Config.Labels['com.docker.compose.service']!==service)throw Error('Owned resource guard failed');return c}
|
||||
const worker=owned('worker'),storage=owned('s3');if(!worker.State.Running||!storage.State.Running)throw Error('Owned worker/storage must already be ready');const rawS3=JSON.parse(await readFile(resolve(root,'.local/s3_root'),'utf8')),ip=storage.NetworkSettings.Networks[project+'_private']?.IPAddress;if(!/^\d+\.\d+\.\d+\.\d+$/.test(ip??''))throw Error('Owned storage private address missing');const s3=new Bun.S3Client({endpoint:'http://'+ip+':9000',bucket:rawS3.Bucket,accessKeyId:rawS3.Access,secretAccessKey:rawS3.Secret,region:'us-east-1'});
|
||||
const identity=process.env.VP6_SECRET_IDENTITY_FILE;if(!identity?.startsWith(root+'/.local/')||!identity.endsWith('/identity.agekey'))throw Error('Explicit owned encryption identity required');async function seal(name:string,bytes:Uint8Array){const r=Bun.spawnSync(['/home/rey/.local/bin/age','--encrypt','-i',identity!],{stdin:bytes,stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw Error('Private archival failed');await writeFile(resolve(out,name+'.age'),r.stdout,{flag:'wx',mode:0o600})}
|
||||
const correlations=new Map<string,string|null>();const http=createAccountHTTP({request:async input=>{const binary=input.body instanceof Uint8Array,r=await fetch('http://127.0.0.1:28206'+input.path,{method:input.method,headers:{'Content-Type':binary?'image/png':'application/json',Authorization:input.auth??''},body:input.body===undefined?undefined:binary?input.body as Uint8Array<ArrayBuffer>:JSON.stringify(input.body),signal:AbortSignal.timeout(7000)});correlations.set(input.captureId,r.headers.get('X-Request-Id'));return{status:r.status,chunks:r.body??(async function*(){})()}},capture:async c=>{await seal(c.captureId,c.raw);await writeFile(resolve(out,c.captureId+'.meta.json'),JSON.stringify({status:c.status,outcome:c.outcome,complete:c.complete,bytes:c.raw.length})+'\n',{flag:'wx',mode:0o600})}},1048576);
|
||||
async function api(path:string,method='GET',body?:unknown,auth?:string){const captureId='response-'+String(++sequence).padStart(4,'0'),r=await http({path,method,body,auth:auth??(token?'Bearer '+token:undefined),captureId});return{...r,requestId:correlations.get(captureId)}}
|
||||
function job(){const sql="SELECT jsonb_build_object('id',j.id,'attachment_id',a.id,'status',a.status,'error_code',a.error_code,'attempt',j.attempt,'completed',j.completed,'traceparent',j.traceparent,'accepted_at',a.accepted_at,'first_ready_at',a.first_ready_at)::text FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id='"+attachmentId+"' AND j.pipeline_version=a.pipeline_version";return JSON.parse(command(['docker','exec',project+'-postgres-1','psql','-X','-U','messenger','-d','messenger','-Atq','-v','ON_ERROR_STOP=1','-c',sql]))}
|
||||
async function record(kind:string,data:any){observations.push({at:new Date().toISOString(),kind,...data});await writeFile(resolve(out,'observation-'+observations.length+'.json'),JSON.stringify(observations.at(-1),null,2)+'\n',{flag:'wx',mode:0o600})}
|
||||
try{stage='fixture-auth';const username='retry_'+crypto.randomUUID().slice(0,8),password='Aa1!'+crypto.randomUUID();await seal('fixture-auth',Buffer.from(JSON.stringify({username,password})));if((await api('/api/v1/users','POST',{username,display_name:'Owned retry fixture',password})).status!==201)throw Error('Fixture user create failed');const login=await api('/api/v1/auth/sessions','POST',undefined,'Basic '+Buffer.from(username+':'+password).toString('base64'));if(login.status!==201||typeof login.body?.token!=='string')throw Error('Fixture login failed');token=login.body.token;const chat=await api('/api/v1/chats','POST',{title:'Owned retry trace',member_ids:[login.body.user.id]});if(chat.status!==201)throw Error('Fixture chat failed');const image=await readFile(resolve(root,'tests/fixtures/sample.png'));
|
||||
await createOwnedFaultRunner({acquire:async()=>({id:worker.Id,image:worker.Image,key:'',bytes:undefined as Uint8Array|undefined,hidden:false}),exercise:async lease=>{try{stage='pause-only-owned-worker';if(owned('worker',lease.id).Image!==lease.image)throw Error('Worker image mismatch');command(['docker','stop','--time','8',lease.id]);stage='accept-one-owned-upload';const accepted=await api('/api/v1/chats/'+chat.body.id+'/attachments?filename=owned-retry.png','POST',image);if(accepted.status!==202||!/^[a-f0-9-]{36}$/.test(accepted.body?.id??''))throw Error('Synthetic upload not accepted');attachmentId=accepted.body.id;const before=job();if(before.status!=='queued'||before.attempt!==0||before.completed)throw Error('Expected durable unpublished owned job');if(!/^00-[a-f0-9]{32}-[a-f0-9]{16}-01$/.test(before.traceparent))throw Error('Accepted W3C trace context missing');traceId=before.traceparent.split('-')[1];await record('accepted',{...before,requestId:accepted.requestId,traceId});lease.key='staging/'+attachmentId;stage='read-exact-owned-staging';lease.bytes=new Uint8Array(await s3.file(lease.key).arrayBuffer());if(!Buffer.from(lease.bytes).equals(image))throw Error('Owned object differs from accepted fixture');await record('object-verified',{bytes:image.length,sha256:new Bun.CryptoHasher('sha256').update(image).digest('hex')});stage='temporary-owned-object-absence';lease.hidden=true;await s3.delete(lease.key);if(await s3.exists(lease.key))throw Error('Transient object fault not established');command(['docker','start',lease.id]);stage='observe-first-durable-retry';let retry:any;for(let i=0;i<150;i++){const current=job();if(current.attempt>=1&¤t.status==='queued'&¤t.error_code==='processing_failed'&&!current.completed){retry=current;break}if(current.status==='failed')throw Error('Unexpected permanent failure before object recovery');await Bun.sleep(100)}if(!retry)throw Error('Durable retry not observed');await record('durable-retry',retry);stage='restore-exact-owned-object';await s3.write(lease.key,lease.bytes,{type:'image/png'});if(!Buffer.from(await s3.file(lease.key).arrayBuffer()).equals(image))throw Error('Restored object bytes mismatch');lease.hidden=false;await record('object-restored',{bytes:image.length});stage='observe-same-job-ready';let ready:any;for(let i=0;i<300;i++){const current=job();if(current.status==='ready'&¤t.completed&¤t.attempt>=2){ready=current;break}if(current.status==='failed')throw Error('Retry unexpectedly permanently failed');await Bun.sleep(200)}if(!ready)throw Error('Same accepted job not ready after automatic retry');await record('same-job-ready',ready);const content=await fetch('http://127.0.0.1:28206/api/v1/attachments/'+attachmentId+'/content',{headers:{Authorization:'Bearer '+token}});if(content.status!==200||!Buffer.from(await content.arrayBuffer()).equals(image))throw Error('Recovered original bytes mismatch');}catch(error){failureStage=stage;throw error}},restore:async lease=>{stage='restore-owned-object-and-worker';const current=owned('worker',lease.id);if(current.Image!==lease.image||owned('s3',storage.Id).Image!==storage.Image)throw Error('Restore ownership image mismatch');if(lease.hidden&&lease.bytes){await s3.write(lease.key,lease.bytes,{type:'image/png'});lease.hidden=false}if(!current.State.Running)command(['docker','start',lease.id]);}})();
|
||||
}catch(e){failureStage??=stage;failure=e instanceof OwnedFaultFailure?'Owned retry operation failed':e instanceof Error?e.message:'Retry failed';if(e instanceof OwnedFaultFailure&&e.cleanup!==undefined)cleanupFailure='Owned object/worker restore failed';}finally{if(token)try{if((await api('/api/v1/auth/sessions/current','DELETE')).status!==204)cleanupFailure='Synthetic session revocation failed'}catch{cleanupFailure='Synthetic session revocation failed'}}
|
||||
const result={checkedAt:new Date().toISOString(),project,stage,failureStage,attachmentId,traceId,observations,failure,cleanupFailure,passed:!failure&&!cleanupFailure,out};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({out,stage,attachmentId,traceId,failure,cleanupFailure,passed:result.passed}));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,4 @@
|
||||
import{test,expect}from'bun:test';import{validateGrafanaRuleIntervals}from'../scripts/lib/grafana-scheduler';
|
||||
test('rejects actual provisioning failure1s under native13.3.1 scheduler10s',()=>{expect(()=>validateGrafanaRuleIntervals([{interval:'1s'}],10)).toThrow();});
|
||||
test('rejects zero and nonmultiple intervals before native startup',()=>{for(const interval of['0s','15s','unknown'])expect(()=>validateGrafanaRuleIntervals([{interval}],10)).toThrow();});
|
||||
test('accepts native10s and its20s multiple',()=>{expect(()=>validateGrafanaRuleIntervals([{interval:'10s'},{interval:'20s'}],10)).not.toThrow();});
|
||||
@@ -0,0 +1,7 @@
|
||||
import{test,expect}from'bun:test';import{readyIncidentObserved,drained}from'../scripts/lib/incident-readback';
|
||||
const fact={id:'own',status:'ready',accepted_at:'2026-11-16T04:14:31Z',first_ready_at:'2026-11-16T04:15:22Z',ready_seconds:51},stop='2026-11-16T04:14:30Z',start='2026-11-16T04:15:16Z';
|
||||
const sample=(at:string,phase='worker_recovery')=>({at,phase,rules:[{name:'MessengerReadyErrorBudgetBurn',state:'Alerting'}]});
|
||||
test('recognizes firing while the same accepted backlog is recovering after process start',()=>{expect(readyIncidentObserved([sample('2026-11-16T04:15:19Z')],[fact],['own'],stop,start)).toBe(true)});
|
||||
test('accepts firing during worker stop and requires the complete owned late-job cohort',()=>{expect(readyIncidentObserved([sample('2026-11-16T04:15:10Z','worker_stopped')],[fact],['own'],stop,start)).toBe(true);expect(readyIncidentObserved([sample('2026-11-16T04:15:10Z','worker_stopped')],[],['own'],stop,start)).toBe(false)});
|
||||
test('rejects an unrelated later alert or timely successful workload',()=>{expect(readyIncidentObserved([sample('2026-11-16T04:17:19Z')],[fact],['own'],stop,start)).toBe(false);expect(readyIncidentObserved([sample('2026-11-16T04:15:19Z')],[{...fact,ready_seconds:2}],['own'],stop,start)).toBe(false)});
|
||||
test('queue drain needs actual finite samples rather than empty NoData',()=>{expect(drained([])).toBe(false);expect(drained([0])).toBe(true);expect(drained([0,1])).toBe(false);expect(drained([NaN])).toBe(false)});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createAccountHTTP, type AccountCapture } from '../scripts/lib/openobserve-account-http';
|
||||
const request={captureId:'fixture-create',path:'/api/default/service_accounts',method:'POST',body:{email:'fixture@example.invalid'},auth:'fixture-only'};
|
||||
const bytes=(value:string)=>new TextEncoder().encode(value);
|
||||
test('malformed one-time response is captured before JSON decoding fails',async()=>{
|
||||
const captures:AccountCapture[]=[];const raw=bytes('{"token":"fixture-once",');
|
||||
const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield raw})()}),capture:async r=>{captures.push(r)}},1000);
|
||||
await expect(call(request)).rejects.toThrow();expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(raw);expect(captures[0].status).toBe(200);
|
||||
});
|
||||
test('partial response is retained as uncertain when body reading fails',async()=>{
|
||||
const captures:AccountCapture[]=[];const raw=bytes('{"token":"fixture-partial');
|
||||
const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield raw;throw new Error('synthetic truncated body')})()}),capture:async r=>{captures.push(r)}},1000);
|
||||
await expect(call(request)).rejects.toThrow();expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(raw);expect(captures[0].complete).toBe(false);expect(captures[0].outcome).toBe('body_uncertain');
|
||||
});
|
||||
test('oversized response retains bounded available bytes before reporting its cap',async()=>{
|
||||
const captures:AccountCapture[]=[];const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield bytes('123456')})()}),capture:async r=>{captures.push(r)}},4);
|
||||
await expect(call(request)).rejects.toThrow();expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(bytes('1234'));expect(captures[0].outcome).toBe('size_exceeded');expect(captures[0].complete).toBe(false);
|
||||
});
|
||||
test('network failure records uncertain request without retry',async()=>{
|
||||
const captures:AccountCapture[]=[];let calls=0;const call=createAccountHTTP({request:async()=>{calls++;throw new Error('synthetic network failure')},capture:async r=>{captures.push(r)}},1000);
|
||||
await expect(call(request)).rejects.toThrow();expect(calls).toBe(1);expect(captures).toHaveLength(1);expect(captures[0].status).toBeNull();expect(captures[0].outcome).toBe('network_uncertain');
|
||||
});
|
||||
test('valid response is captured before it is returned to the create caller',async()=>{
|
||||
const captures:AccountCapture[]=[];const raw=bytes('{"code":200,"token":"fixture-valid"}');const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield raw})()}),capture:async r=>{captures.push(r)}},1000);
|
||||
const result=await call(request);expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(raw);expect(result.body.token).toBe('fixture-valid');
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createAccountBootstrap, accountEmail, type Account, type AccountKey, type Intent, type Capability, type BootstrapPorts } from '../scripts/lib/openobserve-bootstrap';
|
||||
const account=(key:AccountKey):Account=>({email:accountEmail(key),token:'fixture-'+key+'-token-only'});
|
||||
function fixture() {
|
||||
const checkpoints:Partial<Record<AccountKey,Account>>={},intents:Partial<Record<AccountKey,Intent>>={},captured:Record<string,any>={},creates:AccountKey[]=[];
|
||||
let index:Record<AccountKey,Account>|undefined,derived=0,published=0,failCreate:AccountKey|undefined,proof:Partial<Capability>={},persistedBeforeQuery=false;
|
||||
const ports:BootstrapPorts={readIndex:async()=>index,readAccount:async k=>checkpoints[k],readIntent:async k=>intents[k],makeIntent:k=>({email:accountEmail(k),rawFile:'/fake/'+k,captureId:'create-'+k}),claimIntent:async(k,v)=>{if(intents[k])throw new Error('claim exists');intents[k]=v;},readCaptured:async i=>captured[i.rawFile],create:async(k)=>{creates.push(k);if(k==='query')persistedBeforeQuery=!!checkpoints.ingest;if(k===failCreate)throw new Error('synthetic second create failure');return{status:200,body:{code:200,user:accountEmail(k),token:account(k).token}};},saveAccount:async(k,a)=>{checkpoints[k]=a;},verify:async()=>({role:'service_account',searchHTTP:200,searchHasRows:true,ingestHTTP:200,adminRotateHTTP:403,...proof}),publishIndex:async a=>{published++;index=a;},publishDerived:async()=>{derived++;}};
|
||||
return{ports,checkpoints,intents,captured,creates,setIndex(v:Record<AccountKey,Account>){index=v;},fail(k:AccountKey){failCreate=k;},setProof(v:Partial<Capability>){proof=v;},get derived(){return derived},get published(){return published},get persistedBeforeQuery(){return persistedBeforeQuery}};
|
||||
}
|
||||
test('first received credential survives a second account creation failure',async()=>{const f=fixture();f.fail('query');await expect(createAccountBootstrap(f.ports)()).rejects.toThrow();expect(f.checkpoints.ingest).toEqual(account('ingest'));expect(f.derived).toBe(0);});
|
||||
test('resume reuses one persisted credential instead of repeating its account POST',async()=>{const f=fixture();f.checkpoints.ingest=account('ingest');await createAccountBootstrap(f.ports)();expect(f.creates).toEqual(['query']);});
|
||||
test('resume recovers a valid captured response without repeating account POST',async()=>{const f=fixture();f.intents.ingest=f.ports.makeIntent('ingest');f.captured['/fake/ingest']={status:200,body:{code:200,user:accountEmail('ingest'),token:account('ingest').token}};await createAccountBootstrap(f.ports)();expect(f.creates).toEqual(['query']);expect(f.checkpoints.ingest).toEqual(account('ingest'));});
|
||||
test('uncertain intent without recoverable native JSON fails closed without POST retry',async()=>{const f=fixture();f.intents.ingest=f.ports.makeIntent('ingest');await expect(createAccountBootstrap(f.ports)()).rejects.toThrow();expect(f.creates).toHaveLength(0);expect(f.published).toBe(0);expect(f.derived).toBe(0);});
|
||||
for(const [name,proof]of [['stale search token401',{searchHTTP:401}],['unavailable ingest503',{ingestHTTP:503}],['rotation401 is not the required403 denial',{adminRotateHTTP:401}]] as const){test(name+' prevents derived publication and successful continuation',async()=>{const f=fixture();f.setIndex({ingest:account('ingest'),query:account('query')});f.setProof(proof);let started=false;await expect((async()=>{await createAccountBootstrap(f.ports)();started=true;})()).rejects.toThrow();expect(f.derived).toBe(0);expect(started).toBe(false);});}
|
||||
test('healthy initial bootstrap checkpoints ingest before starting query creation',async()=>{const f=fixture();await createAccountBootstrap(f.ports)();expect(f.persistedBeforeQuery).toBe(true);expect(f.published).toBe(1);expect(f.derived).toBe(1);});
|
||||
test('healthy saved index revalidates both native identities without new account POST',async()=>{const f=fixture();f.setIndex({ingest:account('ingest'),query:account('query')});await createAccountBootstrap(f.ports)();expect(f.creates).toHaveLength(0);expect(f.derived).toBe(1);});
|
||||
@@ -0,0 +1,2 @@
|
||||
import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),out=resolve(root,'.local/openobserve-cohort-query-'+crypto.randomUUID());await mkdir(out,{mode:0o700});const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64'),queries=['ready_slo_matured_300s','ready_slo_timely_300s','database_observer_up','timestamp(ready_slo_matured_300s)>time()-10','ready_slo_matured_300s-ready_slo_timely_300s','ready_slo_matured_300s and on(service_name,service_instance_id) (database_observer_up == 1)','(ready_slo_matured_300s-ready_slo_timely_300s)/clamp_min(ready_slo_matured_300s,1)','ready_slo_matured_300s and on(service_name,service_instance_id) (timestamp(ready_slo_matured_300s)>time()-10)'];const results=[];for(const query of queries){const r=await fetch('http://127.0.0.1:28906/api/default/prometheus/api/v1/query?'+new URLSearchParams({query,time:'1794784832'}),{headers:{Authorization:auth},signal:AbortSignal.timeout(12000)});const j=await r.json();results.push({query,http:r.status,status:j.status,result:j.data?.result});}await writeFile(resolve(out,'RESULT.json'),JSON.stringify({checkedAt:new Date().toISOString(),time:1794784832,results},null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(out,'RESULT.json'),results}));
|
||||
@@ -0,0 +1,4 @@
|
||||
import{mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),phase=process.argv[2];if(!['before','down','recovered'].includes(phase))throw new Error('explicit fault phase required');const inspect=Bun.spawnSync(['docker','inspect','mtuci-vp6-medvedev-otel-collector-1'],{stdout:'pipe',stderr:'pipe'});if(inspect.exitCode!==0)throw new Error('own Collector absent');const n=JSON.parse(new TextDecoder().decode(inspect.stdout))[0];if(n.Config.Labels['com.docker.compose.project']!=='mtuci-vp6-medvedev'||n.Config.Labels['com.docker.compose.service']!=='otel-collector'||!n.State.Running)throw new Error('own running Collector identity mismatch');
|
||||
const response=await fetch('http://127.0.0.1:28806/metrics',{signal:AbortSignal.timeout(2000)});if(!response.ok)throw new Error('native Collector metrics unavailable');let raw=new Uint8Array();for await(const part of response.body??[]){if(raw.length+part.length>1_048_576)throw new Error('Collector metrics cap');const next=new Uint8Array(raw.length+part.length);next.set(raw);next.set(part,raw.length);raw=next;}const totals:Record<string,number>={};for(const line of new TextDecoder().decode(raw).split('\n')){const m=line.match(/^(otelcol_[A-Za-z0-9_]+)(?:\{[^}]*\})?\s+([+\-0-9.eE]+)(?:\s+\d+)?$/);if(m&&/^otelcol_(receiver_(accepted|refused)|exporter_(sent|send_failed|queue_size|queue_capacity)|process_memory)/.test(m[1])){const value=Number(m[2]);if(Number.isFinite(value))totals[m[1]]=(totals[m[1]]??0)+value;}}
|
||||
const stats=Bun.spawnSync(['docker','stats','--no-stream','--format','{{.MemUsage}}',n.Id],{stdout:'pipe',stderr:'pipe'});if(stats.exitCode!==0)throw new Error('own Collector memory snapshot failed');const memory=new TextDecoder().decode(stats.stdout).trim();if(!/^[0-9.]+[kMGTiB]+ \/ [0-9.]+[kMGTiB]+$/.test(memory))throw new Error('unexpected native memory format');const result={checkedAt:new Date().toISOString(),phase,containerId:n.Id,memoryLimitBytes:n.HostConfig.Memory,oomKilled:n.State.OOMKilled,memory,aggregateCountersAcrossComponents:totals,uniqueLossCountClaimed:false};const path=resolve(root,'evidence/openobserve/collector-'+phase+'-'+crypto.randomUUID()+'.json');await mkdir(resolve(root,'evidence/openobserve'),{recursive:true});await writeFile(path,JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:path,...result}));
|
||||
@@ -0,0 +1,18 @@
|
||||
import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-parser-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query;const auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64'),base='http://127.0.0.1:28906',now=Date.now()*1000;
|
||||
const q=(size=1)=>({query:{sql:'SELECT trace_id FROM "messenger" LIMIT 2',start_time:now-300_000_000,end_time:now,size}});const encoded=JSON.stringify(q());const cases=[
|
||||
{name:"reverse duplicate values size rejected",path:"/api/default/messenger/_values?fields=service_name&start_time="+(now-300_000_000)+"&end_time="+now+"&size=1001&size=1&type=logs",expected:400},
|
||||
{name:"duplicate JSON query objects rejected",path:"/api/default/_search?type=traces",body:encoded.slice(0,-1)+",\"query\":"+JSON.stringify(q(1001).query)+"}",expected:400},
|
||||
{name:"fractional inverted subsecond window rejected",path:"/api/default/prometheus/api/v1/query_range?"+new URLSearchParams({query:"vector(1)",start:String(Math.floor(now/1e6)+0.9),end:String(Math.floor(now/1e6)+0.1),step:"1"}),expected:400},
|
||||
{name:'duplicate values size rejected',path:'/api/default/messenger/_values?fields=service_name&start_time='+(now-300_000_000)+'&end_time='+now+'&size=1&size=1001&type=logs',expected:400},
|
||||
{name:'encoded duplicate values size rejected',path:'/api/default/messenger/_values?fields=service_name&start_time='+(now-300_000_000)+'&end_time='+now+'&size=1&%73ize=1001&type=logs',expected:400},
|
||||
{name:'duplicate JSON size rejected',path:'/api/default/_search?type=traces',body:encoded.replace('"size":1','"size":1,"size":1001'),expected:400},
|
||||
{name:'encoded duplicate JSON size rejected',path:'/api/default/_search?type=traces',body:encoded.replace('"size":1','"size":1,"\\u0073ize":1001'),expected:400},
|
||||
{name:'fractional window greater than1hour rejected',path:'/api/default/prometheus/api/v1/query_range?'+new URLSearchParams({query:'max(database_observer_up)',start:String(Math.floor(now/1e6)-3600),end:String(Math.floor(now/1e6)+0.5),step:'60'}),expected:400},
|
||||
{name:'native SQL LIMIT controls row count',path:'/api/default/_search?type=traces',body:encoded,expected:200,maxRows:2}
|
||||
];const results:any[]=[];
|
||||
for(const c of cases){const response=await fetch(base+c.path,{method:c.body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:c.body,signal:AbortSignal.timeout(12_000)});const body=await response.text();let rows:number|undefined;try{rows=JSON.parse(body).hits?.length}catch{}results.push({name:c.name,expected:c.expected,actual:response.status,rows,maxRows:c.maxRows,pass:(c.name.includes('duplicate JSON')?[400,422].includes(response.status):response.status===c.expected)&&(c.maxRows===undefined||rows===c.maxRows)});}
|
||||
async function raw(name:string,headers:string,body:string,expected:number[],tail='',delay=0){const start=performance.now();let socket:any;let tailTimer:ReturnType<typeof setTimeout>|undefined;let result:string='';await new Promise<void>((done,fail)=>{const timeout=setTimeout(()=>{socket?.terminate();fail(new Error('raw parser boundary exceeded14seconds'));},14_000);Bun.connect({hostname:'127.0.0.1',port:28906,socket:{open(s){socket=s;s.write('POST /api/default/_search?type=traces HTTP/1.1\r\nHost: own-query\r\nAuthorization: '+auth+'\r\nContent-Type: application/json\r\nConnection: close\r\n'+headers+'\r\n'+body);if(tail)tailTimer=setTimeout(()=>s.write(tail),delay);},data(s,b){result+=new TextDecoder().decode(b);if(result.length>1_048_576){clearTimeout(timeout);s.terminate();fail(new Error('raw parser response cap'));}},close(){clearTimeout(timeout);if(tailTimer)clearTimeout(tailTimer);done();},error(){clearTimeout(timeout);if(tailTimer)clearTimeout(tailTimer);fail(new Error('raw parser socket failure'));}}}).catch(()=>{clearTimeout(timeout);fail(new Error('raw parser connect failure'));});});const actual=Number(result.match(/^HTTP\/\S+ (\d{3})/)?.[1]??0);results.push({name,expected,actual,elapsedMs:Math.round(performance.now()-start),pass:expected.includes(actual)});}
|
||||
const chunk=(s:string)=>Buffer.byteLength(s).toString(16)+'\r\n'+s+'\r\n';await raw('complete chunked JSON remains usable','Transfer-Encoding: chunked\r\n',chunk(encoded)+'0\r\n\r\n',[200]);await raw('oversized chunked JSON rejected','Transfer-Encoding: chunked\r\n',chunk(JSON.stringify({...q(),padding:'x'.repeat(150_000)}))+'0\r\n\r\n',[413]);await raw('incomplete body explicitly fails within transport budget','Content-Length: 500\r\n',encoded,[400,408,413,504]);
|
||||
await raw("delayed chunked oversize rejects beyond inspection timeout","Transfer-Encoding: chunked\r\n",chunk(encoded),[408,413],chunk(" ".repeat(150_000))+"0\r\n\r\n",2200);
|
||||
await writeFile(resolve(output,'RESULT.json'),JSON.stringify({checkedAt:new Date().toISOString(),base,results,output},null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),results}));if(results.some(r=>!r.pass))process.exitCode=1;
|
||||
@@ -0,0 +1,28 @@
|
||||
import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),baseline=process.argv.includes('--baseline'),base=baseline?'http://127.0.0.1:28406':'http://127.0.0.1:28906',output=resolve(root,'.local/openobserve-gateway-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const accounts=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8'));const auth=(label:string)=>'Basic '+Buffer.from(accounts[label].email+':'+accounts[label].token).toString('base64');
|
||||
const now=Date.now()*1000;const query=(size:number,start=now-300_000_000,end=now)=>({query:{sql:'SELECT trace_id FROM "messenger" LIMIT 1',start_time:start,end_time:end,size}});
|
||||
const cases=baseline?[{name:'query principal cannot ingest',path:'/api/default/identity_probe/_json',method:'POST',body:[{event:'owned_query_baseline_red'}],expected:403}]:[
|
||||
{name:'query native search',path:'/api/default/_search?type=traces',method:'POST',body:query(100),expected:200},
|
||||
{name:'query native PromQL',path:'/api/default/prometheus/api/v1/query?query=max(database_observer_up)',expected:200},
|
||||
{name:'editor organizations',path:'/api/organizations?page_num=0&page_size=1000',expected:200},
|
||||
{name:'editor streams',path:'/api/default/streams?type=traces&fetchSchema=false',expected:200},
|
||||
{name:"editor values",path:"/api/default/messenger/_values?"+new URLSearchParams({fields:"service_name",start_time:String(now-300_000_000),end_time:String(now),size:"50",type:"logs"}),expected:200},
|
||||
{name:"values over1000 limit denied",path:"/api/default/messenger/_values?"+new URLSearchParams({fields:"service_name",start_time:String(now-300_000_000),end_time:String(now),size:"1001",type:"logs"}),expected:400},
|
||||
{name:"values over1hour window denied",path:"/api/default/messenger/_values?"+new URLSearchParams({fields:"service_name",start_time:String(now-3_600_000_001),end_time:String(now),size:"50",type:"logs"}),expected:400},
|
||||
{name:"PromQL bounded range with fractional epoch",path:"/api/default/prometheus/api/v1/query_range?"+new URLSearchParams({query:"max(database_observer_up)",start:String(now/1e6-60),end:String(now/1e6),step:"1"}),expected:200},
|
||||
{name:"PromQL over1hour window denied",path:"/api/default/prometheus/api/v1/query_range?"+new URLSearchParams({query:"max(database_observer_up)",start:String(now/1e6-7200),end:String(now/1e6),step:"60"}),expected:400},
|
||||
{name:'editor schema',path:'/api/default/streams/messenger/schema?type=traces',expected:200},
|
||||
{name:'query principal cannot ingest',path:'/api/default/identity_probe/_json',method:'POST',body:[{event:'owned_query_gateway_negative'}],expected:403},
|
||||
{name:'query principal cannot read admin users',path:'/api/default/users',expected:403},
|
||||
{name:'query principal cannot select another organization',path:'/api/other/streams',expected:403},
|
||||
{name:'query principal cannot write stream settings',path:'/api/default/streams/messenger/settings',method:'PUT',body:{},expected:403},
|
||||
{name:'ingest principal cannot use query gateway',path:'/api/default/streams',principal:'ingest',expected:401},
|
||||
{name:'anonymous cannot use query gateway',path:'/api/default/streams',principal:'anonymous',expected:401},
|
||||
{name:'native zero size allowed within finite response and query budgets',path:'/api/default/_search?type=traces',method:'POST',body:query(0),expected:200},
|
||||
{name:'over1000 result limit denied',path:'/api/default/_search?type=traces',method:'POST',body:query(1001),expected:400},
|
||||
{name:'inverted time window denied',path:'/api/default/_search?type=traces',method:'POST',body:query(10,now,now-1),expected:400},
|
||||
{name:'over1hour time window denied',path:'/api/default/_search?type=traces',method:'POST',body:query(10,now-3_600_000_001),expected:400},
|
||||
{name:'oversized search body denied',path:'/api/default/_search?type=traces',method:'POST',body:{...query(10),padding:'x'.repeat(70_000)},expected:413}
|
||||
];
|
||||
const results=[];for(const c of cases){const principal=(c as any).principal??'query';const r=await fetch(base+c.path,{method:c.method??'GET',headers:{'Content-Type':'application/json',...(principal==='anonymous'?{}:{Authorization:auth(principal)})},body:c.body===undefined?undefined:JSON.stringify(c.body),redirect:'manual',signal:AbortSignal.timeout(12_000)});await r.arrayBuffer();results.push({name:c.name,expected:c.expected,actual:r.status,pass:r.status===c.expected});}
|
||||
const result={checkedAt:new Date().toISOString(),base,baseline,nativeRole:'service_account',nativeReadOnly:false,results,output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),baseline,results}));if(results.some(r=>!r.pass))process.exitCode=1;
|
||||
@@ -0,0 +1,7 @@
|
||||
import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),fixtureBytes=await readFile(resolve(root,'evidence/openobserve/native-signals-sa.json')),fixture=JSON.parse(fixtureBytes.toString());const end=fixture.spans.reduce((n:bigint,s:any)=>BigInt(s.endTimeNs)>n?BigInt(s.endTimeNs):n,0n),base=Number(end/1_000_000_000n);if(!Number.isSafeInteger(base)||base<=0)throw new Error('Persisted native trace generation required');
|
||||
const output=resolve(root,'.local/openobserve-historical-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const account=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(account.email+':'+account.token).toString('base64');
|
||||
const dashboard=JSON.parse(await readFile(resolve(root,'config/grafana/dashboards/messenger.json'),'utf8')),rules:any=Bun.YAML.parse(await readFile(resolve(root,'config/grafana/provisioning/alerting/rules.yaml'),'utf8'));const provisioned=[...dashboard.panels.flatMap((p:any)=>p.targets.map((q:any)=>({id:'panel-'+p.id,query:q.expr}))),...rules.groups.flatMap((g:any)=>g.rules.map((r:any)=>({id:r.uid,query:r.data.find((q:any)=>q.refId==='A').model.expr})))];
|
||||
const controls=[{id:'http-actual-labels',query:'sum by(method,route,status_class,service_name)(http_requests)'},{id:'job-actual-labels',query:'sum by(job_type,outcome,service_name)(jobs_processed)'},{id:'cohort-matured',query:'max(ready_slo_matured_300s)'},{id:'cohort-timely',query:'max(ready_slo_timely_300s)'}];const results=[];
|
||||
for(const offset of[5,40])for(const q of[...provisioned,...controls]){const time=base+offset,response=await fetch('http://127.0.0.1:28906/api/default/prometheus/api/v1/query?'+new URLSearchParams({query:q.query,time:String(time)}),{headers:{Authorization:auth},signal:AbortSignal.timeout(12_000)});const raw=new Uint8Array(await response.arrayBuffer());if(raw.length>1_048_576)throw new Error('Historical native query response bound');await writeFile(resolve(output,q.id+'-'+offset+'.private.json'),raw,{flag:'wx',mode:0o600});let body:any;try{body=JSON.parse(new TextDecoder().decode(raw))}catch{}const samples=(body?.data?.result??[]).map((v:any)=>({labels:v.metric,value:Number(v.value?.[1]),finite:Number.isFinite(Number(v.value?.[1]))}));results.push({id:q.id,query:q.query,time,offset,http:response.status,status:body?.status,samples,finiteNonempty:samples.length>0&&samples.every((v:any)=>v.finite)});}
|
||||
const result={checkedAt:new Date().toISOString(),scope:'Native persisted data at actual original generation; no new producer, Grafana not run',fixtureSHA256:new Bun.CryptoHasher('sha256').update(fixtureBytes).digest('hex'),traceId:fixture.traceId,base,results,output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),summary:results.map(r=>({id:r.id,offset:r.offset,http:r.http,finite:r.finiteNonempty,values:r.samples.map((s:any)=>s.value),labels:r.id.includes('labels')?r.samples.map((s:any)=>s.labels):undefined}))}));
|
||||
@@ -0,0 +1,4 @@
|
||||
import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-instant-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64');const now=Date.now(),cases:[string,string|null][]=[['absent',null],['unix-integer-seconds',String(Math.floor(now/1000))],['unix-fractional-seconds',String(now/1000)],['unix-milliseconds',String(now)],['unix-microseconds',String(now*1000)],['RFC3339',new Date(now).toISOString()]],results=[];
|
||||
for(const [kind,time]of cases){const params=new URLSearchParams({query:'vector(1)'});if(time!==null)params.set('time',time);const r=await fetch('http://127.0.0.1:28906/api/default/prometheus/api/v1/query?'+params,{headers:{Authorization:auth},signal:AbortSignal.timeout(10_000)});const raw=new Uint8Array(await r.arrayBuffer());await writeFile(resolve(output,kind+'.private'),raw,{flag:'wx',mode:0o600});let body:any;try{body=JSON.parse(new TextDecoder().decode(raw))}catch{}const text=new TextDecoder().decode(raw);const errorCategory=['Failed to deserialize query string','invalid type','expected a string','invalid time format','missing field','duplicate field'].filter(s=>text.includes(s));results.push({kind,time,httpStatus:r.status,contentType:r.headers.get('Content-Type'),status:['success','error'].includes(body?.status)?body.status:null,errorCategory,responseBytes:raw.length,value:body?.data?.result?.[0]?.value??body?.data?.result??null});}
|
||||
await writeFile(resolve(output,'RESULT.json'),JSON.stringify({checkedAt:new Date().toISOString(),query:'vector(1)',results,output},null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),results}));
|
||||
@@ -0,0 +1,7 @@
|
||||
import {writeFile,mkdir} from 'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..');const phase=process.argv[2];if(!['after'].includes(phase))throw new Error('Explicit final owned network case required');
|
||||
const inspect=(name:string)=>{const r=Bun.spawnSync(['docker','inspect',name],{stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw new Error('Owned container absent');return JSON.parse(new TextDecoder().decode(r.stdout))[0];};
|
||||
const oo=inspect('mtuci-vp6-medvedev-openobserve-1'),gw=inspect('mtuci-vp6-medvedev-observe-query-1');for(const c of[oo,gw])if(!c.State.Running||c.Config.Labels['com.docker.compose.project']!=='mtuci-vp6-medvedev')throw new Error('Owned project identity mismatch');if(oo.Image!=='sha256:26618f379c86b253c0d91624c487dd14b71293699845ecbc8457c94dca14819f')throw new Error('Storage image mismatch');
|
||||
const raw=oo.NetworkSettings.Networks['mtuci-vp6-medvedev_telemetry-data']?.IPAddress;if(!raw||Object.keys(oo.NetworkSettings.Networks).some(n=>!["mtuci-vp6-medvedev_telemetry-data","mtuci-vp6-medvedev_edge"].includes(n))||!gw.NetworkSettings.Networks['mtuci-vp6-medvedev_grafana-query-v2'])throw new Error('Network isolation not configured');
|
||||
const out=resolve(root,'.local/network-'+crypto.randomUUID());await mkdir(out,{mode:0o700});
|
||||
const run=Bun.spawnSync(['docker','run','--pull=never','--rm','--read-only','--cap-drop','ALL','--user','1000:1000','--label','mtuci.task=vp6-network-check','--network','mtuci-vp6-medvedev_grafana-query-v2','--env-file',resolve(root,'.local/grafana-openobserve.env'),'--env','VP_NETWORK_PHASE=after','--env','VP_RAW_OO_IP='+raw,'--env','VP_HOST_GATEWAY=172.23.0.1','-v',resolve(root,'student-tests/openobserve-network.ts')+':/probe.ts:ro','-v',out+':/out','--entrypoint','/usr/local/bin/bun','sha256:9e123d5fc069e29d519fd4c981afb61b8542ac80274771961136db1e4538d53e','/probe.ts'],{stdout:'pipe',stderr:'pipe'});await writeFile(resolve(out,'stdout.txt'),run.stdout,{flag:'wx',mode:0o600});await writeFile(resolve(out,'stderr.txt'),run.stderr,{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(out,'network-after.json'),exitCode:run.exitCode}));process.exitCode=run.exitCode??1;
|
||||
@@ -0,0 +1,6 @@
|
||||
import{writeFile}from'node:fs/promises';
|
||||
const phase=process.env.VP_NETWORK_PHASE;if(!['before','after'].includes(phase??''))throw new Error('explicit owned network phase required');const user=process.env.O2_QUERY_USER,password=process.env.O2_QUERY_PASSWORD,rawIP=process.env.VP_RAW_OO_IP,gateway=process.env.VP_HOST_GATEWAY;if(!user||!password||!/^\d+\.\d+\.\d+\.\d+$/.test(rawIP??'')||!/^\d+\.\d+\.\d+\.\d+$/.test(gateway??''))throw new Error('owned query principal/network metadata missing');const auth='Basic '+Buffer.from(user+':'+password).toString('base64');
|
||||
async function request(name:string,url:string,body?:unknown){let status=0,rows=false;try{const r=await fetch(url,{method:body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(2000)});status=r.status;const text=await r.text();try{const parsed=JSON.parse(text);rows=Array.isArray(parsed.hits)&&parsed.hits.length>0}catch{}}catch{}return{name,httpStatus:status,hasRows:rows};}
|
||||
const now=Date.now()*1000;const search={query:{sql:'SELECT event FROM "identity_probe" LIMIT 1',start_time:now-1_800_000_000,end_time:now+1_000_000,size:1}};
|
||||
const results=[await request('query gateway positive','http://observe-query:5082/api/default/_search?type=logs',search),await request('raw OpenObserve read by IP','http://'+rawIP+':5080/api/default/streams'),await request('raw OpenObserve write by IP','http://'+rawIP+':5080/api/default/identity_probe/_json',[{event:'owned_network_boundary_control'}]),await request('host gateway cannot use loopback-published raw port','http://'+gateway+':28406/api/default/streams'),await request('Collector cannot be used as ingest bypass','http://otel-collector:4318/v1/traces',{})];
|
||||
const passed=results[0].httpStatus===200&&results[0].hasRows&&(phase==='before'?results[1].httpStatus===0&&results[2].httpStatus===0:results.slice(1).every(r=>r.httpStatus===0));const result={checkedAt:new Date().toISOString(),phase,scope:'unprivileged cached client on the actual configured Grafana network using actual query SA; Grafana binary not run',results,passed};await writeFile('/out/network-'+phase+'.json',JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify(result));if(!passed)process.exitCode=1;
|
||||
@@ -0,0 +1,7 @@
|
||||
import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),fixture=JSON.parse(await readFile(resolve(root,'evidence/openobserve/native-signals-sa.json'),'utf8')),after=process.argv[2]==='--after';const output=after?resolve(process.argv[3]??''):resolve(root,'.local/openobserve-persisted-'+crypto.randomUUID());if(!output.startsWith(root+'/.local/openobserve-persisted-'))throw new Error('owned persistence receipt path required');if(!after)await mkdir(output,{mode:0o700});
|
||||
const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64');const begin=fixture.spans.reduce((n:bigint,s:any)=>BigInt(s.startTimeNs)<n?BigInt(s.startTimeNs):n,BigInt(fixture.spans[0].startTimeNs)),end=fixture.spans.reduce((n:bigint,s:any)=>BigInt(s.endTimeNs)>n?BigInt(s.endTimeNs):n,0n),startMicros=Number(begin/1000n)-1_000_000,endMicros=Number(end/1000n)+1_000_000;if(!Number.isSafeInteger(startMicros)||!Number.isSafeInteger(endMicros)||startMicros<=0||endMicros<=startMicros||endMicros-startMicros>3_600_000_000)throw new Error('exact persisted fixture window invalid');
|
||||
async function request(path:string,body?:unknown){const response=await fetch('http://127.0.0.1:28906'+path,{method:body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(12_000)});const raw=new Uint8Array(await response.arrayBuffer());if(raw.length>1_048_576)throw new Error('persistence response cap');if(response.status!==200)throw new Error('native persisted read HTTP'+response.status);return JSON.parse(new TextDecoder().decode(raw));}
|
||||
const trace=await request('/api/default/_search?type=traces',{query:{sql:`SELECT trace_id,span_id,reference_parent_span_id,operation_name FROM "messenger" WHERE trace_id='${fixture.traceId}' ORDER BY span_id LIMIT 100`,start_time:startMicros,end_time:endMicros,size:100}});if(trace.hits?.length!==fixture.spanCount||new Set(trace.hits.map((s:any)=>s.span_id)).size!==fixture.spanCount)throw new Error('persisted exact trace span set absent');const logs=await request('/api/default/_search?type=logs',{query:{sql:`SELECT trace_id,span_id,event,service_name,request_id FROM "messenger" WHERE trace_id='${fixture.traceId}' ORDER BY span_id,event LIMIT 100`,start_time:startMicros,end_time:endMicros,size:100}});if(logs.hits?.length!==fixture.correlatedLogs.length)throw new Error('persisted exact correlated logs absent');
|
||||
const queryTimeSeconds=String(end/1_000_000_000n+5n),metric=await request('/api/default/prometheus/api/v1/query?'+new URLSearchParams({query:'sum(http_requests)',time:queryTimeSeconds}));if(metric.status!=='success'||!metric.data?.result?.length)throw new Error('persisted point-in-time metric absent');const stable={traceId:fixture.traceId,startMicros,endMicros,queryTimeSeconds,spans:trace.hits,logs:logs.hits,metrics:metric.data};const hash=new Bun.CryptoHasher('sha256').update(JSON.stringify(stable)).digest('hex');let preserved:null|boolean=null;if(after){const before=JSON.parse(await readFile(resolve(output,'BEFORE.json'),'utf8'));preserved=before.hash===hash;if(!preserved)throw new Error('persisted trace/log/metric fingerprint changed');}
|
||||
const result={checkedAt:new Date().toISOString(),phase:after?'after':'before',hash,preserved,spanCount:trace.hits.length,logCount:logs.hits.length,metricValue:metric.data.result[0].value,stable,output};await writeFile(resolve(output,after?'AFTER.json':'BEFORE.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,after?'AFTER.json':'BEFORE.json'),phase:result.phase,hash,preserved,spanCount:result.spanCount,logCount:result.logCount,metricValue:result.metricValue}));
|
||||
@@ -0,0 +1,6 @@
|
||||
import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),fixtureRaw=await readFile(resolve(root,'evidence/openobserve/native-signals-sa.json')),f=JSON.parse(fixtureRaw.toString()),end=f.spans.reduce((n:bigint,s:any)=>BigInt(s.endTimeNs)>n?BigInt(s.endTimeNs):n,0n),base=Number(end/1_000_000_000n);if(!Number.isSafeInteger(base)||base<=0)throw new Error('Finite original generation required');
|
||||
const output=resolve(root,'.local/openobserve-positive-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64');const db=await Bun.file(resolve(root,'config/grafana/dashboards/messenger.json')).json(),rules:any=Bun.YAML.parse(await Bun.file(resolve(root,'config/grafana/provisioning/alerting/rules.yaml')).text());const results=[];
|
||||
const cases=[...db.panels.filter((p:any)=>[1,2,3,4,5,10,11,12,14,16].includes(p.id)).map((p:any)=>({id:'panel-'+p.id,query:p.targets[0].expr,offset:p.id===16?15:5,expectZero:[2,16].includes(p.id)})),...rules.groups.flatMap((g:any)=>g.rules.filter((r:any)=>['vp6-high-error','vp6-fast-burn','vp6-ready-burn'].includes(r.uid)).map((r:any)=>({id:r.uid,query:r.data.find((q:any)=>q.refId==='A').model.expr,offset:r.uid==='vp6-ready-burn'?15:5,expectZero:true}))),{id:'http-labels',query:'sum by(method,route,status_class,service_name)(http_requests)',offset:5,labels:['method','route','status_class','service_name']},{id:'job-labels',query:'sum by(job_type,outcome,service_name)(jobs_processed)',offset:5,labels:['job_type','outcome','service_name']},{id:'matured-positive',query:'max(ready_slo_matured_300s)',offset:15,positive:true},{id:'timely-positive',query:'max(ready_slo_timely_300s)',offset:15,positive:true}];
|
||||
for(const c of cases){const r=await fetch('http://127.0.0.1:28906/api/default/prometheus/api/v1/query?'+new URLSearchParams({query:c.query,time:String(base+c.offset)}),{headers:{Authorization:auth},signal:AbortSignal.timeout(12000)});const raw=new Uint8Array(await r.arrayBuffer());if(raw.length>1_048_576)throw new Error('Actual query output exceeds receiver cap');await writeFile(resolve(output,c.id+'.private.json'),raw,{flag:'wx',mode:0o600});let b:any;try{b=JSON.parse(new TextDecoder().decode(raw))}catch{}const rows=b?.data?.result??[],values=rows.map((s:any)=>Number(s.value?.[1]));const pass=r.status===200&&b?.status==='success'&&values.length>0&&values.every(Number.isFinite)&&(!c.expectZero||values.every((v:number)=>v===0))&&(!c.positive||values.every((v:number)=>v>0))&&(!c.labels||rows.every((v:any)=>c.labels!.every((key:string)=>typeof v.metric?.[key]==='string'&&v.metric[key].length>0)));results.push({id:c.id,query:c.query,time:base+c.offset,http:r.status,values,labels:c.labels?rows.map((v:any)=>v.metric):undefined,pass});}
|
||||
const result={checkedAt:new Date().toISOString(),scope:'actual provisioned native queries on retained known workload; no new smoke/producer; Grafana evaluation not run',fixtureSHA256:new Bun.CryptoHasher('sha256').update(fixtureRaw).digest('hex'),traceId:f.traceId,results,passed:results.every(r=>r.pass),output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),passed:result.passed,cases:results.length,failed:results.filter(r=>!r.pass).map(r=>({id:r.id,values:r.values,http:r.http}))}));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,5 @@
|
||||
import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-provisioned-queries-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const accounts=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')),auth='Basic '+Buffer.from(accounts.query.email+':'+accounts.query.token).toString('base64');
|
||||
const dashboard=JSON.parse(await readFile(resolve(root,'config/grafana/dashboards/messenger.json'),'utf8')),rules:any=Bun.YAML.parse(await readFile(resolve(root,'config/grafana/provisioning/alerting/rules.yaml'),'utf8'));const queries=[...dashboard.panels.flatMap((p:any)=>p.targets.map((q:any)=>({id:'panel-'+p.id,query:q.expr}))),...rules.groups.flatMap((g:any)=>g.rules.map((r:any)=>({id:r.uid,query:r.data.find((q:any)=>q.refId==='A').model.expr})))];
|
||||
const results=[];for(const q of queries){const r=await fetch('http://127.0.0.1:28906/api/default/prometheus/api/v1/query?'+new URLSearchParams({query:q.query}),{headers:{Authorization:auth},signal:AbortSignal.timeout(12_000)});let raw=new Uint8Array();for await(const part of r.body??[]){if(raw.length+part.length>1_048_576)throw new Error('native query response cap');const next=new Uint8Array(raw.length+part.length);next.set(raw);next.set(part,raw.length);raw=next;}await writeFile(resolve(output,q.id+'.private.json'),raw,{flag:'wx',mode:0o600});let body:any;try{body=JSON.parse(new TextDecoder().decode(raw))}catch{}const values=(body?.data?.result??[]).map((v:any)=>Number(v.value?.[1]));results.push({id:q.id,query:q.query,http:r.status,status:body?.status==='success'?'success':'error',series:values.length,finiteSamples:values.filter(Number.isFinite).length,nonfiniteSamples:values.filter((v:number)=>!Number.isFinite(v)).length,pass:r.status===200&&body?.status==='success'});}
|
||||
const result={checkedAt:new Date().toISOString(),scope:'native OpenObserve query parsing/content only; Grafana rendering and rule evaluation not executed',results,output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),queries:results.length,passed:results.filter(r=>r.pass).length,failed:results.filter(r=>!r.pass).map(r=>r.id)}));if(results.some(r=>!r.pass))process.exitCode=1;
|
||||
@@ -0,0 +1,6 @@
|
||||
import {mkdir,readFile,writeFile} from 'node:fs/promises';import {resolve} from 'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-readback-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const credential=JSON.parse(await readFile(resolve(root,'.local/openobserve_root-v2.json'),'utf8'));const auth='Basic '+Buffer.from(credential.email+':'+credential.password).toString('base64');
|
||||
async function get(path:string){const r=await fetch('http://127.0.0.1:28406'+path,{headers:{Authorization:auth},signal:AbortSignal.timeout(10_000)});const b=await r.arrayBuffer();if(b.byteLength>2_097_152)throw new Error('bounded native query exceeded2MiB');await writeFile(resolve(output,encodeURIComponent(path)+'.json'),new Uint8Array(b),{flag:'wx',mode:0o600});if(!r.ok)throw new Error('native OpenObserve endpoint rejected '+r.status);return JSON.parse(new TextDecoder().decode(b));}
|
||||
const safe=(x:unknown)=>typeof x==='string'&&/^[A-Za-z0-9_:.\/-]{1,128}$/.test(x)?x:'withheld';const streams=[];
|
||||
for(const type of ['metrics','logs','traces']){const result=await get('/api/default/streams?type='+type+'&fetchSchema=true');const list=result.list??result.data??result;if(!Array.isArray(list))throw new Error('native stream shape unexpected');streams.push(...list.map((s:any)=>({type,name:safe(s.name??s.stream_name),columns:Array.isArray(s.schema)?s.schema.map((f:any)=>safe(f.name)):Object.keys(s.schema??{}).map(safe)})));}
|
||||
const names=await get('/api/default/prometheus/api/v1/label/__name__/values');const result={checkedAt:new Date().toISOString(),streams,metricNames:(names.data??[]).map(safe),output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify(result));
|
||||
@@ -0,0 +1,13 @@
|
||||
import {mkdir,readFile,writeFile} from 'node:fs/promises';import {resolve} from 'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-signals-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const accounts=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8'));const credential=accounts.query;const auth='Basic '+Buffer.from(credential.email+':'+credential.token).toString('base64');const base='http://127.0.0.1:28906';
|
||||
async function request(path:string,body?:unknown){const r=await fetch(base+path,{method:body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(15_000)});const bytes=await r.arrayBuffer();if(bytes.byteLength>2_097_152)throw new Error('native response exceeds limit');if(!r.ok)throw new Error('native bounded query HTTP'+r.status);return JSON.parse(new TextDecoder().decode(bytes));}
|
||||
async function search(type:string,sql:string){return request('/api/default/_search?type='+type,{query:{sql,start_time:(Date.now()-900_000)*1000,end_time:Date.now()*1000,from:0,size:100}});}
|
||||
const worker=await search('traces',`SELECT trace_id FROM "messenger" WHERE operation_name='attachment.process' ORDER BY _timestamp DESC LIMIT 1`);const traceId=worker.hits?.[0]?.trace_id;if(!/^[a-f0-9]{32}$/.test(traceId??''))throw new Error('actual worker trace absent');
|
||||
const trace=await search('traces',`SELECT trace_id, span_id, reference_parent_span_id, operation_name, service_name, CAST(start_time AS VARCHAR) AS start_ns, CAST(end_time AS VARCHAR) AS end_ns, duration, _timestamp FROM "messenger" WHERE trace_id='${traceId}' ORDER BY start_time LIMIT 100`);const rows=trace.hits??[];await writeFile(resolve(output,'TRACE-ROWS.json'),JSON.stringify({traceId,rows},null,2)+'\n',{flag:'wx',mode:0o600});const names=[...new Set(rows.map((r:any)=>r.operation_name))];for(const required of ['attachment.publish','attachment.process'])if(!names.includes(required))throw new Error('cross-process trace chain missing '+required);
|
||||
if(!rows.some((r:any)=>r.service_name==='messenger-api'&&r.operation_name.startsWith('POST ')))throw new Error('actual API upload span absent');
|
||||
const spans=new Set(rows.map((r:any)=>r.span_id));const childLinks=rows.filter((r:any)=>r.reference_parent_span_id&&spans.has(r.reference_parent_span_id));if(childLinks.length<2)throw new Error('native parent relations absent');
|
||||
const times=rows.map((r:any)=>{if(!/^\d{18,20}$/.test(r.start_ns)||!/^\d{18,20}$/.test(r.end_ns))throw new Error('noncanonical native nanosecond field');const ns=BigInt(r.end_ns)-BigInt(r.start_ns),us=Number(ns)/1000;if(ns<0n||Math.abs(us-Number(r.duration))>1.01)throw new Error('native trace duration unit mismatch');if(Math.abs(Number(BigInt(r.start_ns)/1000n)-Number(r._timestamp))>1)throw new Error('native timestamp unit mismatch');return{spanId:r.span_id,parentSpanId:r.reference_parent_span_id,operation:r.operation_name,service:r.service_name,startTimeNs:r.start_ns,endTimeNs:r.end_ns,durationMicroseconds:r.duration};});
|
||||
if(!times.some((r:any)=>r.durationMicroseconds>0))throw new Error('zero-duration waterfall');
|
||||
const logs=await search('logs',`SELECT trace_id, span_id, event, service_name, request_id FROM "messenger" WHERE trace_id='${traceId}' LIMIT 100`);if(!logs.hits?.some((l:any)=>l.service_name==='messenger-api')||!logs.hits?.some((l:any)=>l.service_name==='messenger-worker'))throw new Error('correlated API/worker logs missing');if(!logs.hits.some((l:any)=>/^[a-f0-9-]{36}$/.test(l.request_id??'')))throw new Error('response request_id log field absent');
|
||||
const queries=['sum(http_requests)','sum(jobs_processed)','histogram_quantile(0.95, sum by(le)(http_duration_bucket))','max(queue_depth)','max(database_observer_up)'];const metrics=[];for(const query of queries){const result=await request('/api/default/prometheus/api/v1/query?'+new URLSearchParams({query}));if(result.status!=='success'||!result.data?.result?.length)throw new Error('native PromQL query returned no sample: '+query);const values=result.data.result.map((r:any)=>Number(r.value?.[1]));if(values.some((v:number)=>!Number.isFinite(v)))throw new Error('native PromQL returned nonfinite sample: '+query);metrics.push({query,values});}
|
||||
const result={checkedAt:new Date().toISOString(),traceId,queryPrincipalRole:'service_account',queryGateway:base,traceStream:'messenger',logStream:'messenger',traceTimeUnits:{start_time:'nanoseconds',end_time:'nanoseconds',duration:'microseconds',_timestamp:'microseconds'},parentField:'reference_parent_span_id',spanCount:rows.length,parentRelations:childLinks.length,spans:times,correlatedLogs:logs.hits.map((l:any)=>({event:l.event,service:l.service_name,traceId:l.trace_id,spanId:l.span_id,requestId:l.request_id??null})),metrics,output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),traceId,spanCount:rows.length,parentRelations:childLinks.length,operations:names,correlatedLogCount:logs.hits.length,metrics}));
|
||||
@@ -0,0 +1 @@
|
||||
const server=Bun.serve({hostname:'0.0.0.0',port:3000,fetch(request){return new URL(request.url).pathname==='/owned-ui-publication'?Response.json({owned:'vp6-network-publication'}):new Response('missing',{status:404});}});process.on('SIGTERM',()=>{server.stop(true);process.exit(0);});
|
||||
@@ -0,0 +1,7 @@
|
||||
import{mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
||||
const root=resolve(import.meta.dir,'..'),cfg:any=Bun.YAML.parse(await Bun.file(resolve(root,'compose.yaml')).text()),network=cfg.networks['grafana-query'].name,image='sha256:9e123d5fc069e29d519fd4c981afb61b8542ac80274771961136db1e4538d53e';
|
||||
if(network!=='mtuci-vp6-medvedev_grafana-query-v2'||cfg.networks['grafana-query'].internal||JSON.stringify(cfg.services.grafana.networks)!==JSON.stringify(['grafana-query'])||!cfg.services.grafana.ports.includes('127.0.0.1:28306:3000'))throw new Error('Actual Grafana publication configuration outside owned contract');
|
||||
const out=resolve(root,'.local/ui-publication-'+crypto.randomUUID());await mkdir(out,{mode:0o700});const name='mtuci-vp6-ui-check-'+crypto.randomUUID();
|
||||
const run=Bun.spawnSync(['docker','run','--detach','--rm','--pull=never','--read-only','--cap-drop','ALL','--user','1000:1000','--label','mtuci.task=vp6-ui-publication','--name',name,'--network',network,'--publish','127.0.0.1:28306:3000','-v',resolve(root,'student-tests/openobserve-ui-listener.ts')+':/listener.ts:ro','--entrypoint','/usr/local/bin/bun',image,'/listener.ts'],{stdout:'pipe',stderr:'pipe'});await writeFile(resolve(out,'launch-stderr.private'),run.stderr,{flag:'wx',mode:0o600});if(run.exitCode!==0)throw new Error('Owned cached listener launch failed; no Grafana was stopped');const id=new TextDecoder().decode(run.stdout).trim();if(!/^[a-f0-9]{64}$/.test(id))throw new Error('Owned launch identity absent');
|
||||
let pass=false,stopExit:number|null=null;try{for(let attempt=0;attempt<15;attempt++){try{const response=await fetch('http://127.0.0.1:28306/owned-ui-publication',{signal:AbortSignal.timeout(1000)});pass=response.status===200&&(await response.json()).owned==='vp6-network-publication';if(pass)break;}catch{}await Bun.sleep(100);}}finally{const r=Bun.spawnSync(['docker','inspect',id],{stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw new Error('Owned cached listener disappeared before stop');const c=JSON.parse(new TextDecoder().decode(r.stdout))[0];if(c.Id!==id||c.Name!=='/'+name||c.Image!==image||c.Config.Labels['mtuci.task']!=='vp6-ui-publication')throw new Error('Owned cached listener stop identity mismatch');const stopped=Bun.spawnSync(['docker','stop','--time','3',id],{stdout:'pipe',stderr:'pipe'});stopExit=stopped.exitCode;await writeFile(resolve(out,'stop-stderr.private'),stopped.stderr,{flag:'wx',mode:0o600});}
|
||||
const result={checkedAt:new Date().toISOString(),scope:'cached listener on actual configured Grafana network/port, Grafana binary not run',network,httpEndpoint:'http://127.0.0.1:28306/owned-ui-publication',httpPositive:pass,stopExit,passed:pass&&stopExit===0};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(out,'RESULT.json'),...result}));if(!result.passed)process.exitCode=1;
|
||||
@@ -0,0 +1,5 @@
|
||||
import{test,expect}from'bun:test';import{createOwnedFaultRunner,OwnedFaultFailure}from'../scripts/lib/owned-fault';
|
||||
test('restores the acquired owned lease after successful exercise',async()=>{const lease={id:'synthetic'},restored:unknown[]=[];const result=await createOwnedFaultRunner({acquire:async()=>lease,exercise:async()=>7,restore:async l=>{restored.push(l)}})();expect(result).toBe(7);expect(restored).toEqual([lease]);});
|
||||
test('restores owned lease even when its mutation or traffic fails',async()=>{const lease={id:'synthetic'},failure=new Error('fixture failed'),restored:unknown[]=[];let result;try{await createOwnedFaultRunner({acquire:async()=>lease,exercise:async()=>{throw failure},restore:async l=>{restored.push(l)}})()}catch(e){result=e}expect(restored).toEqual([lease]);expect(result).toBeInstanceOf(OwnedFaultFailure);expect((result as OwnedFaultFailure).primary).toBe(failure);});
|
||||
test('preserves primary failure separately from failed restoration',async()=>{const first=new Error('exercise'),second=new Error('cleanup');let result;try{await createOwnedFaultRunner({acquire:async()=>({id:'owned'}),exercise:async()=>{throw first},restore:async()=>{throw second}})()}catch(e){result=e}expect(result).toBeInstanceOf(OwnedFaultFailure);expect((result as OwnedFaultFailure).primary).toBe(first);expect((result as OwnedFaultFailure).cleanup).toBe(second);});
|
||||
test('does not restore anything when ownership acquisition fails',async()=>{let restored=0;await expect(createOwnedFaultRunner({acquire:async()=>{throw new Error('ownership')},exercise:async()=>0,restore:async()=>{restored++}})()).rejects.toThrow();expect(restored).toBe(0);});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {resolve} from 'node:path';
|
||||
const root=resolve(import.meta.dir,'..');
|
||||
const lab=(await Bun.file(resolve(root,'lab.json')).json()).number;
|
||||
const base=process.env.BASE_URL??`http://127.0.0.1:${28200+lab}`;
|
||||
const needed=lab>=3?Number(process.env.API_REPLICAS??2):1;
|
||||
const instances=new Set<string>();
|
||||
for(let attempt=0;attempt<600;attempt++){
|
||||
try{
|
||||
const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1000)});await r.arrayBuffer();
|
||||
if(r.status===200){instances.add(r.headers.get('X-Instance-Id')??'single');if(instances.size>=needed){console.log(`Ready: ${instances.size} API process(es)`);process.exit(0);}}
|
||||
}catch{}
|
||||
await Bun.sleep(150);
|
||||
}
|
||||
throw new Error('Stand readiness deadline expired');
|
||||
Reference in New Issue
Block a user