feat(monitor): keep operator telemetry live and retire local replicas
Keep operator monitoring in bounded live snapshots and provide scoped replica retirement. Update the board dashboard and retirement regressions.
This commit is contained in:
@@ -2,42 +2,51 @@ import {useEffect,useState} from 'react';
|
||||
|
||||
export interface MetricDefinition {label:string;group:string;resource:string;unit:string;reason:string|null}
|
||||
export interface BoardMonitor {
|
||||
available:boolean;fresh:boolean;storage:string;source_id:string;
|
||||
available:boolean;fresh:boolean;mode:'live';history_available:false;ttl_seconds:number;
|
||||
source_id:string|null;
|
||||
latest:{seq:number;at:number;boot_id:string;values:Record<string,number|null>}|null;
|
||||
definitions:Record<string,MetricDefinition>;received_at:number;backlog:number;
|
||||
database_bytes:number|null;database_budget_bytes:number;archive_since:number|null;
|
||||
start:number;end:number;bucket_seconds:number;
|
||||
series:{at:number;min:number|null;max:number|null;mean:number|null;count:number}[];
|
||||
definitions:Record<string,MetricDefinition>;received_at:number|null;
|
||||
sample_age_seconds:number|null;received_age_seconds:number|null;expires_in_seconds:number;
|
||||
events:{at:number;code:string;kind:string;locations:string[]}[];
|
||||
}
|
||||
export function useBoardMonitor(vehicle:string,metric:string,window:number,end:number|null){
|
||||
const [value,setValue]=useState<BoardMonitor|null>(null),[error,setError]=useState('');
|
||||
|
||||
export function ageBoardMonitor(value:BoardMonitor|null,elapsed:number):BoardMonitor|null {
|
||||
if(!value)return null;
|
||||
const age=Math.max(0,elapsed);
|
||||
if(!value.available||!Number.isFinite(age)||age>=value.expires_in_seconds){
|
||||
return {...value,available:false,fresh:false,latest:null,definitions:{},events:[],source_id:null,received_at:null,expires_in_seconds:0};
|
||||
}
|
||||
return {...value,fresh:value.fresh&&(value.sample_age_seconds??Infinity)+age<10&&(value.received_age_seconds??Infinity)+age<15};
|
||||
}
|
||||
|
||||
export function useBoardMonitor(vehicle:string){
|
||||
const [snapshot,setSnapshot]=useState<{vehicle:string;value:BoardMonitor;tick:number;wall:number}|null>(null);
|
||||
const [error,setError]=useState(''),[loading,setLoading]=useState(true),[,setTick]=useState(0);
|
||||
useEffect(()=>{
|
||||
let active=true;let pending:AbortController|undefined;let timer:ReturnType<typeof setTimeout>|undefined;
|
||||
setValue(null);setError('');
|
||||
setSnapshot(null);setError('');setLoading(true);
|
||||
// Expiry still reaches the screen when requests fail, hang, or a suspended tab resumes.
|
||||
const expiry=setInterval(()=>setTick(value=>value+1),1000);
|
||||
const read=async()=>{
|
||||
const controller=new AbortController();pending=controller;
|
||||
const started=performance.now(),wall=Date.now();
|
||||
const deadline=setTimeout(()=>controller.abort(),12000);
|
||||
try {
|
||||
const query=new URLSearchParams({metric,window:String(window),...(end===null?{}:{end:String(end)})});
|
||||
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor?${query}`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
|
||||
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
|
||||
if(!response.ok)throw new Error('Мониторинг БК недоступен.');
|
||||
const next=await response.json() as BoardMonitor;
|
||||
if(active){setValue(next);setError('');}
|
||||
if(next.mode!=='live'||next.history_available!==false||!Number.isFinite(next.expires_in_seconds)||next.expires_in_seconds<0||next.expires_in_seconds>30)throw new Error('Invalid live monitor contract');
|
||||
if(active){setSnapshot({vehicle,value:next,tick:started,wall});setError('');}
|
||||
}catch {if(active)setError('Не удалось обновить мониторинг БК.');}
|
||||
finally {clearTimeout(deadline);if(active)timer=setTimeout(()=>void read(),5000);}
|
||||
finally {clearTimeout(deadline);if(active){setLoading(false);timer=setTimeout(()=>void read(),5000);}}
|
||||
};
|
||||
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);};
|
||||
},[vehicle,metric,window,end]);
|
||||
return {value,error,dismissError:()=>setError('')};
|
||||
}
|
||||
export function monitorSeries(value:BoardMonitor,mode:'min'|'max'|'mean') {
|
||||
const count=Math.ceil((value.end-value.start)/value.bucket_seconds)+1;
|
||||
const values:Array<number|null>=Array(Math.min(count,302)).fill(null);
|
||||
const first=Math.floor(value.start/value.bucket_seconds)*value.bucket_seconds;
|
||||
for(const point of value.series){const index=Math.round((point.at-first)/value.bucket_seconds);if(index>=0&&index<values.length)values[index]=point[mode];}
|
||||
return values;
|
||||
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);clearInterval(expiry);};
|
||||
},[vehicle]);
|
||||
const current=snapshot?.vehicle===vehicle?snapshot:null;
|
||||
const elapsed=current?Math.max(performance.now()-current.tick,Date.now()-current.wall)/1000:0;
|
||||
return {value:ageBoardMonitor(current?.value??null,elapsed),error,loading,dismissError:()=>setError('')};
|
||||
}
|
||||
|
||||
export function monitorValue(value:number|null|undefined,unit=''){
|
||||
if(value==null||!Number.isFinite(value))return 'Нет измерения';
|
||||
if(unit==='bytes'||unit==='bytes/s'){
|
||||
|
||||
@@ -1,46 +1,42 @@
|
||||
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
|
||||
import {useState} from 'react';
|
||||
import {ActivityIndicator,Button,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
|
||||
import {useBoardMonitor,monitorSeries,monitorValue} from '../../core/fleet/boardMonitor';
|
||||
import {TelemetrySeries} from '../../components/system/TelemetrySeries';
|
||||
import '../../styles/system-telemetry.css';
|
||||
import {LoadingRegion,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,ToastStack} from '@nodedc/ui-react';
|
||||
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
|
||||
import {useBoardMonitor,monitorValue,type BoardMonitor} from '../../core/fleet/boardMonitor';
|
||||
import './board-monitor.css';
|
||||
|
||||
const eventLabels:Record<string,string>={'ui-error':'Ошибка интерфейса','ui-rejection':'Ошибка асинхронной операции','ui-render-error':'Ошибка представления','system-oom':'Нехватка памяти','gpu-reset':'Сброс GPU','disk-error':'Ошибка диска','usb-disconnected':'Отключение USB','usb-error':'Ошибка USB','service-failed':'Сбой службы','ui-process-exit':'Завершение процесса окна','ui-load-failed':'Ошибка загрузки окна'};
|
||||
const time=(value:number)=>new Date(value*1000).toLocaleString('ru-RU');
|
||||
export function BoardMonitorView({vehicle,name,back,headerToolsHost}:{vehicle:string;name:string;back:()=>void;headerToolsHost?:HTMLElement|null}) {
|
||||
const [metric,setMetric]=useState('cpu.usage'),[group,setGroup]=useState('CPU'),[window,setWindow]=useState(900),[end,setEnd]=useState<number|null>(null),[mode,setMode]=useState<'min'|'max'|'mean'>('max');
|
||||
const {value,error,dismissError}=useBoardMonitor(vehicle,metric,window,end);
|
||||
const definitions=value?.definitions??{},definition=definitions[metric];
|
||||
|
||||
export function BoardMonitorReadout({name,value,error,loading}:{name:string;value:BoardMonitor|null;error:string;loading:boolean}) {
|
||||
const [selectedGroup,setGroup]=useState('CPU');
|
||||
const definitions=value?.definitions??{},latest=value?.latest;
|
||||
const groups=[...new Set(Object.values(definitions).map(item=>item.group))];
|
||||
const group=groups.includes(selectedGroup)?selectedGroup:groups[0]??'';
|
||||
const metrics=Object.entries(definitions).filter(([,item])=>item.group===group);
|
||||
const latest=value?.latest;
|
||||
return <>
|
||||
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
|
||||
{latest&&<p>Измерено на БК: {time(latest.at)}.</p>}
|
||||
</SettingsCard>
|
||||
<LoadingRegion loading={loading&&!value} label="Получение мониторинга БК"><div className="board-monitor-readings">
|
||||
{!value?.available?<SettingsCard align="center" title={loading?'Ожидание показателей':error?'Мониторинг БК недоступен':'Нет текущих измерений'} description={error?'Обновление повторяется автоматически.':'Показатели появятся после получения свежих данных с борта.'}/>:<>
|
||||
<SettingsCard title="Текущие показатели" description={latest?time(latest.at):undefined}>
|
||||
{!!groups.length&&<div className="board-monitor-controls"><Select label="Ресурс" value={group} options={groups.map(label=>({value:label,label}))} onChange={setGroup}/></div>}
|
||||
<ResourceList aria-label="Показатели системы">{metrics.map(([key,item])=><li key={key}><ResourceRow title={`${item.resource} · ${item.label}`} description={latest?.values[key]==null?item.reason??'Счётчик недоступен':undefined} metadata={monitorValue(latest?.values[key],item.unit)}/></li>)}</ResourceList>
|
||||
{!metrics.length&&<p>Измерения для этого ресурса не поступили.</p>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="События последнего измерения">
|
||||
{value.events.length?<ResourceList aria-label="События БК">{value.events.map((event,index)=><li key={`${event.at}-${index}`}><ResourceRow title={eventLabels[event.code]??'Событие системы'} description={time(event.at)}/></li>)}</ResourceList>:<p>Событий не получено.</p>}
|
||||
</SettingsCard>
|
||||
</>}
|
||||
</div></LoadingRegion>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function BoardMonitorView({vehicle,name,back,headerToolsHost}:{vehicle:string;name:string;back:()=>void;headerToolsHost?:HTMLElement|null}) {
|
||||
const {value,error,loading,dismissError}=useBoardMonitor(vehicle);
|
||||
return <div className="board-monitor">
|
||||
<WorkspaceBackButton label="К аппарату" onClick={back} host={headerToolsHost}/>
|
||||
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
|
||||
{latest&&<p>Измерено на БК: {time(latest.at)}. {value?.storage==='ready'?'Локальная история записывается.':'Запись локальной истории недоступна.'} {value?.backlog?'История догружается в Mission Core.':''}</p>}
|
||||
{value?.database_bytes!=null&&<p>Архив на БК: {monitorValue(value.database_bytes,'bytes')} из {monitorValue(value.database_budget_bytes,'bytes')}. {value.archive_since?`Копия в Mission Core с ${time(value.archive_since)}.`:''}</p>}
|
||||
</SettingsCard>
|
||||
{!value?<ActivityIndicator label="Получение мониторинга БК"/>:!value.available?<SettingsCard title="История БК пока не получена" description="Данные появятся после подключения бортового сборщика телеметрии."/>:<>
|
||||
<SettingsCard title="История нагрузки">
|
||||
<div className="board-monitor-controls">
|
||||
<Select label="Ресурс" value={group} options={groups.map(label=>({value:label,label}))} onChange={next=>{setGroup(next);const first=Object.entries(definitions).find(([,item])=>item.group===next);if(first)setMetric(first[0]);}}/>
|
||||
<Select label="Показатель" value={metric} options={metrics.map(([key,item])=>({value:key,label:`${item.resource} · ${item.label}`}))} onChange={setMetric}/>
|
||||
<Select label="Период" value={String(window)} options={[{value:'900',label:'15 минут'},{value:'3600',label:'1 час'},{value:'21600',label:'6 часов'},{value:'86400',label:'24 часа'},{value:'604800',label:'7 дней'}]} onChange={next=>setWindow(Number(next))}/>
|
||||
<Select label="Значение в интервале" value={mode} options={[{value:'max',label:'Максимум'},{value:'mean',label:'Среднее'},{value:'min',label:'Минимум'}]} onChange={next=>setMode(next as typeof mode)}/>
|
||||
</div>
|
||||
<div className="board-monitor-controls"><Button onClick={()=>setEnd(end===null?Date.now()/1000:null)}>{end===null?'Зафиксировать время':'В реальном времени'}</Button>{end!==null&&<TextField label="Конец периода" type="datetime-local" step="1" value={new Date((end-new Date(end*1000).getTimezoneOffset()*60)*1000).toISOString().slice(0,19)} onChange={event=>{const next=new Date(event.target.value).getTime()/1000;if(Number.isFinite(next))setEnd(next);}}/>}</div>
|
||||
<TelemetrySeries label={definition?`${definition.resource} · ${definition.label}`:'Загрузка CPU'} resource="Последний интервал периода" value={monitorValue(value.series.at(-1)?.[mode],definition?.unit)} values={monitorSeries(value,mode)} ceiling={definition?.unit==='%'?100:undefined}/>
|
||||
<p>{time(value.start)} — {time(value.end)} · интервал {value.bucket_seconds} с. Разрывы означают отсутствие измерений.</p>
|
||||
{!value.series.length&&<p>За выбранный период измерений нет.</p>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title={`Последние измерения · ${group}`} description={latest?time(latest.at):'Ожидание измерений'}>
|
||||
<ResourceList aria-label="Показатели системы">{metrics.map(([key,item])=><li key={key}><ResourceRow title={`${item.resource} · ${item.label}`} description={latest?.values[key]==null?item.reason??'Счётчик недоступен':undefined} metadata={monitorValue(latest?.values[key],item.unit)}/></li>)}</ResourceList>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="События системы и приложения" description="За выбранный период">
|
||||
{value.events.length?<ResourceList aria-label="События БК">{value.events.map((event,index)=><li key={`${event.at}-${index}`}><ResourceRow title={eventLabels[event.code]??'Событие системы'} description={time(event.at)}/></li>)}</ResourceList>:<p>Событий не получено.</p>}
|
||||
</SettingsCard>
|
||||
</>}
|
||||
<BoardMonitorReadout name={name} value={value} error={error} loading={loading}/>
|
||||
<ToastStack items={error?[{id:'monitor-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={dismissError}/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
.board-monitor { display: grid; gap: var(--nodedc-space-4); min-width: 0; }
|
||||
.board-monitor, .board-monitor-readings { display: grid; gap: var(--nodedc-space-4); min-width: 0; }
|
||||
.board-monitor-controls { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--nodedc-space-3); align-items: end; margin-bottom: var(--nodedc-space-3); }
|
||||
.board-monitor p { font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
|
||||
|
||||
@@ -1,24 +1,57 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createServer} from 'vite';
|
||||
let server,series,segments,frames,localPreview,MEDIA_PROTOCOL;
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
import {createElement} from 'react';
|
||||
import {renderToStaticMarkup as render} from 'react-dom/server';
|
||||
let server,age,segments,frames,localPreview,MEDIA_PROTOCOL,Readout;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||
({monitorSeries:series}=await server.ssrLoadModule('/src/core/fleet/boardMonitor.ts'));
|
||||
({ageBoardMonitor:age}=await server.ssrLoadModule('/src/core/fleet/boardMonitor.ts'));
|
||||
({BoardMonitorReadout:Readout}=await server.ssrLoadModule('/src/workspaces/fleet/BoardMonitorView.tsx'));
|
||||
({lineSegments:segments}=await server.ssrLoadModule('/src/components/system/TelemetrySeries.tsx'));
|
||||
({MEDIA_PROTOCOL}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/previewFrames.ts'));
|
||||
({localPreviewFrames:frames,localPreview}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/localPreview.ts'));
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
test('archive gaps break the plot instead of manufacturing zero or connecting missing time',()=>{
|
||||
const values=series({start:0,end:20,bucket_seconds:5,series:[{at:0,max:80},{at:5,max:90},{at:20,max:10}]},'max');
|
||||
assert.deepEqual(values,[80,90,null,null,10]);
|
||||
test('plot gaps remain gaps for other telemetry consumers',()=>{
|
||||
const values=[80,90,null,null,10];
|
||||
const result=segments(values,100);
|
||||
assert.equal(result.length,2);
|
||||
assert.match(result[0],/^0.00,8.80 25.00,5.40$/);
|
||||
assert.deepEqual(segments([null,NaN,null]),[]);
|
||||
assert.notEqual(segments([-10,0,10])[0].split(' ')[0].split(',')[1],segments([-10,0,10])[0].split(' ')[1].split(',')[1]);
|
||||
});
|
||||
const live=()=>({available:true,fresh:true,mode:'live',history_available:false,ttl_seconds:30,source_id:'source',
|
||||
latest:{seq:1,at:1000,boot_id:'boot',values:{'cpu.usage':72.3}},
|
||||
definitions:{'cpu.usage':{label:'Загрузка',group:'CPU',resource:'CPU',unit:'%',reason:null}},received_at:1000,
|
||||
sample_age_seconds:0,received_age_seconds:0,expires_in_seconds:30,events:[]});
|
||||
test('network loss cannot leave a fresh badge or stale values indefinitely',()=>{
|
||||
const value=live();
|
||||
assert.equal(age(value,9).fresh,true);assert.equal(age(value,10).fresh,false);
|
||||
assert.equal(age(value,29).available,true);
|
||||
const expired=age(value,30);
|
||||
assert.equal(expired.available,false);assert.equal(expired.latest,null);
|
||||
assert.deepEqual(expired.definitions,{});assert.deepEqual(expired.events,[]);
|
||||
assert.equal(age(value,3600).latest,null);assert.equal(age(value,Infinity).latest,null);
|
||||
assert.equal(age(null,0),null);
|
||||
});
|
||||
test('server remaining lifetime is never restarted by a successful poll',()=>{
|
||||
const value={...live(),fresh:false,sample_age_seconds:27,expires_in_seconds:3};
|
||||
assert.equal(age(value,2).fresh,false);assert.equal(age(value,3).available,false);
|
||||
});
|
||||
test('monitor readout renders live values and has no historical navigation',()=>{
|
||||
const html=render(createElement(Readout,{name:'Synthetic board',value:live(),error:'',loading:false}));
|
||||
assert.match(html,/Текущие показатели/);assert.match(html,/72,3/);assert.match(html,/Данные поступают/);
|
||||
assert.doesNotMatch(html,/История нагрузки|7 дней|Конец периода|Зафиксировать время|Копия в Mission Core/);
|
||||
const unavailable=render(createElement(Readout,{name:'Synthetic board',value:age(live(),30),error:'',loading:false}));
|
||||
assert.match(unavailable,/Нет текущих измерений/);assert.doesNotMatch(unavailable,/72,3|Данные поступают/);
|
||||
});
|
||||
test('initial error terminates loading and stale readout never claims fresh data',()=>{
|
||||
const html=render(createElement(Readout,{name:'Synthetic board',value:null,error:'unavailable',loading:false}));
|
||||
assert.match(html,/Мониторинг БК недоступен/);assert.doesNotMatch(html,/role="status"[^>]*aria-busy="true"/);
|
||||
const stale=render(createElement(Readout,{name:'Synthetic board',value:age(live(),11),error:'',loading:false}));
|
||||
assert.match(stale,/Нет свежих данных/);assert.doesNotMatch(stale,/Данные поступают/);
|
||||
});
|
||||
test('HTTP media framing survives every byte boundary and refuses oversized frames',()=>{
|
||||
const output=[],receive=frames((kind,bytes)=>output.push([kind,[...bytes]]));
|
||||
const encoded=Uint8Array.of(2,0,0,0,3,4,5,6,3,0,0,0,2,7,8);
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# Operator monitoring: bounded live snapshots
|
||||
|
||||
Implemented 2026-10-16, following the operator storage rule in `AGENTS.md`.
|
||||
The operator's job is to see current onboard computer health. The existing Fleet
|
||||
board monitoring page retains its placement and canonical Design Guideline
|
||||
components. It no longer offers historical windows or claims to own an archive.
|
||||
Keeping the old chart/window controls would promise data this operator service
|
||||
must not retain; moving this view to a new workspace would add navigation without
|
||||
changing that job. No new product root or visual component is introduced.
|
||||
|
||||
## Producer, transport and storage contract
|
||||
|
||||
`src/k1link/fleet/monitor.py` admits one validated latest observation per node.
|
||||
It never creates, opens or migrates a SQLite database. The existing FleetRegistry
|
||||
constructor remains compatible; its storage path is ignored by MonitorReceiver.
|
||||
|
||||
- At most 32 active node snapshots. When full, a new node is refused until an
|
||||
existing entry expires; established nodes can still replace their own snapshot.
|
||||
- At most 384 metric definitions/values and 64 classified events per observation.
|
||||
Each serialized sample is limited to 32 KiB; the projected snapshot to 192 KiB.
|
||||
The retained serialized payload and duplicate-comparison sample together are
|
||||
bounded by 7 MiB for 32 nodes, plus bounded Python metadata/string overhead.
|
||||
This is not a process RSS ceiling.
|
||||
- Only `schema`, `source_id`, `definitions` and `latest` are projected. Incoming
|
||||
historical batches and archive metadata are not copied into retained memory
|
||||
or disk. Existing HTTP transport still receives the v1 envelope.
|
||||
- Expiry is 30 seconds from receipt or observation time, whichever expires first.
|
||||
Receipt expiry uses a monotonic clock; stale and more-than-5-second-future
|
||||
observations cannot populate the view. A one-second idle sweeper also runs
|
||||
without API consumers. UTC date changes clear the store; process restart starts
|
||||
empty. No age-based cleanup of simulation data is involved.
|
||||
- Replayed or duplicate sequences never extend freshness or expiry; conflicting
|
||||
duplicates are rejected. A delayed observation cannot replace a newer one.
|
||||
- Fresh means observation age below 10 seconds and receipt age below 15 seconds.
|
||||
Older retained values are explicitly stale until expiry, then unavailable.
|
||||
|
||||
The existing v1 transport acknowledgement now includes `mode: "live"` and
|
||||
advances `after` to the consumed latest sequence. This is transport consumption,
|
||||
not a durable replication receipt. The current Node transport accepts this
|
||||
cursor and ignores the additive field. Board archive retention is independent
|
||||
of the cursor: the archive batch is a SELECT, not acknowledgement-driven deletion.
|
||||
No onboard installation, archive retention policy or board data is changed by
|
||||
this operator migration. Future transport versions may omit historical batches
|
||||
at the sender; that is not claimed by this change.
|
||||
|
||||
## API and UI
|
||||
|
||||
`GET /api/v1/fleet/{vehicle}/monitor` returns `mode: "live"`,
|
||||
`history_available: false`, freshness/age and remaining lifetime; its response
|
||||
has `Cache-Control: no-store`. Legacy `metric`, `window` or `end` query parameters
|
||||
return HTTP 400 instead of silently pretending to provide history.
|
||||
|
||||
The existing page shows current metric groups and events belonging to the latest
|
||||
observation. Missing measurements remain missing, never numeric zero. Polling is
|
||||
sequential every five seconds with a 12-second request timeout. A separate local
|
||||
expiry tick removes values even during request failure, a hung request or a
|
||||
suspended tab. Expiry includes request duration and uses the greater of wall and
|
||||
monotonic elapsed time. Initial errors end the loader; stale/error states cannot
|
||||
claim fresh data. Historical chart controls, aggregates and window selection are
|
||||
removed from this live-only surface.
|
||||
|
||||
## Retiring an existing Mac replica
|
||||
|
||||
Install and accept the live producer/consumer first. Then generate a fresh plan:
|
||||
|
||||
```sh
|
||||
.venv/bin/python scripts/retire_monitor_replica.py plan > .runtime/monitor-retirement-plan.json
|
||||
.venv/bin/python scripts/retire_monitor_replica.py apply --plan .runtime/monitor-retirement-plan.json
|
||||
```
|
||||
|
||||
The tool permits only `monitor.sqlite3`, `monitor.sqlite3-wal` and
|
||||
`monitor.sqlite3-shm` directly under `.runtime/mission-core/fleet`. It checks the
|
||||
known four-table schema with an immutable read-only connection, canonical paths,
|
||||
regular-file identities and SHA-256. Unexplained orphan sidecars, links, changed
|
||||
plans or unknown tables block removal. Apply independently verifies canonical
|
||||
Core health and every existing Fleet monitor's live-only contract. `lsof` must
|
||||
show no process holding any target; identities are checked again before unlink.
|
||||
Sidecars are removed first and the main database last, allowing interrupted
|
||||
operations to be replanned against the remaining known schema. There is no
|
||||
recursive cleanup, vacuum, board command or raw-sample export.
|
||||
|
||||
Intent, removed identities and filesystem free-space observations are journaled
|
||||
under `.runtime/storage-maintenance/monitor-retirement`. These small maintenance
|
||||
receipts are evidence, not persistent monitoring samples. Logical file bytes are
|
||||
an upper bound on space reclaimed; concurrent filesystem activity affects the
|
||||
observed free-space delta. Repeating plan after completion returns no candidates.
|
||||
|
||||
## Verification
|
||||
|
||||
`tests/test_board_monitor.py` covers bounds, sequence/source ordering, duplicate
|
||||
freshness, stale/future samples, idle expiry, UTC reset, restart, JSON validation,
|
||||
copy isolation, current events and the API. `tests/test_monitor_retirement.py`
|
||||
covers exact scope, schema/path/hash rejection, open-file refusal (including a
|
||||
real open SQLite reader), interruption and independent live-mode acceptance.
|
||||
The existing Node package tests keep collector/packaging coverage. Frontend tests
|
||||
cover unavailable/stale/error states, client expiry and absence of history controls.
|
||||
Live endpoint, UI and deletion acceptance are recorded separately in the dated
|
||||
operator report; unit tests alone are not proof of deployment or reclaimed space.
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Retire only the obsolete operator fleet monitoring replica after live-mode acceptance."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
FILES = ("monitor.sqlite3-shm", "monitor.sqlite3-wal", "monitor.sqlite3")
|
||||
TABLES = {
|
||||
"samples": ["node", "source", "seq", "at", "body"],
|
||||
"minutes": ["node", "at", "body"],
|
||||
"events": ["node", "source", "seq", "at", "body"],
|
||||
"states": ["node", "source", "body", "received", "ack"],
|
||||
}
|
||||
|
||||
|
||||
def canonical(value):
|
||||
return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
|
||||
|
||||
|
||||
def stamp(s):
|
||||
return [s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_nlink]
|
||||
|
||||
|
||||
def directory(root, relative):
|
||||
path = root
|
||||
for component in Path(relative).parts:
|
||||
path /= component
|
||||
if not stat.S_ISDIR(path.lstat().st_mode):
|
||||
raise ValueError("Monitor directory contains a link or special file")
|
||||
return path
|
||||
|
||||
|
||||
def identity(path):
|
||||
metadata = path.lstat()
|
||||
if not stat.S_ISREG(metadata.st_mode):
|
||||
raise ValueError("Monitor file is not a regular file")
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
with os.fdopen(fd, "rb") as stream:
|
||||
if stamp(os.fstat(stream.fileno())) != stamp(metadata):
|
||||
raise ValueError("Monitor file changed while opening")
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if stamp(os.fstat(stream.fileno())) != stamp(metadata):
|
||||
raise ValueError("Monitor file changed during verification")
|
||||
if stamp(path.lstat()) != stamp(metadata):
|
||||
raise ValueError("Monitor path changed during verification")
|
||||
return dict(name=path.name, sha256=digest, bytes=metadata.st_size, stamp=stamp(metadata))
|
||||
|
||||
|
||||
def plan(root):
|
||||
root = Path(root).absolute()
|
||||
if root.is_symlink() or root != root.resolve(strict=True):
|
||||
raise ValueError("Use the canonical repository path")
|
||||
fleet = directory(root, ".runtime/mission-core/fleet")
|
||||
paths = [
|
||||
fleet / name for name in FILES if (fleet / name).exists() or (fleet / name).is_symlink()
|
||||
]
|
||||
main = fleet / "monitor.sqlite3"
|
||||
if paths and main not in paths:
|
||||
raise ValueError("Unexplained orphan monitoring sidecars")
|
||||
files = [identity(path) for path in paths]
|
||||
if files:
|
||||
# Immutable read checks the established schema without opening a writer,
|
||||
# checkpointing WAL, or creating sidecars. No raw samples are exported.
|
||||
uri = main.as_uri() + "?mode=ro&immutable=1"
|
||||
with closing(sqlite3.connect(uri, uri=True)) as database:
|
||||
tables = {
|
||||
row[0]
|
||||
for row in database.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
||||
}
|
||||
if tables != set(TABLES):
|
||||
raise ValueError("Database contains unexpected tables")
|
||||
for table, expected in TABLES.items():
|
||||
if [row[1] for row in database.execute(f"PRAGMA table_info({table})")] != expected:
|
||||
raise ValueError("Unexpected monitor table layout")
|
||||
if any(stamp((fleet / row["name"]).lstat()) != row["stamp"] for row in files):
|
||||
raise ValueError("Monitoring files changed during schema verification")
|
||||
result = dict(
|
||||
schema="missioncore.monitor-replica-retirement-plan/v1",
|
||||
root=str(root),
|
||||
files=files,
|
||||
logical_bytes_upper_bound=sum(row["bytes"] for row in files),
|
||||
)
|
||||
result["plan_id"] = hashlib.sha256(canonical(result)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def live_acceptance():
|
||||
def read(path):
|
||||
with urllib.request.urlopen("http://127.0.0.1:8000" + path, timeout=5) as response:
|
||||
data = response.read(2 * 1024**2 + 1)
|
||||
if len(data) > 2 * 1024**2:
|
||||
raise ValueError("Acceptance response budget")
|
||||
return json.loads(data)
|
||||
|
||||
health = read("/api/health")
|
||||
if not health.get("readiness", {}).get("operational"):
|
||||
raise ValueError("Canonical Core is not operational")
|
||||
vehicles = read("/api/v1/fleet")["items"]
|
||||
if not vehicles:
|
||||
raise ValueError("No existing vehicle to verify live monitor contract")
|
||||
for vehicle in vehicles:
|
||||
value = read("/api/v1/fleet/" + urllib.parse.quote(vehicle["id"], safe="") + "/monitor")
|
||||
if value.get("mode") != "live" or value.get("history_available") is not False:
|
||||
raise ValueError("The running Core still exposes the archive contract")
|
||||
return {"core_operational": True, "mode": "live", "verified_vehicles": len(vehicles)}
|
||||
|
||||
|
||||
def assert_closed(paths):
|
||||
if not paths:
|
||||
return
|
||||
result = subprocess.run(
|
||||
["lsof", "-t", *map(str, paths)], capture_output=True, text=True, timeout=10
|
||||
)
|
||||
if result.stdout.strip() or result.returncode not in (0, 1) or result.stderr.strip():
|
||||
raise ValueError("Monitoring files may still be open; retirement refused")
|
||||
|
||||
|
||||
def save(path, receipt):
|
||||
temporary = path.with_suffix(".tmp")
|
||||
with temporary.open("xb") as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
stream.write(canonical(receipt) + b"\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def apply(expected, *, probe=live_acceptance, closed=assert_closed):
|
||||
proof = probe()
|
||||
current = plan(expected["root"])
|
||||
if current != expected:
|
||||
raise ValueError("Stale or changed monitor retirement plan")
|
||||
root = Path(current["root"])
|
||||
fleet = directory(root, ".runtime/mission-core/fleet")
|
||||
closed([fleet / row["name"] for row in current["files"]])
|
||||
# The receipt is owned maintenance evidence, separate from operator telemetry.
|
||||
parent = directory(root, ".runtime")
|
||||
for name in ("storage-maintenance", "monitor-retirement"):
|
||||
parent /= name
|
||||
parent.mkdir(mode=0o700, exist_ok=True)
|
||||
if not stat.S_ISDIR(parent.lstat().st_mode):
|
||||
raise ValueError("Unsafe receipt directory")
|
||||
path = parent / (uuid.uuid4().hex + ".json")
|
||||
receipt = dict(
|
||||
schema="missioncore.monitor-replica-retirement-receipt/v1",
|
||||
plan=current,
|
||||
proof=proof,
|
||||
status="applying",
|
||||
removed=[],
|
||||
started_ns=time.time_ns(),
|
||||
free_before=shutil.disk_usage(root).free,
|
||||
)
|
||||
save(path, receipt)
|
||||
try:
|
||||
# Sidecars go first, main last. A partial operation can be replanned
|
||||
# against the remaining known schema; unrelated fleet files are untouched.
|
||||
for row in current["files"]:
|
||||
candidate = fleet / row["name"]
|
||||
closed([candidate])
|
||||
if identity(candidate) != row:
|
||||
raise ValueError("Monitor file changed before unlink")
|
||||
receipt["next"] = row["name"]
|
||||
save(path, receipt)
|
||||
candidate.unlink()
|
||||
receipt["removed"].append(row)
|
||||
save(path, receipt)
|
||||
receipt["status"] = "complete"
|
||||
except BaseException as error:
|
||||
receipt.update(status="interrupted", error=str(error))
|
||||
raise
|
||||
finally:
|
||||
receipt.update(finished_ns=time.time_ns(), free_after=shutil.disk_usage(root).free)
|
||||
save(path, receipt)
|
||||
return dict(receipt, receipt=str(path))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("plan", "apply"))
|
||||
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
|
||||
parser.add_argument("--plan", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.action == "plan":
|
||||
result = plan(args.root)
|
||||
else:
|
||||
if args.plan is None:
|
||||
parser.error("apply requires --plan")
|
||||
result = apply(json.loads(args.plan.read_text()))
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+209
-287
@@ -1,15 +1,25 @@
|
||||
"""Idempotent local replica of a board-owned Timescale history, behind fleet mTLS."""
|
||||
"""Bounded live operator snapshots; the board owns its independent archive.
|
||||
|
||||
Nothing in this module opens or migrates monitor.sqlite3. The v1 transport ACK
|
||||
advances past the accepted latest observation in live mode; it is NOT a durable
|
||||
replication receipt. Node's collector retention is independent of this cursor.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from uuid import UUID
|
||||
|
||||
SCHEMA = "missioncore.node-system-monitor/v1"
|
||||
KEY = re.compile(r"^[A-Za-z0-9_.:-]{1,180}$")
|
||||
MAX_NODES = 32
|
||||
MAX_SNAPSHOT_BYTES = 196608
|
||||
TTL_SECONDS = 30
|
||||
SAMPLE_FRESH_SECONDS = 10
|
||||
RECEIVE_FRESH_SECONDS = 15
|
||||
FUTURE_SKEW_SECONDS = 5
|
||||
|
||||
|
||||
def checked_sample(value):
|
||||
@@ -24,7 +34,7 @@ def checked_sample(value):
|
||||
raise ValueError("Invalid sample")
|
||||
if type(value["seq"]) is not int or not 0 < value["seq"] < 2**53:
|
||||
raise ValueError("Invalid sequence")
|
||||
if str(UUID(value["boot_id"])) != value["boot_id"]:
|
||||
if not isinstance(value["boot_id"], str) or str(UUID(value["boot_id"])) != value["boot_id"]:
|
||||
raise ValueError("Invalid boot")
|
||||
for name in ["at", "uptime"]:
|
||||
if (
|
||||
@@ -36,8 +46,13 @@ def checked_sample(value):
|
||||
if not isinstance(value["values"], dict) or len(value["values"]) > 384:
|
||||
raise ValueError("Metric budget")
|
||||
for key, number in value["values"].items():
|
||||
if not KEY.fullmatch(key) or (
|
||||
number is not None and (type(number) not in (int, float) or not math.isfinite(number))
|
||||
if (
|
||||
not isinstance(key, str)
|
||||
or not KEY.fullmatch(key)
|
||||
or (
|
||||
number is not None
|
||||
and (type(number) not in (int, float) or not math.isfinite(number))
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid metric")
|
||||
if not isinstance(value["events"], list) or len(value["events"]) > 64:
|
||||
@@ -79,312 +94,219 @@ def checked_sample(value):
|
||||
return json.dumps(value, allow_nan=False, separators=(",", ":"), sort_keys=True)
|
||||
|
||||
|
||||
class MonitorReplica:
|
||||
def __init__(self, root):
|
||||
path = root / "monitor.sqlite3"
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid monitor store")
|
||||
self.db = sqlite3.connect(path, check_same_thread=False, timeout=2)
|
||||
try:
|
||||
path.chmod(0o600)
|
||||
self.lock = threading.RLock()
|
||||
self.maintenance = 0
|
||||
self.db.execute("PRAGMA journal_mode=WAL")
|
||||
self.db.execute("PRAGMA synchronous=FULL")
|
||||
self.db.execute("PRAGMA max_page_count=524288")
|
||||
self.db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS samples(node TEXT,source TEXT,seq INTEGER,at REAL,"
|
||||
"body TEXT,PRIMARY KEY(node,source,seq))"
|
||||
)
|
||||
self.db.execute("CREATE INDEX IF NOT EXISTS samples_time ON samples(node,at)")
|
||||
self.db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS minutes(node TEXT,at INTEGER,body TEXT,"
|
||||
"PRIMARY KEY(node,at))"
|
||||
)
|
||||
self.db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS events(node TEXT,source TEXT,seq INTEGER,at REAL,"
|
||||
"body TEXT,PRIMARY KEY(node,source,seq))"
|
||||
)
|
||||
self.db.execute("CREATE INDEX IF NOT EXISTS events_time ON events(node,at)")
|
||||
self.db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS states(node TEXT PRIMARY KEY,source TEXT,"
|
||||
"body TEXT,received REAL,ack INTEGER)"
|
||||
)
|
||||
self.db.commit()
|
||||
except Exception:
|
||||
self.db.close()
|
||||
raise
|
||||
def checked_snapshot(value):
|
||||
if not isinstance(value, dict) or value.get("schema") != SCHEMA:
|
||||
return None
|
||||
source = value.get("source_id")
|
||||
if not isinstance(source, str) or str(UUID(source)) != source:
|
||||
raise ValueError("Invalid source")
|
||||
definitions = value.get("definitions")
|
||||
if not isinstance(definitions, dict) or len(definitions) > 384:
|
||||
raise ValueError("Definition budget")
|
||||
for key, definition in definitions.items():
|
||||
if (
|
||||
not isinstance(key, str)
|
||||
or not KEY.fullmatch(key)
|
||||
or not isinstance(definition, dict)
|
||||
or set(definition) != {"label", "group", "resource", "unit", "reason"}
|
||||
):
|
||||
raise ValueError("Invalid definition")
|
||||
if any(
|
||||
(name != "reason" or v is not None) and (not isinstance(v, str) or len(v) > 256)
|
||||
for name, v in definition.items()
|
||||
):
|
||||
raise ValueError("Invalid definition")
|
||||
if value.get("latest") is None:
|
||||
return None
|
||||
sample = checked_sample(value["latest"])
|
||||
if len(sample.encode()) > 32768:
|
||||
raise ValueError("Sample budget")
|
||||
# Projection precedes serialization: backfill, archive metadata and unknown
|
||||
# extensions are neither walked nor retained on the operator machine.
|
||||
snapshot = {
|
||||
"schema": SCHEMA,
|
||||
"source_id": source,
|
||||
"definitions": definitions,
|
||||
"latest": value["latest"],
|
||||
}
|
||||
payload = json.dumps(snapshot, allow_nan=False, separators=(",", ":"), sort_keys=True)
|
||||
if len(payload.encode()) > MAX_SNAPSHOT_BYTES:
|
||||
raise ValueError("Live snapshot budget")
|
||||
return payload, sample
|
||||
|
||||
|
||||
def unavailable():
|
||||
return dict(
|
||||
available=False,
|
||||
fresh=False,
|
||||
mode="live",
|
||||
history_available=False,
|
||||
ttl_seconds=TTL_SECONDS,
|
||||
source_id=None,
|
||||
latest=None,
|
||||
definitions={},
|
||||
events=[],
|
||||
received_at=None,
|
||||
sample_age_seconds=None,
|
||||
received_age_seconds=None,
|
||||
expires_in_seconds=0,
|
||||
)
|
||||
|
||||
|
||||
class LiveMonitor:
|
||||
"""One serialized snapshot per node, with monotonic expiry and UTC day reset."""
|
||||
|
||||
def __init__(self, *, clock=None, monotonic=None):
|
||||
self.clock = clock or time.time
|
||||
self.monotonic = monotonic or time.monotonic
|
||||
self.lock = threading.RLock()
|
||||
self.entries = {}
|
||||
self.day = int(self.clock() // 86400)
|
||||
|
||||
def _prune(self):
|
||||
now, tick = self.clock(), self.monotonic()
|
||||
day = int(now // 86400)
|
||||
if day != self.day:
|
||||
self.entries.clear()
|
||||
self.day = day
|
||||
for node, entry in list(self.entries.items()):
|
||||
age = now - entry["at"]
|
||||
if (
|
||||
tick - entry["tick"] >= TTL_SECONDS
|
||||
or age >= TTL_SECONDS
|
||||
or age < -FUTURE_SKEW_SECONDS
|
||||
):
|
||||
del self.entries[node]
|
||||
|
||||
def prune(self):
|
||||
with self.lock:
|
||||
self._prune()
|
||||
|
||||
def ingest(self, node, value):
|
||||
if not isinstance(value, dict) or value.get("schema") != SCHEMA:
|
||||
if not isinstance(node, str) or not KEY.fullmatch(node):
|
||||
raise ValueError("Invalid node")
|
||||
checked = checked_snapshot(value)
|
||||
if checked is None:
|
||||
return None
|
||||
source = value.get("source_id")
|
||||
if not isinstance(source, str) or str(UUID(source)) != source:
|
||||
raise ValueError("Invalid source")
|
||||
definitions = value.get("definitions")
|
||||
if not isinstance(definitions, dict) or len(definitions) > 384:
|
||||
raise ValueError("Definition budget")
|
||||
for key, definition in definitions.items():
|
||||
if (
|
||||
not KEY.fullmatch(key)
|
||||
or not isinstance(definition, dict)
|
||||
or set(definition) != {"label", "group", "resource", "unit", "reason"}
|
||||
):
|
||||
raise ValueError("Invalid definition")
|
||||
if any(
|
||||
v is not None and (not isinstance(v, str) or len(v) > 256)
|
||||
for v in definition.values()
|
||||
):
|
||||
raise ValueError("Invalid definition")
|
||||
if value.get("latest") is not None:
|
||||
checked_sample(value["latest"])
|
||||
batch = value.get("batch") or {}
|
||||
rows = batch.get("samples", [])
|
||||
if (
|
||||
not isinstance(rows, list)
|
||||
or len(rows) > 32
|
||||
or (rows and (batch.get("source_id") != source or batch.get("schema") != SCHEMA))
|
||||
):
|
||||
raise ValueError("Invalid batch")
|
||||
serialized = [(row, checked_sample(row)) for row in rows]
|
||||
if sum(len(text.encode()) for _, text in serialized) > 196608:
|
||||
raise ValueError("Batch budget")
|
||||
if any(
|
||||
a[0]["seq"] >= b[0]["seq"] for a, b in zip(serialized, serialized[1:], strict=False)
|
||||
):
|
||||
raise ValueError("Unordered batch")
|
||||
snapshot = {
|
||||
key: item
|
||||
for key, item in value.items()
|
||||
if key
|
||||
in {
|
||||
"schema",
|
||||
"source_id",
|
||||
"latest",
|
||||
"definitions",
|
||||
"storage",
|
||||
"database_bytes",
|
||||
"sample_interval_seconds",
|
||||
"retention_days",
|
||||
"database_budget_bytes",
|
||||
"free_reserve_bytes",
|
||||
}
|
||||
}
|
||||
snapshot.update(
|
||||
retained_since=batch.get("retained_since"), first_seq=batch.get("first_seq")
|
||||
)
|
||||
with self.lock, self.db:
|
||||
previous = self.db.execute(
|
||||
"SELECT source,ack FROM states WHERE node=?", (node,)
|
||||
).fetchone()
|
||||
ack = previous[1] if previous and previous[0] == source else 0
|
||||
minutes = {}
|
||||
for row, text in serialized:
|
||||
old = self.db.execute(
|
||||
"SELECT body FROM samples WHERE node=? AND source=? AND seq=?",
|
||||
(node, source, row["seq"]),
|
||||
).fetchone()
|
||||
if old and old[0] != text:
|
||||
raise ValueError("Conflicting history sequence")
|
||||
self.db.execute(
|
||||
"INSERT OR IGNORE INTO samples VALUES(?,?,?,?,?)",
|
||||
(node, source, row["seq"], row["at"], text),
|
||||
)
|
||||
if not old:
|
||||
minute = int(row["at"] // 60) * 60
|
||||
if minute not in minutes:
|
||||
saved = self.db.execute(
|
||||
"SELECT body FROM minutes WHERE node=? AND at=?", (node, minute)
|
||||
).fetchone()
|
||||
minutes[minute] = json.loads(saved[0]) if saved else {}
|
||||
for key, number in row["values"].items():
|
||||
if number is not None:
|
||||
aggregate = minutes[minute].setdefault(key, [number, number, 0, 0])
|
||||
aggregate[0] = min(aggregate[0], number)
|
||||
aggregate[1] = max(aggregate[1], number)
|
||||
aggregate[2] += number
|
||||
aggregate[3] += 1
|
||||
if row["events"]:
|
||||
self.db.execute(
|
||||
"INSERT INTO events VALUES(?,?,?,?,?)",
|
||||
(node, source, row["seq"], row["at"], json.dumps(row["events"])),
|
||||
)
|
||||
ack = max(ack, row["seq"])
|
||||
for minute, aggregate in minutes.items():
|
||||
self.db.execute(
|
||||
"INSERT INTO minutes VALUES(?,?,?) ON CONFLICT(node,at) "
|
||||
"DO UPDATE SET body=excluded.body",
|
||||
(node, minute, json.dumps(aggregate)),
|
||||
)
|
||||
self.db.execute(
|
||||
"INSERT INTO states VALUES(?,?,?,?,?) ON CONFLICT(node) DO UPDATE SET "
|
||||
"source=excluded.source,body=excluded.body,received=excluded.received,ack=excluded.ack",
|
||||
(node, source, json.dumps(snapshot), time.time(), ack),
|
||||
payload, sample = checked
|
||||
snapshot = json.loads(payload)
|
||||
latest, source = snapshot["latest"], snapshot["source_id"]
|
||||
with self.lock:
|
||||
self._prune()
|
||||
now, tick = self.clock(), self.monotonic()
|
||||
previous = self.entries.get(node)
|
||||
ack = dict(source_id=source, after=latest["seq"], mode="live")
|
||||
# Consuming a stale live observation advances transport only; it
|
||||
# cannot populate the current view or trigger historical backfill.
|
||||
if not -FUTURE_SKEW_SECONDS <= now - latest["at"] < TTL_SECONDS:
|
||||
return ack
|
||||
if previous and previous["source"] == source:
|
||||
if latest["seq"] < previous["seq"]:
|
||||
return dict(source_id=source, after=previous["seq"], mode="live")
|
||||
if latest["seq"] == previous["seq"]:
|
||||
if sample != previous["sample"]:
|
||||
raise ValueError("Conflicting live sequence")
|
||||
# Repeated packets never extend freshness or expiry.
|
||||
return ack
|
||||
if previous and latest["at"] < previous["at"]:
|
||||
return None
|
||||
if previous is None and len(self.entries) >= MAX_NODES:
|
||||
return None
|
||||
self.entries[node] = dict(
|
||||
payload=payload,
|
||||
sample=sample,
|
||||
source=source,
|
||||
seq=latest["seq"],
|
||||
at=latest["at"],
|
||||
tick=tick,
|
||||
received=now,
|
||||
)
|
||||
if time.time() - self.maintenance > 60:
|
||||
self.db.execute("DELETE FROM samples WHERE at<?", (time.time() - 7 * 86400,))
|
||||
self.db.execute("DELETE FROM minutes WHERE at<?", (time.time() - 7 * 86400,))
|
||||
self.db.execute("DELETE FROM events WHERE at<?", (time.time() - 7 * 86400,))
|
||||
self.maintenance = time.time()
|
||||
return dict(source_id=source, after=ack)
|
||||
return ack
|
||||
|
||||
def query(self, node, metric="cpu.usage", window=900, end=None):
|
||||
if not KEY.fullmatch(metric) or window not in (900, 3600, 21600, 86400, 604800):
|
||||
raise ValueError("Invalid range")
|
||||
end = time.time() if end is None else end
|
||||
if not math.isfinite(end) or end < 0:
|
||||
raise ValueError("Invalid time")
|
||||
coarse = window >= 21600
|
||||
width = math.ceil(window / 300 / 60) * 60 if coarse else max(1, window // 300)
|
||||
if coarse:
|
||||
end = math.floor(end / 60) * 60
|
||||
start = end - window
|
||||
path = '$.values."' + metric + '"'
|
||||
def query(self, node):
|
||||
with self.lock:
|
||||
row = self.db.execute(
|
||||
"SELECT body,received,ack FROM states WHERE node=?", (node,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return dict(available=False, series=[], events=[])
|
||||
snapshot = json.loads(row[0])
|
||||
if coarse:
|
||||
aggregate = '$."' + metric + '"'
|
||||
points = self.db.execute(
|
||||
"SELECT CAST(at/? AS INTEGER),min(json_extract(body,?)), "
|
||||
"max(json_extract(body,?)),sum(json_extract(body,?))*1.0/"
|
||||
"nullif(sum(json_extract(body,?)),0),sum(json_extract(body,?)) "
|
||||
"FROM minutes WHERE node=? AND at>=? AND at<? "
|
||||
"GROUP BY CAST(at/? AS INTEGER) ORDER BY 1",
|
||||
(
|
||||
width,
|
||||
aggregate + "[0]",
|
||||
aggregate + "[1]",
|
||||
aggregate + "[2]",
|
||||
aggregate + "[3]",
|
||||
aggregate + "[3]",
|
||||
node,
|
||||
start,
|
||||
end,
|
||||
width,
|
||||
),
|
||||
).fetchall()
|
||||
else:
|
||||
points = self.db.execute(
|
||||
"SELECT CAST(at/? AS INTEGER),min(json_extract(body,?)), "
|
||||
"max(json_extract(body,?)),avg(json_extract(body,?)),"
|
||||
"count(json_extract(body,?)) FROM samples "
|
||||
"WHERE node=? AND at>=? AND at<=? GROUP BY CAST(at/? AS INTEGER) ORDER BY 1",
|
||||
(width, path, path, path, path, node, start, end, width),
|
||||
).fetchall()
|
||||
event_rows = self.db.execute(
|
||||
"SELECT body FROM events WHERE node=? AND at>=? AND at<=? "
|
||||
"ORDER BY at DESC LIMIT 64",
|
||||
(node, start, end),
|
||||
).fetchall()
|
||||
earliest = self.db.execute(
|
||||
"SELECT min(at) FROM samples WHERE node=?", (node,)
|
||||
).fetchone()[0]
|
||||
latest = snapshot.get("latest")
|
||||
fresh = bool(latest and -5 <= time.time() - latest["at"] < 10 and time.time() - row[1] < 15)
|
||||
return dict(
|
||||
available=True,
|
||||
**snapshot,
|
||||
fresh=fresh,
|
||||
received_at=row[1],
|
||||
replicated_after=row[2],
|
||||
archive_since=earliest,
|
||||
backlog=max(0, (latest or {}).get("seq", 0) - row[2]),
|
||||
start=start,
|
||||
end=end,
|
||||
bucket_seconds=width,
|
||||
series=[
|
||||
dict(at=bucket * width, min=minimum, max=maximum, mean=mean, count=count)
|
||||
for bucket, minimum, maximum, mean, count in points
|
||||
],
|
||||
events=[event for record in event_rows for event in json.loads(record[0])][:64],
|
||||
)
|
||||
self._prune()
|
||||
entry = self.entries.get(node)
|
||||
if entry is None:
|
||||
return unavailable()
|
||||
now = self.clock()
|
||||
sample_age = now - entry["at"]
|
||||
received_age = self.monotonic() - entry["tick"]
|
||||
snapshot = json.loads(entry["payload"])
|
||||
events = [
|
||||
e
|
||||
for e in snapshot["latest"]["events"]
|
||||
if -FUTURE_SKEW_SECONDS <= now - e["at"] < TTL_SECONDS
|
||||
]
|
||||
# Do not leave expired events accessible via the nested sample.
|
||||
snapshot["latest"]["events"] = events
|
||||
return dict(
|
||||
**snapshot,
|
||||
available=True,
|
||||
mode="live",
|
||||
history_available=False,
|
||||
ttl_seconds=TTL_SECONDS,
|
||||
fresh=sample_age < SAMPLE_FRESH_SECONDS and received_age < RECEIVE_FRESH_SECONDS,
|
||||
received_at=entry["received"],
|
||||
sample_age_seconds=sample_age,
|
||||
received_age_seconds=received_age,
|
||||
expires_in_seconds=max(
|
||||
0, min(TTL_SECONDS - sample_age, TTL_SECONDS - received_age)
|
||||
),
|
||||
events=events,
|
||||
)
|
||||
|
||||
def close(self):
|
||||
def clear(self):
|
||||
with self.lock:
|
||||
self.db.close()
|
||||
self.entries.clear()
|
||||
|
||||
|
||||
class MonitorReceiver:
|
||||
"""Replica I/O never runs under the fleet/control lock, including startup.
|
||||
"""Bounded in-memory admission only; no disk I/O under the fleet lock.
|
||||
|
||||
Heartbeats may repeat a batch until this worker commits it. Replacing a
|
||||
queued retry is safe: the sender advances only from the returned commit ACK.
|
||||
An idle sweeper expires snapshots even when nobody polls the API. Invalid
|
||||
optional monitor payloads are rejected without disrupting control traffic.
|
||||
"""
|
||||
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
def __init__(self, root=None, *, clock=None, monotonic=None):
|
||||
# root remains an accepted constructor argument for FleetRegistry. It is
|
||||
# deliberately never read, created, or retained as a storage destination.
|
||||
self.live = LiveMonitor(clock=clock, monotonic=monotonic)
|
||||
self.lock = threading.Lock()
|
||||
self.pending = {}
|
||||
self.acks = {}
|
||||
self.archive = None
|
||||
self.worker = None
|
||||
self.wake = threading.Event()
|
||||
self.stop = threading.Event()
|
||||
self.worker = None
|
||||
|
||||
def _start(self):
|
||||
with self.lock:
|
||||
if self.stop.is_set():
|
||||
return False
|
||||
if self.worker is None:
|
||||
self.worker = threading.Thread(
|
||||
target=self.run, name="fleet-monitor-expiry", daemon=True
|
||||
)
|
||||
self.worker.start()
|
||||
return True
|
||||
|
||||
def submit(self, node, value):
|
||||
if not isinstance(value, dict) or value.get("schema") != SCHEMA:
|
||||
if not self._start():
|
||||
return None
|
||||
with self.lock:
|
||||
if node not in self.pending and len(self.pending) >= 32:
|
||||
if self.stop.is_set():
|
||||
return None
|
||||
self.pending[node] = value
|
||||
if self.worker is None:
|
||||
self.worker = threading.Thread(
|
||||
target=self.run, name="fleet-monitor-replica", daemon=True
|
||||
)
|
||||
self.worker.start()
|
||||
self.wake.set()
|
||||
ack = self.acks.get(node)
|
||||
return ack if ack and ack["source_id"] == value.get("source_id") else None
|
||||
return self.live.ingest(node, value)
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
while not self.stop.is_set():
|
||||
self.wake.wait(1)
|
||||
with self.lock:
|
||||
pending, self.pending = self.pending, {}
|
||||
self.wake.clear()
|
||||
if self.archive is None:
|
||||
try:
|
||||
self.archive = MonitorReplica(self.root)
|
||||
except (OSError, ValueError, sqlite3.Error):
|
||||
continue
|
||||
for node, value in pending.items():
|
||||
try:
|
||||
if self.archive is None:
|
||||
self.archive = MonitorReplica(self.root)
|
||||
ack = self.archive.ingest(node, value)
|
||||
with self.lock:
|
||||
self.acks[node] = ack
|
||||
except (OSError, ValueError, TypeError, KeyError, sqlite3.Error):
|
||||
# No ACK: the board retains and retries its own archive.
|
||||
continue
|
||||
finally:
|
||||
if self.archive is not None:
|
||||
self.archive.close()
|
||||
while not self.stop.wait(1):
|
||||
self.live.prune()
|
||||
|
||||
def query(self, *args, **kwargs):
|
||||
with self.lock:
|
||||
if self.worker is None:
|
||||
self.worker = threading.Thread(
|
||||
target=self.run, name="fleet-monitor-replica", daemon=True
|
||||
)
|
||||
self.worker.start()
|
||||
self.wake.set()
|
||||
try:
|
||||
if self.archive is not None:
|
||||
return self.archive.query(*args, **kwargs)
|
||||
except sqlite3.Error:
|
||||
pass
|
||||
return dict(available=False, series=[], events=[])
|
||||
def query(self, node):
|
||||
if self.stop.is_set():
|
||||
return unavailable()
|
||||
return self.live.query(node)
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
self.wake.set()
|
||||
with self.lock:
|
||||
self.stop.set()
|
||||
if self.worker is not None:
|
||||
self.worker.join(5)
|
||||
self.worker.join(2)
|
||||
self.live.clear()
|
||||
|
||||
+209
-79
@@ -6,7 +6,7 @@ from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.monitor import SCHEMA, MonitorReceiver, MonitorReplica
|
||||
from k1link.fleet.monitor import MAX_NODES, SCHEMA, LiveMonitor, MonitorReceiver
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -37,70 +37,6 @@ def envelope(source, rows, latest=None):
|
||||
)
|
||||
|
||||
|
||||
def test_replica_retries_restart_backfill_and_latest_are_separate(tmp_path):
|
||||
source, boot = str(uuid4()), str(uuid4())
|
||||
now = time.time()
|
||||
rows = [record(i, now - 40 + i, boot) for i in range(1, 41)]
|
||||
archive = MonitorReplica(tmp_path)
|
||||
assert archive.ingest("board", envelope(source, rows[:32], rows[-1]))["after"] == 32
|
||||
result = archive.query("board")
|
||||
assert result["latest"]["seq"] == 40 and result["backlog"] == 8
|
||||
assert archive.db.execute("SELECT count(*) FROM samples").fetchone()[0] == 32
|
||||
archive.close()
|
||||
archive = MonitorReplica(tmp_path)
|
||||
# A lost reply cannot duplicate history; ACK comes from the durable commit.
|
||||
assert archive.ingest("board", envelope(source, rows[:32], rows[-1]))["after"] == 32
|
||||
assert archive.ingest("board", envelope(source, rows[32:]))["after"] == 40
|
||||
assert archive.db.execute("SELECT count(*) FROM samples").fetchone()[0] == 40
|
||||
assert archive.query("board")["backlog"] == 0
|
||||
# Retention on the board can leave a real gap; no zero samples are invented.
|
||||
assert archive.ingest("board", envelope(source, [record(51, now + 11, boot)]))["after"] == 51
|
||||
archive.close()
|
||||
|
||||
|
||||
def test_conflicting_or_nonfinite_batch_rolls_back_and_missing_values_are_null(tmp_path):
|
||||
source, boot = str(uuid4()), str(uuid4())
|
||||
now = time.time()
|
||||
archive = MonitorReplica(tmp_path)
|
||||
original = record(2, now - 20, boot)
|
||||
archive.ingest("board", envelope(source, [original]))
|
||||
bad = envelope(source, [record(1, now - 21, boot), {**original, "values": {"cpu.usage": 99}}])
|
||||
with pytest.raises(ValueError):
|
||||
archive.ingest("board", bad)
|
||||
assert archive.db.execute("SELECT count(*) FROM samples").fetchone()[0] == 1
|
||||
with pytest.raises(ValueError):
|
||||
archive.ingest("board", envelope(source, [record(3, now, boot, float("nan"))]))
|
||||
archive.ingest("board", envelope(source, [record(3, now, boot, None)]))
|
||||
point = archive.query("board")["series"][-1]
|
||||
assert point["max"] is None and point["count"] == 0
|
||||
archive.close()
|
||||
|
||||
|
||||
def test_receiver_failure_isolated_and_offline_history_reopens(tmp_path, monkeypatch):
|
||||
source, boot = str(uuid4()), str(uuid4())
|
||||
archive = MonitorReplica(tmp_path)
|
||||
archive.ingest("board", envelope(source, [record(1, time.time(), boot)]))
|
||||
archive.close()
|
||||
receiver = MonitorReceiver(tmp_path)
|
||||
try:
|
||||
deadline = time.monotonic() + 2
|
||||
while not receiver.query("board")["available"] and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert receiver.query("board")["available"]
|
||||
monkeypatch.setattr(
|
||||
receiver.archive,
|
||||
"ingest",
|
||||
lambda *_: (_ for _ in ()).throw(sqlite3.OperationalError("synthetic full disk")),
|
||||
)
|
||||
start = time.monotonic()
|
||||
assert receiver.submit("board", envelope(source, [record(2, time.time(), boot)])) is None
|
||||
assert time.monotonic() - start < 0.1
|
||||
time.sleep(0.05)
|
||||
assert receiver.acks.get("board") is None
|
||||
finally:
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_linux_rates_distinguish_absent_initial_reset_and_gap(tmp_path):
|
||||
now = [100]
|
||||
|
||||
@@ -151,18 +87,212 @@ def test_journal_retains_classification_without_freeform_data():
|
||||
assert classify({"MESSAGE": "private Wi-Fi password"}) is None
|
||||
|
||||
|
||||
def test_long_range_aggregates_keep_peaks_counts_and_exclude_incomplete_minute(tmp_path):
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.wall = 1_000_000.0
|
||||
self.tick = 100.0
|
||||
|
||||
def advance(self, seconds):
|
||||
self.wall += seconds
|
||||
self.tick += seconds
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def live():
|
||||
clock = Clock()
|
||||
state = LiveMonitor(clock=lambda: clock.wall, monotonic=lambda: clock.tick)
|
||||
return state, clock, str(uuid4()), str(uuid4())
|
||||
|
||||
|
||||
def test_latest_is_accepted_without_replicating_backfill_or_creating_files(live, tmp_path):
|
||||
state, clock, source, boot = live
|
||||
old = [record(i, clock.wall - 100 + i, boot) for i in range(1, 33)]
|
||||
value = envelope(source, old, record(1000, clock.wall, boot))
|
||||
value["unrelated"] = object() # Unknown fields/backfill are not serialized.
|
||||
ack = state.ingest("board", value)
|
||||
assert ack == dict(source_id=source, after=1000, mode="live")
|
||||
result = state.query("board")
|
||||
assert result["fresh"] and result["latest"]["seq"] == 1000
|
||||
assert result["mode"] == "live" and result["history_available"] is False
|
||||
assert not {"series", "batch", "backlog", "archive_since", "database_bytes"} & result.keys()
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
|
||||
def test_duplicates_never_extend_freshness_or_expiry(live):
|
||||
state, clock, source, boot = live
|
||||
value = envelope(source, [record(1, clock.wall, boot)])
|
||||
state.ingest("board", value)
|
||||
clock.advance(11)
|
||||
assert state.ingest("board", value)["after"] == 1
|
||||
result = state.query("board")
|
||||
assert result["available"] and not result["fresh"]
|
||||
assert result["received_age_seconds"] == 11 and result["expires_in_seconds"] == 19
|
||||
clock.advance(19)
|
||||
assert not state.query("board")["available"] and not state.entries
|
||||
state.ingest("board", value)
|
||||
assert not state.entries
|
||||
|
||||
|
||||
def test_utc_day_reset_and_monotonic_expiry(live):
|
||||
state, clock, source, boot = live
|
||||
clock.wall = (int(clock.wall // 86400) + 1) * 86400 - 2
|
||||
state.ingest("board", envelope(source, [record(1, clock.wall, boot)]))
|
||||
clock.advance(3)
|
||||
assert not state.query("board")["available"]
|
||||
state.ingest("board", envelope(source, [record(2, clock.wall, boot)]))
|
||||
assert state.query("board")["fresh"]
|
||||
clock.tick += 30 # Wall time can freeze/adjust; monotonic time still expires RAM.
|
||||
assert not state.query("board")["available"]
|
||||
|
||||
|
||||
def test_out_of_order_conflicting_and_changed_source_cannot_restore_old_values(live):
|
||||
state, clock, source, boot = live
|
||||
current = record(10, clock.wall, boot, 50)
|
||||
state.ingest("board", envelope(source, [current]))
|
||||
assert state.ingest("board", envelope(source, [record(9, clock.wall - 1, boot)]))["after"] == 10
|
||||
with pytest.raises(ValueError, match="Conflicting"):
|
||||
state.ingest("board", envelope(source, [{**current, "values": {"cpu.usage": 99}}]))
|
||||
assert state.query("board")["latest"]["values"]["cpu.usage"] == 50
|
||||
newer = str(uuid4())
|
||||
clock.advance(1)
|
||||
state.ingest("board", envelope(newer, [record(1, clock.wall, boot, 60)]))
|
||||
assert state.ingest("board", envelope(source, [current])) is None
|
||||
assert state.query("board")["source_id"] == newer
|
||||
|
||||
|
||||
@pytest.mark.parametrize("age", [30, 3600, -6])
|
||||
def test_stale_or_future_clock_snapshots_do_not_populate_live_state(live, age):
|
||||
state, clock, source, boot = live
|
||||
assert (
|
||||
state.ingest("board", envelope(source, [record(1, clock.wall - age, boot)]))["mode"]
|
||||
== "live"
|
||||
)
|
||||
assert not state.query("board")["available"]
|
||||
|
||||
|
||||
def test_node_capacity_is_bounded_and_released_by_expiry(live):
|
||||
state, clock, source, boot = live
|
||||
value = envelope(source, [record(1, clock.wall, boot)])
|
||||
for i in range(MAX_NODES):
|
||||
assert state.ingest(f"board-{i}", value)
|
||||
assert state.ingest("overflow", value) is None
|
||||
assert len(state.entries) == MAX_NODES
|
||||
clock.advance(31)
|
||||
assert state.ingest("overflow", envelope(source, [record(2, clock.wall, boot)]))
|
||||
assert len(state.entries) == 1
|
||||
|
||||
|
||||
def test_snapshot_size_and_metric_validation_leave_previous_state_untouched(live):
|
||||
state, clock, source, boot = live
|
||||
value = envelope(source, [record(1, clock.wall, boot)])
|
||||
state.ingest("board", value)
|
||||
huge = envelope(source, [record(2, clock.wall, boot)])
|
||||
huge["definitions"] = {
|
||||
f"metric{i}": dict(
|
||||
label="x" * 256, group="x" * 256, resource="x" * 256, unit="x" * 256, reason="x" * 256
|
||||
)
|
||||
for i in range(384)
|
||||
}
|
||||
with pytest.raises(ValueError, match="budget"):
|
||||
state.ingest("board", huge)
|
||||
for invalid in [float("nan"), float("inf"), True, "private text"]:
|
||||
with pytest.raises(ValueError):
|
||||
state.ingest("board", envelope(source, [record(2, clock.wall, boot, invalid)]))
|
||||
assert state.query("board")["latest"]["seq"] == 1
|
||||
|
||||
|
||||
def test_sample_budget_and_invalid_ids_are_rejected(live):
|
||||
state, clock, source, boot = live
|
||||
row = record(1, clock.wall, boot)
|
||||
row["values"] = {"m" * 175 + str(i): 1 for i in range(384)}
|
||||
with pytest.raises(ValueError, match="budget"):
|
||||
state.ingest("board", envelope(source, [row]))
|
||||
for bad in [None, 23, False, {}, "not-a-uuid"]:
|
||||
with pytest.raises((ValueError, TypeError)):
|
||||
state.ingest("board", envelope(source, [record(1, clock.wall, bad)]))
|
||||
|
||||
|
||||
def test_snapshot_is_detached_and_missing_values_remain_null(live):
|
||||
state, clock, source, boot = live
|
||||
value = envelope(source, [record(1, clock.wall, boot, None)])
|
||||
state.ingest("board", value)
|
||||
value["latest"]["values"]["cpu.usage"] = 100
|
||||
result = state.query("board")
|
||||
assert result["latest"]["values"]["cpu.usage"] is None
|
||||
result["latest"]["values"]["cpu.usage"] = 99
|
||||
assert state.query("board")["latest"]["values"]["cpu.usage"] is None
|
||||
|
||||
|
||||
def test_only_events_in_latest_unexpired_observation_are_visible(live):
|
||||
state, clock, source, boot = live
|
||||
row = record(1, clock.wall, boot)
|
||||
row["events"] = [
|
||||
dict(code="usb-error", kind="Kernel", locations=[], at=clock.wall),
|
||||
dict(code="system-oom", kind="Kernel", locations=[], at=clock.wall - 60),
|
||||
]
|
||||
state.ingest("board", envelope(source, [row]))
|
||||
assert [e["code"] for e in state.query("board")["events"]] == ["usb-error"]
|
||||
assert len(state.query("board")["latest"]["events"]) == 1
|
||||
clock.advance(1)
|
||||
state.ingest("board", envelope(source, [record(2, clock.wall, boot)]))
|
||||
assert state.query("board")["events"] == []
|
||||
|
||||
|
||||
def test_receiver_never_opens_legacy_db_and_restart_has_no_history(tmp_path, monkeypatch):
|
||||
path = tmp_path / "monitor.sqlite3"
|
||||
path.write_bytes(b"old telemetry, preserved until explicit retirement")
|
||||
source, boot = str(uuid4()), str(uuid4())
|
||||
now = int(time.time()//60)*60
|
||||
archive = MonitorReplica(tmp_path)
|
||||
rows = [record(1, now-120, boot, 10), record(2, now-110, boot, 90),
|
||||
record(3, now-60, boot, 30), record(4, now+1, boot, 100)]
|
||||
value = envelope(source, rows)
|
||||
archive.ingest('board', value)
|
||||
archive.ingest('board', value) # Duplicate delivery cannot inflate aggregates.
|
||||
result = archive.query('board', window=21600, end=now+10)
|
||||
assert result['end'] == now
|
||||
assert sum(point['count'] for point in result['series']) == 3
|
||||
assert max(point['max'] for point in result['series']) == 90
|
||||
assert min(point['min'] for point in result['series']) == 10
|
||||
archive.close()
|
||||
monkeypatch.setattr(
|
||||
sqlite3, "connect", lambda *args, **kwargs: pytest.fail("monitor opened SQLite")
|
||||
)
|
||||
receiver = MonitorReceiver(tmp_path)
|
||||
assert receiver.submit("board", envelope(source, [record(1, time.time(), boot)]))["after"] == 1
|
||||
assert receiver.query("board")["available"]
|
||||
receiver.close()
|
||||
assert not receiver.worker.is_alive()
|
||||
assert receiver.submit("board", envelope(source, [record(2, time.time(), boot)])) is None
|
||||
assert path.read_bytes() == b"old telemetry, preserved until explicit retirement"
|
||||
another = MonitorReceiver(tmp_path)
|
||||
assert not another.query("board")["available"]
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
another.close()
|
||||
|
||||
|
||||
def test_idle_sweeper_expires_without_api_reads(tmp_path):
|
||||
clock = Clock()
|
||||
receiver = MonitorReceiver(tmp_path, clock=lambda: clock.wall, monotonic=lambda: clock.tick)
|
||||
try:
|
||||
source, boot = str(uuid4()), str(uuid4())
|
||||
receiver.submit("board", envelope(source, [record(1, clock.wall, boot)]))
|
||||
clock.advance(31)
|
||||
deadline = time.monotonic() + 2
|
||||
while receiver.live.entries and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert not receiver.live.entries
|
||||
finally:
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_live_api_refuses_historical_queries_and_returns_no_store(live):
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.web import fleet_api
|
||||
|
||||
state, clock, source, boot = live
|
||||
state.ingest("board", envelope(source, [record(1, clock.wall, boot)]))
|
||||
fleet = SimpleNamespace(
|
||||
lock=threading.RLock(), find=lambda _: {"node_id": "board"}, monitor=state
|
||||
)
|
||||
app = FastAPI()
|
||||
app.include_router(fleet_api.router)
|
||||
app.dependency_overrides[fleet_api.local_operator] = lambda: fleet
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/api/v1/fleet/vehicle/monitor")
|
||||
assert response.status_code == 200 and response.headers["cache-control"] == "no-store"
|
||||
assert response.json()["mode"] == "live"
|
||||
for query in ["window=900", "end=1000000", "metric=cpu.usage"]:
|
||||
assert client.get("/api/v1/fleet/vehicle/monitor?" + query).status_code == 400
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"retire_monitor_replica",
|
||||
Path(__file__).resolve().parents[1] / "scripts/retire_monitor_replica.py",
|
||||
)
|
||||
retire = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(retire)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def root(tmp_path):
|
||||
fleet = tmp_path / ".runtime/mission-core/fleet"
|
||||
fleet.mkdir(parents=True)
|
||||
with closing(sqlite3.connect(fleet / "monitor.sqlite3")) as db:
|
||||
for table, columns in retire.TABLES.items():
|
||||
db.execute(f"CREATE TABLE {table} ({', '.join(columns)})")
|
||||
db.commit()
|
||||
(fleet / "monitor.sqlite3-wal").write_bytes(b"closed legacy sidecar")
|
||||
(fleet / "monitor.sqlite3-shm").write_bytes(b"closed legacy sidecar")
|
||||
return tmp_path
|
||||
|
||||
|
||||
def accepted():
|
||||
return {"mode": "live", "core_operational": True, "verified_vehicles": 1}
|
||||
|
||||
|
||||
def test_only_exact_obsolete_files_removed_after_live_acceptance(root):
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
unrelated = fleet / "registry.json"
|
||||
unrelated.write_text("durable fleet data")
|
||||
snapshot = retire.plan(root)
|
||||
receipt = retire.apply(snapshot, probe=accepted, closed=lambda _: None)
|
||||
assert receipt["status"] == "complete" and len(receipt["removed"]) == 3
|
||||
assert unrelated.read_text() == "durable fleet data"
|
||||
assert retire.plan(root)["files"] == []
|
||||
assert json.loads(Path(receipt["receipt"]).read_text())["removed"] == receipt["removed"]
|
||||
|
||||
|
||||
def test_stale_plan_does_not_remove_any_files(root):
|
||||
snapshot = retire.plan(root)
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
(fleet / "monitor.sqlite3-wal").write_bytes(b"changed")
|
||||
with pytest.raises(ValueError, match="Stale"):
|
||||
retire.apply(snapshot, probe=accepted, closed=lambda _: None)
|
||||
assert all((fleet / name).exists() for name in retire.FILES)
|
||||
|
||||
|
||||
def test_open_reader_or_old_running_core_blocks_retirement(root):
|
||||
snapshot = retire.plan(root)
|
||||
|
||||
def blocked(*_):
|
||||
raise ValueError("not accepted")
|
||||
|
||||
with pytest.raises(ValueError, match="accepted"):
|
||||
retire.apply(snapshot, probe=blocked, closed=lambda _: None)
|
||||
with pytest.raises(ValueError, match="accepted"):
|
||||
retire.apply(snapshot, probe=accepted, closed=blocked)
|
||||
assert len(retire.plan(root)["files"]) == 3
|
||||
|
||||
|
||||
def test_unexpected_schema_or_symlink_is_never_deleted(root):
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
with closing(sqlite3.connect(fleet / "monitor.sqlite3")) as db:
|
||||
db.execute("CREATE TABLE recordings (id)")
|
||||
db.commit()
|
||||
with pytest.raises(ValueError, match="tables"):
|
||||
retire.plan(root)
|
||||
side = fleet / "monitor.sqlite3-wal"
|
||||
side.unlink(missing_ok=True)
|
||||
side.symlink_to(fleet / "monitor.sqlite3")
|
||||
with pytest.raises(ValueError, match="regular"):
|
||||
retire.plan(root)
|
||||
|
||||
|
||||
def test_partial_retirement_keeps_main_last_and_can_be_replanned(root):
|
||||
snapshot = retire.plan(root)
|
||||
unlink = Path.unlink
|
||||
|
||||
def fail(path, *args, **kwargs):
|
||||
if path.name == "monitor.sqlite3-wal":
|
||||
raise OSError("simulated interruption")
|
||||
return unlink(path, *args, **kwargs)
|
||||
|
||||
with patch.object(Path, "unlink", fail), pytest.raises(OSError, match="interruption"):
|
||||
retire.apply(snapshot, probe=accepted, closed=lambda _: None)
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
assert (fleet / "monitor.sqlite3").exists()
|
||||
assert not (fleet / "monitor.sqlite3-shm").exists()
|
||||
receipt = json.loads(
|
||||
next((root / ".runtime/storage-maintenance/monitor-retirement").glob("*.json")).read_text()
|
||||
)
|
||||
assert receipt["status"] == "interrupted" and len(receipt["removed"]) == 1
|
||||
assert (
|
||||
len(retire.apply(retire.plan(root), probe=accepted, closed=lambda _: None)["removed"]) == 2
|
||||
)
|
||||
|
||||
|
||||
def test_orphan_sidecar_is_not_assumed_disposable(root):
|
||||
(root / ".runtime/mission-core/fleet/monitor.sqlite3").unlink()
|
||||
with pytest.raises(ValueError, match="orphan"):
|
||||
retire.plan(root)
|
||||
|
||||
|
||||
def test_actual_open_file_check_refuses_a_reader_and_accepts_closed_file(root):
|
||||
target = root / ".runtime/mission-core/fleet/monitor.sqlite3"
|
||||
with target.open("rb"), pytest.raises(ValueError, match="open"):
|
||||
retire.assert_closed([target])
|
||||
retire.assert_closed([target])
|
||||
Reference in New Issue
Block a user