Compare commits
179 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
291620f5d5 | ||
|
|
f21bd45077 | ||
|
|
75e231c707 | ||
|
|
02afc659a4 | ||
|
|
d501db689c | ||
|
|
6759555744 | ||
|
|
e4d9d7c9ff | ||
|
|
e1f594425e | ||
|
|
9a4542de5f | ||
|
|
7d2650ae5e | ||
|
|
da8fa2a927 | ||
|
|
6a92a1902b | ||
|
|
37b3195b0b | ||
|
|
4b29f08c21 | ||
|
|
49e48a5075 | ||
|
|
bbbfe4b68a | ||
|
|
5dad5b3cd7 | ||
|
|
7d817d8cee | ||
|
|
0004ffaf36 | ||
|
|
8b696f8f1c | ||
|
|
6a063d32b4 | ||
|
|
48aedd25ff | ||
|
|
91d0214cbc | ||
|
|
9d5dd398ca | ||
|
|
29b51ff336 | ||
|
|
6bc447a5bd | ||
|
|
4935dcc045 | ||
|
|
210296a0ff | ||
|
|
fc5a579027 | ||
|
|
ef48a6aed9 | ||
|
|
a2449488a5 | ||
|
|
0a35b393aa | ||
|
|
2bae8a7b6a | ||
|
|
eaae6fd82a | ||
|
|
49309a83bd | ||
|
|
397a589fae | ||
|
|
d5b576a2c1 | ||
|
|
076a6bcbbf | ||
|
|
c6ab8247d9 | ||
|
|
7dc744fe63 | ||
|
|
ae05221495 | ||
|
|
3181c5ef7b | ||
|
|
d7547085e5 | ||
|
|
ae5db47801 | ||
|
|
49bae21a4d | ||
|
|
872dcfc214 | ||
|
|
24753db620 | ||
|
|
1ebf35d845 | ||
|
|
0caade6b20 | ||
|
|
7d98fbf8ba | ||
|
|
d50914e4c7 | ||
|
|
3ea56ef3f8 | ||
|
|
74a3c12857 | ||
|
|
1382f94cf3 | ||
|
|
021c92c66f | ||
|
|
b2fd148f52 | ||
|
|
8b6d69e13c | ||
|
|
673eec54d5 | ||
|
|
49f5496d2a | ||
|
|
39efc4af5c | ||
|
|
8474d93eb0 | ||
|
|
29f9b7da3b | ||
|
|
6851d6f5a3 | ||
|
|
5ca3488c1f | ||
|
|
6612f9ae9c | ||
|
|
12321bb513 | ||
|
|
23cc217221 | ||
|
|
46e25ef3fc | ||
|
|
49bb69e5da | ||
|
|
2c1b51695a | ||
|
|
ac7be4a204 | ||
|
|
ab537d1045 | ||
|
|
80104f0d98 | ||
|
|
15ab7ee002 | ||
|
|
ecff9bcff4 | ||
|
|
2ca0853c9a | ||
|
|
a6632b4acf | ||
|
|
2dcce9452a | ||
|
|
85d2da363a | ||
|
|
8fa98b0b03 | ||
|
|
390d118460 | ||
|
|
16cb3b754b | ||
|
|
519503a523 | ||
|
|
e8d8584647 | ||
|
|
01fae60e37 | ||
|
|
ff67e6cdd6 | ||
|
|
239a86f793 | ||
|
|
b39ee8e805 | ||
|
|
32df851c16 | ||
|
|
c418a9b352 | ||
|
|
b03ddc957d | ||
|
|
ac7762eb00 | ||
|
|
56a315eda1 | ||
|
|
ce6dcfeb65 | ||
|
|
2e92381296 | ||
|
|
e4272ba00d | ||
|
|
18bef06cef | ||
|
|
e35858e96e | ||
|
|
a84e617fc9 | ||
|
|
d7f5ef5ff7 | ||
|
|
539d73bc36 | ||
|
|
7420541df6 | ||
|
|
59ac004b76 | ||
|
|
6eeff4a735 | ||
|
|
4200a99e7e | ||
|
|
c0be101c5f | ||
|
|
6c0cc2b717 | ||
|
|
a3a0d957e2 | ||
|
|
c1f0dde9e9 | ||
|
|
416c73941a | ||
|
|
b3f6d6fbba | ||
|
|
b996695f0a | ||
|
|
7f5f5d0e5d | ||
|
|
6b77b87991 | ||
|
|
0b56e03ae3 | ||
|
|
e04b0c76b0 | ||
|
|
f7ca35ba2c | ||
|
|
c56e04cdf8 | ||
|
|
d2d65a4a60 | ||
|
|
5a7747210f | ||
|
|
6634b33e80 | ||
|
|
2058fff54a | ||
|
|
606e386e86 | ||
|
|
790347af7d | ||
|
|
8618e38a5f | ||
|
|
9a2d7c0286 | ||
|
|
be73014bf5 | ||
|
|
fa8c9305a7 | ||
|
|
d10aa09afa | ||
|
|
9462c2e28a | ||
|
|
e9d8f1a753 | ||
|
|
3914f824ce | ||
|
|
17c4c88423 | ||
|
|
dfc9a2d227 | ||
|
|
c433316179 | ||
|
|
d4b448f14c | ||
|
|
9aa7b92d04 | ||
|
|
aaf660d48e | ||
|
|
35d5a1f38d | ||
|
|
504e4bb116 | ||
|
|
19d84de387 | ||
|
|
a472adcaf4 | ||
|
|
37c7befc11 | ||
|
|
2d8b529f42 | ||
|
|
e085876d79 | ||
|
|
4bf664ee22 | ||
|
|
9a3a4f5a9c | ||
|
|
c09ac100ce | ||
|
|
095cf7b1da | ||
|
|
12f361436f | ||
|
|
105f526200 | ||
|
|
68bde25493 | ||
|
|
6c7c58b35a | ||
|
|
eaf588d2e2 | ||
|
|
405cf11498 | ||
|
|
1d29ab1ff8 | ||
|
|
7ec9a3c9ef | ||
|
|
12940a5215 | ||
|
|
d35eda399b | ||
|
|
1bfaf923b2 | ||
|
|
d3c61286bf | ||
|
|
2fc9fd7247 | ||
|
|
42f3c91c29 | ||
|
|
5cf40c3148 | ||
|
|
46d07260e9 | ||
|
|
0776fab225 | ||
|
|
7a61877e78 | ||
|
|
002fcbe26c | ||
|
|
0012759ace | ||
|
|
98f29e47c6 | ||
|
|
4fcd9233c7 | ||
|
|
95614122a9 | ||
|
|
7ef16be317 | ||
|
|
e561c81295 | ||
|
|
e6fa92613a | ||
|
|
1a6e064e4f | ||
|
|
851b4f85c4 | ||
|
|
7c8d5a33dc | ||
|
|
817318f014 |
242 changed files with 44769 additions and 1453 deletions
BIN
apps/stage/mockups/row68-ticker-hits.png
Normal file
BIN
apps/stage/mockups/row68-ticker-hits.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 52 KiB |
BIN
apps/stage/mockups/row68-ticker-ko.png
Normal file
BIN
apps/stage/mockups/row68-ticker-ko.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 52 KiB |
|
|
@ -698,6 +698,24 @@ export function App() {
|
|||
ingest.commit(hot.lastSnapshotMs, true);
|
||||
return useStage.getState().chat.length;
|
||||
},
|
||||
/**
|
||||
* Feed reward events into the ticker by hand, `stepMs` of feed time apart, for the ticker
|
||||
* mockups (a battle's hits, a KO), and settle the dwell gate five seconds after the last.
|
||||
* The events go through the same `TickerQueue.push` a snapshot's do.
|
||||
*/
|
||||
ticker: (events, stepMs = 7000) => {
|
||||
let at = hot.lastSnapshotMs;
|
||||
for (const [index, item] of events.entries()) {
|
||||
at = hot.lastSnapshotMs + index * stepMs;
|
||||
ingest.queue().push(
|
||||
{ id: 900_000 + index, wallMs: 0, brainMs: 0, kind: 'reward', label: item.label, value: item.value },
|
||||
at,
|
||||
);
|
||||
}
|
||||
at += 5000;
|
||||
ingest.commit(at, true);
|
||||
return useStage.getState().ticker.map((row) => `${row.label} ${String(row.amount ?? '')}`);
|
||||
},
|
||||
/**
|
||||
* Put a notice on the recovery splash by hand, the same way `fire` drives a moment: for the
|
||||
* splash mockups and e2e assertions. The raw object goes through the same validation as a
|
||||
|
|
@ -790,6 +808,8 @@ declare global {
|
|||
fire: (type: MomentType, label?: string, detail?: string) => number | null;
|
||||
/** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */
|
||||
chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number;
|
||||
/** Push reward events into the ticker by hand; returns the rows shown. */
|
||||
ticker: (events: readonly { label: string; value: number }[], stepMs?: number) => string[];
|
||||
/** Show a recovery notice by hand (validated like a polled one); null clears it. */
|
||||
recovery: (notice: unknown, nowS?: number) => RecoveryView | null;
|
||||
fly: () => {
|
||||
|
|
|
|||
|
|
@ -89,6 +89,11 @@ export const pokemonRed: GameConfig = {
|
|||
badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 },
|
||||
},
|
||||
|
||||
// The fly's own hits (adapter `damage`): several a battle, no protocol kind, so one row per
|
||||
// battle that counts up. 45 s covers the slowest turn seen (about 7 s from press to payout)
|
||||
// several times over and is far shorter than the gap between two battles.
|
||||
hitCopy: { label: 'damage dealt', gapMs: 45_000, tier: 'quiet', koTier: 'notable' },
|
||||
|
||||
counters: [
|
||||
{ field: 'badges', label: 'badges', outOf: 8 },
|
||||
{ field: 'uniqueLocations', label: 'places' },
|
||||
|
|
|
|||
|
|
@ -29,6 +29,21 @@ export interface RewardCopy {
|
|||
collapsedNoun?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy and window for the adapter's per-hit reward, which the protocol has no `rewardKind` for
|
||||
* (Pokémon Red's `damage`, `HIT #<species> FOR <n> HP[ KO]`). Hits are folded stage-side into one
|
||||
* row per battle instead of one row per hit.
|
||||
*/
|
||||
export interface HitCopy {
|
||||
/** Row text. Constant; the feed's label is only read for the KO suffix. */
|
||||
label: string;
|
||||
/** A row is joined by a hit up to this long after the previous hit folded into it. */
|
||||
gapMs: number;
|
||||
/** Tier of the row; a KO raises it to `koTier`. */
|
||||
tier: RewardTier;
|
||||
koTier: RewardTier;
|
||||
}
|
||||
|
||||
/** A counter shown in the progress row beside the milestone ladder. */
|
||||
export interface GameCounter {
|
||||
/** Which `FeedGame` field to read. */
|
||||
|
|
@ -64,6 +79,8 @@ export interface GameConfig {
|
|||
modeLabels: Record<GameMode, string>;
|
||||
/** Human copy and presentation tier for each reward kind. */
|
||||
rewardCopy: Record<RewardKind, RewardCopy>;
|
||||
/** How a reward event with no `rewardKind` that reads as a hit is rolled up. Absent: never. */
|
||||
hitCopy?: HitCopy;
|
||||
/**
|
||||
* Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g.
|
||||
* "3/8 badges · 214 places". Per-game *data*, not copy: the values come
|
||||
|
|
|
|||
|
|
@ -68,6 +68,9 @@ export const DEFAULT_TICKER_OPTIONS = {
|
|||
*/
|
||||
const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']);
|
||||
|
||||
/** The adapter's hit label: `HIT #<species> FOR <n> HP` with ` KO` when the hit felled a trainer's Pokémon. */
|
||||
const HIT_LABEL = /^HIT #\d+ FOR \d+ HP( KO)?$/;
|
||||
|
||||
export class TickerQueue {
|
||||
private readonly visibleRows: number;
|
||||
private readonly minDwellMs: number;
|
||||
|
|
@ -77,6 +80,8 @@ export class TickerQueue {
|
|||
private visible: TickerItem[] = [];
|
||||
private pending: TickerItem[] = [];
|
||||
private lastPromotionMs = Number.NEGATIVE_INFINITY;
|
||||
/** Feed time of the last hit folded into each hit row, by the row. */
|
||||
private readonly lastHitMs = new WeakMap<TickerItem, number>();
|
||||
/** Bumped whenever the visible list changes, so the store can push to React on change only. */
|
||||
private revision = 0;
|
||||
|
||||
|
|
@ -106,10 +111,11 @@ export class TickerQueue {
|
|||
push(event: FeedEvent, nowMs: number): boolean {
|
||||
if (HIDDEN_KINDS.has(event.kind)) return false;
|
||||
|
||||
const tier = this.tierOf(event);
|
||||
const label = this.labelOf(event);
|
||||
const hit = this.hitOf(event);
|
||||
const tier = hit ? this.hitTier(hit.ko) : this.tierOf(event);
|
||||
const label = hit ? `${this.game.hitCopy?.label ?? event.label}${hit.ko ? ' KO' : ''}` : this.labelOf(event);
|
||||
|
||||
const folded = this.fold(event, nowMs);
|
||||
const folded = hit ? this.foldHit(event, hit.ko, nowMs) : this.fold(event, nowMs);
|
||||
if (folded) return true;
|
||||
|
||||
const item: TickerItem = {
|
||||
|
|
@ -125,6 +131,8 @@ export class TickerQueue {
|
|||
...(event.by === undefined ? {} : { by: event.by }),
|
||||
};
|
||||
|
||||
if (hit) this.lastHitMs.set(item, nowMs);
|
||||
|
||||
if (tier === 'moment') {
|
||||
// Jump the gate: the badge is the reason anyone is watching.
|
||||
this.promote(item, nowMs);
|
||||
|
|
@ -176,6 +184,42 @@ export class TickerQueue {
|
|||
return false;
|
||||
}
|
||||
|
||||
/** Is this a hit the game rolls up? Only a reward with no `rewardKind` and the adapter's own label. */
|
||||
private hitOf(event: FeedEvent): { ko: boolean } | null {
|
||||
if (!this.game.hitCopy || event.kind !== 'reward' || event.rewardKind) return null;
|
||||
const match = HIT_LABEL.exec(event.label);
|
||||
return match ? { ko: match[1] !== undefined } : null;
|
||||
}
|
||||
|
||||
private hitTier(ko: boolean): TickerTier {
|
||||
const copy = this.game.hitCopy;
|
||||
return copy ? (ko ? copy.koTier : copy.tier) : 'quiet';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold a hit into the battle's row: the newest hit row whose last hit is within `gapMs`. The
|
||||
* window slides with each hit (unlike `fold`'s, which is from creation) because a battle has
|
||||
* no fixed length; a row that has left the panel is not resurrected, the next hit starts one.
|
||||
* The row shows the summed reward, a `x<n>` count and a KO once any hit in it felled a Pokémon.
|
||||
*/
|
||||
private foldHit(event: FeedEvent, ko: boolean, nowMs: number): boolean {
|
||||
const copy = this.game.hitCopy;
|
||||
if (!copy) return false;
|
||||
for (const item of [...this.visible, ...this.pending]) {
|
||||
const last = this.lastHitMs.get(item);
|
||||
if (last === undefined || nowMs - last > copy.gapMs) continue;
|
||||
item.count += 1;
|
||||
if (event.value !== undefined) item.amount = (item.amount ?? 0) + event.value;
|
||||
const knocked = ko || item.label.endsWith(' KO');
|
||||
item.label = `${copy.label} x${item.count}${knocked ? ' KO' : ''}`;
|
||||
if (knocked) item.tier = copy.koTier;
|
||||
this.lastHitMs.set(item, nowMs);
|
||||
this.revision += 1;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private tierOf(event: FeedEvent): TickerTier {
|
||||
if (event.kind === 'reward' && event.rewardKind) {
|
||||
return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet';
|
||||
|
|
|
|||
|
|
@ -147,3 +147,41 @@ test('the platformer config paces the same way with different copy', async () =>
|
|||
queue.push(reward('explore'), 100);
|
||||
assert.equal(queue.items()[0]?.label, '2 new ground');
|
||||
});
|
||||
|
||||
function hit(hp: number, value: number, ko = false): FeedEvent {
|
||||
return event('reward', `HIT #59 FOR ${hp} HP${ko ? ' KO' : ''}`, { value });
|
||||
}
|
||||
|
||||
test('a battle\'s hits fold into one damage row that sums and counts', () => {
|
||||
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
|
||||
queue.push(hit(10, 0.06), 0);
|
||||
queue.push(hit(9, 0.05), 7_000);
|
||||
queue.push(hit(4, 0.03), 15_000);
|
||||
assert.equal(queue.items().length, 1);
|
||||
const row = queue.items()[0];
|
||||
assert.equal(row?.label, 'damage dealt x3');
|
||||
assert.equal(row?.count, 3);
|
||||
assert.ok(Math.abs((row?.amount ?? 0) - 0.14) < 1e-9);
|
||||
assert.equal(row?.tier, 'quiet');
|
||||
});
|
||||
|
||||
test('a KO marks the row and raises its tier; the window slides, then a new battle is a new row', () => {
|
||||
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
|
||||
queue.push(hit(10, 0.06), 0);
|
||||
queue.push(hit(5, 0.08, true), 30_000);
|
||||
assert.equal(queue.items()[0]?.label, 'damage dealt x2 KO');
|
||||
assert.equal(queue.items()[0]?.tier, 'notable');
|
||||
queue.push(hit(3, 0.02), 70_000);
|
||||
assert.equal(queue.items().length, 1, 'still inside 45 s of the last hit');
|
||||
queue.push(hit(3, 0.02), 200_000);
|
||||
assert.equal(queue.items().length, 2, 'a later battle gets its own row');
|
||||
assert.equal(queue.items()[0]?.label, 'damage dealt');
|
||||
});
|
||||
|
||||
test('a hit is not confused with other rewards, and a lone KO says so', () => {
|
||||
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
|
||||
queue.push(hit(31, 0.25, true), 0);
|
||||
assert.equal(queue.items()[0]?.label, 'damage dealt KO');
|
||||
queue.push(event('reward', 'NEW MAP', { value: 0.1 }), 10);
|
||||
assert.equal(queue.items().length, 2, 'an unrelated no-kind reward keeps its own row');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -93,6 +93,31 @@ const CHAT_WRAP: { by: string; text: string; bot?: boolean }[] = [
|
|||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* The ticker in a battle (row 68): the fly's hits arrive as `HIT #<species> FOR <n> HP` rewards and
|
||||
* fold into one "damage dealt" row. Injected by hand through `window.__stage.ticker`, seven feed
|
||||
* seconds apart, because no fixture holds a battle recorded on adapter v8.
|
||||
*/
|
||||
const TICKER_SHOTS: { name: string; events: { label: string; value: number }[] }[] = [
|
||||
{
|
||||
name: 'row68-ticker-hits',
|
||||
events: [
|
||||
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
|
||||
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
|
||||
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
|
||||
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'row68-ticker-ko',
|
||||
events: [
|
||||
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
|
||||
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
|
||||
{ label: 'HIT #59 FOR 12 HP KO', value: 0.13 },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [
|
||||
{ name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' },
|
||||
{ name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' },
|
||||
|
|
@ -294,6 +319,18 @@ async function main(): Promise<void> {
|
|||
console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`);
|
||||
}
|
||||
|
||||
for (const shot of TICKER_SHOTS) {
|
||||
if (!wanted(shot.name)) continue;
|
||||
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
|
||||
await settle(page);
|
||||
const rows = await page.evaluate((events) => window.__stage?.ticker(events) ?? [], shot.events);
|
||||
await page.waitForTimeout(500);
|
||||
const path = resolve(outDir, `${shot.name}.png`);
|
||||
await page.screenshot({ path, clip: FRAME });
|
||||
written.push(path);
|
||||
console.log(` ${path} (${rows.join(' | ')})`);
|
||||
}
|
||||
|
||||
for (const shot of RECOVERY_SHOTS) {
|
||||
if (!wanted(shot.name)) continue;
|
||||
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
|
||||
|
|
|
|||
|
|
@ -89,8 +89,9 @@ decoder preset to use.
|
|||
disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already
|
||||
achieved flags on the first sample so a restore never replays them, and pays only positive
|
||||
rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer
|
||||
flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors and items
|
||||
picked up (`docs/rewards-learning.md`). Version `pokered-unique8-v7`; a deploy that names the
|
||||
flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors, items
|
||||
picked up and the HP the fly's own attacks remove in battle (`docs/rewards-learning.md`).
|
||||
Version `pokered-unique8-v8`; a deploy that names the
|
||||
previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them.
|
||||
- Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel,
|
||||
Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a
|
||||
|
|
@ -135,7 +136,8 @@ publish. Pacing uses absolute deadlines at 1.0x by default; it never skips frame
|
|||
audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset.
|
||||
flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an
|
||||
embedded flybus router and the `fly-edge` process serves the same bytes
|
||||
(`docs/design/flybus.md`, "Feed over the bus").
|
||||
(`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook
|
||||
"Feed over the bus").
|
||||
- Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM
|
||||
pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat`
|
||||
(sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,12 @@ nothing outside the container can reach it, and the bridge is the only intended
|
|||
There is deliberately **no endpoint that presses buttons, edits game memory, or changes the
|
||||
reward catalog**. That is a structural guarantee, not a configuration.
|
||||
|
||||
Who serves it (2026-10-01): flysim itself (`FLY_CONTROL_VIA=direct`, the default), or
|
||||
`fly-control-edge` from flysim's control services on the bus (`FLY_CONTROL_VIA=bus`,
|
||||
`docs/design/flybus.md`, "Control over the bus"). Both are the same HTTP code over the same
|
||||
request handling, so nothing in this document depends on the switch. On the bus, the
|
||||
guarantee above is also a grant table.
|
||||
|
||||
| Method and path | Body | Effect |
|
||||
|---|---|---|
|
||||
| `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). |
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
# flybus: the communications bus
|
||||
|
||||
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default**.
|
||||
Written 2026-09-22, amended 2026-09-23 (EDGE-01, below). Index only; the
|
||||
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
|
||||
`FLY_CONTROL_VIA=bus`, both off by default; EDGE-02 (2026-10-01) made the feed switchable in
|
||||
production with one command, `fly-feed bus|direct`**. Written 2026-09-22, amended 2026-09-23
|
||||
(EDGE-01) and 2026-10-01 (EDGE-02 and CTRL-01, below). Index only; the
|
||||
authority for the API and the wire format is the crate's own
|
||||
[README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against
|
||||
the draft is the [conformance report](session-framework/bus-conformance.md).
|
||||
|
|
@ -61,13 +63,13 @@ allocate/seal/read with quotas and router restarts, plus the conformance suites
|
|||
## Wiring still pending
|
||||
|
||||
- ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus".
|
||||
- **flysim control services.** The control endpoints as RPC services with grants, so the
|
||||
"no button endpoint" structural guarantee is expressed as a grant table.
|
||||
- ~~**flysim control services.**~~ Done 2026-10-01 behind `FLY_CONTROL_VIA=bus`: see "Control
|
||||
over the bus". The "no button endpoint" guarantee is a grant table there.
|
||||
- **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either
|
||||
a binding or a thin translating edge process is required before they leave the WebSocket
|
||||
and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for
|
||||
the feed it exists (`fly-edge`), and they keep the WebSocket contract unchanged. The
|
||||
control API (:7401) is the next slice and stays in flysim until then.
|
||||
the feed it is `fly-edge` and for the control API `fly-control-edge`, and both keep their
|
||||
contracts byte for byte.
|
||||
- ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below.
|
||||
- ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below.
|
||||
- **Migration order.** The feed is the cheaper first move; control should follow only once
|
||||
|
|
@ -188,3 +190,252 @@ Accepted for now and written down rather than fixed:
|
|||
escalates. Switch back to `direct` first (the unit header's way back), then roll back.
|
||||
- **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a
|
||||
Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`.
|
||||
|
||||
### Amendment 2026-10-01: the feed in production (EDGE-02)
|
||||
|
||||
- **The session runtime needed nothing.** `flysim-session` serves its listeners through
|
||||
`flysim::serve`, the same function `flysim` does, so `FLY_FEED_VIA=bus` works on it as it was
|
||||
written for legacy. It is now a test, not an inference: `fly-legacy-session/tests/feed_bus.rs`
|
||||
runs the real `flysim-session` binary (toy connectome, the real cartridge) twice from copies of
|
||||
one store, direct and bus, records both feeds over a WebSocket and requires every frame in
|
||||
common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then
|
||||
stops the binary and starts a new one under the same edge, which must unbind, reconnect and
|
||||
serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the
|
||||
host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher,
|
||||
never on a pinned sweep CPU. That shared CPU costs the sim about a millisecond a frame (review
|
||||
N1), so `FLY_SESSION_AUX_CPUS` moves them: `place_workers_aux` takes the aux CPUs out of the
|
||||
sim's set and the `flysim-bus` runtime pins itself to them (`SESSION_AUX_CPUS` in the deploy puts
|
||||
one page CPU into `flysim.slice` for it).
|
||||
- **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an
|
||||
`ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`;
|
||||
`flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and
|
||||
start of `fly-loop-reset` that `Requires=` alone left without an edge, brings the edge up in bus
|
||||
mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim
|
||||
all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct`
|
||||
rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the
|
||||
page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen
|
||||
or when it is interrupted; `direct` is never rolled back. It works on either runtime and survives `fly-runtime` changes.
|
||||
- **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off
|
||||
the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle
|
||||
header, so silence means a wedged subscription, which `Subscription::next` alone would never
|
||||
report.
|
||||
- **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote
|
||||
fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while
|
||||
flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth
|
||||
switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line), whatever the time the failures were spread over; an edge fault never reboots.
|
||||
Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to
|
||||
connect to.
|
||||
- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the
|
||||
env file or the container says `bus` (before `current` moves; `fly-feed direct` needs no
|
||||
binary), and warns when the container's `FLY_FEED_VIA` differs from the env file's. flysim and
|
||||
the edge both follow fly.env at their next start, so a disagreement never leaves the stage with
|
||||
no feed.
|
||||
- **Known limits, revisited.** *Feed counters off the container*: the edge's `/metrics` now listens
|
||||
on `0.0.0.0:9102` like flysim's `:9101`; a dashboard adds it as a second target (the watchdog
|
||||
stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by
|
||||
`fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written.
|
||||
|
||||
## Control over the bus (2026-10-01, CTRL-01)
|
||||
|
||||
`control.via` (`FLY_CONTROL_VIA`) picks who serves `http://127.0.0.1:7401`. `direct` is the
|
||||
default and the behaviour that predates the bus. With `bus`:
|
||||
|
||||
```text
|
||||
api router (flysim::api) BusBackend flybus (Unix socket) control host (in flysim)
|
||||
:7401 in fly-control-edge --> encode_request --> <bus_dir>/control-edge.sock --> fly.control.s.main.* services
|
||||
same routes, extractors, (controlbus) bound to "fly-control-edge" -> flysim::control::handle
|
||||
404s, headers, bodies -> the same Command queue
|
||||
```
|
||||
|
||||
- `docs/control-api.md` is unchanged and still binding: every endpoint, status code and body.
|
||||
flysim's control code is split in two. `flysim::control` holds the semantics: one
|
||||
`ControlRequest` per endpoint, and `handle`, the only code that validates a request, talks to
|
||||
the loop and picks a status. `flysim::api` is the HTTP layer over any `ControlBackend`. Direct
|
||||
mode is `api` over `control` in one process. Bus mode is the same `api` in `fly-control-edge`
|
||||
over a `BusBackend`, which carries the request to the `control` services in flysim. Neither
|
||||
process has an HTTP table or a validation rule of its own, so the bytes on `:7401` are the
|
||||
same in both modes. `crates/fly-control-edge/tests/parity.rs` sends every endpoint, each
|
||||
validation case and each refusal to both paths and requires equal status, headers and
|
||||
body. Over real sockets, it also requires the whole HTTP/1.1 response to be equal apart from
|
||||
`date`. `fly-legacy-session/tests/service_parity.rs` runs the session runtime once more with
|
||||
its control on the bus and compares it with the legacy loop. The comparison covers 120
|
||||
frames, 19 control responses, the event log, the journal and the final checkpoint.
|
||||
- Both runtimes get it: `flysim` and `flysim-session` both run `flysim::serve`, which in bus mode
|
||||
does not bind `control.bind`. Instead it registers the services on the embedded router. That
|
||||
is the feed's router when the feed is on the bus too: one router, one store, one closed policy
|
||||
(`flysim::bus`). The read-only `control.metrics_bind` listener (`:9101`) stays in flysim in
|
||||
both modes.
|
||||
- Nothing about the fly changes. The command queue, its bound and its timeouts are the same.
|
||||
The compatibility string is byte-identical in both modes.
|
||||
|
||||
### Services and methods
|
||||
|
||||
flybus grants name services, not methods. The surface is therefore split into six service
|
||||
*families*, and a grant names families. Every family is scoped either to a session or to one
|
||||
agent (fly) of it. Each method's payload and outcome:
|
||||
|
||||
| Service (live names) | Method | Endpoint | Payload |
|
||||
| --- | --- | --- | --- |
|
||||
| `fly.control.s.main.read` | `Control.Status` | `GET /status`, `/status.json` | `{}` |
|
||||
| | `Control.Healthz` | `GET /healthz` | `{}` |
|
||||
| | `Control.Metrics` | `GET /metrics` | `{}` |
|
||||
| | `Control.Events` | `GET /events` | `{since?: string, limit?: string}`, the raw query values |
|
||||
| `fly.control.s.main.a.fly.status` | `Control.Status` | (none: the fly's own status, for native clients) | `{}` |
|
||||
| `fly.control.s.main.a.fly.sugar` | `Control.Stimulate` | `POST /stimulate` | `{request?: <body JSON>}` |
|
||||
| `fly.control.s.main.a.fly.reward` | `Control.Reward` | `POST /reward` | `{request?: <body JSON>}` |
|
||||
| `fly.control.s.main.chat` | `Control.Chat` | `POST /chat` | `{request?: <body JSON>}` |
|
||||
| `fly.control.s.main.ops` | `Control.Checkpoint`, `Control.Pause`, `Control.Resume` | `POST /checkpoint`, `/pause`, `/resume` | `{}` |
|
||||
|
||||
- **Outcome.** `{"status": <the control-api.md code>, "body": <the JSON body>}`, or `{"status",
|
||||
"text"}` for `/metrics`. Above 48 KiB (a full `/events` page can be 4,096 events) the body
|
||||
travels as a sealed `body` artifact instead, with `bodyArtifact` naming its type. The status
|
||||
code is the outcome's vocabulary, not transport. A bus caller reads `429 {retryAfterMs}` as an
|
||||
HTTP caller does, so the edge needs no table of its own.
|
||||
- **Requests** carry the body as the caller sent it (`request` is absent when it was empty or
|
||||
not JSON), so validation stays in `control::handle`. A `request` over 48 KiB of JSON travels as
|
||||
a sealed `request` artifact with `requestArtifact: true` in the payload, so a large body gets
|
||||
the answer direct mode gives it, not an envelope error (`tests/parity.rs`). An unknown payload field is a 400. A
|
||||
method the service does not have is a 404. Neither reaches the loop.
|
||||
- **Concurrency.** Each service has 16 queued and 16 in flight (`controlbus::SERVICE_CONFIG`).
|
||||
The router dispatches FIFO per service. The host answers each request in a task of its own, so
|
||||
a pause waiting on a durable write does not hold up a resume. Families are separate services,
|
||||
so a stuck `ops` never delays `/status`.
|
||||
- **Backpressure.** The bound is on the queue at the moment of admission. A burst can
|
||||
therefore be refused before the router has dispatched its first calls into the in-flight
|
||||
slots. That is measured, not assumed (`tests/backpressure.rs`). A full service refuses at
|
||||
once with `BACKPRESSURE`, and the edge answers it
|
||||
with direct mode's `503 {"error": "the simulation command queue is full"}`. Bus failures use
|
||||
direct mode's words for the same failure (`control::unavailable`). `NO_SERVICE` before
|
||||
dispatch is "has stopped"; `NO_SERVICE` after dispatch, `CALL_GONE` and `ROUTER_LOST` are
|
||||
"dropped the request". `NOT_AUTHORIZED` is a 403.
|
||||
- **Deadlines and cancel.** The host keeps direct mode's own timeouts: 2 s for a command,
|
||||
none for `/checkpoint` and `/pause`, which wait for a durable write. The edge adds a guard of
|
||||
that plus 2 s for timed requests only. At the guard it cancels the call and answers direct
|
||||
mode's timeout 503. A call cancelled before dispatch never reaches the loop. A dispatched call
|
||||
may still act, as a direct request whose caller timed out may. An HTTP client that goes away
|
||||
drops its handler, and with it the pending call. The router discards the late result, and
|
||||
the call record goes once the host answers (`tests/backpressure.rs`).
|
||||
|
||||
### Grants: the structural guarantee as a table
|
||||
|
||||
| Participant (socket) | read | status | sugar | reward | chat | ops | register |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `flysim-control`, the host (in-process, no socket) | | | | | | | every control service, exact names |
|
||||
| `fly-stage` (`control/stage.sock`) | yes | yes | | | | | |
|
||||
| `fly-bridge` (`control/bridge.sock`) | yes | yes | yes | | yes | | |
|
||||
| `fly-watchdog` (`control/watchdog.sock`): watchdog, loop-recover ladder, `fly-runtime`, probation, shadow guard, stream check | yes | yes | | | | | |
|
||||
| `fly-operator` (`control/operator.sock`) | yes | yes | yes | yes | yes | yes | |
|
||||
| `fly-control-edge` (`control-edge.sock`): everything on `:7401` | yes | yes | yes | yes | yes | yes | |
|
||||
| a player backing one fly (`player_grants`, not wired yet) | yes | that fly | that fly | | | | |
|
||||
|
||||
The status, sugar and reward columns are per agent: a role gets them for every fly of the
|
||||
session (`grants`), or for one fly by id or by controller port (`grants_for`, `player_grants`
|
||||
with `Agents::Id` or `Agents::Port`). The table is `controlbus::Role` and `controlbus::grants`. It reflects what each client calls
|
||||
today: the stage only waits on `/healthz`; the bridge calls `/status`, `/stimulate`, `/chat`,
|
||||
`/events` and `/healthz`; the infra scripts only read; the operator uses `curl`. Each socket is
|
||||
launcher-bound to its participant. The watchdog and the ladder restart through systemd, never
|
||||
through a control call.
|
||||
|
||||
"Nothing can press buttons" is structurally true because of four properties. Each is tested:
|
||||
|
||||
1. **No method takes input.** `ControlRequest` and the loop's `Command` have no variant that
|
||||
presses a button, edits game memory or changes the reward catalog, so no method can be added
|
||||
without a contract change. Service and method names are scanned for the same words `api.rs`
|
||||
scans routes for (`controlbus` unit tests).
|
||||
2. **Grants are exact calls and nothing else.** No role is granted `Any`, a prefix, `register`,
|
||||
`publish`, `subscribe` or topic management (`every_grant_is_an_exact_call_...`). On a router
|
||||
that also carries an environment's input service, no control participant can call that
|
||||
service, the operator and the edge included. The router refuses before dispatch
|
||||
(`tests/grants.rs`, `on_a_shared_router_no_control_participant_can_reach_an_input_service`).
|
||||
3. **Only the host registers.** The one register grant belongs to an in-process participant
|
||||
with no socket, so nothing outside flysim can stand in for a control service. A socket admits
|
||||
only its own participant; claiming another id at hello is refused.
|
||||
4. **The policy is closed.** An id that is not in the table cannot connect.
|
||||
|
||||
What this does not change: loopback HTTP has no caller identity, so `fly-control-edge` carries
|
||||
the whole surface. That is exactly the trust `:7401` has today. A client is narrowed by moving
|
||||
it off HTTP onto its own role socket. That needs a native client for the TypeScript processes
|
||||
(a later slice; the operator chose edges over a Node binding for now). The bus's own limit still
|
||||
applies: processes running as the same OS user are inside the trust boundary (crate README,
|
||||
"Limitations").
|
||||
|
||||
### N flies, M environments, controller ports, players
|
||||
|
||||
Operator direction (2026-10-01): first the existing Game Boy fly goes fully onto the framework
|
||||
and the bus. A later project puts several flies on multi-controller consoles, one fly per
|
||||
controller port. This slice does not build that, but the services and grants are scoped per
|
||||
session, per agent and per port from the start, so multi-fly is configuration, not a redesign.
|
||||
A single-fly deployment is the same design with one agent.
|
||||
|
||||
- **Scope** (`controlbus::Scope`): a session id and its agents, each an id and, where the
|
||||
environment has controller ports, the port it plays on (`AgentScope { id, port }`). The live
|
||||
fly is session `main`, agent `fly` on port 0, the Game Boy's one pad (`Scope::live`). A scope
|
||||
refuses two agents with one id or on one port.
|
||||
- **Session-scoped** families (read, chat, ops) are `fly.control.s.<session>.<family>`. Pause and
|
||||
checkpoint act on a whole session: one coordinator steps every agent, and one save is one
|
||||
generation. The chat ring is the session's stage. `read` holds the session's status, health,
|
||||
metrics and event log.
|
||||
- **Agent-scoped** families (status, sugar, reward) are
|
||||
`fly.control.s.<session>.a.<agent>.<family>`, one service per fly. A sugar or reward pulse goes
|
||||
into one brain. Each fly's own view is its `status` service. Adding a fly adds its three
|
||||
services, and nothing else changes.
|
||||
- **Ports.** A port is a property of an agent's binding, not part of a name, because a pulse
|
||||
goes into a brain, not into a controller. A grant limited to a port
|
||||
(`Agents::Port(n)`) is resolved to the agent bound to that port when the policy is built. The
|
||||
policy is fixed for a router's lifetime, so rebinding ports is a session restart. A port nobody
|
||||
plays on grants no agent service.
|
||||
- **M sessions** on one router (several games, or one multiplayer game) have disjoint names, so
|
||||
a grant on one session never names another's. `:7401` addresses the live scope only. A second
|
||||
session gets native bus clients, or an edge of its own on another port with its own scope.
|
||||
- **Environments.** Environment-scoped status is reserved as
|
||||
`fly.control.s.<session>.e.<env>.read`. Environment *input* services (`Environment.Step` and
|
||||
the like) are never in a control scope. An agent's decision reaches its environment through
|
||||
the coordinator, never through control, and on a multi-controller console each fly's decoder
|
||||
writes only its own port. Property 2 holds however many environments and ports share the
|
||||
router.
|
||||
- **Players.** A viewer who backs one fly gets `player_grants(scope, Agents::Port(n))` or
|
||||
`Agents::Id(..)`: read the session, see and sugar that fly, nothing else
|
||||
(`a_player_sugars_their_own_fly_and_no_other`). In a multiplayer game the players on the pads
|
||||
are flies, and their presses come from their decoders. A human input path would be a new
|
||||
contract, never a control grant.
|
||||
|
||||
### What in `docs/control-api.md` is single-fly
|
||||
|
||||
The contract is unchanged by this slice. These parts of it assume one fly per session. Each
|
||||
would need a contract amendment before a second fly could be served over HTTP. The bus services
|
||||
above are already addressed per agent, so the amendments are to the HTTP shapes, not the bus.
|
||||
|
||||
| Endpoint or rule | Why it is single-fly | Multi-fly direction |
|
||||
| --- | --- | --- |
|
||||
| `GET /status` | The feed header reshaped: one `buttons`, `rates`, `decoder`, `learning`, `game`, `milestone`, `sugar`, `version` | Per agent: each fly's `status` service. The session's `Control.Status` becomes a session shape listing its agents and ports |
|
||||
| `POST /stimulate` | No agent field; addresses "the fly" | The agent's `sugar` service; over HTTP an `agent` (or `port`) field, absent meaning the only fly |
|
||||
| sugar limits ("6 per minute globally, no overlap with an active pulse") | The overlap rule is per brain; the budget is per deployment | Overlap per agent; whether the budget is per fly or per session is a policy decision |
|
||||
| `POST /reward` | No agent field | The agent's `reward` service; same field as `/stimulate` |
|
||||
| `GET /events`, `events.jsonl` | `FeedEvent` has no agent: reward, sugar and macro events cannot say whose they are | An `agent` field on agent events, absent for session events |
|
||||
| `POST /checkpoint` | One generation of one FLYSIM01 envelope, which is single-fly by format | A session checkpoint holding every agent. FLYSIM01 stays the format of record until RETIRE-01 |
|
||||
| `GET /metrics` | Series carry no agent label (`fly_reward_*`, the rates) | An `agent` label on per-fly series |
|
||||
| `[macros]`, `loop.game` | One mode and one game per deployment | Per environment |
|
||||
| `POST /chat`, `/pause`, `/resume`, `/healthz` | Session-level already | None |
|
||||
|
||||
### Lifecycle and operations
|
||||
|
||||
- `bus_dir` (`FLY_BUS_DIR`, `/run/fly/bus`) as for the feed. Sockets are `control-edge.sock` and
|
||||
`control/{stage,bridge,watchdog,operator}.sock`. Stale sockets are removed at start. With
|
||||
control on the bus, the router's `max_clients` and `max_services` are the feed's plus 8.
|
||||
- `flycontrol-edge.service` has no `[Install]` section: `flysim.service` `Wants=` it, and its
|
||||
`ExecCondition=` on `FLY_CONTROL_VIA` skips it in direct mode (EDGE-02's pattern for
|
||||
`flyedge`), so every start of flysim, `fly-loop-reset`'s stop and start included, brings
|
||||
`:7401` back. It is `After=` and `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own
|
||||
counters on loopback `:9103` (`fly_control_edge_bus_connected`, `_calls_total`,
|
||||
`_call_failures_total`, `_cancelled_total`, `_bus_lost_total`, `_bind_failures_total`).
|
||||
- The edge binds `:7401` only once the services answer. When the bus goes away it unbinds and
|
||||
reconnects every 500 ms. To a client that looks exactly like flysim restarting
|
||||
(`tests/backpressure.rs`, `tests/serve.rs`).
|
||||
- Watchdog. Check 1 reads flysim's own `/healthz` on `:9101` when `FLY_CONTROL_VIA=bus`, so an
|
||||
edge outage never restarts the fly. Check 1b restarts the edge alone when `:7401` fails while
|
||||
flysim is healthy. Every other `:7401` reader (`fly-runtime`, probation, shadow guard,
|
||||
loop-recover, the stream check) goes through the edge unchanged.
|
||||
- Switch and rollback: `infra/docs/runbook.md`, "Control over the bus".
|
||||
- **Migration order.** This document's rule stands: the control API moves after the feed has
|
||||
been on the bus in production for a full session. The switch exists independently of the
|
||||
feed's, and when to throw it is the coordinator's call.
|
||||
|
|
|
|||
|
|
@ -398,6 +398,19 @@ on-screen ticker cannot disagree with what the sim did.
|
|||
slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed").
|
||||
`STATE_VERSION` stays 4.
|
||||
|
||||
**`v7` -> `v8`** (2026-09-29, the damage reward). `pokered-unique8-v8`'s `migrates_from()` is
|
||||
`["pokered-unique8-v7", "pokered-unique8-v6"]`: the live run is `v7`, and `v6` still composes,
|
||||
because `v7`'s own step (the item seed on the first sample without `items:seeded`) is still in
|
||||
this build and the damage state starts empty either way. The deploy that ships it sets
|
||||
`FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`; naming `v7` does not admit a `v6` checkpoint, which
|
||||
needs its own id. One optional field is added, `damageCounts` (the wild keys that have paid
|
||||
damage), and one optional object inside a battle in flight, `battle.damage` (the per-battle
|
||||
marks and what the battle has paid). A `v7` state has neither and restores with no wild key paid
|
||||
and, if the checkpoint was taken mid-battle, every enemy Pokémon marked at the HP it has when
|
||||
first read, so nothing it lost before the restore is paid. `STATE_VERSION` stays 4. The
|
||||
compatibility string moves in segment 1 only: `.../pokered-unique8-v7/...` becomes
|
||||
`.../pokered-unique8-v8/...`, every other segment byte-identical.
|
||||
|
||||
- **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away;
|
||||
`infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a
|
||||
dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and
|
||||
|
|
|
|||
|
|
@ -155,6 +155,21 @@ which neither `gen_symbols.py` nor `resolve_wram.py` resolves, and a hand-writte
|
|||
thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame
|
||||
before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM.
|
||||
|
||||
### The damage reward's reads (2026-09-29)
|
||||
|
||||
**New 2026-09-29** (`damage`, `docs/rewards-learning.md`, "Damage rewards"). The two WRAM names were
|
||||
resolved by `services/flysim/tools/resolve_wram.py` from `ram/wram.asm` at the pinned commit and
|
||||
are bracketed by addresses `symbols.rs` already carried. The HRAM byte is the second hand-counted
|
||||
HRAM address in the crate, after row 63's `hJoyLast`, and is held to the same standard: counted
|
||||
from that pinned anchor and checked against the section's end, then pinned on the cartridge.
|
||||
|
||||
| what | symbol | address | notes | verified |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| whose side is acting | `hWhoseTurn` | `$FFF3` | "0 on player's turn, 1 on enemy's turn" (`ram/hram.asm`). Counted from `hJoyLast` (`$FFB1`) with each `UNION` at its largest member; the nine bytes after it end at `$FFFE`, the end of HRAM. `ExecutePlayerMove` writes 0 before the fly's move and `MainInBattleLoop` 1 before the enemy's; `HandlePoisonBurnLeechSeed` picks whose HP to cut by it. MEM-01's memory image captures HRAM, so the session runtime reads the same byte. | survey (`tests/rom_damage.rs`, the row 67 state: every enemy HP drop with 0, every own HP drop with 1) |
|
||||
| the move executing | `wPlayerMoveNum` | `$cfd2` | the first of the six move bytes `ExecutePlayerMove` loads; `STRUGGLE` (`$a5`) for a Pokémon with no PP. Bracketed by `wWalkCounter` and `wEnemyMonSpecies`. | survey (BUBBLE `$91` and TACKLE `$21` read on the frames their hits landed) |
|
||||
| which enemy slot is out | `wEnemyMonPartyPos` | `$cfe8` | `battle_struct`'s third field (`macros/ram.asm`: Species, HP, PartyPos, aliasing BoxLevel); `$ff` until a trainer's first send-out, then the 0-based party slot. Bracketed by `wEnemyMonHP` and `wEnemyMonStatus`. | trace (`pokemon_red/tests.rs`), survey |
|
||||
| (stale) the enemy | `wEnemyMonSpecies` ... `wEnemyMonMaxHP` | as above | **not cleared between battles**: `InitBattleVariables` leaves `wEnemyMon` alone, and a trainer battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData`. The first samples of a battle can hold the last battle's Pokémon at the HP it finished on; the damage rule marks a target only once it reads full. | disassembly, trace |
|
||||
|
||||
### Battle menu and cursor, own turn against forced switch
|
||||
|
||||
`HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it
|
||||
|
|
@ -1043,3 +1058,48 @@ one `$77`) from (10, 3). The run's length is the capacity (`PLAYER_NAME_LENGTH -
|
|||
`NAME_LENGTH - 1`). The menu bytes outlive the screen, so both halves are needed, as for
|
||||
`yes_no_prompt`. The player's and rival's names at the start of a game are this screen before
|
||||
`wStatusFlags6`'s game-timer bit is set, and `scene::detect` answers `Title` for them first.
|
||||
|
||||
## 16. The list's scroll offset (2026-10-01, `docs/design/macros.md` 12.34)
|
||||
|
||||
Row 71. One byte the reviewed list does not carry. It is pinned the way `hJoyLast` is, and
|
||||
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM) reads it back from the
|
||||
code that uses it. Section 7's "cannot be pinned" applied to the symbol table. The pin comes from
|
||||
the cartridge instead.
|
||||
|
||||
| name | where | what reads it |
|
||||
| --- | --- | --- |
|
||||
| `wListScrollOffset` | `$CC36` | entries scrolled off the top of a `DisplayListMenuID` window; the operand of `DisplayListMenuIDLoop.buttonAPressed`'s `ld a, [wCurrentMenuItem] / ld c, a / ld a, [wListScrollOffset] / add c / ld c, a`, found once in the cartridge |
|
||||
|
||||
**`BattleMenu::Bag`'s `cursor`** is now `wCurrentMenuItem + wListScrollOffset`, the bag entry
|
||||
under the arrow, which is the sum the cartridge makes on A. In the live trap the arrow was on row 1
|
||||
with an offset of 3, so it was on entry 4, the Poké Ball. `state::shop`'s buy and sell lists
|
||||
report their cursor (and its `max`) as the entry the same way. The offset is added only while a
|
||||
list is on screen, because the byte outlives every list. Purchases still use only the first three
|
||||
rows (`MART_CURSOR_ROWS`, section 7).
|
||||
|
||||
## 17. The hidden-event tables (2026-10-02, `docs/design/macros.md` 12.35)
|
||||
|
||||
Row 73. Two ROM tables, read through `MemoryReader::read_rom` from the cartridge image the process
|
||||
already holds, never through the bus and never by switching banks. Pinned the way
|
||||
`ItemUsePtrTable` is, and read back from the code that uses them by
|
||||
`row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` (FLY_ROM).
|
||||
|
||||
| name | where | what reads it |
|
||||
| --- | --- | --- |
|
||||
| `HiddenEventMaps` | `$11:$6A40` | one map id per byte to a `$ff` (85 maps at the pinned commit); the operand of `CheckForHiddenEvent`'s `ld hl, HiddenEventMaps`, followed by `ld a, [hli] / ld b, a / cp $ff` |
|
||||
| `HiddenEventPointers` | `$11:$6A96` | one little-endian pointer per map of the list above, into the same bank; the operand of the routine's `ld hl, HiddenEventPointers`, followed by `add hl, de` |
|
||||
|
||||
Both are in `SECTION "Hidden Events Core"`, which `layout.link` places in bank `$11`. Each map's
|
||||
list is six bytes an entry to a `$ff` (`hidden_event`): y, x, the routine's argument, and the
|
||||
routine as `dba` (bank, then a little-endian address). The coordinates are in the same tile space as
|
||||
`wXCoord`/`wYCoord`, like a sign's.
|
||||
|
||||
**`state::hidden_events`** answers the current map's entries as `HiddenEvent { x, y, index,
|
||||
facing }`: `index` is the entry's position in the map's list, which is how `wHiddenEventIndex`
|
||||
counts and the talked ledger's key (`TalkTarget::Hidden`); `facing` is the argument when it is a
|
||||
`SPRITE_FACING_*` value (`$00`, `$04`, `$08`, `$0C`), the side a routine such as `BillsHousePC`
|
||||
checks. It answers nothing for a map list with no end within 128 entries or an id above `$f7`, a
|
||||
pointer outside `$4000..$8000`, a list longer than 64 entries (the Game Corner's 48 are the longest), a tile off the loaded map or a
|
||||
routine address at `$8000` or above. Bill's house (`$58`) has one entry: (1, 4), argument `$04`,
|
||||
`BillsHousePC` at `$07:$6B6E`.
|
||||
|
||||
|
|
|
|||
|
|
@ -2079,6 +2079,186 @@ Nothing presses for the fly on the keyboard but the bound's one button, dealt as
|
|||
chosen by the fly's own macro group. The decoder, the reward catalog, the adapter version, the
|
||||
roles and the compatibility string are untouched.
|
||||
|
||||
### 12.33 The SHIFT offer's party list is the fly's turn, not a forced switch (2026-09-30, row 70)
|
||||
|
||||
Live on v0.7.0, rung 12, Mt. Moon 1F: the fly caught its first Pokémon (a Zubat). Minutes later, a
|
||||
Lass's battle. Wartortle fainted to her Oddish, the forced switch sent out the Zubat, and the Zubat
|
||||
knocked the Oddish out. With two Pokémon in the party, the cartridge's SHIFT battle style asks
|
||||
"Will ZUBAT change POKéMON?" before the trainer's next one (`EnemySendOut`,
|
||||
`engine/battle/core.asm`). The fly answered YES, and the game opened the party list. From then on,
|
||||
the event log was `NEXT start/done` every 0.8 brain seconds for 58 brain minutes, and nothing
|
||||
else happened until the ladder reset the run to rung 11.
|
||||
|
||||
- **The misread.** `EnemySendOut` opens that list with `wPartyMenuTypeOrMessageID =
|
||||
BATTLE_PARTY_MENU`, the same value `ChooseNextMon` uses after a faint. `state::battle` took
|
||||
BATTLE_PARTY_MENU alone as the forced switch, so the pad was the forced switch's `SWITCH, NEXT`.
|
||||
`SWITCH` had no one to switch to, because the Wartortle had fainted. `NEXT`'s A landed on the
|
||||
cursor, which the game parks on the Pokémon already out. The game printed "ZUBAT is already out!"
|
||||
and reopened the list. The one press that leaves this list is B, which declines the offer:
|
||||
`DisplayPartyMenu` returns carry and the trainer sends the next one out. No button on the pad
|
||||
sent B.
|
||||
- **The rule.** A battle party list is a forced switch only when BATTLE_PARTY_MENU is set **and
|
||||
the active battler's HP is 0**. Both callers of `ChooseNextMon` (`HandlePlayerMonFainted`, and
|
||||
the enemy's faint after a double knock-out) reach it only with `wBattleMonHP` at 0, so the faint
|
||||
is what the forced switch has and the offer does not. On the offer's list it is the fly's turn,
|
||||
and its pad is the party list's own answers, `SWITCH` and `BACK` (12.9). `SWITCH` is dealt only
|
||||
when another Pokémon can go out. Nothing is chosen for the fly. It can still take the offer with
|
||||
`SWITCH`, and `BACK` is the way out that the pad was missing.
|
||||
- **Why it waited for a catch.** The offer needs a second Pokémon (`wPartyCount - 1 != 0`), so
|
||||
with a party of one it never appeared. Every catch from now on makes it likelier.
|
||||
|
||||
Tests: `the_shift_offers_party_list_is_the_flys_turn_and_its_way_out_is_back`, the second half of
|
||||
`the_party_list_a_fainted_mon_forces_is_a_forced_switch`, and two ROM tests.
|
||||
`row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` uses
|
||||
`FLY_ROW70_CHECKPOINT`, the live trap. `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered`
|
||||
uses `FLY_ROW70_FORCED_CHECKPOINT`, the rung-12 archive carried forward by the stub to the same
|
||||
Lass with a Zubat caught.
|
||||
|
||||
### 12.34 The battle bag's cursor is the entry, not the window's row (2026-10-01, row 71)
|
||||
|
||||
Live on v0.7.3, rung 15, Route 25 (map 36): a wild Oddish L13 at 8 of 36, Wartortle L35 out, the
|
||||
bag open. Row 69's rule saw the HP low enough for the ball and left `THROW BALL` alone on the pad.
|
||||
Every start was `blocked`, 131 of 131 in ten minutes and about two hours in all. A flysim restart
|
||||
restored the same battle with the same bag open, so the trap came straight back.
|
||||
|
||||
- **Not a trainer.** `wIsInBattle` was 1 (wild), so the cartridge would have taken the ball.
|
||||
There were two Poké Balls in the bag, the party had room, the Oddish was a new species, and
|
||||
Wartortle's moves had PP left. `THROW BALL` was a correct button that its script could not
|
||||
carry out.
|
||||
- **The misread.** The battle bag is a `DisplayListMenuID` list. Its window shows three entries,
|
||||
the arrow moves over rows `0, 1, 2` (`wCurrentMenuItem`), and the list scrolls under the arrow.
|
||||
The entry under the arrow is the row plus `wListScrollOffset`. `state::battle` reported the row
|
||||
as the bag cursor. `THROW BALL` aims at the ball's bag index, here 4 (TM34, HELIX FOSSIL, NUGGET
|
||||
and TM45 come first), and no row can ever be 4. The cursor step walked between rows 1 and 2, ran out
|
||||
of budget and blocked, even though the arrow was on the ball (offset 3, row 1).
|
||||
- **The rule.** The bag cursor is `wCurrentMenuItem + wListScrollOffset`, the same sum
|
||||
`DisplayListMenuIDLoop` makes when A selects. `wListScrollOffset` (`$CC36`) is pinned from the
|
||||
operand of that read and checked against the cartridge, the same way as `hJoyLast` (12.27).
|
||||
Every UP or DOWN press then moves the entry by one, either by moving the arrow or by scrolling
|
||||
the window, so the existing cursor step reaches any entry. `ITEM`'s Potion had the same limit
|
||||
(fourth entry or later) and is fixed by the same change.
|
||||
- **Why row 69 turned it into a trap.** Before row 69, a ball fourth or later in the bag was a
|
||||
dead `THROW BALL` next to the moves. That cost a hold but did not trap the fly. Row 69 withholds
|
||||
the moves, `SWITCH`, `RUN` and the bag's `BACK` at low HP, so the dead button became the only
|
||||
one.
|
||||
|
||||
Other lists, checked: the mart's buy and sell lists are `DisplayListMenuID` lists too, and
|
||||
`state::shop` now reports their cursor as the entry in the same way. The battle menu, the move
|
||||
list, the party list and the start menu do not scroll. No macro navigates the PC's lists.
|
||||
`MART_CURSOR_ROWS` (row 55) still limits purchases to the first three rows, because lifting it puts
|
||||
new buttons on the pad and needs its own survey on the cartridge.
|
||||
|
||||
Tests: `a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn` (state, a bag scrolled by
|
||||
three), `a_mart_reports_which_of_its_screens_is_up` (a scrolled buy list, and a stale offset on the
|
||||
counter menu), the catch test's check that its ball is in the window's first rows (it still
|
||||
throws),
|
||||
`row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`, the live trap) and
|
||||
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM).
|
||||
|
||||
### 12.35 An errand is its people, then its things, and a hidden event is a thing (2026-10-02, row 73)
|
||||
|
||||
Live on v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. Scout B3 measured it from the live
|
||||
checkpoint on six seeds (2.8 brain hours): `GO ROUTE` walked the fly into Bill's house, and inside
|
||||
it `GO OBJECTIVE` or `GO OUT` walked it straight back out, 30 to 60 times per ten brain minutes.
|
||||
`GO NPC` was chosen 0 times in about 600 starts in the house, and new tiles stopped (2527 to 2531
|
||||
in 35 minutes). Rung 16 (MET BILL, `EVENT_GOT_SS_TICKET`) was never earned.
|
||||
|
||||
- **The place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`, because the house's id was
|
||||
not derived. A fly on Route 25 was already "there", so inside the house `GO OBJECTIVE` was an
|
||||
exit into the objective's own map, which is the same door as `GO OUT`. That is row 29's lab loop
|
||||
again, one rung later.
|
||||
- **The rung is an errand, not a conversation.** `scripts/BillsHouse.asm`: Bill (a Pokémon, a
|
||||
person sprite) asks for help and walks into the teleporter, the cartridge hides his sprite; the
|
||||
cell separator is started from the PC at (1, 4), pressed facing up; Bill then steps out of the
|
||||
machine as a second sprite and hands over the ticket. Two people and a thing, in that order.
|
||||
- **The PC is a hidden event.** `wNumSigns` is 0 in the house and the only sprite is Bill: the PC
|
||||
is an entry of the cartridge's own hidden-event table (`data/events/hidden_events.asm`), which
|
||||
`CheckForHiddenEvent` searches on every A in the overworld. No macro could aim at it and `TALK`
|
||||
was never dealt in front of it, so even a fly that talked to Bill could not earn the rung.
|
||||
|
||||
What changed, all of it knowledge inside macros:
|
||||
|
||||
- **`PlaceKind::Errand`.** Rung 16's place is `errand(BILLS_HOUSE)` (`$58`, confirmed by Route
|
||||
25's warp table and by the hidden-event map list). An errand's targets are the room's people,
|
||||
drawn or off the screen, and once none is left untalked, its things: objects, signs and hidden
|
||||
events. No step is named anywhere. The cartridge shows and hides the people as the errand moves
|
||||
on, the talked ledger records what has been had, and what is left is the next step. People come
|
||||
first because a thing pressed out of turn is in the talked ledger for the session: Bill's PC
|
||||
pressed before he has asked prints the monitor and does nothing, and a PC recorded as talked to
|
||||
would never be the next step again. Everything 12.5 and 12.22 give a person place applies: the
|
||||
ways out are withheld while a target waits, `GO OBJECTIVE` aims at the four sides, facing a
|
||||
target is the arrival and `TALK` is the press; the blocked ledger is the escape hatch.
|
||||
- **Hidden events are read from the cartridge's table, not written down.** `state::hidden_events`
|
||||
walks `HiddenEventMaps` and `HiddenEventPointers` in ROM bank `$11` through
|
||||
`MemoryReader::read_rom`, the same read the move and item tables use: no WRAM is written and the
|
||||
mapper's bank register is not touched. The two addresses are pinned from the operands of
|
||||
`CheckForHiddenEvent`'s own `ld hl` instructions and checked on the cartridge
|
||||
(`macros-wram.md` section 17); every read checks the table's shape and answers nothing for a
|
||||
table that is not the one the disassembly describes, which narrows and never invents a tile. A
|
||||
hard-coded `(1, 4)` would have been a number nobody can check from the running game; the table is
|
||||
what the cartridge itself consults when the A is pressed.
|
||||
- **A hidden event is only ever the errand's next step.** It is in `objective_targets` for an
|
||||
errand and in `facing_target` (so `TALK` is dealt) only while it is that step. It is not added to
|
||||
`GO ITEM`, `GO NPC` or `TALK` anywhere else. The table holds every PC, poster, trash can,
|
||||
bookshelf and hidden item in Kanto; making them general targets would add a walk to most
|
||||
buildings' pads and an entry to the talked ledger for each, which is a change to what the fly is
|
||||
offered everywhere and not a fix for this trap. The day that is wanted it is one line in
|
||||
`path::interactable_targets`, and it needs its own survey.
|
||||
- **A hidden event's side.** Where the entry's argument is a `SPRITE_FACING_*` value it is the side
|
||||
the routine checks before it does anything (`BillsHousePC` returns unless the player faces up),
|
||||
so the walk's one aim is the tile on that side and only facing it from there is the arrival and
|
||||
`TALK`'s precondition. An argument that is an item or a text id and happens to equal a facing
|
||||
value only narrows the approach.
|
||||
- **An errand is recoverable inside one session (row 73 review).** The talked ledger is the
|
||||
session's and never forgot, but the cartridge re-shows people: Route 25's script resets Bill's
|
||||
event once the fly has left, and a Bill whose bag was full never handed over the ticket. A
|
||||
conversation had on the last visit then retired this one's and the rung was unreachable until a
|
||||
restart. The palette now notes the room while the errand is the objective and, on the first
|
||||
frame the fly stands anywhere else with that errand still the objective, forgets that room's
|
||||
talked entries (`Talked::forget_map`). Other rooms' entries and a room that is not the errand
|
||||
keep theirs. The bag-full case needs no extra rule: nothing is left to aim at, the exits return,
|
||||
and the fly leaves and comes back.
|
||||
- **A one-sided target nobody can stand in front of is not waited for.** If every tile a hidden
|
||||
event can be pressed from is one the cartridge pushes the fly off (the pushed ledger, row 37),
|
||||
the walk had no aim, so no walk ended `blocked` and the ways out stayed withheld for good. Such
|
||||
a target leaves the errand's list at once (`palette::servable`), which returns the exits.
|
||||
- **A hidden-event entry off its own map is skipped.** The Safari Zone gate lists a nugget
|
||||
"inaccessible" at (10, 1) on an 8 x 6 map, and the rest houses a copied Pokecenter PC; one such
|
||||
entry no longer voids the rest of the map's list.
|
||||
|
||||
The fly still chooses every press: `GO OBJECTIVE` to walk, `TALK` to press A, `YES`, `NO` or
|
||||
`NEXT` in Bill's boxes. Nothing presses for it, no button is added to any pad, and the readout, the
|
||||
catalog, the adapter and the compatibility string are unchanged. What the scene deals inside the
|
||||
house is narrower than before, not wider: the ways out leave the pad while the errand waits.
|
||||
|
||||
**The road after the ticket (the third trap).** With the ticket the objective is rung 17,
|
||||
Vermilion, south through Cerulean. Cerulean's ground is in three pieces, not two: the town's ends at
|
||||
row 28 (the gap at (16, 28) opens onto a wall and the trainer-tips sign), and the south of the map,
|
||||
the road to Route 5 and the east edge onto Route 9 are reached through the trashed house (`$3e`),
|
||||
in by its front door at (27, 11) and out by the hole in its back wall onto (27, 9) in the Rocket's
|
||||
yard. Scout B3 flooded the grid: 378 of the map's 801 walkable tiles are the town's. The house was
|
||||
off the map graph, so `GO OBJECTIVE` aimed at ground the town cannot reach (`blocked` at (17, 28))
|
||||
and the fly rang between the town and its houses (0 of 6 seeds past row 28 in 43 brain minutes
|
||||
each). The house is now on the graph and the south is `SPLIT`'s third piece of Cerulean, so the
|
||||
objective walks into the house and out through the hole. Before the ticket a guard stands on the
|
||||
tile in front of the door (`TOGGLE_CERULEAN_GUARD_2`, (27, 12)), which the ticket's own script hides; the objective only
|
||||
points south after the ticket.
|
||||
|
||||
**Not fixed, predicted:** the road from Route 5 to Vermilion on the graph is Route 5, Saffron,
|
||||
Route 6, as plain map edges. The cartridge's gate houses are guarded until the guard's drink is
|
||||
given, and the way the game means is the Underground Path, whose houses are off the graph. No run
|
||||
has reached Route 5's gate yet; it needs its own checkpoint and row.
|
||||
|
||||
Tests: `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`,
|
||||
`a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`,
|
||||
`a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`,
|
||||
and on the cartridge `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it`,
|
||||
`row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door`,
|
||||
`row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket`,
|
||||
`row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket`,
|
||||
`row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` and
|
||||
`row73_the_fly_takes_the_trashed_house_south_to_route_5`.
|
||||
|
||||
## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a
|
||||
## priority to visit the shop at least once per area; make shop macros item purchases. same
|
||||
## for the Pokécenter. heal should be a macro.")
|
||||
|
|
@ -2108,9 +2288,10 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th
|
|||
- **Ladder.** Unchanged; no reward for shopping or healing (rewards are the adapter's,
|
||||
untouched).
|
||||
- **Screen.** Two new channel tags; the cells and the MACROS rate row take them as they come.
|
||||
- **Proof.** ROM-gated from the Viridian checkpoint: `GO SHOP` enters the Viridian mart and
|
||||
`BUY POTION` buys one; `GO HEAL` enters the center and `HEAL` restores the party; the errand is
|
||||
not offered again in Viridian; trap hunt before/after.
|
||||
- **Proof.** ROM-gated: from the Viridian checkpoint `GO HEAL` enters the center and `HEAL`
|
||||
restores the party; from the rung-11 Pewter checkpoint (a state where `GO SHOP` is dealt, since
|
||||
rows 62/66: money, no ball, no parcel) `GO SHOP` enters the mart and walks to its counter, and
|
||||
is not dealt back from the street for the reached window; trap hunt before/after.
|
||||
|
||||
## 14. The full pad and four move buttons (the operator, 2026-09-17: "scoot fly over. make it 2
|
||||
## columns" … "four, one per move slot" … "2 cols.")
|
||||
|
|
|
|||
|
|
@ -78,7 +78,10 @@ Application / supervisor Application presentation
|
|||
This diagram is connectivity, not execution order. The step contract defines causal order.
|
||||
One router can host several independent sessions and application consumers; a deployment may
|
||||
choose one router per application for fault isolation. A router crash affects all its clients,
|
||||
so choose that boundary deliberately. In-process mode still exercises routing and ownership.
|
||||
so choose that boundary deliberately. In-process mode still exercises routing and ownership,
|
||||
unless its participants are offered over the local lane ([session RPCs](ipc-v1.md) section 1,
|
||||
amendment 2026-09-30), as the legacy composition's in-process release configuration is; process
|
||||
mode always goes through the router.
|
||||
|
||||
Defaults: coordinator per session, worker per fly, environment worker per world. Task and
|
||||
per-agent executors begin as coordinator-local libraries. An environment helper may own a
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
|
|||
| Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` |
|
||||
| The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
|
||||
| Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
|
||||
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies | `wire.rs::Location`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
|
||||
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies and, since the 2026-10-01 amendment (BUS-01), in a delivery's attachments, never in a body | `wire.rs::Location`, `wire.rs::Attachment`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained`, `::deliveries_carry_the_read_location_their_ownership_grants` (both) |
|
||||
| Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse |
|
||||
| `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) |
|
||||
| Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
|
||||
|
|
@ -187,9 +187,10 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
|
|||
| The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` |
|
||||
| The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
|
||||
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
|
||||
| Sealing on send (amendment 2026-10-02, BUS-02): an `rpc.call`/`rpc.reply`/`publish` attachment naming the sender's own writer is sealed (its declared prefix, copied outside the state lock) before the command is admitted, the writer becomes the sender's hold, `recycle` reissues the staging file as a new writer, and a refused sealing send releases every writer it named | conforms | `router/state.rs::{sealing_attachments, finish_sealing_send}`, `router/mod.rs::read_loop` (`SealThenAdmit`), `store.rs::{seal_prefix, rename}`, `client/handles.rs::{ArtifactWriter::into_unsealed, Responder::reply_sealing}` | `tests/sealing.rs::{a_reply_seals_and_recycles_its_writers, a_refused_sealing_send_releases_its_writers}` (both), `tests/artifacts.rs::unsealed_artifacts_cannot_be_used` (both) |
|
||||
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
|
||||
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
|
||||
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
|
||||
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
|
||||
| Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
|
||||
| All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` |
|
||||
|
||||
|
|
@ -345,7 +346,7 @@ behind "latest replaces only queued messages": the replacement never turns into
|
|||
|
||||
## The crate README's differences from the draft
|
||||
|
||||
Each of the ten differences the crate lists, kept with the sentence that allows it or fixed.
|
||||
Each of the differences the crate lists, kept with the sentence that allows it or fixed.
|
||||
|
||||
| README difference | Verdict |
|
||||
| --- | --- |
|
||||
|
|
@ -359,6 +360,8 @@ Each of the ten differences the crate lists, kept with the sentence that allows
|
|||
| 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) |
|
||||
| 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` |
|
||||
| 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) |
|
||||
| 11. Read locations in deliveries | Kept. The bus-v1 amendment of 2026-10-01 (BUS-01) |
|
||||
| 12. Sealing sends, `recycle`, and no `rpc.responder.release` after an admitted reply | Kept. The bus-v1 amendment of 2026-10-02 (BUS-02); section 8.1's immutability holds because the sealed bytes are still a copy, and a reply the router admitted already ended the reply authority the release would give up |
|
||||
|
||||
## Measured on the dev VM
|
||||
|
||||
|
|
|
|||
|
|
@ -207,7 +207,11 @@ roots, so an idempotent repeat may report zero. Queue/credit requests are intege
|
|||
and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters.
|
||||
call target is a service name; expectedIncarnation is its registration ID, not worker process ID.
|
||||
Location grants are `{storeId, relativePath}` resolved by the client beneath the configured
|
||||
local store root; absolute paths, parent traversal and symlink escapes are rejected. They
|
||||
local store root; absolute paths, parent traversal and symlink escapes are rejected (the
|
||||
reference SDK caches a store's canonical directories per connection, BUS-02, and still checks
|
||||
each file with an lstat and an `O_NOFOLLOW` open; a store directory replaced by a symlink after a
|
||||
connection first used it is not re-checked by that connection, which the store's 0700 owner-only
|
||||
directory makes a same-user act). They
|
||||
are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not
|
||||
committed into application schemas or source configuration.
|
||||
|
||||
|
|
@ -523,3 +527,83 @@ this same section forbids to reject one.
|
|||
longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because
|
||||
section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled
|
||||
illustrative.
|
||||
|
||||
**2026-09-30, PERF-01 (SDK only; no wire change, `contractDigest` unchanged).** The Rust client
|
||||
gains *in-memory artifacts*: `Artifact::in_memory(contentType, bytes)` is an immutable buffer in
|
||||
the caller's address space with an ordinary `ArtifactRef` whose `storeId` is `in-memory` (no
|
||||
router issues that id) and whose digest is null; `Artifact::to_memory` reads a sealed handle into
|
||||
one under the same reference. They read, clone and retain without a router, and no router ever
|
||||
learns of them: the SDK refuses one as an attachment of `rpc.call`, `rpc.reply` or `publish`
|
||||
before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for participants of one
|
||||
process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of
|
||||
the same date); section 8's ownership rules apply to every artifact a router stores, which these
|
||||
never are.
|
||||
|
||||
**2026-10-01, BUS-01 (wire change; `contractDigest` changes).** A delivery's attachments carry the
|
||||
read location their delivery ownership grants. Section 8.1 makes a consumer resolve a
|
||||
store-issued `readLocation` through `artifact.open` before it reads, which is one router round
|
||||
trip per artifact read. The legacy composition on the bus reads four artifacts a frame on its
|
||||
critical path (the frame in `Agent.Prepare`, the memory image and the audio chunk after
|
||||
`Environment.Advance`, the spike bitset after `Agent.Commit`), so that rule cost four round trips
|
||||
a frame for an answer the router already knows when it delivers.
|
||||
|
||||
- In an `rpc.request`, `rpc.result` or `topic.message` delivery, every attachment is
|
||||
`{name, ref, ownerId, readLocation}`, where `readLocation` is the `{storeId, relativePath}`
|
||||
`artifact.open` would return for that artifact under that delivery's ownership. It is still
|
||||
store-issued, private to the SDK, resolved beneath the store root with the same traversal and
|
||||
symlink checks, and never placed in an application body.
|
||||
- A client never sends one: an attachment in a command that carries `readLocation` is an unknown
|
||||
field, and the connection closes as for any malformed envelope.
|
||||
- The SDK's handle on a delivered artifact reads through it with no round trip. Section 8.1's
|
||||
guarantee is unchanged: the delivery's root holds the bytes while the handle (or a file opened
|
||||
from it) lives, exactly as after an `artifact.open`. `artifact.open` stays for every handle that
|
||||
did not come from a delivery (a sealed writer's hold, an explicit `retain` of one) and for any
|
||||
client that prefers to ask.
|
||||
|
||||
Two SDK-only changes of the same slice, no wire change: small store operations (creating or sealing
|
||||
a staging file, reading a sealed one, up to 256 KiB) run in place rather than on the blocking pool
|
||||
-- on the store's tmpfs a hop to the pool and back costs more than the copy -- and
|
||||
`Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder
|
||||
that needs the bytes kept alive can keep a clone instead of taking a second hold.
|
||||
|
||||
**2026-10-02, BUS-02 (wire change; `contractDigest` changes).** A sending command may seal the
|
||||
artifacts it attaches. Section 8.1 makes a producer seal (`artifact.seal`, one router round trip)
|
||||
before any message may name the artifact, and section 5 allocates every artifact afresh
|
||||
(`artifact.allocate`, another). A participant that replies with media every transition -- the
|
||||
legacy world a frame, a memory image and an audio chunk, the agent a spike bitset and its feed
|
||||
status -- paid both for every artifact of every transition, two of them on the transition's
|
||||
critical path, for answers the router could give as it admits the reply.
|
||||
|
||||
- **Sealing attachments.** In `rpc.call`, `rpc.reply` and `publish`, an attachment's `ownerId` may
|
||||
be the sender's own writer of `ref.artifactId`, still unsealed. Its `ref` is the reference the
|
||||
sealed artifact will have: this store, generation 1, the allocation's content type, a null
|
||||
digest, and a `byteLength` of at most the allocation -- the sealed artifact is the first
|
||||
`byteLength` staging bytes. As part of admitting the command the router seals each such writer
|
||||
exactly as `artifact.seal` would (section 8.1: the copy into a fresh sealed inode happens outside
|
||||
the routing state lock, before anything is admitted, and the connection's later commands wait
|
||||
for it), the writer becomes the sender's explicit hold on the sealed artifact (as after
|
||||
`artifact.seal`), and only then is the command admitted as if its sender had sealed first. If a
|
||||
seal fails, or the command is then refused, nothing is admitted and every writer the command
|
||||
named is released (with whatever it sealed): the reply carries the refusal, `not-dispatched`.
|
||||
- **Recycling.** Such a command's body may carry `recycle: true` (a body member of `rpc.call`,
|
||||
`rpc.reply` and `publish` with at least one sealing attachment, refused otherwise). The router
|
||||
then keeps each sealed writer's staging file and reissues it as a new writer -- a new
|
||||
`artifactId`, a new hold `ownerId`, the same allocation and content type -- and the command's
|
||||
reply value carries `writers: [{name, artifactId, generation, ownerId, writeLocation}]`, one per
|
||||
attachment it sealed, named by attachment. A writer it cannot reissue (owner budget) is simply
|
||||
left out. Section 8.1's immutability is unchanged: the sealed bytes are a copy, so a producer
|
||||
writing into the recycled staging file reaches only the staging inode. A reissued writer is a
|
||||
fresh allocation in content as well: the router overwrites the staging file with zeros before
|
||||
the reply, so it reads as zeros and no artifact sealed from it -- a prefix, or the whole
|
||||
allocation through `artifact.seal` -- can carry bytes of the artifact it was before (review N3,
|
||||
2026-10-02). `recycle` in a body with no sealing attachment is refused, `false` included, and
|
||||
one writer named by two attachments of the same command is refused (`INVALID_ENVELOPE`).
|
||||
- Nothing else changes: deliveries, ownership roots, credits and quotas are those of the command
|
||||
with pre-sealed attachments; a sealing attachment counts its sealed copy against the store quota
|
||||
at admission, as `artifact.seal` counts it at the seal.
|
||||
|
||||
SDK changes of the same slice, no wire change: `ArtifactWriter::into_unsealed` and
|
||||
`Responder::reply_sealing` (the client side of the above); a reply the router admitted spends the
|
||||
call's reply authority, so the SDK no longer sends `rpc.responder.release` after one (it was a
|
||||
no-op command on every call); the router encodes each frame once and forwards an admitted
|
||||
payload as the bytes it re-encoded once at admission instead of deep-copying it per delivery.
|
||||
|
|
|
|||
|
|
@ -344,6 +344,516 @@ CUT-01 shadow need.
|
|||
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
|
||||
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
|
||||
|
||||
### TASK-01 — The `pokered-macros-v1` task and executor (port slice)
|
||||
|
||||
**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 +
|
||||
ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of
|
||||
the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it
|
||||
the live fly's whole composition -- agent, world, task and executor -- runs on the session
|
||||
framework, from a fresh start or from a FLYSIM01 checkpoint.
|
||||
|
||||
- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one
|
||||
object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds
|
||||
any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide`
|
||||
over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs
|
||||
`PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's
|
||||
decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe`
|
||||
over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order;
|
||||
there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is
|
||||
retained until Phase C has read it.
|
||||
- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the
|
||||
coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the
|
||||
agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A
|
||||
declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with
|
||||
`RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters
|
||||
cover the backend and task config, the media, the decision schema, the world's state format and
|
||||
per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's
|
||||
`preStepStimulations` and reports every admission applied or aborted. `Coordinator::import`
|
||||
installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are
|
||||
kept for a parity run.
|
||||
- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's
|
||||
`legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves
|
||||
go into each participant's own capture format, and the ordinary group restore installs them:
|
||||
stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first,
|
||||
because ENV-01 stages only on a replacement. The context the agent resumes with is computed
|
||||
from the checkpoint's own memory image, and the coordinator holds the task to it after the
|
||||
install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`.
|
||||
- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's
|
||||
`LegacyCheckpointer`).
|
||||
- `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy
|
||||
candidate order, holding each candidate to the legacy gate. Any refusal falls to the next
|
||||
candidate; each attempt runs on a session of its own, because a refused install fences its
|
||||
session. It is a fresh start when the stores are empty. After either, the startup durable
|
||||
save is written and the intervals start.
|
||||
- `advance` keeps the declared boundary order: the slot save (inside the step), the milestone
|
||||
archive on a rank climb, the rollback (deferred by the coordinator until the host has
|
||||
captured), a durable save after a rollback, then the interval saves.
|
||||
- `shutdown_save` is the legacy shutdown's durable save.
|
||||
- The session runtime writes no sugar journal yet: its admission is the coordinator's, and the
|
||||
journal's boot header needs the edge.
|
||||
- `lastEventId` carries the restored file's watermark; the runtime has no feed event log
|
||||
before EDGE-01.
|
||||
- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged,
|
||||
against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the
|
||||
next cut.
|
||||
- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment.
|
||||
|
||||
**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session
|
||||
writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built
|
||||
from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the
|
||||
executor's batch, the view, the image and the boundary actions. It is compared field by field with
|
||||
the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list
|
||||
order. Where the legacy side runs in the test, the ledgers are compared after every boundary as
|
||||
well: adapter export, ratchet state, and the executor's scene, bound channels, running macro,
|
||||
counts and "nearer". Results: see the TASK-01 run report and the amendment below.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted
|
||||
N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover
|
||||
B1, N1 and N3.
|
||||
|
||||
- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB,
|
||||
past the 32 KiB `TypedValue` bound.
|
||||
- `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`.
|
||||
- The coordinator files those attachments as `task-ledger-<name>` payloads in captures and
|
||||
imports.
|
||||
- A bad ledger is an error, never a panic, so a boot falls to the next candidate.
|
||||
- Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB).
|
||||
- **N1: a sugar admitted before the next commit is an active pulse.**
|
||||
- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the
|
||||
seed is never read.
|
||||
- **N4: saves are queued to the writer thread.**
|
||||
- **N5: speed.** The profile is below. Changes:
|
||||
- The world seals its three artifacts concurrently.
|
||||
- Cache and caller holds are taken concurrently.
|
||||
- In-process participants use the in-memory transport.
|
||||
- A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded
|
||||
history.
|
||||
- `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside
|
||||
the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state
|
||||
under the lock, then encodes, digests and seals it off the lock. The coordinator's
|
||||
`begin_capture` / `finish_capture` let the session step on while the payload is written.
|
||||
- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`):
|
||||
- The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a
|
||||
few percent.
|
||||
- What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a
|
||||
quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit,
|
||||
plus the world's and the agent's artifact seals and reads.
|
||||
- Against it, the legacy loop spends about 0.7 ms per frame outside the ticks.
|
||||
- The report `claude-task-01` has the per-phase table and what would close the rest.
|
||||
|
||||
### PERF-01 — The session runtime's per-frame cost (port slice)
|
||||
|
||||
**2026-09-30: built** on `port/perf-01` (off `port/task-01`, with `main` v0.6.7 merged) and
|
||||
awaiting review. Goal: cutover must not slow the live stream. TASK-01's fix round left the
|
||||
in-process session about 4.7 ms a frame above its brain, against 0.7 ms for everything the legacy
|
||||
loop does outside its ticks. No behaviour changes: the parity runs are identical frame by frame,
|
||||
in-process and process, and the compatibility string is unchanged.
|
||||
|
||||
- **The local lane** (the big one; ipc-v1 section 1 and bus-v1 section 12, amended 2026-09-30).
|
||||
An in-process worker's shell is offered to the coordinator directly (`worker::LocalLane`,
|
||||
`launcher::Via::Local`, `WorkerRef::local`); `rpc::send` takes it for every endpoint method.
|
||||
The request still goes through the shell's admission, deduplication, arrival order and
|
||||
endpoint, and the reply is the same outcome. Handler media over the lane are in-memory
|
||||
artifacts (`flybus::Artifact::in_memory`, `HandlerCtx::seal`): no store file, no seal copy,
|
||||
no retain or open round trip. A bus call or a publication carries a sealed copy
|
||||
(`rpc::promote`), begun while the task and the commits run. Process mode is untouched.
|
||||
`FLY_SESSION_LOCAL_LANE=0` runs in-process over the bus. Every synthetic transport test also
|
||||
runs over the lane.
|
||||
- **The spike bitset** is the union of the kernel's per-tick spike lists, gathered while Prepare
|
||||
ticks (`LifNetwork::tick_spikes`), instead of a 139,255-neuron scan in Commit. Same bits,
|
||||
proved by `flybrain-core/tests/tick_spikes.rs` and compared every frame by the parity runs.
|
||||
- **The session topic** gets a committed snapshot every 60th boundary in a service session (and
|
||||
at every boundary with events or boundary actions), not every other one. Nothing in the
|
||||
release subscribes; the stream is the legacy feed.
|
||||
- Small ones: a single dispatch job is called in place, the shell moves the reply result
|
||||
instead of cloning it, `digest_views` and `media_bytes` as SERVE-01 has them, and profiling
|
||||
spans for the shell, the lane, each handler and the brain's own phase clock.
|
||||
- **Tried and dropped**: publishing without waiting for the router (a deferred publish) and any
|
||||
other overlap with Prepare. On the release CPU the sweep owns every core of the cpuset, and
|
||||
work beside the ticks slowed them by up to 30% in one run. Spikes only at the feed rate
|
||||
(an AGENT-01 amendment) was not needed once the bitset cost nothing.
|
||||
- **Measured** (`tests/speed_ab.rs` with `FLY_PERF_ARMS`, `FLY_PERF_SERVICE`, `FLY_PERF_WORKERS`;
|
||||
the report `claude-perf-01` has the tables): on the release host's CPU model, pinned to the
|
||||
release cpuset's size, the in-process session's cost outside the brain fell from about 9.3 ms
|
||||
to about 3.5 ms a frame. The legacy loop's is about 1.3 ms. What is left is mostly the per-frame
|
||||
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
|
||||
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
|
||||
|
||||
### PERF-02 — The session's ticks on the release cpuset (port slice)
|
||||
|
||||
**2026-10-01: built** on `port/perf-02` off `main` (v0.7.3 + two infra fixes), awaiting review.
|
||||
CUT-01's probation fell back at a median realtime factor of 0.959. Cause: with exactly as many
|
||||
CPUs as sweep threads, the session's sleeping and waking host threads let the scheduler stack two
|
||||
sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loop's (same frames,
|
||||
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
|
||||
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
|
||||
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
|
||||
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. Pinning is only safe in a cpuset that is the sim's alone (a pinned worker cannot leave a CPU that something else hogs: 0.14x real time): the deploy makes it so with `flysim.slice` and `fly-cpu-confine` and writes `FLY_SESSION_PIN=0` when it cannot (`infra/docs/runbook.md`). The legacy loop and process mode are
|
||||
unchanged; the compatibility string is unchanged. `flybrain-core/tests/placement.rs` runs pinned
|
||||
workers against the sequential kernel on the real connectome. The service's periodic profile
|
||||
line also prints the measurement spans (and the brain's phase split) when
|
||||
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
|
||||
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
|
||||
|
||||
### BUS-01 (port slice) — The live session's participants on the router
|
||||
|
||||
Not the framework guide's BUS-01 above (the router itself); the port plan reuses the name.
|
||||
**2026-10-01: built** on `port/bus-01` off `main` (v0.7.5), awaiting review. Operator direction:
|
||||
run the live session over the flybus router on Unix sockets, one emulator and one fly, because
|
||||
multiplayer and more flies follow. The topology, its rules and the shadow procedure are
|
||||
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 12 (amendment 2026-10-01) and section 18
|
||||
(amendment of the same date); the wire change is [bus-v1](bus-v1.md) section 12 (2026-10-01).
|
||||
|
||||
- **Selecting it.** `FLY_SESSION_TRANSPORT=bus` / `flysim-session --transport bus` (process mode
|
||||
by default; `FLY_SESSION_MODE=thread` and `in-process` too), `fly-runtime session --bus`
|
||||
(`session-bus`) on the container, `fly-shadow --mode bus/process` and
|
||||
`fly-shadow-run start --bus` / `check --bus` for its shadow. The local lane stays the default.
|
||||
`SessionArm` names the four arms; `FLY_PARITY_ARMS` picks them for the parity suites (default
|
||||
`local,bus/thread,bus/process`).
|
||||
- **What it took.** Per-process CPU placement (`Launcher::place_process`,
|
||||
`--host-cpus`/`--sweep-cpus`, `flybrain_core::pool::apply_placement`), the launcher's own clients
|
||||
in memory in thread and process modes, `block_in_place` for a bus request's handler (without it a
|
||||
slow `Agent.Initialize` could not be resolved and a process-mode session failed to boot on a
|
||||
loaded box: "never resolved"), delivered read locations (bus-v1 amendment), writers allocated
|
||||
ahead (`WriterPool`), no second hold on a worker's own seals, small store I/O in place, the
|
||||
envelope encoded without copying its body, and the agent's feed status attached to a bus Commit
|
||||
(the host's 30 Hz `Legacy.FeedStatus` call was a round trip of its own).
|
||||
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
|
||||
`7b940584`, as v0.7.5) are the same in every arm: the toy and FAFB parity suites
|
||||
(`session_trace`, `service_parity`, `rollback_sequence`, `save_handoff`) ran `local`,
|
||||
`bus/thread` and `bus/process`.
|
||||
- **Measured, and not fast enough to go live.** The report `claude-bus-01` has the tables. On a
|
||||
build box with the release CPU model and the release cpuset's shape (four CPUs, four sweep
|
||||
threads), same frames, interleaved, unpaced: legacy 16.1 ms a frame, the lane 17.4,
|
||||
`bus/thread` 25.1, `bus/process` 25.7 (`main`'s process mode: 30.4, so this slice took about a
|
||||
third off the bus's cost). Paced at real time the lane holds 1.00 and the bus 0.69 to 0.71, with a
|
||||
neighbour CPU busy or not. Every round trip through the router is 0.5 to 1 ms there (the
|
||||
synthetic `fly-session measure` puts a bare `Worker.Status` at 0.5 ms whether the processes
|
||||
share one CPU or four), and a transition needs at least five in sequence: Prepare; Advance and
|
||||
its seals; Commit and its seals. That is a realtime factor of roughly 0.7 on the release
|
||||
container, so the lane stays live and nothing is switched. Moving the router, the coordinator
|
||||
and the world to a fifth CPU (`FLY_SESSION_AUX_CPUS`) made it 1.5 to 2 ms slower. What would close
|
||||
it is a cheaper round trip, not more CPUs: the router's own per-message work (strict JSON parsed
|
||||
and re-encoded per hop, the state lock, about three task hops a direction), and sealing a reply's
|
||||
media in the reply itself (one round trip fewer for Advance and for Commit).
|
||||
- **`fly_frame_work_*`** on `/metrics` (both runtimes): the loop's compute time per frame without
|
||||
its pacing sleep, mean, p99 and max over the last 3,600 frames. It agrees with the unpaced
|
||||
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
|
||||
hides.
|
||||
|
||||
### BUS-02 (port slice) — A cheaper bus transition
|
||||
|
||||
**2026-10-02: built** on `port/bus-02` off `port/bus-01`, awaiting review. Goal: make the
|
||||
session-over-flybus transport cheap enough to carry the live fly (operator: run on the bus with
|
||||
real sockets, because more consoles and more flies follow). The wire change is [bus-v1](bus-v1.md)
|
||||
section 12 (amendment 2026-10-02); [step-v1](step-v1.md)'s ordering is untouched.
|
||||
|
||||
- **Where a bus transition's time went** (a build box with the release CPU model and the release
|
||||
cpuset's shape, router traffic counted per frame, cross-process timestamps per hop). About 35
|
||||
commands a transition went through the router -- three calls and their replies, but also five
|
||||
`artifact.seal`, six `artifact.allocate`, five `artifact.retain`, four `artifact.release`, six
|
||||
`delivery.consumed` and three no-op `rpc.responder.release` -- and the router encoded every frame
|
||||
twice and deep-copied every payload three or four times. The session's host CPU (the dispatcher's
|
||||
CPU, which the router, the coordinator and the world share) was about 96% busy in every arm, so
|
||||
bus cost was frame time almost one for one.
|
||||
- **What changed.** Sealing sends (bus-v1 amendment: a reply seals the writers it attaches and
|
||||
recycles their staging files as new writers, so a reply's media cost no seal or allocate round
|
||||
trip); result attachments kept as delivered instead of retained; no responder release after an
|
||||
admitted reply; the router encodes each frame once and forwards an admitted payload as bytes;
|
||||
seal copies with `copy_file_range`; client location resolution cached; the session's writer pool
|
||||
keyed by capacity (4 KiB buckets) so the variable-length feed status no longer misses it. About
|
||||
14 commands a transition remain (three calls, three replies, consumes, cache releases).
|
||||
- **Measured.** Before/after tables in the run report `claude-bus-02`. Unpaced, same rounds:
|
||||
`bus/process` 17.1-17.2 ms a frame before, 14.9-15.8 after; paced at 1.0, the frame-work metric
|
||||
17.4 before, 15.0 after (the lane 12.5, legacy 10.7). The bus still costs 2.5 to 3.5 ms a frame
|
||||
more than the lane on that box, short of the 1.5 ms target, so the lane stays live. Also found:
|
||||
BUS-01's numbers had the bus store on a disk-backed directory; on tmpfs (as the release, under
|
||||
`/run`) its own binaries were 2.5 ms a frame faster.
|
||||
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
|
||||
`7b940584`) in `local`, `bus/thread` and `bus/process` (the FAFB parity suites, all arms).
|
||||
- **Review notes (2026-10-02).** The review approved with notes; since the feed and the control
|
||||
API already run over flybus in production, the router and SDK changes carry live traffic, so
|
||||
every note was treated as live-path correctness. A recycled writer's staging file is zero-filled
|
||||
when the router reissues it (about 10 us a 92,160-byte reply on tmpfs), so no artifact sealed from it -- by prefix or
|
||||
whole -- carries the previous artifact's bytes (N3). A sealing reply is sent with the worker's
|
||||
result cache held, so a duplicate replays the sealed artifacts rather than racing the reply
|
||||
with an unsealed writer (N2). A refused sealing reply is answered as the handler's own seal
|
||||
failure was before this slice (`BACKEND_FAILURE`, mutation applied), cached the same way, and
|
||||
logged (N1). A failed staging rename leaves no file (N5). `recycle` without a sealing
|
||||
attachment is refused even when false, a writer named by two attachments is refused, and the
|
||||
SDK checks `writers` on every sealing send's reply (N4). The store-directory cache is per
|
||||
connection (N6). Two test races are closed: the fly-edge stall test waits for the feed topic,
|
||||
and SERVE-01's parity accepts a refused `/stimulate` drained one frame late (N7). The review's
|
||||
adversarial lifecycle tests are in `flybus/tests/sealing_lifecycle.rs`.
|
||||
|
||||
### SHADOW-01 — The session runtime beside the live fly (port slice)
|
||||
|
||||
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no
|
||||
live behaviour. flysim gains trace switches that are off unless set, and the compatibility string
|
||||
is unchanged. The contract is [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18: the inputs,
|
||||
the architecture, what is compared, the declared differences, the window and the verdict CUT-01
|
||||
reads.
|
||||
|
||||
- **flysim** (`trace.rs`, `frame.rs`). These additions are recording only:
|
||||
- `FLY_TRACE_DIR` writes one trace file per process. A restart truncated the one `FLY_TRACE`
|
||||
path.
|
||||
- `FLY_TRACE_MAX_BYTES` caps a file; the default in directory mode is 4 GiB.
|
||||
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions.
|
||||
- `frame::ledgers_string` is now the one definition of the ledger string. The session task's
|
||||
`ledgers_of` calls it.
|
||||
- **`fly-legacy-session::shadow`** and the binary `fly-shadow`:
|
||||
- `follow` reads the per-process files. It hands out complete lines only, and a file ends when
|
||||
a newer one exists.
|
||||
- `spool` copies every new store generation as it appears. It keeps a floor and a byte bound,
|
||||
and never writes to a live store.
|
||||
- `checkpoint` exports the shadow's capture of a live save's boundary and compares it with the
|
||||
live file byte for byte, after `host-fields` and `archive-order`.
|
||||
- `verdict` is `fly-shadow-verdict-v1` and the cutover rule (`allows_cutover`,
|
||||
`fly-shadow check`).
|
||||
- The runner boots each segment from the live process's startup save (TASK-01's import). It
|
||||
replays the admissions, runs the transition, and takes the live captures in the live order
|
||||
around a deferred rollback. It compares with `trace::compare_line`, which is now shared with
|
||||
`trace::compare`. It stops on the first divergence and writes `divergence.json` with 30
|
||||
transitions of context.
|
||||
- **infra.** `units/flyshadow.service` is report-only and has no `[Install]`. It is not bound to
|
||||
flysim, runs `SCHED_IDLE` and stays stopped on exit status 3. `bin/fly-shadow-run` has the
|
||||
commands `start`, `stop`, `status` and `check`. `05-deploy.sh` converges both and pins the
|
||||
unit to the page and encoder CPUs. `build-flysim.sh` and `package-release.sh` ship
|
||||
`fly-shadow` and `fly-session`. `lint.sh` holds the unit to all of this. The runbook has a
|
||||
"Shadow run (SHADOW-01)" section.
|
||||
- **Rehearsal** (`tools/shadow-rehearsal.sh`). It runs the real `flysim` service and the real
|
||||
`fly-shadow` side by side from one checkpoint, with sugar posted to the control API and service
|
||||
restarts. It runs on a build box, never on a host.
|
||||
|
||||
**Offline rehearsal** (a build box, `tools/shadow-rehearsal.sh`, FAFB in macros mode). The real
|
||||
service ran at real time or unthrottled, with sugar posted every 10 to 20 s and a restart in every
|
||||
run. It totalled **4,090 brain seconds (68 brain minutes), 244,327 transitions, 13 processes and
|
||||
zero divergence**:
|
||||
|
||||
| Run | Start | Brain s | Transitions | What it covered |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| main | the row 67 Pewter Gym stream checkpoint (rung 10), real time, restarts at 12 and 24 min | 2,161 | 129,086 | 126 sugar, 7 rewards, 4,134 macro events, 484 saves byte-identical, a ledger digest every boundary |
|
||||
| reward | row 58 door, adapter ledger thinned (the TASK-01 brain arm, `examples/reward_bearing.rs`) | 601 | 35,894 | the real brain earns `map`, `exploration`, `boundary`, `talk` and `battle` (11 rewards); 138 saves |
|
||||
| rollback | FND-01's `rollback` checkpoint | 302 | 18,056 | a ratchet rollback and the durable save after it; a `talk` reward |
|
||||
| climb | FND-01's `climb` checkpoint | 303 | 18,069 | a ratchet slot save, and the milestone archive before it compared under `archive-order` |
|
||||
| smoke | row 67, unthrottled | 122 | 7,305 | the first run |
|
||||
| final | row 67, real time, the final binary, the lag guard on | 601 | 35,917 | the box was contended by other runs, so the live loop fell behind real time 5 times; each time the guard paused the shadow (667 s in all), and all 143 saves were still compared |
|
||||
|
||||
The reward run's box was loaded: the shadow ran at 25 frames a second against the live 52 and
|
||||
finished 12 minutes behind. Every save was still compared, from the spool.
|
||||
|
||||
`tests/shadow.rs` (ROM, the toy connectome in raw mode) runs the real service through a restart
|
||||
under a shadow, then plants four differences on copies of that run's trace and spool. Each one
|
||||
stops a fresh shadow with the right kind, field and step:
|
||||
|
||||
- a work-RAM digest;
|
||||
- a ledger digest;
|
||||
- a sugar removed, which diverges on the brain at that transition;
|
||||
- a live save's `rankSinceMs`.
|
||||
|
||||
**Cost.** These figures come from a shared 8-core build box, so they are indicative only. Other
|
||||
agents' runs made paired measurements vary by up to 2x.
|
||||
|
||||
- *The shadow.* Over the whole main run it used 1.47 cores to follow 52.3 frames a second. The
|
||||
live service used 1.43 cores for 53.5 frames a second. That is about 28 ms and 27 ms of CPU a
|
||||
frame, so the session runtime costs about what the legacy loop does (x1.05).
|
||||
- *Wall time a frame.* With 2 sweep threads the mean was 14.7 ms on the quieter box. Replaying the
|
||||
main trace unthrottled gave these means:
|
||||
- in-process with 1, 2 and 3 threads: 23.7, 19.7 and 17.0 ms;
|
||||
- thread mode with 2 threads: 18.5 ms;
|
||||
- process mode with 2 threads: 18.5 ms.
|
||||
|
||||
Every replay was identical again: five more comparisons of 20,000 transitions each.
|
||||
- *Memory.* The shadow's resident size was about 130 MB, against the live service's 54 MB.
|
||||
- *The live trace* with a ledger digest every frame costs about 1 ms of CPU a frame in the best
|
||||
paired sample, which is within this box's noise; FND-01 measured about 2 ms. The live loop has
|
||||
1.7-1.8x real-time capacity on 3 threads. The trace is about 750 bytes a transition, which is
|
||||
160 MB per live hour.
|
||||
|
||||
The resource plan for the release container is in the SHADOW-01 run report and in
|
||||
`units/flyshadow.service`:
|
||||
|
||||
- `SCHED_IDLE` on the page and encoder CPUs, never flysim's;
|
||||
- 2 sweep threads;
|
||||
- a back-off whenever the live `fly_lag_seconds` grows;
|
||||
- a 3 GB memory ceiling;
|
||||
- a ledger digest every 60 transitions.
|
||||
|
||||
To keep up, the shadow needs about 1.7 idle cores. With less it runs behind real time: the trace
|
||||
is on disk, the spool covers about 15 minutes of hot saves, and the verdict comes later.
|
||||
|
||||
**Found on the way.** binjgb's exported state does not carry the audio resampler's phase. An
|
||||
emulator imported from a state therefore drifts from a powered-on one in its channel accumulators.
|
||||
The drift shows in the exported bytes only (frame and WRAM are identical). Every restart restores
|
||||
through an import in both runtimes, so the two agree. A fresh start does not import, and the
|
||||
shadow follows one by powering on as well.
|
||||
|
||||
**Gates** (a build box with rom-env): `cargo test --workspace --release` with `--no-fail-fast`
|
||||
had three failures, each accounted for:
|
||||
|
||||
- `flysim` `integration` is the known load-sensitive test. It failed at box load 25 and passes
|
||||
alone.
|
||||
- `rom_macros_mode`'s no-PP turn is red on this base. Row 67 fixes it on main.
|
||||
- A shadow-test threshold depended on the box's speed. It was fixed, and the test passes at load
|
||||
22.
|
||||
|
||||
`clippy --workspace --all-targets -D warnings` is clean. `npm test` passed 688 with 0 failures,
|
||||
typecheck is clean, and `infra/tests/lint.sh` passed every check. The compatibility string is
|
||||
648 B `8ce67b97...` in raw and macros mode, unchanged.
|
||||
|
||||
**Review fix round, 2026-09-29** (APPROVE-WITH-NOTES). The branch was rebased onto port/task-01's
|
||||
fix round, `2fc9fd7`: an artifact-backed task ledger, the palette seed, queued saves and bounded
|
||||
history. The shadow now bounds its coordinator's history per segment. The fixes:
|
||||
|
||||
- *R1.* The verdict hashes `flysim-session`, SERVE-01's service, with the other release binaries.
|
||||
`check` defaults to `--binary flysim-session --current /opt/fly/current`. It requires the
|
||||
verdict's release to be the directory the link resolves to, with every shadowed binary
|
||||
unchanged there.
|
||||
- *R2.* Every session-side failure is a divergence:
|
||||
- a session that does not start;
|
||||
- a restore-gate refusal (`tests/shadow.rs` now plants one);
|
||||
- a capture with no agent;
|
||||
- an unrecorded transition;
|
||||
- an unbuildable trace line.
|
||||
|
||||
Skips carry a kind, and only the live side's own kinds allow a cutover.
|
||||
- *N1.* The live trace needs the shadow's heartbeat to start and to keep going, and flysim keeps
|
||||
the trace directory under 8 GiB. The runbook's claim is corrected.
|
||||
- *N2.* `fly-shadow-run` records a baseline and runs `flyshadow-guard.timer`. The guard stops
|
||||
everything and restarts flysim without the trace on 1 s of lag growth, or when the realtime
|
||||
factor drops below min(0.97, baseline - 0.03). `lint.sh` drives the rule on six cases.
|
||||
- *N3.* Both `pass` and the cutover require one live save compared per 600 brain seconds, with at
|
||||
most 10 % unavailable. The cutover also requires a shadow at most 3,600 transitions behind.
|
||||
|
||||
**Cost re-measured on the rebased tip.** This was a 12-brain-minute rehearsal on the same box,
|
||||
at real time, with a restart and the guard on. It had 43,104 transitions, 197 saves byte-identical
|
||||
and zero divergence. The box was contended by other runs again; the guard paused the shadow for
|
||||
911 s and it still passed. Unthrottled replays of its trace, all identical, gave these mean
|
||||
milliseconds per frame:
|
||||
|
||||
| Mode | ms per frame (mean) |
|
||||
| --- | --- |
|
||||
| in-process, 2 threads | 15.1 |
|
||||
| in-process, 3 threads | 13.3 |
|
||||
| thread mode, 3 threads | 14.9 |
|
||||
| process mode, 2 threads | 15.4 |
|
||||
|
||||
Earlier the same 2-thread and 3-thread in-process arms took 19.7 and 17.0 ms. With 3 threads the
|
||||
shadow keeps real time with about 20 % to spare.
|
||||
|
||||
**Review round 2, 2026-09-30** (APPROVE-WITH-NOTES; R3 and G1 were required before `start`).
|
||||
The branch was rebased onto port/task-01 `eaf588d`, and main v0.6.7 was merged in: row 68 and
|
||||
adapter `pokered-unique8-v8`. The live shadow will therefore carry the v8 compatibility string.
|
||||
The fixtures were already v8 on main.
|
||||
|
||||
- *R3.* `allows_cutover` floors the window at `REQUIRED_BRAIN_SECONDS` (10,800). A verdict run with
|
||||
a shorter `--required-brain-seconds` passes as a rehearsal but never passes `check`. There is a
|
||||
test case for this.
|
||||
- *G1, the host guard.*
|
||||
- `start` measures a 10-minute baseline of 60 samples before the shadow exists: the median RTF,
|
||||
its spread as 1.4826 x MAD, and the lag growth rate over the most recent half.
|
||||
- The guard trips only on a sustained degradation *against that baseline*: 3 checks in a row in
|
||||
which the last 5 samples of the same process fall below it, in RTF or in lag rate, by more
|
||||
than max(0.05, 4 x spread / sqrt 5).
|
||||
- It stops itself when the shadow is not running. `check` refuses after a trip or with the
|
||||
shadow down.
|
||||
- Tested over two kinds of trace:
|
||||
- *Synthetic*, shaped on the release container: a flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per
|
||||
second and per sample, and real time with hiccups. There was no false trip in 800 3-hour
|
||||
runs, and every one of 400 degradations tripped (to 0.55-0.75, and 0.66 to 0.58).
|
||||
- *Recorded* from a real flysim, now fixtures: alone (at about 1.0, and at 0.4-1.0 under box
|
||||
load) no trip; with a real idle shadow on other cpus no trip; with a real shadow on the fly's
|
||||
own cpu (0.66 to 0.44-0.60) a trip at check 7.
|
||||
- One recording had a load step inside its baseline, which widened a mean/sd baseline to a
|
||||
0.25 margin. That is why the baseline is robust.
|
||||
- *G1, the in-shadow back-off* (`LagJudge`). It pauses the shadow while the live lag grows faster
|
||||
than the baseline rate plus the margin (re-read from `baseline.json`). It lifts itself for
|
||||
10 minutes when a pause did not help, because then the shadow is not the cause. Tests show:
|
||||
- a flat 0.66 fly is never paused;
|
||||
- with no baseline, at most 1 minute in 11 is paused;
|
||||
- a shadow that costs the fly time stays paused about half the time.
|
||||
- *N3.* `lagTransitions` is recomputed at every verdict write, over the rest of the current file
|
||||
and every newer one, including while the shadow is backed off.
|
||||
|
||||
**2026-09-30: `tests/shadow.rs` "one trace file per process" (0 vs 2) on a build box.** It is not
|
||||
a timing, load or segment-handling bug.
|
||||
- *Cause.* The failing runs used a `flysim` binary that was not built from the tree under test.
|
||||
`cargo test -p fly-legacy-session` does not build `flysim`'s binary, and the build box's bx
|
||||
target directory was shared by name with other trees. That binary predated `FLY_TRACE_DIR`, so
|
||||
it wrote no trace at all. The failure was reproduced by running such a test binary against its
|
||||
own stale `flysim`.
|
||||
- *Fix.* The test now builds the `flysim` binary itself: `cargo build -p flysim --bin flysim`,
|
||||
with the same target directory and profile, which does nothing when the binary is current.
|
||||
This was proved on a target that another tree's `flysim` had populated.
|
||||
- *What production could miss, and now cannot.* A live process that runs without a trace is now
|
||||
a `coverage` divergence (above). That covers a process whose consumer check failed, and one
|
||||
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
|
||||
stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
|
||||
|
||||
### SHADOW-02 — The shadow on a build box (port slice)
|
||||
|
||||
**2026-09-30: built** on `port/shadow-02` off main (v0.7.0), and awaiting review. It changes no
|
||||
live behaviour until `fly-shadow-run start` runs; the flysim binary is unchanged. The contract is
|
||||
the SHADOW-02 amendment of [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18.
|
||||
|
||||
**Why.** On the release container the shadow (v0.7.0, started 2026-09-30) compared 1,119 brain
|
||||
seconds with zero divergence, but at about 27 ms a frame on the page and encoder CPUs it fell
|
||||
further behind every hour, and the live realtime factor fell from 0.9998 to 0.93-0.98. It went
|
||||
back to 0.999-1.0 the moment the shadow was stopped.
|
||||
|
||||
- **`shadow::remote`**: the frame protocol (a JSON header line and a body), the name checks that
|
||||
guard every path, the forwarded settings (`FORWARDED_ENV`: game, macro mode, accepted adapters,
|
||||
pins; no path, no secret).
|
||||
- **`shadow::relay`** (`fly-shadow relay`, the container's `flyshadow.service` through a drop-in):
|
||||
per quarter-second tick, the new saves, then the trace bytes of this run in file order, then
|
||||
the journal read before the listing. A writer thread owns the ssh pipe, so a stalled link never
|
||||
blocks it: saves are read as they appear and queued in memory (256 MiB), trace bytes wait on
|
||||
disk, and a newer file and the journal wait for every older file. The heartbeat is touched only
|
||||
while healthy (connected, the box's shadow of this run alive within 30 s, the box has every
|
||||
byte that was on disk a minute ago). The box's verdict is written back only when it is this
|
||||
run's, with the unsynced tail added to `lagTransitions` and a `relay` member.
|
||||
- **`shadow::ingest`** (`fly-shadow ingest --root`, the forced command of the relay's key on the
|
||||
box): the release directory and binary hashes must equal its own; a new run id resets the mirror
|
||||
and restarts the shadow; appends only at the offset it holds (else `resync`); a file the shadow
|
||||
finished is never written again (`done`, and the relay then deletes the container's copy);
|
||||
reports liveness (heartbeat fresh, verdict this run's and running or passed).
|
||||
- **The shadow**: `--run-id-file` (the verdict's `runId`; a new id exits 4); a `no-consumer` trace
|
||||
stop while following is a `coverage` divergence; coverage reads the journal before listing the
|
||||
traces. `shadow::release` holds the release hashing the binary and `check` share.
|
||||
- **infra.** `fly-shadow-run start` runs remote when `/etc/fly/shadow-remote.env` exists and
|
||||
refuses otherwise (`--local` keeps the old placement); `check` also needs `relay.json` healthy
|
||||
and under a minute old; `status` shows the relay. `infra/box/` (never deployed by 05-deploy):
|
||||
`flyshadow-remote.service` (the same release at the same path, `--run-id-file`, no lag back-off,
|
||||
`Restart=always`, stays stopped on exit 3, `CPUWeight=1000`), `flyshadow-remote.path` (starts it
|
||||
on a new run id) and `fly-shadow-remote-setup` (MANIFEST-verified root-owned release, the
|
||||
`flyshadow` user, a root-owned `authorized_keys` with `restrict,command=` and optional `from=`).
|
||||
`02-base.sh` installs `openssh-client` (no sshd). Lint holds all of it; the runbook's shadow
|
||||
section has the set-up.
|
||||
|
||||
**Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and
|
||||
the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow:
|
||||
a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops
|
||||
the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and
|
||||
follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops
|
||||
its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings
|
||||
it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets
|
||||
and `resync`, the run reset, the env allowlist.
|
||||
|
||||
**Two-box rehearsal** (FAFB, macros, row 67, real time, sugar every 10-30 s; a real flysim on one
|
||||
build box standing in for the release container, the remote shadow on another behind a real sshd
|
||||
with a `restrict,command=` key): see the SHADOW-02 run report. Cost of the shadow per live frame
|
||||
(unthrottled replay of a recorded trace, mean of the step): fly-build-1 14.1 ms with 3 threads,
|
||||
11.9 ms with 6; fly-build-2 13.9 / 13.0 / 12.2 ms with 3 / 4 / 6; fly-build-3 11.9 / 11.8 ms with
|
||||
3 / 4 (beside another agent's 1.6-core soak). The relay took about 0.5 % of a core; the stream to
|
||||
the box is about 2.1 GB per live hour (a 2.7 MB hot save every 5 s, and about 140 MB of trace).
|
||||
|
||||
**The trace's own cost on the live loop** (the coordinator's question): +1.3 ms a frame on the
|
||||
sim thread (11.14 to 12.45 ms, unpaced, 3 threads, 4 A/B rounds on a build box), about half in
|
||||
the post-frame digests (frame and work RAM) and half in the record's digests and JSON. A writer
|
||||
thread for the digests and the file was tried and rejected: on flysim's pinned CPUs it preempts
|
||||
the brain's parallel sweep and the frame took 19 ms. The live guard's baseline is taken before
|
||||
the trace is on, so the trace's cost counts against it.
|
||||
|
||||
### STATE-01 — Coherent all-participant checkpoint/recovery
|
||||
|
||||
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.
|
||||
|
|
@ -487,6 +997,114 @@ coordinator (TASK-01); this slice ships the pieces and proves them on the worker
|
|||
- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive
|
||||
holds the post-capture ratchet and slot. It is excluded from the shadow comparison.
|
||||
|
||||
### SERVE-01 — The session runtime as the live service (port slice)
|
||||
|
||||
**2026-09-29: built** on `port/serve-01` off `port/task-01` and awaiting review. It makes the
|
||||
session runtime a drop-in for the live `flysim` service, so CUT-01 can switch the stream over
|
||||
with one command and roll back with one. It changes no live behaviour: the legacy loop's frame,
|
||||
feed, checkpoint bytes and compatibility string are unchanged, and nothing runs the new binary
|
||||
until `fly-runtime session` is run on a container.
|
||||
|
||||
- **One service shell, two runtimes** (`flysim::serve`). `flysim::run` is split: `serve(config,
|
||||
sim)` binds the feed (`:7400`, or the feed bus that `fly-edge` serves), the control API
|
||||
(`:7401`) and the metrics listener (`:9101`), handles SIGTERM/SIGINT/SIGHUP, and runs `sim` on
|
||||
the calling thread with the `Shared` state, the snapshot slot and the command queue. The
|
||||
legacy loop is `serve(config, Sim::boot + Sim::run)`. The pieces of a feed header that come
|
||||
from the fly (`feed_rates`, `feed_learning`, `feed_game`, `feed_milestone`, `feed_sugar`) and
|
||||
the chat admission (`admit_chat`) move out of `Sim` into free functions both runtimes call.
|
||||
The feed codec, the bus publisher, the router, `/status`, `/events`, `/metrics` and the
|
||||
WebSocket framing are therefore one copy of the code whichever runtime is behind them.
|
||||
- **The service host** (`fly-legacy-session::service`, binary `flysim-session`). It reads
|
||||
`flysim`'s own `Config` (so `/etc/fly/fly.env`, `FLY_ACCEPT_ADAPTERS` through STATE-02's
|
||||
`RestoreGate`, the macro mode, speed, threads, chat, the store paths) and keeps `Sim`'s order
|
||||
call site for call site: boot by TASK-01's `boot_unsaved` (the legacy candidate order and gate),
|
||||
the boot event, the chat sidecar, the journal's boot header (`runtime: fly-session`), the
|
||||
startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro
|
||||
and reward events, the rank and its milestone archive, the deferred ratchet rollback with its
|
||||
recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock
|
||||
saves, the event log fsync and flysim's `Pacer`. Saves are queued (`queue_save`, TASK-01) so the
|
||||
encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them.
|
||||
- **Where each header field comes from.** The frame is the committed `lcd` view; the audio is
|
||||
each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`,
|
||||
the same filter on the environment's `v / 255`); the spike bitset is the OR of the commits'
|
||||
`telemetry.spikes` since the last publish, which equals the legacy window exactly; `buttons`
|
||||
is the executor's mask (the checkpoint's after an import, 0 after a rollback, as
|
||||
`LegacyFrame` has it); the game, milestone and macro fields are the task's own adapter,
|
||||
ratchet and macro layer (`PokeredTask::inspect`, `take_feed`). The numbers from inside the
|
||||
network that no session message carries -- the plasticity statistics (`learning.changed`,
|
||||
`learning.synapses`), the decoder's baselines and scores for `/status`, and the rates and pulse
|
||||
at the boundary -- come from one declared extension of the legacy agent,
|
||||
`Legacy.FeedStatus` (capability `legacy-feed-status-v1`): read-only, answered at a committed
|
||||
`Ready(k)`, once per published snapshot, never in a trace. `Coordinator::read_agent_extension`
|
||||
calls it without fencing the epoch; `Coordinator::media_bytes` reads the committed view and
|
||||
audio chunk.
|
||||
- **Sugar.** flysim's `RateLimiter` and clamp, over the pulse the network holds: the last commit's
|
||||
`stimulusRemainingMs`, raised by each sugar admitted since (`network.stimulate` is a maximum),
|
||||
so a second request in one drain is refused with the legacy `retryAfterMs`. The admission lands
|
||||
in the next Prepare, which is the frame the legacy drain applies it before, and the journal
|
||||
stamps it with that frame.
|
||||
- **Long-running hygiene.** The coordinator kept every transition's trace, every phase change,
|
||||
an audit line per step and every timing sample: about 120 KB/s of heap on the live fly
|
||||
(the first soak's RSS). `Coordinator::trim_records` bounds them at each boundary; the timings
|
||||
are logged once a minute as a `session profile` line and cleared.
|
||||
- **Declared differences** (the rest is byte-equal, below): `POST /reward` is always 403
|
||||
(`control.allow_reward` is forced off; the operator pulse has no session-framework
|
||||
counterpart, `legacy-gameboy-v1` section 15); a fresh start publishes no audio for its setup
|
||||
frame (the environment discards O[0]'s); `FLY_TRACE` and `FLY_PROFILE_SECONDS` are the legacy
|
||||
loop's tools; only the Pokémon composition exists (another `FLY_GAME` is refused at start); the
|
||||
toy connectome cannot run macros mode (AGENT-01 refuses a macro channel the dataset does not
|
||||
track, and the toy tracks none).
|
||||
- **Infra.** `flysim.service` stays the fly's one unit. `infra/bin/fly-runtime session|legacy|status`
|
||||
switches the binary it runs with one drop-in (`flysim.service.d/10-runtime.conf`), so every
|
||||
consumer that names `flysim.service` -- `fly.target`, `flyedge.service`'s `Requires=`, the
|
||||
watchdog, `fly-loop-recover`'s sudoers-granted restart, `fly-loop-reset`,
|
||||
`fly-reset-to-milestone`, the unstick rule -- works unchanged and the choice survives reboots and
|
||||
deploys. It refuses a release without `flysim-session` or with a different compatibility
|
||||
string, waits for `/healthz` and an advancing frame, and falls back to legacy by itself if the
|
||||
session runtime does not come up. `flysim-session.service` is the standalone unit (flysim's
|
||||
limits and cpuset, `Conflicts=flysim.service`, no `[Install]`) for rehearsals.
|
||||
`build-flysim.sh`/`package-release.sh` ship `flysim-session` and `fly-session`; `05-deploy.sh`
|
||||
installs `fly-runtime`, writes the standalone unit's cpuset drop-in and refuses a release
|
||||
without `flysim-session` while the drop-in is present; tmpfiles creates `/run/fly/session`.
|
||||
The runbook's "Switch the runtime" is the operator's page.
|
||||
|
||||
**Proof** (`fly-legacy-session/tests/service_parity.rs`, `journal_replay.rs`, rom-env; the SERVE-01
|
||||
run report has the numbers). Both runtimes are started from the same seeded store behind
|
||||
flysim's own control router and driven by one script of control requests, each landing before
|
||||
the same frame: every running feed header is equal field by field (wall-clock fields excepted)
|
||||
and every frame, audio and spike attachment byte for byte; every control response is equal
|
||||
(`/stimulate` 202/429 with the same `retryAfterMs`, `/reward` 403, `/chat` 202/422,
|
||||
`/checkpoint` the same generation, `/pause`, `/resume`, `/events`, 404s); the event log, the
|
||||
journal and the final checkpoint are equal. Toy connectome raw mode, and the real connectome in
|
||||
macros mode through a ratchet rollback, each in-process and as processes. A soak of both
|
||||
runtimes side by side with the stage's decoder and the bridge's `HttpSimClient`
|
||||
(`tools/runtime-soak.ts`), the hot/durable cadence sampled from the stores, and a `SIGKILL`
|
||||
whose journal is replayed from the seed in the legacy loop onto the killed process's last hot
|
||||
checkpoint.
|
||||
|
||||
Results (2026-09-29, the build boxes; the run report has the logs):
|
||||
|
||||
| Proof | Result |
|
||||
| --- | --- |
|
||||
| Toy raw, 120 frames, 19 scripted requests incl. two sugars in one drain | identical, in-process and process |
|
||||
| Real connectome, macros, `rollback` checkpoint (ratchet rollback on frame 1), 120 frames | identical, both modes, before and after the TASK-01 fixes |
|
||||
| Real connectome, macros, engage checkpoint (ledger thinned), 2400 frames, 46 macro and 2 reward events | identical, both modes |
|
||||
| Real connectome, macros, row 64 (a 42 KB adapter ledger, TASK-01 B1), 1200 frames | identical, both modes |
|
||||
| Soak, 35 min, both runtimes from the row 67 checkpoint, production configuration | 0 decode or schema errors, no 2 s stall, `/healthz` 100 %, event ids gapless, hot every 5 s and durable at 300 s on both (same intervals) |
|
||||
| Soak, 36 min, the session killed -9 at +6 min | back in about 1 s from the hot checkpoint 3.5 s old, 1 `/healthz` 503, the feed client reconnected (533 ms gap), two journal segments |
|
||||
| The killed process's journal, 17 sugars, replayed from the seed in the legacy loop | 18,838 frames onto its last hot checkpoint: agent, emulator, frame, adapter, ratchet equal |
|
||||
| Feed over the bus (`FLY_FEED_VIA=bus`) with `fly-edge` | 3,050 snapshots through the edge, 0 errors |
|
||||
|
||||
Open for CUT-01: **speed.** Unpaced on a shared box the session ran 54-61 fps where the legacy
|
||||
loop ran 68-118 (per frame p50: `Agent.Prepare` 7.8 ms, `Environment.Advance` 2.6,
|
||||
`Agent.Commit` 1.6, publication 0.4; `Legacy.FeedStatus` 0.9 ms at 30 Hz). The live container
|
||||
must be measured (SHADOW-01's cost run) before cutover. **Memory.** After `trim_records` the
|
||||
session's RSS still grows about 5-8 MB an hour, tied to the saves (an unpaced run without saves
|
||||
is flat); at `MemoryMax=4G` that is weeks, and a restart clears it, but it is not explained yet.
|
||||
**Number form.** A checkpoint the session writes carries the adapter ledger's integral numbers
|
||||
as `7580031` where the legacy loop writes `7580031.0` (the ledger crossed canonical JSON); equal
|
||||
values, and both runtimes read both.
|
||||
|
||||
### PUBLISH-01 — Committed snapshots and observer isolation
|
||||
|
||||
**Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to
|
||||
|
|
|
|||
|
|
@ -17,6 +17,37 @@ ownership. This document owns Scope, model-related scalar types, worker capabili
|
|||
domain operation deduplication and errors. Domain request identity is independent of the bus
|
||||
callId: a safe retry has a new transport callId but the original domain requestId/body.
|
||||
|
||||
**Amendment, 2026-09-30 (PERF-01; operator-approved slice).** One exception to "every session/worker
|
||||
RPC is a Flybus call", for participants that share the coordinator's process. The release
|
||||
container runs the legacy composition in-process, and there the bus path cost about 4.7 ms a
|
||||
frame above the brain (three round trips through the router and four or five sealed store files
|
||||
a frame), against 0.7 ms for everything the legacy loop does outside its ticks.
|
||||
|
||||
- **The local lane.** A launcher MAY offer an in-process worker's shell to the coordinator
|
||||
directly (`fly-session` `worker::LocalLane`, `launcher::Via::Local`). Endpoint methods --
|
||||
step mutations, lifecycle/capture and an endpoint's own read-only extensions -- then go to
|
||||
that shell without a bus message. `Worker.*` stays on the bus, where the supervisor asks.
|
||||
- **Same domain semantics.** The request is the same `SessionRpcRequest`, and it goes through
|
||||
the same shell code as a bus request: section 5's classification, canonical body digest,
|
||||
result cache and conflict/IN_PROGRESS/RESULT_EXPIRED rules, the arrival-order lock, and the
|
||||
endpoint. The reply is the same `SessionRpcOutcome`, checked by the coordinator for worker,
|
||||
incarnation, scope and request id exactly as a bus reply is. Section 6's deadline and
|
||||
resolution procedure are unchanged: a lane send is the "bus call", and a worker that stopped
|
||||
before answering is a lost connection (mutation unknown).
|
||||
- **Artifacts.** Over the lane, a handler's reply media are *in-memory artifacts* (bus-v1
|
||||
section 12, 2026-09-30): immutable buffers in the process with a normal `ArtifactRef`
|
||||
(`storeId` `in-memory`, no digest), no store file and no router owner. The rule of section 3
|
||||
holds as written: every `ArtifactRef` in a payload is backed by a live handle the message
|
||||
carries. An in-memory artifact never crosses a router: a bus call or a publication that needs
|
||||
one carries a sealed copy (the coordinator makes it), and the snapshot names the copy.
|
||||
A sealed handle a handler returns over the lane reaches the caller in memory under the same
|
||||
reference.
|
||||
- **Scope.** Only `ExecutionMode::InProcess`. A thread or process participant is always reached
|
||||
over the bus, so process mode keeps exercising routing and ownership, and the bus path stays
|
||||
the reference: `FLY_SESSION_LOCAL_LANE=0` runs an in-process session over it. Every synthetic
|
||||
transport test also runs over the lane (`tests/common` `local_lane` module), and the legacy
|
||||
parity runs in-process (lane) and process (bus).
|
||||
|
||||
## 2. Common domain types
|
||||
|
||||
```ts
|
||||
|
|
|
|||
|
|
@ -288,6 +288,37 @@ signal. The object serves exactly one agent on one port.
|
|||
- **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world
|
||||
the fly now stands in.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01).** Choices the section above leaves open, fixed as built by
|
||||
`fly-legacy-session::task`:
|
||||
|
||||
- *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment
|
||||
as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot".
|
||||
So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot
|
||||
save is asked for exactly when the legacy capture closure runs: safe, and rank above best.
|
||||
- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's
|
||||
lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past
|
||||
the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet,
|
||||
slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A
|
||||
checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's
|
||||
explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable
|
||||
attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate.
|
||||
- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette
|
||||
from the brain's RNG state after boot. A restore does the same: it seeds with the restored
|
||||
agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up,
|
||||
so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro
|
||||
has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge:
|
||||
two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future
|
||||
macro that draws from the generator fails there.
|
||||
- *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the
|
||||
warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's
|
||||
`Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a
|
||||
restore the layer observes at the restored brain time.
|
||||
- *A reward event with `stimulation_ms` = 0* is one `Reward` and no `Stimulus`, because
|
||||
`Stimulus.durationMs` is positive. The legacy `stimulate(0)` changes nothing.
|
||||
- *Executor events.* Macro starts and finishes are not `executionEvents`. They are reported as
|
||||
`FLY_TRACE` `macroEvents` (phases `execute`, `evaluate`, `rollback`). Reward events are the
|
||||
task's `TaskEvent`s.
|
||||
|
||||
## 11. Episode policy `legacy-ratchet-rollback-v1`
|
||||
|
||||
The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during
|
||||
|
|
@ -331,6 +362,14 @@ the adapter's persistent state. The first audio chunk after the rollback marks a
|
|||
discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent.
|
||||
Each half touches only its own state, so the order between the halves does not matter.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01).** The coordinator applies the policy itself, as the section
|
||||
describes. The phase is `RollingBack(k)`. The new epoch is the session's epoch root plus `.rb<n>`,
|
||||
which is deterministic, so two runs of one session name the same epochs. A composition that
|
||||
declares the policy refuses to start unless every agent advertises `legacy-ratchet-rollback-v1`.
|
||||
The task's rollback request carries `{slotId: best, trigger}`. The world must advertise
|
||||
`gameboy-slots-v1` before anything is saved or restored. Service traces with a ratchet slot save
|
||||
and a ratchet rollback reproduce as described in the implementation guide's TASK-01 entry.
|
||||
|
||||
## 12. Composition declaration and digest
|
||||
|
||||
```ts
|
||||
|
|
@ -376,6 +415,120 @@ interface LegacyGameboyComposition {
|
|||
for publication, traces and descriptor revisions, not a restore gate. This matches today's
|
||||
behaviour, where a decoder change does not refuse a checkpoint.
|
||||
|
||||
**Amendment, 2026-09-30 (PERF-01): the in-process release configuration.** Nothing in the
|
||||
declaration, the digest or the compatibility string changes; these are execution choices of the
|
||||
composition as `fly-legacy-session` builds it, recorded here because the shadow compares the
|
||||
behaviour they must not change.
|
||||
|
||||
- *In-process participants are called over the local lane* ([session RPCs](ipc-v1.md) section 1,
|
||||
2026-09-30): the frame, the memory image, the audio chunk and the spike bitset are in-memory
|
||||
artifacts, handed over without a store file. Process mode is unchanged and still goes through
|
||||
the router. `FLY_SESSION_LOCAL_LANE=0` puts an in-process session back on the bus.
|
||||
- *`telemetry.spikes` is unchanged*: one bitset per transition, bit `i` set when neuron `i`
|
||||
spiked in `[transition start, brain time)`, the legacy layout. The agent now builds it as the
|
||||
union of the kernel's per-tick spike lists while Prepare ticks (`LifNetwork::tick_spikes`)
|
||||
instead of scanning 139,255 last-spike times in Commit; the two are equal by construction and
|
||||
by test, and the parity runs compare the bitset every frame. The AGENT-01 alternative -- attach
|
||||
it only at the feed rate -- was not needed and was not made.
|
||||
- *Committed snapshots on the session topic*: a service session publishes every 60th boundary and
|
||||
every boundary with task events or boundary actions (it was every other boundary). The live
|
||||
presentation is the legacy feed, which the service host builds from the committed boundary at
|
||||
30 Hz; nothing in the release subscribes to the session topic, and each publication seals a
|
||||
store copy of the frame and the audio chunk. Every publication is still of a committed
|
||||
boundary and still attaches the media it names (publishing-v1 section 3).
|
||||
- *Nothing runs beside the brain's ticks.* On the release CPU with the sweep owning every core of
|
||||
the flysim cpuset, work overlapping Prepare (a publication left in flight, for instance) slowed
|
||||
the ticks by up to a third, so the coordinator finishes each boundary before the next Prepare.
|
||||
|
||||
**Amendment, 2026-10-01 (PERF-02): thread placement in the service.** Again nothing in the
|
||||
declaration, the digest or the compatibility string changes, and no result can: placement chooses
|
||||
the CPU a thread runs on, never what an index of a parallel phase computes.
|
||||
|
||||
- `flysim-session` (in-process and thread modes), before it spawns any thread, gives each of the
|
||||
`RAYON_NUM_THREADS - 1` spawned sweep workers one CPU of the unit's cpuset to itself and confines
|
||||
every other thread -- the dispatching runtime worker, the coordinator, the listeners, the
|
||||
checkpoint writer -- to the rest (the first CPU, plus any beyond the sweep's). Process mode and
|
||||
the legacy loop are unchanged. `FLY_SESSION_PIN=0` keeps every thread floating, as before. The infra keeps other processes off the pinned CPUs (`flysim.slice`, `fly-cpu-confine`) and sets it to `0` where it cannot.
|
||||
- Why: the session's host threads sleep and wake around every transition, so the sweep workers
|
||||
park and wake every transition too, and the scheduler often woke two of them onto one CPU while
|
||||
a host thread held another: each parallel phase of that transition then took two shares' time.
|
||||
On the release CPU model with a four-CPU cpuset the session's ticks ran 35% slower than the
|
||||
legacy loop's, which is what failed CUT-01's speed probation (0.959 < 0.97); placed, they cost
|
||||
what the legacy loop's do.
|
||||
|
||||
**Amendment, 2026-10-01 (BUS-01): the composition on the router.** The operator's direction of
|
||||
2026-10-01: run the live session's participants over the flybus router on Unix sockets, one
|
||||
emulator and one fly today, because multiplayer and more flies follow. Nothing in the declaration,
|
||||
the digest or the compatibility string changes, and no result can: the bus carries the same
|
||||
domain calls, in the same order, to the same endpoints as the local lane. Traces, checkpoints and
|
||||
the FAFB parity runs are identical in every arm (`local`, `bus/thread`, `bus/process`;
|
||||
`fly_legacy_session::composition::SessionArm`).
|
||||
|
||||
*Selecting it.* `FLY_SESSION_TRANSPORT=bus` (or `flysim-session --transport bus`) puts every
|
||||
participant on the router's sockets; `FLY_SESSION_MODE` then defaults to `process`, and `thread` and
|
||||
`in-process` are also allowed (`in-process` on the bus is every participant a socket client from
|
||||
the coordinator's own runtime). `local`, the default, is the PERF-01 lane and stays the release
|
||||
configuration until a cutover onto the bus. `local` with a thread or a process is refused: those
|
||||
have no lane. On the container, `fly-runtime session --bus` (`session-bus`) writes
|
||||
`Environment=FLY_SESSION_TRANSPORT=bus` into the runtime drop-in, and `session --local` takes it out.
|
||||
|
||||
*The topology (process mode, the bus default).*
|
||||
|
||||
| Process | Runs | Bus client | Reached by |
|
||||
| --- | --- | --- | --- |
|
||||
| `flysim-session` (the unit's main process) | the router (one per session), the launcher's supervisor, the coordinator with the `pokered-macros-v1` task and executor, the service host (feed, control API, metrics, checkpoint writer, sugar journal) | `coordinator`, `launcher` | in memory: they live with the router |
|
||||
| `fly-session legacy-agent` (child) | AGENT-01: the brain, its readout and its sweep pool | `legacy-fly`, registers `agent.fly` | `<session dir>/attempt-N/sockets/legacy-fly-<n>.sock`, launcher-bound |
|
||||
| `fly-session legacy-environment` (child) | ENV-01: binjgb, the slot, the memory image | `legacy-world`, then `legacy-world-r2` for the restore's replacement world; registers `env.world` | `.../sockets/legacy-world[-r2]-<n>.sock`, launcher-bound |
|
||||
|
||||
- *Policy* (closed, `composition.rs`): the coordinator may call `agent.*` and `env.*` and owns
|
||||
`session.*` (publish, topics, its query service); the supervisor may call `agent.*` and `env.*`
|
||||
and register nothing; each participant may register exactly its own service and call nothing.
|
||||
An identity is bound by the launcher before Hello, so a process cannot answer as another.
|
||||
- *Media* stay artifacts in the router's store (`<session dir>/attempt-N/store`, tmpfs, `fly`
|
||||
0700): the 92,160-byte frame, the 65,536-byte memory image, the audio chunk (about 6.4 KB a frame
|
||||
of `f32le`) and the 17,407-byte spike bitset every transition, and the captures (MBs, every hot
|
||||
save). Inline is not an option: bus-v1 section 8.1 forbids binary in a body, and the image alone
|
||||
would not fit the 64 KiB envelope once encoded. A delivery names each attachment's read location
|
||||
(bus-v1 section 12, 2026-10-01), so a read is a local file read; a worker seals into writers it
|
||||
allocated after the previous step (`worker::WriterPool`). Over the bus the agent's Commit also
|
||||
attaches its feed status (`legacy.feed-status`, the `Legacy.FeedStatus` result's bytes as of the
|
||||
committed boundary), which the service host reads instead of making that call at every publish;
|
||||
a rollback after the Commit makes it ask again.
|
||||
- *One unit, restarted as a whole.* The session cannot survive the loss of a participant: its
|
||||
state is split across them and is recovered only as a group (STATE-01), and the store's last save
|
||||
is that group. So the children belong to `flysim.service` (the launcher spawns them; systemd's
|
||||
default `KillMode=control-group` reaps them with the unit), a dead participant fails the step
|
||||
within `ipc-v1` section 6's ten seconds, `flysim-session` exits, and `Restart=always` starts the
|
||||
whole session again from the store -- what a crash of the in-process session does today. A
|
||||
child also exits when its router connection closes. The router lives in the coordinator's
|
||||
process for the same reason: its loss is the session's. One unit keeps `fly-runtime`'s one
|
||||
drop-in switch, the `OnFailure=` fallback to legacy (three starts in ten minutes), the speed
|
||||
probation, the watchdog and the unstick rule's restart unchanged; separate units would need
|
||||
`BindsTo=` chains and three start limits for no recovery a group restore does not already give.
|
||||
- *CPUs.* The unit's cpuset is unchanged (on the release container `flysim.slice`'s four CPUs).
|
||||
The service splits it as PERF-02 does and hands the split out: the agent process pins its spawned
|
||||
sweep workers one per CPU and keeps its other threads (its dispatcher is sweep worker 0) on the
|
||||
remaining CPU (`fly-session ... --sweep-cpus 3,5,7 --host-cpus 1`); the service process and the
|
||||
world process run on that same host CPU. The transaction is serial -- nothing overlaps Prepare
|
||||
(PERF-01) -- so they take turns on it rather than contend. `FLY_SESSION_AUX_CPUS` moves the
|
||||
service and the world elsewhere in the unit's cpuset; it was measured and does not pay
|
||||
(implementation guide, BUS-01). `FLY_SESSION_PIN=0` floats everything, as before.
|
||||
- *Each participant process has one async worker, and a long handler gives it up*
|
||||
(`tokio::task::block_in_place` for `*.Initialize`, `State.*`, `Agent.Rollback`): the agent's
|
||||
warm-up runs for seconds, and a Tokio worker blocked that long stranded the shell's own bus loop,
|
||||
so `ipc-v1` section 6's resolution of a slow `Agent.Initialize` failed ("never resolved") and a
|
||||
session could not boot on a loaded box. A step's handlers (milliseconds) run in place, so a bus
|
||||
request crosses no thread inside a participant. The local lane is unchanged.
|
||||
|
||||
*N agents and M environments are configuration.* Nothing above assumes one of each: the
|
||||
launcher starts any number of `LegacyAgentLaunch` and environment launches, each with its own
|
||||
client id, service name and socket; the policy grants are per client; placements are per worker
|
||||
id (`Launcher::place_process`), so each agent process pins its own sweep to its own CPUs; the
|
||||
coordinator calls agents concurrently and assembles one batch over every declared port; the router
|
||||
has no notion of a fly. What is one-of-each today is this composition (`LegacyConfig`, one
|
||||
`PokeredTask`, `FLYSIM01`'s one agent and one world) and the service's CPU split (one agent's
|
||||
plan), which a multi-agent composition replaces rather than extends.
|
||||
|
||||
## 13. Machine-readable parts
|
||||
|
||||
| Where | What |
|
||||
|
|
@ -500,6 +653,27 @@ Resume tests compare against the legacy restore outcome, not against an uninterr
|
|||
unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps
|
||||
the rung.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01): a FLYSIM01 checkpoint as the start.** A new-runtime session
|
||||
starts from the live fly's own save through the ordinary group restore
|
||||
(`Coordinator::import`, `fly-legacy-session::import`):
|
||||
|
||||
- The world is ENV-01's `WorldState::from_flysim01` at `k = emulatorFrame - 1`, staged on a
|
||||
replacement world.
|
||||
- The agent is the checkpoint's agent state in the worker's own capture format: STATE-02's
|
||||
`legacy_checkpoint::agent_payload`. It carries the file's reinforcement count and the file's
|
||||
framebuffer as the next input, and its ids come from the file.
|
||||
- The task is STATE-02's ledger `{reward, ratchet, slotFilled}`.
|
||||
|
||||
A session boots from the live stores the way `Sim::boot` does: the legacy candidate order, the
|
||||
legacy gate, the next candidate on any refusal, then a startup durable save. See the
|
||||
implementation guide's TASK-01 entry.
|
||||
|
||||
This section's resets then apply, and nothing else. The executor is fresh and observes the restored
|
||||
image once, at the restored brain time. The agent's readout transient is a fresh process's. The
|
||||
decision context is computed from the checkpoint's memory image before the install, and the
|
||||
coordinator refuses the install if the task, re-observing the restored world, derives another
|
||||
context.
|
||||
|
||||
## 15. Sugar admission
|
||||
|
||||
The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap
|
||||
|
|
@ -523,6 +697,29 @@ applies it never commits, the admission is reported aborted and the edge refunds
|
|||
bridge's fulfil path and refund path both get tests in the slice that wires them
|
||||
([workers-v1](workers-v1.md) section 5 amendment).
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01).** As built:
|
||||
|
||||
- *Admission.* The coordinator's `AdmissionQueue` is cut at the top of each Prepare. It reports
|
||||
every admission `applied` at the boundary its Prepare committed at, or `aborted` when the epoch
|
||||
fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the
|
||||
clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply.
|
||||
After a restore the pulse is unknown and a request is refused with a retry of one frame.
|
||||
*Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit
|
||||
counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The
|
||||
legacy `stimulate` activates the pulse the moment it admits, so this matches:
|
||||
- two sugars between two commits get one admission and one `PulseActive`, as the legacy drain
|
||||
gives them;
|
||||
- the rate-limit slot is not spent on the refused one.
|
||||
|
||||
The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the
|
||||
ticks between drains; here it is undecayed until the commit reports it.
|
||||
- *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless
|
||||
an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API
|
||||
answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside
|
||||
`Agent.Commit` is not a session-framework operation. `LegacyAdmission::reward` therefore always
|
||||
refuses. A legacy trace that carries a reward pulse cannot be reproduced; FND-01's checker
|
||||
refuses one as well.
|
||||
|
||||
## 16. Checkpoint format of record
|
||||
|
||||
**Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)`
|
||||
|
|
@ -597,3 +794,247 @@ graph validation for new bundles, and the composite behaviour identity of FOUNDA
|
|||
**not** in this document. They ship with PROF-02b, before DATA-01, as their own contract.
|
||||
Nothing here constrains them, except that a new profile never reuses this profile's id or its
|
||||
legacy exception.
|
||||
|
||||
## 18. The shadow run (SHADOW-01)
|
||||
|
||||
**Amendment, 2026-09-29 (SHADOW-01).** The operator's decision of 2026-09-23 gates the automatic
|
||||
cutover (CUT-01) on "a 3-hour shadow run with zero divergence". This section fixes what that
|
||||
means. The implementation is `fly-legacy-session::shadow` and the binary `fly-shadow`, with the unit
|
||||
`infra/units/flyshadow.service` and the script `infra/bin/fly-shadow-run`.
|
||||
|
||||
**The inputs.** The legacy loop is deterministic, given two things: the state a process starts
|
||||
from and the admissions applied at the top of each frame. Every nondeterministic input reaches
|
||||
the fly through one of those two:
|
||||
|
||||
| Input | How it reaches the fly | How the shadow gets it |
|
||||
| --- | --- | --- |
|
||||
| Restart, watchdog kill, `fly-loop-recover`, `fly-reset-to-milestone`, deploy | A new process restores a checkpoint (section 14), or warms up a fresh fly, and writes a durable startup save of the state it starts from | The trace's start line names that save (`g<N>`); the shadow boots a new session from it through the ordinary FLYSIM01 import |
|
||||
| Sugar (`POST /stimulate`) | Admitted on wall time and the live pulse (rate limiter, "no overlap"), applied at the top of a frame | The transition's `admissions`, replayed into the admission queue (`LegacyAdmission::replay_sugar`) |
|
||||
| Operator reward pulse (`POST /reward`) | Off in every shipped configuration (403) | Cannot be reproduced (section 15 amendment): the rest of that segment is reported uncompared |
|
||||
| Wall time | Pacing, publish rate, checkpoint intervals, pause (no frame runs). None changes a transition | Not needed. The trace records which saves were taken where |
|
||||
| Chat | A caption track; it reaches nothing the fly does | Not needed |
|
||||
| Threads | The sweep's result does not depend on the thread count (AGENT-01) | The shadow picks its own |
|
||||
|
||||
So "the same inputs" means *the same start state per process and the same admissions per
|
||||
transition*. Admission itself is not compared. The session runtime decides admission against a
|
||||
pulse one commit stale, by the operator's decision (section 15). A shadow that re-decided sugar on
|
||||
its own clock would diverge by design, not by fault.
|
||||
|
||||
**The architecture: the legacy fly stays primary, and the shadow follows its trace.** The live
|
||||
service writes `FLY_TRACE` (FND-01) with three switches added for the shadow. None changes a
|
||||
behaviour field or anything the fly does:
|
||||
|
||||
- `FLY_TRACE_DIR` writes one file per process, `trace-<start wall ms>-<pid>.jsonl`.
|
||||
- `FLY_TRACE_MAX_BYTES` caps each file (4 GiB by default in directory mode).
|
||||
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions. This is the SHA-256 of
|
||||
`flysim::frame::ledgers_string` after the boundary: adapter export, ratchet, slot, and the
|
||||
executor's scene, bound set, running macro, counts and "nearer".
|
||||
|
||||
`fly-shadow` follows the files in start order. For each file it takes these steps:
|
||||
|
||||
1. It boots a session (agent, world, task and executor, as in TASK-01) from that process's startup
|
||||
save. A fresh start is different: the stores were empty and the startup save is at boundary 0.
|
||||
In that case the shadow runs the same power-on scaffold and warm-up
|
||||
(`Environment.Initialize`, `Agent.Initialize`), and holds the startup save to its own
|
||||
boundary 0, byte for byte. An import would not give the same emulator. binjgb's audio
|
||||
resampler phase is not in its exported state, so the channel accumulators of an imported
|
||||
emulator drift from those of a powered-on one, in the exported state only. Both restores of a
|
||||
restart import, so they agree.
|
||||
2. For every transition, it replays the admissions and runs `Coordinator::step`. It takes a
|
||||
capture wherever the live trace records one, before or after the boundary's rollback as the
|
||||
live loop took it, then applies the deferred rollback.
|
||||
3. It builds its own trace line from what crossed the session's boundaries (`trace::line`) and
|
||||
compares it with the live line, field by field.
|
||||
|
||||
A spool thread copies every new store generation as it appears, because a hot file lives only
|
||||
about ten seconds. The shadow never writes to the live stores.
|
||||
|
||||
The reverse arrangement was considered: the session runtime as primary, with legacy as the
|
||||
checker. It would make the shadow run the cutover itself, and a divergence would already be on
|
||||
the stream. A second legacy process in lockstep was also considered. It adds nothing, because the
|
||||
live process's own trace *is* the legacy behaviour.
|
||||
|
||||
**What is compared, per boundary.**
|
||||
|
||||
- *The trace line*, every transition. The fields are `step`, `admissions`, `ticksAdvanced`,
|
||||
`brainTicks`, `remainder`, `ratesDigest`, `spikesDigest`, `spikeCount`, `decision`, `mask`,
|
||||
`macroEvents`, `framebufferDigest`, `wramDigest`, `rewards`, `rank`, `acknowledgedBoundary`
|
||||
and `boundaryActions`. `boundaryActions` covers the slot saves with their state digests and
|
||||
the rollbacks.
|
||||
- *The ledgers*: `ledgersDigest` on the transitions that carry it. The shadow digests the same
|
||||
string from its own task (`task::ledgers_of` is `ledgers_string`). This covers the executor's
|
||||
ledgers, which no checkpoint carries.
|
||||
- *The checkpoint bytes*, at every live save the spool still holds. The shadow captures the same
|
||||
boundary and exports FLYSIM01 through the shared encoder (STATE-02). It compares the export
|
||||
byte for byte with the live file after the substitutions named below. `compatibility`,
|
||||
`speed` and `rankSinceMs` are the shadow's own, so they are compared too.
|
||||
|
||||
**Declared differences**, excluded by name. The verdict lists the same names.
|
||||
|
||||
| Name | What is excluded |
|
||||
| --- | --- |
|
||||
| `archive-order` | A legacy milestone archive taken before that boundary's slot save (`afterActions` 0 ahead of a `save-slot`, sections 4 and 16) holds the pre-capture ratchet and slot. The live file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's in that capture only. The operator accepted this on 2026-09-23 ("Archive order") |
|
||||
| `decision-list-order` | The decision is compared as `gameboy-channels-v1` sees it (section 6, `trace::channels`) |
|
||||
| `host-fields` | `generation`, `wallMs` and `lastEventId` are the live file's. They are host bookkeeping: the shadow keeps no feed event log (SERVE-01's service host keeps its own) and allocates no generations, because it writes no store |
|
||||
| `admission-replay` | Sugar is replayed, not re-decided (above) |
|
||||
| `operator-reward-pulse` | A segment with one is reported uncompared from that transition on |
|
||||
|
||||
**The window.** The verdict is `pass` once the compared transitions add up to **10,800 s of
|
||||
live brain time** (the sum of `ticksAdvanced`, 3 h at real time) with zero divergence, and at least
|
||||
one live save per 600 of those brain seconds has been compared byte for byte. That time may span
|
||||
several processes.
|
||||
|
||||
*Skips* are only the live side's own events (`SKIP_KINDS`):
|
||||
|
||||
- `startup-save-gone`: a process whose startup save was already gone when the shadow reached it,
|
||||
because the shadow started late or its spool evicted the file;
|
||||
- `operator-reward-pulse`;
|
||||
- `no-transition`: a process that ran none.
|
||||
|
||||
A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which
|
||||
refuses the cutover. A process killed hard loses its unflushed tail, and those transitions are
|
||||
not compared.
|
||||
|
||||
The first difference of any kind stops the shadow with `diverged` (exit status 3) and writes
|
||||
`divergence.json` with the 30 transition pairs before it. The same applies to every session-side
|
||||
failure, which is **never** a skip:
|
||||
|
||||
- a trace field;
|
||||
- the ledgers;
|
||||
- the checkpoint bytes;
|
||||
- a session that does not start;
|
||||
- a startup save the candidate's restore gate refuses or the session runtime cannot restore;
|
||||
- a step, capture or rollback error;
|
||||
- a transition the session did not record;
|
||||
- *coverage*: a live flysim process that booted while the shadow ran and left no trace
|
||||
(amended 2026-09-30).
|
||||
|
||||
The shadow reads every boot header in the live sugar journal. Every flysim process writes one,
|
||||
traced or not. It holds each header to a trace file created after the previous boot and before
|
||||
this one. A process that ran untraced can never be compared, so the verdict fails. It does not
|
||||
pass on the processes that were traced.
|
||||
|
||||
A shadow that keeps running after `pass` turns the verdict to `diverged` on a later difference.
|
||||
|
||||
**The live fly never pays for the shadow (amended by the SHADOW-01 review).** Three mechanisms
|
||||
make sure of it:
|
||||
|
||||
- *The trace is on only while a shadow consumes it.* The shadow writes a heartbeat
|
||||
(`<trace dir>/consumer`) every 30 s and removes it when it stops. flysim starts no trace without
|
||||
a fresh heartbeat, stops a running one within a minute of frames once the heartbeat is more than
|
||||
10 minutes old, and keeps the directory under 8 GiB. A heartbeat dated ahead of flysim's clock
|
||||
counts as fresh. A trace flysim cannot create (a full disk, the directory's permissions) never
|
||||
stops the live fly from starting: that process runs untraced, and the shadow reports it as a
|
||||
coverage divergence.
|
||||
- *The guard* (`fly-shadow-run guard`, every 60 s, root) judges the live fly against its own pace
|
||||
before the shadow existed. The live fly does not always keep real time: the release container
|
||||
has run at a realtime factor of 0.66, and at 0.77-0.99 after its cpuset rebalance. So `start`
|
||||
first measures a 10-minute baseline over sixty 10-s `fly_realtime_factor` means. It records
|
||||
their median and their spread (1.4826 x MAD), so a step in the window cannot set or widen it,
|
||||
and the `fly_lag_seconds` growth rate over the most recent half. The guard trips only on a *sustained* degradation against
|
||||
that baseline: 3 checks in a row in which the last 5 samples of the same process fall below the
|
||||
baseline realtime factor, or grow lag faster than the baseline rate, by more than
|
||||
max(0.05, 4 x spread / sqrt 5). A trip stops everything and restarts flysim without the trace.
|
||||
The guard stops itself when the shadow is not running. `lint.sh` holds the rule to the release
|
||||
container's profiles, synthesized, and to four traces recorded from a real flysim with and
|
||||
without a real shadow (`infra/tests/fixtures/shadow-guard`). In 800 synthetic 3-hour runs it
|
||||
found no false trip, and it caught all 400 degradations.
|
||||
- *The shadow* runs at `SCHED_IDLE` off flysim's CPUs. It pauses for a minute while the live lag
|
||||
grows faster than the baseline rate. When a pause does not help, the shadow is not the cause,
|
||||
and it stops pausing for 10 minutes.
|
||||
|
||||
**The verdict contract (for CUT-01).** The shadow writes `verdict.json` in the format
|
||||
`fly-shadow-verdict-v1` (`shadow::verdict`, whose module notes list the fields). CUT-01 cuts over
|
||||
automatically only if all of the following hold when it reads the file, at the moment of cutting
|
||||
over:
|
||||
|
||||
- `status` is `pass` and `firstDivergence` is `null`;
|
||||
- `compared.brainSeconds` ≥ `required.brainSeconds`, and never less than the operator's 10,800 s,
|
||||
whatever window the shadow was run with;
|
||||
- *Saves were compared.* At least one per 600 brain seconds was compared byte for byte, and at
|
||||
most 10 % of those the trace named were unavailable.
|
||||
- *The release.* `candidate.release` is the directory `/opt/fly/current` resolves to now. Every
|
||||
binary in `candidate.binaries` still has its recorded SHA-256 there. The binary switched to,
|
||||
`flysim-session` (SERVE-01's service), is one of them.
|
||||
- `candidate.compatibility` is the live `--print-compatibility`;
|
||||
- every `skipped` entry is one of the live side's own kinds;
|
||||
- *the shadow is alive and caught up*: `updatedAt` is at most 5 minutes old and
|
||||
`lagTransitions` is at most 3,600, counted at every write (paused or not) over the rest of the
|
||||
current file and every newer one;
|
||||
- (`fly-shadow-run check`) the guard has not tripped and `flyshadow.service` is running.
|
||||
|
||||
`fly-shadow check` (and `fly-shadow-run check`) implements exactly this rule and exits 0 only when
|
||||
it holds. Anything else keeps the legacy fly. The one-command rollback `fly-runtime legacy` is
|
||||
CUT-01's.
|
||||
|
||||
**Amendment, 2026-09-30 (SHADOW-02): the shadow runs on a build box.** On the release container
|
||||
the shadow cost the live fly real time: SCHED_IDLE on the page and encoder CPUs, sharing them with
|
||||
the encoder and the browser and the memory bandwidth of flysim's NUMA node, it took about 27 ms a
|
||||
frame, fell further behind every hour (so it could never meet the catch-up bound), and the live
|
||||
realtime factor fell from 0.9998 to 0.93-0.98. It recovered to 0.999-1.0 the moment the shadow
|
||||
stopped. The comparison itself is unchanged: the shadow is the same binary of the same release,
|
||||
following the same trace. What moves is where it runs, and so how its inputs reach it and its
|
||||
verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
|
||||
|
||||
- *The relay* (`fly-shadow relay`, the container's `flyshadow.service` with the drop-in
|
||||
`fly-shadow-run start` writes) opens one ssh connection to the box and streams, every quarter
|
||||
second: the new live saves of both stores, then the new bytes of every trace file of this run
|
||||
(oldest first; a file's size read after the directory listing, so an older file is complete
|
||||
when a newer one reaches the box), then the sugar journal as read before the listing. Trace files
|
||||
that started before the run (`FLY_SHADOW_RUN_ID`, the start's Unix ms) and saves older than a
|
||||
minute before it are not sent. A writer thread owns the link, so a stall never blocks the relay:
|
||||
new saves are read as they appear and held in memory (256 MiB, about 8 minutes; a hot save lives
|
||||
about ten seconds), trace bytes wait on disk, and a newer file and the journal wait until every
|
||||
older file is complete on its way.
|
||||
- *The ingest* (`fly-shadow ingest --root <dir>`) is the forced command of the relay's key on the
|
||||
box (`authorized_keys` `restrict,command=`); the box holds no credential for the container. It
|
||||
refuses a relay whose release directory or binary SHA-256 differ from its own, so the box runs the
|
||||
container's release, installed from the same tarball at the same path, and the verdict's
|
||||
`candidate` is exactly what `check` recomputes on the container. A new run id resets the mirror
|
||||
and restarts the box's shadow (it exits with status 4; `--run-id-file`).
|
||||
- *The heartbeat.* flysim's `<trace dir>/consumer` on the container is now the relay's. The relay
|
||||
touches it only while it is healthy: connected; the box reported within 30 s that the shadow of
|
||||
this run is alive (its own heartbeat fresh and its verdict this run's, running or passed); and
|
||||
the box has acknowledged every byte that was on the container's disk a minute earlier. A dead box,
|
||||
shadow or link, and a stalled sync, therefore stop the live trace exactly as a dead local shadow
|
||||
does. The relay removes the file when it stops.
|
||||
- *The verdict* on the container is the box's `verdict.json`, written back only when its new
|
||||
`runId` member is this run's, with two changes: `lagTransitions` is the box's plus the live
|
||||
trace not yet acknowledged by the box, so the catch-up bound covers the sync; and a `relay`
|
||||
member (`relayedAt`, `remoteLagTransitions`, `unsyncedBytes`, `unsyncedTransitions`). A diverged
|
||||
verdict brings `divergence.json` and the checkpoint files back, and the relay exits with status 3.
|
||||
- *Coverage, tightened for both placements.* A trace that stops for want of a consumer
|
||||
(`"truncated":true,"reason":"no-consumer"`) while the shadow is following it is now a `coverage`
|
||||
divergence, not a `trace-cap` skip: the rest of that live process can never be compared, and with
|
||||
a relay a stalled sync is exactly how that happens. A stop already in the file when the shadow
|
||||
started, and the byte cap, end the verdict's window instead (`window.ends`): what was compared
|
||||
before them stops counting, and a pass needs its brain time after the last one (SHADOW-02 B2). The coverage
|
||||
check reads the sugar journal before it lists the trace directory (a process creates its trace
|
||||
file before it writes its boot header, so a boot between the two reads could look untraced
|
||||
the other way round).
|
||||
- *`fly-shadow-run check`*, remote: in addition to everything above, `/srv/fly/shadow/relay.json`
|
||||
must be less than a minute old and say `healthy`. `fly-shadow check` (the Rust rule) is
|
||||
unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
|
||||
- *The guard* stays on the container and guards the live fly as before; it now watches the relay's
|
||||
cost, which is a few file reads and one ssh stream.
|
||||
|
||||
**Amendment, 2026-10-01 (BUS-01): a shadow of the bus topology.** A cutover onto the bus is a
|
||||
cutover into another topology, so it needs a shadow that ran it. `fly-shadow --mode` (and
|
||||
`FLY_SHADOW_MODE`) names the topology as `SessionArm` does: `local` (the default, the in-process
|
||||
lane; `in-process` is the same), `bus/thread`, `bus/process` (`bus`, `process`), `bus/in-process`.
|
||||
`fly-shadow-run start --bus` sets `FLY_SHADOW_MODE=bus/process` in a drop-in of
|
||||
`flyshadow.service` (`mode.conf`); in remote mode the relay forwards it with the rest of the live
|
||||
composition's settings (it is in `FORWARDED_ENV`), so the box's shadow -- the same release, which
|
||||
ships `fly-session` beside `fly-shadow` -- starts its agent and its world as child processes on its
|
||||
own router's sockets. Its placement is the box's: the shadow places no thread. The verdict records
|
||||
the topology (`candidate.executionMode`, and `candidate.transport`, new), and
|
||||
`fly-shadow check --require-arm bus/process` (`fly-shadow-run check --bus`) refuses a verdict that
|
||||
did not run it; a verdict from before this amendment, with no `transport`, counts as `local` when
|
||||
it ran in process. The comparison, the window and every other rule of this section are unchanged.
|
||||
|
||||
The shadow follows the trace only the legacy loop writes (`FLY_TRACE_DIR`); the session runtime
|
||||
ignores it. So the live fly runs the legacy runtime for the shadow's window, as it did for CUT-01:
|
||||
`fly-shadow-run start` refuses while `flysim.service` runs the session runtime. The procedure for a
|
||||
switch onto the bus is: `fly-runtime legacy`; `fly-shadow-run start --bus`; three hours of zero
|
||||
divergence; `fly-shadow-run check --bus && fly-runtime session --bus` (the probation then judges
|
||||
the bus topology). Shadowing the session runtime from its own trace is not built.
|
||||
|
|
|
|||
|
|
@ -12,6 +12,14 @@ ordering. Its frame order is this document's transaction order (legacy-gameboy-v
|
|||
maps it step by step), so the amendments below add capabilities to the protocol and change
|
||||
none of its ordering rules.
|
||||
|
||||
**Amendment, 2026-09-30 (PERF-01).** In-process participants MAY be called over the local lane of
|
||||
[session RPC](ipc-v1.md) section 1 (amendment of the same date) instead of through the router:
|
||||
the arrows below are then direct calls into the same worker shell, carrying the same requests and
|
||||
replies. No ordering rule changes. Measured on the release container's CPU and cpuset, work that
|
||||
overlaps the brain's ticks slows them (the sweep owns every core of the cpuset), so the
|
||||
coordinator overlaps nothing with Prepare: a boundary's publication copies are made while the
|
||||
world, the task and the commits run, and the snapshot is published before the next Prepare.
|
||||
|
||||
## 1. Committed boundary
|
||||
|
||||
At `Ready(epoch, k)`:
|
||||
|
|
@ -65,6 +73,19 @@ amendment). The boundary number does not change; the epoch does. A pause request
|
|||
lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is
|
||||
not allowed in `RollingBack`.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01).** Two edges are implemented as written above (`fly-session`
|
||||
`phase.rs`): `Ready(k) -> RollingBack(k) -> Ready(k)`, where the epoch is the coordinator's and
|
||||
the boundary stays the same. One edge is added for a checkpoint of another format installed as a
|
||||
session's start (the legacy composition's FLYSIM01 import):
|
||||
|
||||
```text
|
||||
Ready(0), no transition taken -> Restoring(k) -> Paused(k)
|
||||
```
|
||||
|
||||
The install is the group restore of [state-media-v1](state-media-v1.md) section 6, unchanged. Only
|
||||
a session that has not advanced may take the edge; the coordinator enforces this, because the phase
|
||||
alone cannot tell a fresh `Ready(0)` from a reset one.
|
||||
|
||||
## 3. Transaction sequence
|
||||
|
||||
### Phase A: prepare all agents concurrently
|
||||
|
|
@ -111,6 +132,12 @@ and returns StepResult for `k+1`. It MUST NOT advance another interval while wai
|
|||
the next request. Transport/control scaffolding may have a measured fixed latency; it must
|
||||
be declared in its descriptor and conformance tests.
|
||||
|
||||
*Amendment, 2026-09-29 (TASK-01):* as built, the clock the executor is handed is
|
||||
`brainTicks x tickDuration` from the agent's `PreparedDecision`, exact in `RationalNs`. For the
|
||||
legacy profile this is the legacy `network.ms` in nanoseconds. An artifact-backed inspection reaches
|
||||
the executor and the task as bytes: the coordinator holds each attachment the task declares
|
||||
(`inspection.memory`) from the world's reply until the transition that reads it has been evaluated.
|
||||
|
||||
### Phase C: observe and evaluate the task
|
||||
|
||||
The coordinator receives the environment result and verifies batch identity, boundary,
|
||||
|
|
|
|||
|
|
@ -426,6 +426,22 @@ composition that declares no rollback policy treats the request as a task failur
|
|||
"cannot reset the environment directly": the coordinator applies the policy through the
|
||||
section 7 methods.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01).** The Rust interfaces, as built in `fly-session::task`:
|
||||
|
||||
- The inspection argument is an `Inspection`: the observation's typed `inspection` value, plus the
|
||||
bytes of every attachment the task declares (`Task::inspection_attachments`, for example
|
||||
`inspection.memory`). A synthetic task declares none, and its inspection reads as the typed value
|
||||
it always was.
|
||||
- `Evaluation.slot_saves` names the `Environment.SaveSlot`s the transition asks for at the boundary
|
||||
it reached. They are applied after every Commit, saves first.
|
||||
- `Task::rollback(scope', restored)` is step 3 of a declared rollback policy. It returns the next
|
||||
contexts.
|
||||
- `Task::restored(scope', restored, clock)` runs after a group restore installed the ledger. A task
|
||||
whose executor state is transient re-observes the restored world here, and returns the contexts
|
||||
the coordinator holds against the checkpoint's.
|
||||
- A task and an executor that are one object (`pokered-macros-v1`) are two handles on one shared
|
||||
state.
|
||||
|
||||
## 5. Admission and audience boundary
|
||||
|
||||
The first synthetic implementation has no audience input. Later integration maps permitted
|
||||
|
|
@ -453,6 +469,13 @@ first and refunds the second, and the slice wiring the bridge tests both. This i
|
|||
accepted/applied/aborted distinction the paragraph above asks for, for this one interaction
|
||||
kind; paid interactions in general still need the public v2 contract.
|
||||
|
||||
**Amendment, 2026-09-29 (TASK-01).** As built, the coordinator's `AdmissionQueue` is the
|
||||
admission record: an admitted stimulus carries its interaction id into `preStepStimulations`, and it
|
||||
ends `applied` (with its boundary) or `aborted` (the epoch failed before its Prepare committed). The
|
||||
legacy composition's rules run on the edge side of the queue. No other interaction kind is admitted.
|
||||
The legacy operator reward pulse is refused (legacy-gameboy-v1 section 15, amendment of
|
||||
2026-09-29).
|
||||
|
||||
## 6. Health, shutdown and extensions
|
||||
|
||||
All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore
|
||||
|
|
|
|||
|
|
@ -178,8 +178,9 @@ achievements.
|
|||
| Badge | +3 | each newly set badge bit |
|
||||
|
||||
That is the prototype's catalog as it shipped, kept here as history. The live one is
|
||||
`docs/rewards-learning.md`: `pokered-unique8-v7` adds `boundary` (v5), `catch` (v6), and `talk` and
|
||||
`item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23).
|
||||
`docs/rewards-learning.md`: `pokered-unique8-v8` adds `boundary` (v5), `catch` (v6), `talk` and
|
||||
`item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23), and `damage`
|
||||
(v8, the operator's decision of 2026-09-29).
|
||||
|
||||
Every value is positive; there were no loss or blackout penalties. Values in a frame summed into
|
||||
`R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Rewards and learning
|
||||
|
||||
The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v7`. The code of record is
|
||||
The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v8`. The code of record is
|
||||
`services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the
|
||||
gates and the rules); this page says what each rule pays for and why it is allowed to. The
|
||||
prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules
|
||||
|
|
@ -27,6 +27,7 @@ change what the fly can do.
|
|||
| `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger |
|
||||
| `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger |
|
||||
| `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger |
|
||||
| `damage` | -- | +0.20 per whole Pokémon, in proportion; +0.05 knockout | 80 ms | HP the fly's own attack removed from the enemy (since v8): its share of the target's max HP, below the lowest HP that target has shown this battle; +0.05 when the hit knocks out a trainer's Pokémon; at most 0.50 a battle; a wild battle at 1, 1/2, 1/3 for its first three per `(map, species, level)`, then nothing |
|
||||
|
||||
Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")`
|
||||
is `None` by test. The values in one frame sum into `R`, and the network reinforces once with
|
||||
|
|
@ -34,7 +35,8 @@ is `None` by test. The values in one frame sum into `R`, and the network reinfor
|
|||
|
||||
The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`:
|
||||
`docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its
|
||||
own shares the nearest one. It still reaches the page as an event with its own label.
|
||||
own shares the nearest one. It still reaches the page as an event with its own label. `damage` is
|
||||
the one Pokémon kind with no counter at all ("Damage rewards" below says why).
|
||||
|
||||
Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on
|
||||
`wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on
|
||||
|
|
@ -177,6 +179,87 @@ half, 0.10, once, keyed under the building's id as it always was; walking out pa
|
|||
person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no
|
||||
building can be farmed.
|
||||
|
||||
## Damage rewards
|
||||
|
||||
The operator's decision of 2026-09-29, chosen over a pad rule that would have withheld a stat move
|
||||
once it had been used: pay the fly for the HP its own attack removes from the Pokémon it is
|
||||
fighting. It is a catalog change, an operator decision like the catch and engagement rewards, not a
|
||||
loop-review fix. It answers row 67 (`infra/docs/macros-traps.md`): the live fly lost the Pewter
|
||||
Gym's Jr. Trainer 29 times running, choosing TAIL WHIP 155 times, BUBBLE 23 and TACKLE 0, and
|
||||
nothing in the catalog paid for anything that happened inside a battle it did not win. The pad
|
||||
offered every move; the readout's favourite was the one move that cannot win. The code is
|
||||
`pokemon_red/damage.rs`.
|
||||
|
||||
**What counts as the fly's attack.** A drop in `wEnemyMonHP` on a sample where `hWhoseTurn`
|
||||
(`$FFF3`) reads 0 and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit
|
||||
(`engine/battle/core.asm`), `ApplyDamageToEnemyPokemon` subtracts the damage inside
|
||||
`ExecutePlayerMove`, with `hWhoseTurn` 0, once per hit of a multi-hit move. Everything else that
|
||||
lowers the enemy's HP lands with it 1: the enemy's poison and burn ticks and a Leech Seed on the
|
||||
enemy (`HandlePoisonBurnLeechSeed` picks whose HP to cut *by* `hWhoseTurn`), its recoil, its
|
||||
confusion self-hit, its own Explosion or Self-Destruct, and the HP it pays for a Substitute. A
|
||||
Leech Seed on the fly heals the enemy, and HP going up never pays. Damage into an enemy Substitute
|
||||
never touches `wEnemyMonHP`. `STRUGGLE` is the move the cartridge executes for a Pokémon with no
|
||||
PP; the fly chose FIGHT, not the move, so it pays nothing (winning still pays what winning pays).
|
||||
`tests/rom_damage.rs` pins the address on the cartridge from the live row 67 state: every drop of
|
||||
the enemy's HP lands with `hWhoseTurn` 0 and every drop of the fly's own with 1.
|
||||
|
||||
**How much.** 0.20 per whole enemy Pokémon's max HP, paid in proportion on the sample the HP
|
||||
drops -- BUBBLE for 10 of Diglett's 24 is 0.083, TACKLE for 4 of Sandshrew's 33 is 0.024. The hit
|
||||
that knocks out a trainer's Pokémon adds 0.05 on the same event. At most **0.50 a battle**, which is
|
||||
the `trainer` rule's own value: a battle's worth of damage is worth what winning it is, and the
|
||||
Jr. Trainer's two Pokémon reach it exactly (2 x (0.20 + 0.05)). A wild knockout adds nothing here
|
||||
because the `battle` rule already pays it, on the way out of the battle. Next to the rest of the
|
||||
catalog: a wild battle's damage (0.20) is twice its knockout (0.10) and equal to a new area (0.20);
|
||||
a trainer battle's (0.50) is the trainer's flag; a gym's is a sixth of the badge (3.0).
|
||||
|
||||
**What cannot be farmed.**
|
||||
|
||||
- *Heal.* Each target keeps the lowest HP it has shown this battle, and only HP below that pays. A
|
||||
Potion, Recover, Rest or a drain lifts the HP; the same HP is not paid twice.
|
||||
- *Switch.* A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that goes out
|
||||
and comes back keeps its mark, and two Weedles of one level are two targets.
|
||||
- *A stale enemy.* `InitBattleVariables` does not clear `wEnemyMon`, and a trainer battle sets
|
||||
`wIsInBattle` a whole transition before `LoadEnemyMonData` runs, so the first samples of a
|
||||
battle can hold the last battle's Pokémon at the HP it finished on -- in the row 67 ring, the
|
||||
same trainer's Diglett in the same slot. A target is marked the first time it reads full HP,
|
||||
which is how every enemy Pokémon enters a battle in this game, so the stale one neither pays nor
|
||||
hides the real one's first hit.
|
||||
- *The battle.* 0.50 at most, whatever the party size.
|
||||
- *Wild Pokémon.* A wild battle pays at the wild-KO rule's scale, 1, 1/2, 1/3, for its first three
|
||||
battles per `(map, species, level)` that paid any damage (`damageCounts`), then nothing; attacking
|
||||
a wild Pokémon and running from it counts. A rollback blocks every key that has paid, the way it
|
||||
blocks a paid wild KO or catch.
|
||||
- *Trainers* keep no lifetime ledger. A trainer is fought again only after the fly has lost to it
|
||||
(or after a rollback), and each of those battles is bounded by the cap. In the row 67 ring that
|
||||
is the point: every lost battle pays for the hits that landed, and the hits that land are the
|
||||
moves that win.
|
||||
|
||||
**Feed.** `damage` publishes on no counter (`RewardKind::from_adapter` is `None`). Every other
|
||||
Pokémon kind shares the nearest counter, and the nearest here is `wildwin`, but the stage folds
|
||||
that row into "N wild wins": false of a trainer battle, and false of a battle the fly goes on to
|
||||
lose. A hit reaches the page as a reward event with its own label, `HIT #<species> FOR <n> HP`
|
||||
(`... KO` for a knockout; the species is the cartridge's internal index, as `CAUGHT #<species>` is),
|
||||
and the event log, `/status` and the checkpoint carry it; it is only left out of
|
||||
`game.rewardCounts` and the ticker's per-kind copy, the way the platformer's `started` and `clear`
|
||||
are. No feed kind was added. The stage rolls the hits up itself (`apps/stage/src/lib/ticker.ts`,
|
||||
`hitCopy` in the game config): a reward with no `rewardKind` and that label folds into one
|
||||
"damage dealt x<n>" row with the summed value, ` KO` once a hit in it felled a Pokémon, joined by
|
||||
each hit within 45 s of the last; a later battle starts a new row (`apps/stage/mockups/row68-ticker-*.png`).
|
||||
|
||||
**Learning.** A payout reinforces the recent spike history with `m = tanh(R)` over a 5 s
|
||||
eligibility trace ([plasticity](plasticity.md)). Measured on the cartridge from the row 67 state
|
||||
(`tests/rom_damage.rs`), the HP drops 176 frames (2.9 s) after the `MOVE n` press when the fly
|
||||
moves first and about 420 frames (7 s) when the Jr. Trainer's Pokémon does -- its attack and text
|
||||
come first. So the choice's trace is at a half to a quarter when its hit is paid, and the previous
|
||||
turn's choice, one turn (about 7.5 s) earlier still, at a tenth to a twentieth. That ratio is the
|
||||
whole mechanism: nothing tells the readout which move to press. A hit is small (0.02 to 0.10), so what it can move per battle is small too; whether
|
||||
the brain learns the attacking move inside a few brain hours is a measurement, not a promise, and
|
||||
the first one is `infra/docs/macros-traps.md`, row 68.
|
||||
|
||||
**Migration.** `v7` -> `v8` adds `damageCounts` and, inside a battle in flight, `battle.damage`;
|
||||
both are optional and a `v7` state restores with no wild key paid and its battle's Pokémon marked
|
||||
where they stand. See `docs/design/flysim.md`, "Restoring across an adapter version".
|
||||
|
||||
## Gates
|
||||
|
||||
Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other
|
||||
|
|
@ -276,6 +359,15 @@ body picks the macro; the descending neurons press the buttons.**
|
|||
|
||||
## Honesty
|
||||
|
||||
The catalog now includes damage (v8). It is the first rule that pays for something inside a battle
|
||||
the fly may still lose, and the closest the catalog has come to grading a *choice*: the moves are
|
||||
all on the pad, and the one that lands pays. It is still a reward read out of WRAM after the frame,
|
||||
not a press: nothing in the adapter picks a move, removes one from the pad or tells the readout
|
||||
which is good, and a move pays only if the cartridge says it took HP off the enemy. The pad rule
|
||||
the operator declined (withholding a stat move once used) would have been the doctrine change; this
|
||||
one leaves the pad exactly as the scene deals it. It is also bounded on purpose: at most what winning
|
||||
pays, per battle, and a wild Pokémon only three times.
|
||||
|
||||
The catalog now includes conversations and items (v7). Paying for a conversation is the closest
|
||||
the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a
|
||||
press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is
|
||||
|
|
|
|||
176
docs/scorecard.md
Normal file
176
docs/scorecard.md
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
# The behavioural scorecard
|
||||
|
||||
A repeatable, multi-seed "good play" regression harness. The unit tests say the macros do what
|
||||
they were written to; the trap hunt says a fly stuck in one place got out. Neither says whether a
|
||||
release plays *better or worse* than the one before it across the places the fly actually is. The
|
||||
scorecard does: a fixed set of checkpoints, K seeds each, T brain minutes each, on the real
|
||||
connectome with the macro layer, reduced to one JSON per release and compared release against
|
||||
release by a test over the paired runs, never by a single run.
|
||||
|
||||
It measures and presses nothing. It restores a checkpoint, lets the brain play, and counts. The
|
||||
ethos check (`docs/loop-review.md`) is untouched: the harness is outside the fly.
|
||||
|
||||
```sh
|
||||
export FLY_ROM=/path/to/the-cartridge # read, never copied
|
||||
cargo build --release -p fly-scorecard # from services/flysim
|
||||
|
||||
fly-scorecard list # the set, resolved, each checkpoint's rung
|
||||
fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 10 brain minutes
|
||||
fly-scorecard summary card.json # one screen of markdown
|
||||
fly-scorecard compare old.json new.json # exit 1 when a metric regressed
|
||||
fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE)
|
||||
```
|
||||
|
||||
`--runtime session` (the default) runs the session composition the release cut over to
|
||||
(`fly-legacy-session`, in-process, unpaced); `--runtime legacy` runs the stream's own frame
|
||||
(`flysim::frame::LegacyFrame`). Both hand the same per-frame observation to the same tally, so a
|
||||
card from one runtime is comparable with a card from the other. From the same checkpoint and seed
|
||||
the two give identical reports apart from wall time (`tests/rom_scorecard.rs` holds it), which makes a scorecard
|
||||
run on both a second piece of shadow evidence. `--mode raw` runs without the macro layer.
|
||||
|
||||
## The set
|
||||
|
||||
`tools/scorecard/checkpoints.json` names each checkpoint by the environment variable that holds
|
||||
its path (the ROM tests' own, `rom-env.sh`), never by a path; `--extra id=path` adds more (the
|
||||
newest live checkpoint, a trap's). The checkpoints are not committed (`.local/` is untracked).
|
||||
`list` prints the rung each one stands on, from its reward ledger. The set has two or three
|
||||
states at each of rungs 8, 9, 10, 11, 12 and 15; rungs 13 and 14 have no checkpoint yet and join
|
||||
the set when the scout makes them (a new entry is a line in the JSON). A checkpoint missing from
|
||||
the environment is named on stderr and, with `--strict`, an error.
|
||||
|
||||
## Seeds
|
||||
|
||||
A checkpoint restores a deterministic brain, so two runs from it would be the same run. A seed
|
||||
therefore chooses how many frames the brain's readout is ignored before the measurement starts
|
||||
(60 to 1,800 frames, a splitmix of the seed; seed 0 is none). The brain still ticks and its noise
|
||||
generator still advances, the game sees no button, and from the first measured frame the readout
|
||||
is the brain's own: the run sits on a different point of its own trajectory. The idle frames are
|
||||
not measured. The same seed twice is the same run.
|
||||
|
||||
## What a run reports
|
||||
|
||||
One `RunReport` per (checkpoint, seed). Every number is computed from per-frame observations by
|
||||
`tally.rs`, which has no emulator in it and is unit-tested on synthetic frames.
|
||||
|
||||
| group | what |
|
||||
| --- | --- |
|
||||
| rungs | start, end, gained, the brain minute of each climb; reported per brain hour |
|
||||
| places | the adapter's exploration count, start and end |
|
||||
| empty pad | frames with the macro layer on, nothing running and no button dealt; seconds, share, longest stretch |
|
||||
| watchdog | `fly-watchdog` check 10, rule for rule (`watchdog.rs`): probes, suspected, reasons, **confirmed** (two suspected probes in a row) and **ladder events** (one per run of two or more: a trap the recovery ladder would act on) |
|
||||
| hunt | the trap hunt's windows (two brain minutes, fewer than four tiles or a sequence repeated more than ten times) |
|
||||
| ratchet | rollbacks, split by game over and stall |
|
||||
| macros | starts, done, blocked, timeout, refused, by macro |
|
||||
| funnel | GO SHOP, BUY BALL, THROW BALL, catch: counts at each stage, balls gained and spent, species gained, and how far down the funnel the run got |
|
||||
| heals | GO HEAL and the nurse's HEAL |
|
||||
| whiteouts | the whole party fainted (a rising edge) |
|
||||
| battles | started, ended, wild and trainer, won (a battle or trainer payout), lost (the party fainted in it), caught, other |
|
||||
| rewards, scenes | counts and totals by adapter kind; frames by scene |
|
||||
|
||||
The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe
|
||||
memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about
|
||||
time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds,
|
||||
first at 240; the stream's is five wall minutes) and the window is the last ten brain minutes or
|
||||
the whole run when it is shorter; and the first probe compares the exploration count with the
|
||||
run's starting count, which the live check lacks after a boot.
|
||||
|
||||
## Compare
|
||||
|
||||
`compare A.json B.json` pairs runs by (checkpoint, seed). Each metric (`compare.rs`, `METRICS`)
|
||||
has a direction (more is better, less is better, or info), an absolute tolerance and a relative
|
||||
one. For each metric the pairs give one difference, signed so that positive means B is worse. B
|
||||
**fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip
|
||||
permutation test over the pairs gives a **Holm-adjusted** p below alpha (default 0.05; Holm over
|
||||
the judged metrics, so the whole compare, not each metric, has a false-fail rate of at most
|
||||
alpha when nothing changed; unadjusted, 13 metrics at 0.05 each false-failed about 15% of
|
||||
releases in a bootstrap of the baseline, with Holm 0 of 200). It reports **better** by the
|
||||
same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent,
|
||||
and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a
|
||||
fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The
|
||||
comparison also names its caveats (different lengths, different runtimes, fewer than eight
|
||||
pairs, unpaired runs). Exit status 1 is a failed metric or a failed checkpoint.
|
||||
|
||||
**The trap rule.** The pooled test cannot see a fault confined to one place: three seeds of one
|
||||
checkpoint give a sign-flip p of at least 1/8, and the shift is diluted over thirty-six pairs
|
||||
(the row-71 bag bug, 131 blocked THROW BALLs in every seed of one checkpoint, passed the pooled
|
||||
compare even spliced into an otherwise identical suite). So each checkpoint is also judged on its
|
||||
own, without statistics: it **fails**, named as `trap@<checkpoint>`, when B is trapped on at least
|
||||
two of its runs and on at least two more than A, or when any run of B has a blocked-macro storm
|
||||
(50 or more blocked finishes of one macro) and no run of A on that checkpoint does. A run is
|
||||
trapped on a recovery-ladder event (two suspected watchdog probes in a row, any rule: stalled,
|
||||
zero-progress, sequence, ...), on at least half its probes suspected, or on a storm. Costs: with
|
||||
three seeds a checkpoint whose trap is a coin flip in A already (r09-forest-catch, r10-pewter-center
|
||||
on the baseline) can fail by chance when B traps all three seeds (about 1 in 27 each by bootstrap,
|
||||
so roughly 7% of releases that changed nothing but the trajectory); five seeds make it 1 in 243.
|
||||
Identical suites never fail.
|
||||
|
||||
The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per
|
||||
hour, rollbacks per hour, blocked macro %, buy ball, throws (THROW BALL that finished, not blocked starts) and catches per hour, battles won and
|
||||
lost per hour, whiteouts per hour. Blocked throws per hour, heals per hour, macro starts per minute and the trap hunt's
|
||||
flagged windows are reported, never judged: healing more can follow losing more, and a fly that
|
||||
fights for most of a run presses NEXT through battle text more than ten times in two minutes,
|
||||
which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so
|
||||
the number has no room to move).
|
||||
|
||||
## Cost and size
|
||||
|
||||
A run's brain minute costs about 75 CPU seconds however it is split, and the result does not
|
||||
depend on the thread count (the same seed gives an identical report at one thread and at four).
|
||||
The split matters for wall time, because a run's sweep pool spins at its barriers: on a quiet
|
||||
ten-core box two jobs of four threads are fine, but on a box shared with compiles and tests one
|
||||
job of four threads ran five times slower per brain minute than one-thread jobs did. So the
|
||||
default is one thread per run and eight runs at a time. The default suite, twelve checkpoints by
|
||||
three seeds by ten brain minutes, is 360 brain minutes: about three quarters of an hour of ten
|
||||
quiet cores, about twice that when the box is busy. More seeds tighten the test; longer runs let
|
||||
rungs climb. Three seeds is the smallest suite whose pair count (36) can reach p < 0.001.
|
||||
`--resume` keeps the runs an interrupted suite had finished (`<out>.runs.jsonl`).
|
||||
|
||||
## What it does not do
|
||||
|
||||
- It does not rebuild session ledgers a restore starts empty (the trap hunt's
|
||||
`FLY_TRAP_SEED_*`); a trap that needs them is that tool's.
|
||||
- Ten brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a
|
||||
per-run prediction; a release that is faster by a rung every few hours shows only across the
|
||||
suite.
|
||||
- It judges play against the previous release, not against a notion of good. A regression is
|
||||
"worse than last time"; the absolute numbers say how good last time was.
|
||||
|
||||
## Releases and nightly
|
||||
|
||||
`tools/scorecard/overlay.sh <ref> <tree>` puts the tool on the tree of an older release (the crate,
|
||||
the set, the docs, and the one read-only accessor `PokeredTask::with_reader`), so a release that
|
||||
predates it can be scored and its numbers are its own. The operator's nightly runner builds the
|
||||
latest release tag on a build box, runs the suite, writes the card and a one-screen summary and
|
||||
compares with the previous release's card.
|
||||
|
||||
## The v0.7.5 baseline
|
||||
|
||||
`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8,
|
||||
compatibility `ff09d7dd5483`): the default set, 12 checkpoints by 3 seeds by 10 brain minutes on
|
||||
the session runtime, 6.0 brain hours, 6,130 s wall on a shared build box.
|
||||
|
||||
| headline | v0.7.5 |
|
||||
| --- | ---: |
|
||||
| rungs per brain hour | 1.50 (9 of 36 runs climbed) |
|
||||
| empty-pad time | 6.96% of frames |
|
||||
| watchdog probes suspected | 2.8% |
|
||||
| ladder-worthy traps | 1 (one run, `r09-forest-catch`) |
|
||||
| blocked macro finishes | 0.5% |
|
||||
| buy ball / throw / catch | 10 / 10 / 8 |
|
||||
| heals / whiteouts | 9 / 46 |
|
||||
| battles won / lost | 33 / 45 |
|
||||
| ratchet rollbacks | 1 |
|
||||
|
||||
What the card shows about v0.7.5, worth reading before the next release is compared with it:
|
||||
|
||||
- **The fly fights for most of the frames it is given.** On nine of the twelve checkpoints a
|
||||
battle is half to nine tenths of the frames, and it loses more than it wins (45 lost, 33 won;
|
||||
46 whiteouts). The longest single battle is 18,354 frames (five brain minutes, a trainer, on
|
||||
`r11-mart`); `r09-forest-catch` has one of 26,245 frames in a wild battle.
|
||||
- **`r15-nugget-bridge` keeps walking and finds nothing.** After the Oddish is caught (all three
|
||||
seeds), the fly spends the rest of the run in the overworld, GO OBJECTIVE and GO OUT
|
||||
alternating 13 times each in ten minutes, with the exploration count unmoved (2,527). The
|
||||
watchdog does not flag it (a ring this slow stays under its twenty repeats), so no recovery
|
||||
step would act on it.
|
||||
- The shop-to-catch funnel closes: buy ball, throw and catch all occur, across rungs 9 to 15.
|
||||
|
||||
|
|
@ -931,3 +931,122 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
|
|||
store is now the shared `flysim-store` crate; FLYSIM01 gains an optional `reinforcements`
|
||||
field, downgrade-safe both ways). A PII guard scans lint, tag-release and pushes. Reviews: all
|
||||
APPROVE-WITH-NOTES.
|
||||
|
||||
- 2026-09-29 (unreleased, the operator's decision, row 68): the fly is paid for the HP its own
|
||||
attack removes in battle, the catalog's answer to row 67 (the Pewter Gym's Jr. Trainer lost on
|
||||
repeat with TAIL WHIP six turns in seven). New kind `damage`: 0.20 per whole enemy Pokémon, in
|
||||
proportion, +0.05 when it knocks out a trainer's Pokémon, at most 0.50 a battle; a wild battle at
|
||||
1, 1/2, 1/3 per map/species/level. Only a drop on the fly's own turn (`hWhoseTurn` 0) by a move it
|
||||
chose (not Struggle); a heal is never paid twice; no feed counter (a hit is not a "wild win").
|
||||
Adapter `pokered-unique8-v8`; a deploy with FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 migrates the
|
||||
run (v6 still migrates when named). Survey, 3 starts x 120 brain minutes from the row 67
|
||||
checkpoint: v8 beat the trainer in 2 of 3 (one run also won the Boulder Badge), v7 in 0 of 3, but
|
||||
the move choice did not shift more under v8 than v7 (BUBBLE ~15% -> ~20% in both): no learned
|
||||
preference is shown inside two hours (`infra/docs/macros-traps.md` row 68).
|
||||
- 2026-09-30 (v0.6.7, the operator's call, reward catalog): the fly is paid for damage its own
|
||||
attacks deal. Row 67 found the live fly losing the Pewter Gym's Jr. Trainer on repeat with TAIL
|
||||
WHIP while BUBBLE was on the pad; the operator chose a reward over a pad rule. HP removed on the
|
||||
fly's own turn (hWhoseTurn 0, not Struggle; poison/burn/Leech Seed/recoil/enemy moves never pay;
|
||||
healed HP not re-paid) pays 0.20 per whole enemy mon, +0.05 for knocking out a trainer's mon,
|
||||
capped at 0.50 per battle (a trainer beaten); wild battles diminish 1, 1/2, 1/3 per
|
||||
map/species/level. Adapter pokered-unique8-v8, migrating v7 (compat differs in the adapter
|
||||
segment only). The stage folds a battle's hits into one ticker row ("damage dealt x3 KO").
|
||||
Survey: v8 beat the trainer from 2 of 3 starts (v7 0 of 3); move choice did not measurably shift
|
||||
within two hours. Review: APPROVE-WITH-NOTES.
|
||||
- 2026-09-30 (v0.7.0, the port): the flybus session runtime ships beside the legacy loop, installed
|
||||
and not selected. AGENT-01 (the brain as a worker), MEM-01 (the macros read a 64 KiB memory image
|
||||
with the same engine), ENV-01 (the Game Boy as a worker), STATE-02 (one checkpoint store for
|
||||
both runtimes, FLYSIM01 of record), TASK-01 (the macros in the coordinator), PERF-01 (an
|
||||
in-process local lane: the session costs ~1.3x legacy per frame, down from 2.45x), SERVE-01
|
||||
(`flysim-session` serves the same feed/control/metrics contracts; `fly-runtime session|legacy`
|
||||
swaps the binary behind flysim.service; a crash loop falls back to legacy by itself), SHADOW-01
|
||||
(`fly-shadow` replays the live fly's trace through the session runtime and compares every
|
||||
transition, ledger and save byte; a baseline-relative guard stops it if the live fly suffers),
|
||||
CUT-01 (the switch is a 30-minute speed probation: a median realtime factor under 0.97 falls back
|
||||
with reason "speed"). Deploying changes nothing live: legacy's output is byte-identical to
|
||||
v0.6.7. Cutover is `fly-shadow-run check && fly-runtime session` after three hours of zero
|
||||
divergence; rollback is `fly-runtime legacy`. Every slice and the release candidate were
|
||||
independently reviewed (APPROVE-WITH-NOTES).
|
||||
- 2026-09-30 (v0.7.1, loop review hotfix): row 70. The fly's first live catch (a Zubat, Mt. Moon)
|
||||
gave it a second party member, and in the next trainer battle the cartridge's SHIFT-style offer
|
||||
"Will ZUBAT change POKéMON?" opened the battle party list with the same menu id as a forced
|
||||
switch after a faint. Read as forced, the pad was SWITCH (no healthy target) and NEXT ("ZUBAT is
|
||||
already out!", the list again) for 58 brain minutes; the recovery ladder's rung-11 reset erased
|
||||
the catch and, restores being deterministic, replayed the path back into the trap. A forced
|
||||
switch now also requires the active battler at 0 HP; the offer is the fly's own turn with SWITCH
|
||||
and BACK. ROM test from the live checkpoint: NEXT on all 6,000 frames before, BACK and the battle
|
||||
continues after; a real post-faint switch unchanged. The ladder change (protect recent catches
|
||||
from resets) is held back for a review finding. Review: APPROVE.
|
||||
- 2026-10-01 (v0.7.2, loop review): row 70's recovery ladder. A milestone reset within 2 hours of a
|
||||
new species becomes a restart (operator decision: a catch is worth up to 2 h of a trap, not more);
|
||||
a reset's deterministic replay re-earns rewards the restored archive already had, so progress and
|
||||
catch protection now count only reward names the ladder has not seen; a held reset does not climb;
|
||||
the last-archive marker expires. Escape from a trap only the lower rung clears: 2.08 h (as v0.7.0),
|
||||
3.33 h with a catch just before it; 200-seed mean 4.80 h vs 4.44 h, worst unchanged at 25.4 h; at
|
||||
most 2 resets per 24 h, restarts at least 3 h apart. Watchdog flags unchanged. Reviews: r1 BLOCK,
|
||||
r2 BLOCK, r3 APPROVE, independent read APPROVE-WITH-NOTES.
|
||||
- 2026-10-01 (v0.7.3, port slice SHADOW-02): the shadow moves off the release container. On the
|
||||
container a light relay forwards the live trace, new saves and the sugar journal over one outbound
|
||||
ssh link whose key can only run the receiver; a build box mirrors them and runs the unchanged
|
||||
shadow on its own cores; the verdict comes back. Release binding by binary hashes; the relay's
|
||||
heartbeat is fresh only while the link, the box's shadow and the sync are; any trace stop (no
|
||||
consumer, byte cap, outage) ends the verdict window, so a pass needs 3 h of compared brain time
|
||||
after the last loss. The guard and `check` stay on the container. The on-box shadow (v0.7.0)
|
||||
slowed the live fly; the relay costs about 0.5% of a core. Reviews: BLOCK, BLOCK,
|
||||
APPROVE-WITH-NOTES, APPROVE.
|
||||
- 2026-10-01 (v0.7.4, loop review hotfix): row 71. On Route 24 (rung 15) the fly met a wild
|
||||
Oddish at low HP with two Poké Balls in a bag that had grown to five items (TMs, HELIX FOSSIL,
|
||||
NUGGET), so the ball was the fifth entry and the list scrolled. The macro state read the bag
|
||||
cursor as the window row only, so THROW BALL could never reach the ball and was blocked every
|
||||
time; row 69's low-HP rule left it the only card. A restart restores the open bag, so the ladder
|
||||
could not clear it. The cursor is now the row plus the list's scroll offset, as the cartridge
|
||||
computes it; the mart's lists the same. ROM test from the live checkpoint: 10 blocked before,
|
||||
Oddish caught after. Review: APPROVE.
|
||||
- 2026-10-01 (v0.7.5, port slice PERF-02): the first cutover (v0.7.3, after a 3 h shadow with zero
|
||||
divergence) failed its speed probation at a median 0.959x real time and fell back to legacy on
|
||||
its own. Cause: with exactly as many CPUs as sweep threads, the session's other threads woke each
|
||||
frame and the scheduler often stacked two sweep threads on one CPU. flysim-session now pins each
|
||||
sweep worker to its own CPU and its other threads to the remaining one (16.2 to 13.0 ms a frame on
|
||||
a build box of the release CPU; legacy 10.5), and the sim gets its own slice: every other unit,
|
||||
user session and `pct exec` shell is confined off its CPUs (a hog there collapsed a pinned
|
||||
session). Results, traces and the compatibility string are unchanged. Reviews: two rounds,
|
||||
APPROVE-WITH-NOTES; notes addressed.
|
||||
- 2026-10-01 20:07Z (CUT-01, milestone M4): the stream runs on the session runtime. v0.7.5's remote
|
||||
shadow compared 3 h of live brain time (645,560 transitions, 2,161 identical checkpoints) with
|
||||
zero divergence; `check` allowed the switch; the 30-minute speed probation passed at a median
|
||||
1.000x real time with no lag growth. Legacy stays one command away (`fly-runtime legacy`);
|
||||
RETIRE-01 after a clean week.
|
||||
- 2026-10-02 (v0.7.6, flybus groundwork, nothing switched): the control API as flybus RPC with
|
||||
per-agent grants (CTRL-01, `FLY_CONTROL_VIA`), the video feed over the bus in production form
|
||||
(EDGE-02, `fly-feed bus|direct`), the session's agent and world as processes on the router's
|
||||
Unix sockets (BUS-01, `fly-runtime session --bus`), an optional aux cpu for bus threads off the
|
||||
sim's cores, and a per-frame work metric for both runtimes. All default off; the live stream
|
||||
is unchanged until each is switched on with its rollback. Also: the multi-seed behavioural
|
||||
scorecard (nightly), two stale ROM tests fixed and every ROM suite mapped (row 72), and the
|
||||
parity test's idle-header race.
|
||||
- 2026-10-02 07:13Z: the stream's video feed runs over flybus (`fly-feed bus`, one aux cpu for the
|
||||
bus threads). Over the first 20 minutes the sim's mean work per frame fell from 15.2 to about
|
||||
14.5 ms and its p99 from 46 to about 21 ms (the publisher left the sim's shared cpu); realtime
|
||||
factor unchanged at about 1.0. Rollback: `fly-feed direct`.
|
||||
- 2026-10-02 07:41Z: the control API runs over flybus too (`FLY_CONTROL_VIA=bus`): `:7401` is
|
||||
served by the control edge calling flysim's RPC services under per-client grants. First 15
|
||||
minutes: bus connected, calls flowing, no failures, no restarts, realtime factor about 1.0.
|
||||
Both switches are in the host env, so a deploy keeps them. The session's agent and world stay
|
||||
on the in-process lane: over the router they cost 2.5 to 3.5 ms a frame, more than the
|
||||
release box's headroom (live work about 14.5 of 16.74 ms); the GPU brain is the way there.
|
||||
- 2026-10-02 (v0.7.7, loop review): row 73. The scout found rung 16 unreachable: its place was
|
||||
"on Route 25", so inside Bill's house the walks just left again, and Bill's PC is a hidden
|
||||
object no macro could press. Rung 16 is now Bill's errand inside the house (people first, then
|
||||
things; exits off the pad while the errand waits), and hidden objects are read from the
|
||||
cartridge's own table and become a target only as that errand's next step. Cerulean's north half
|
||||
joins the map graph through the trashed house. Trap hunts: rung 16 in 0 of 6 seeds before, 6 of 6
|
||||
after; Route 5 from the ticket 0 of 6 before, 5 of 6 after. Review: APPROVE-WITH-NOTES; notes
|
||||
fixed. Also: bus worker children die with their parent; the feed test asserts structure, not a
|
||||
wall-clock rate.
|
||||
- 2026-10-02 (v0.7.8, groundwork for the GPU and the bus): the GPU brain steps a whole frame per
|
||||
call with its state resident on the card (about 230 KB a frame crosses PCIe instead of 24 MB),
|
||||
bit-exact against the CPU through rollback, restore and checkpoints; a dead GPU makes the process
|
||||
CPU-only and the replacement restores the last checkpoint on the CPU (cuda feature, off; operator
|
||||
decision: the live brain moves to the release host's Quadro after a 3 h shadow). Cheaper flybus
|
||||
round trips (seal on reply, recycled zero-filled staging writers, frames encoded once); the
|
||||
session's own transport stays on the in-process lane. No behaviour change on the live stream.
|
||||
|
|
|
|||
|
|
@ -18,7 +18,10 @@ need pct
|
|||
|
||||
PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \
|
||||
ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \
|
||||
fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo"
|
||||
fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo \
|
||||
openssh-client"
|
||||
# openssh-client (SHADOW-02): the remote shadow's relay dials OUT to a build box. The client only;
|
||||
# the container still runs no sshd (below).
|
||||
# Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage
|
||||
# needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl`
|
||||
# (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three
|
||||
|
|
|
|||
|
|
@ -123,6 +123,22 @@ need pct
|
|||
# /opt/fly/current, rather than half way through the deploy or at flysim's boot.
|
||||
FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \
|
||||
|| die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'"
|
||||
# Who serves the control API (docs/design/flybus.md, "Control over the bus"): the same.
|
||||
FLY_CONTROL_VIA_EFFECTIVE="$(control_via_normalize "${FLY_CONTROL_VIA:-}")" \
|
||||
|| die "05-deploy: FLY_CONTROL_VIA must be 'direct' or 'bus', got '${FLY_CONTROL_VIA}'"
|
||||
|
||||
# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the
|
||||
# container is not in the env file unless the operator put it there, and this deploy writes the env
|
||||
# file's value into fly.env. Nothing breaks (flysim and flyedge.service both follow fly.env at
|
||||
# their next start, so the feed stays served either way) but the mode would change at the next
|
||||
# restart of flysim, which is not what anyone meant. Said once, loudly, here.
|
||||
FLY_FEED_VIA_LIVE="$(ct_exec "$CTID" -- awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' /etc/fly/fly.env 2>/dev/null \
|
||||
| tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
if [ -n "$FLY_FEED_VIA_LIVE" ] && [ "$FLY_FEED_VIA_LIVE" != "$FLY_FEED_VIA_EFFECTIVE" ]; then
|
||||
log "05-deploy: WARNING: the container's fly.env says FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} and $1 says ${FLY_FEED_VIA_EFFECTIVE};" \
|
||||
"this deploy writes ${FLY_FEED_VIA_EFFECTIVE}, which flysim applies at its next restart (no restart is done here)." \
|
||||
"If ${FLY_FEED_VIA_LIVE} is what you want, set FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} in $1 and deploy again; \`fly-feed status\` shows both."
|
||||
fi
|
||||
|
||||
# CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a
|
||||
# `vgl` on a container that never had VirtualGL installed would only show up as
|
||||
|
|
@ -181,13 +197,26 @@ NEED_RELOAD=0
|
|||
# ---------------------------------------------------------------------------
|
||||
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
|
||||
ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}"
|
||||
# Page cpus given to flysim's bus threads (EDGE-02 review N1): added to flysim.slice, taken from the
|
||||
# page group, named to the session as FLY_SESSION_AUX_CPUS. 0 (the default) changes nothing.
|
||||
SESSION_AUX_EFFECTIVE="${SESSION_AUX_CPUS:-0}"
|
||||
case "$SESSION_AUX_EFFECTIVE" in ''|*[!0-9]*) die "SESSION_AUX_CPUS ('${SESSION_AUX_EFFECTIVE}') must be a number of cpus (0 = none)" ;; esac
|
||||
SESSION_AUX_LIST=""
|
||||
DEPLOY_CPUS=""
|
||||
# 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to
|
||||
# flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone.
|
||||
PARTITION_ACTIVE=0
|
||||
if [ -n "${CPUSET:-}" ]; then
|
||||
deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \
|
||||
"/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)"
|
||||
if [ "$deploy_conf_cpus" = "$CPUSET" ]; then
|
||||
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
|
||||
<<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
|
||||
PARTITION_ACTIVE=1
|
||||
if [ "$SESSION_AUX_EFFECTIVE" -gt 0 ]; then
|
||||
_aux_split="$(cpuset_aux_split "$DEPLOY_CPUS" "$SESSION_AUX_EFFECTIVE")" || exit 1
|
||||
read -r DEPLOY_CPUS SESSION_AUX_LIST <<< "$_aux_split"
|
||||
fi
|
||||
log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim"
|
||||
else
|
||||
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
|
||||
|
|
@ -322,8 +351,9 @@ if [ -n "$RELEASE_TARBALL" ]; then
|
|||
#
|
||||
# FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps
|
||||
# the run. It names adapter version strings whose checkpoints the new build
|
||||
# may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 for the deploy
|
||||
# that adds the engagement rewards (v7; v5 -> v6 was the catch reward's).
|
||||
# may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 for the deploy
|
||||
# that adds the damage reward (v8; v6 -> v7 was the engagement rewards', v5 -> v6
|
||||
# the catch reward's).
|
||||
# It only applies when the adapter segment is the
|
||||
# ONLY difference between the two strings and the new build's adapter says it
|
||||
# can read that one; a dataset, kernel, emulator or state-format change is
|
||||
|
|
@ -377,7 +407,7 @@ The difference is usually an adapter/ladder or dataset version bump. Three ways
|
|||
* deploy a build whose string matches (check out the commit the running release was built from), or
|
||||
* if the ADAPTER VERSION is the only segment that differs and the new build documents a
|
||||
migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live
|
||||
string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6). The run is kept; flysim applies the same
|
||||
string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7). The run is kept; flysim applies the same
|
||||
rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or
|
||||
* accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which
|
||||
archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and
|
||||
|
|
@ -386,6 +416,53 @@ The 'current' symlink has NOT been moved; the running release is untouched."
|
|||
fi
|
||||
fi
|
||||
|
||||
# The session runtime (SERVE-01). While `fly-runtime session` has pointed flysim.service at
|
||||
# flysim-session (the drop-in below), a release without that binary would leave the fly
|
||||
# unable to start at all, and one whose session string differs from flysim's would write
|
||||
# checkpoints the other runtime refuses. Refused here, before the symlink moves; to deploy
|
||||
# such a release anyway, `fly-runtime legacy` first.
|
||||
#
|
||||
# Policy (C2 of the SERVE-01 review), operator decision 2026-09-29: "Session stays, trust gates".
|
||||
# A deploy KEEPS the chosen runtime. It does not drop to legacy and does not re-run
|
||||
# the shadow for the new flysim-session binary; the trust gates before the release (the
|
||||
# parity and service tests, the compat check just below) are what vouch for it. A bad
|
||||
# release is caught afterwards by the persistent fallback: while the drop-in exists,
|
||||
# flysim.service carries OnFailure=fly-runtime-fallback.service and RestartMode=direct with a 3-starts-in-10-minutes
|
||||
# limit, so a session binary that will not stay up puts the fly back on legacy by itself
|
||||
# (`fly-runtime fallback`, /run/fly/runtime-fellback.json), whoever restarted it.
|
||||
if ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
|
||||
ct_exec "$CTID" -- test -x "${release_path}/flysim-session" \
|
||||
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime (fly-runtime session) and this release has no flysim-session. Run \`fly-runtime legacy\` in the container first, or deploy a release that ships it. The 'current' symlink has NOT been moved."
|
||||
# BUS-01: on the bus transport flysim-session starts its participants from fly-session.
|
||||
if ct_exec "$CTID" -- grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' /etc/systemd/system/flysim.service.d/10-runtime.conf; then
|
||||
ct_exec "$CTID" -- test -x "${release_path}/fly-session" \
|
||||
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime on the bus (fly-runtime session --bus) and this release has no fly-session worker. Run \`fly-runtime session --local\` in the container first. The 'current' symlink has NOT been moved."
|
||||
fi
|
||||
session_compat="$(ct_exec "$CTID" -- env \
|
||||
"FLY_GAME=${GAME}" \
|
||||
"FLY_DATASET=${release_path}/data/fafb-v783" \
|
||||
"FLY_ROM=/srv/fly/rom/${ROM_SHA256:-none}.gb" \
|
||||
"${release_path}/flysim-session" --print-compatibility 2>/dev/null | tr -d '\r' || true)"
|
||||
if [ -n "${new_compat:-}" ] && [ "$session_compat" != "$new_compat" ]; then
|
||||
die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime and its compatibility string differs from flysim's.
|
||||
flysim: ${new_compat}
|
||||
flysim-session: ${session_compat}
|
||||
The 'current' symlink has NOT been moved."
|
||||
fi
|
||||
log "05-deploy: flysim.service runs the session runtime; this release ships flysim-session with flysim's compatibility string"
|
||||
fi
|
||||
|
||||
# The feed bus (EDGE-02). Bus mode needs the release's fly-edge: without it flyedge.service's
|
||||
# ConditionPathExists= skips the unit, flysim has left :7400 to it, and the stage has no feed.
|
||||
# Refused when the env file asks for bus, and when the container is in bus mode now (an edge
|
||||
# that is running keeps running, but the first time it restarts there is nothing to start; and
|
||||
# the way back is `fly-feed direct`, which needs no binary of this release).
|
||||
if [ "$FLY_FEED_VIA_EFFECTIVE" = bus ] || [ "$FLY_FEED_VIA_LIVE" = bus ]; then
|
||||
ct_exec "$CTID" -- test -x "${release_path}/fly-edge" \
|
||||
|| die "05-deploy: REFUSING to deploy release ${version}: the feed is on the bus (FLY_FEED_VIA=bus: $([ "$FLY_FEED_VIA_EFFECTIVE" = bus ] && echo "in $1" || echo "on the container")) and this release has no fly-edge. Run \`fly-feed direct\` in the container and set FLY_FEED_VIA=direct in $1 first, or deploy a release that ships fly-edge. The 'current' symlink has NOT been moved."
|
||||
log "05-deploy: the feed is on the bus; this release ships fly-edge"
|
||||
fi
|
||||
|
||||
log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically"
|
||||
ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current"
|
||||
else
|
||||
|
|
@ -396,7 +473,7 @@ fi
|
|||
# 2. systemd units
|
||||
# ---------------------------------------------------------------------------
|
||||
log "05-deploy: converging systemd units"
|
||||
for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do
|
||||
for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.slice "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do
|
||||
[ -f "$f" ] || continue
|
||||
name="$(basename "$f")"
|
||||
changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)"
|
||||
|
|
@ -512,6 +589,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
|
|||
# so FLY_ENCODER-style flipping between backends across restarts keeps the
|
||||
# checkpoint: the compatibility string this script gates on does not move.
|
||||
echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}"
|
||||
# Where the session worker writes fly_brain_backend (which hardware runs the
|
||||
# LIF tick, and the GPU fallback count): the same textfile directory as
|
||||
# fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA").
|
||||
echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom"
|
||||
# On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the
|
||||
# kill switch: POST /chat answers 403 and the feed header omits `chat`, so
|
||||
# the CHAT panel blanks without touching flybridge or the page. flysim reads
|
||||
|
|
@ -527,6 +608,21 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
|
|||
# refuses anything but "raw" for a game with no macros, reads the retired
|
||||
# "palette"/"plan" as "macros" with a warning, and refuses an unrecognised
|
||||
# value outright.
|
||||
# PERF-02: flysim-session pins its sweep workers one per cpu of the cpuset it finds. That is only
|
||||
# safe when the cpuset is the sim's alone: with the partition in force (section 3b) it is, and
|
||||
# bin/fly-cpu-confine keeps every other process off it. Without it (no CPUSET, or a conf that does
|
||||
# not match) the unit sees the container's whole cpuset, where a pinned worker would sit on a cpu
|
||||
# anything can hog (measured 0.14x real time), so pinning is turned off: the threads float. The
|
||||
# runtime reads the exact value 0 as off.
|
||||
if [ "$PARTITION_ACTIVE" -eq 1 ]; then
|
||||
echo "FLY_SESSION_PIN=1"
|
||||
else
|
||||
echo "FLY_SESSION_PIN=0"
|
||||
fi
|
||||
# EDGE-02 review N1: the bus threads' own cpu, in flysim.slice and in nobody else's set.
|
||||
if [ "$PARTITION_ACTIVE" -eq 1 ] && [ -n "$SESSION_AUX_LIST" ]; then
|
||||
echo "FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}"
|
||||
fi
|
||||
echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}"
|
||||
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
|
||||
# bus"). "direct" is the default and is flysim binding :7400 itself, as
|
||||
|
|
@ -535,9 +631,17 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
|
|||
# never enables: see that unit's header for the switch. Written
|
||||
# unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs.
|
||||
# Watchdog check 2 reads this line to know whose /metrics carries the
|
||||
# feed counters (flysim's :9101, or flyedge's loopback :9102).
|
||||
# feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)).
|
||||
# Validated and lowercased above (feed_via_normalize).
|
||||
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
|
||||
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over
|
||||
# the bus"). "direct" is the default: flysim binds it. "bus" makes flysim
|
||||
# register the control services on its embedded router and leave :7401 to
|
||||
# flycontrol-edge.service, which this script never enables (runbook,
|
||||
# "Control over the bus"). Written unconditionally; the watchdog reads it
|
||||
# to know whose /healthz is flysim's own (check 1) and whether to watch
|
||||
# the edge (check 1b). Validated and lowercased above.
|
||||
echo "FLY_CONTROL_VIA=${FLY_CONTROL_VIA_EFFECTIVE}"
|
||||
# How long a macro leaves a target alone after a walk to it aborted
|
||||
# (macros.md section 12.1, the Viridian stall). Only written when it is set,
|
||||
# because the default lives in the crate and a box that has not tuned it
|
||||
|
|
@ -671,35 +775,52 @@ if [ -n "${CPUSET:-}" ]; then
|
|||
"Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \
|
||||
"leaves cpuset.cpus.effective empty and the unit unstartable."
|
||||
else
|
||||
read -r sim_cpus page_cpus encoder_cpus <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
|
||||
log "05-deploy: cpuset partition — flysim=$sim_cpus, xvfb/flystage/flystage-web/pulse/mediamtx/flyedge=$page_cpus, flycast=$encoder_cpus"
|
||||
plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")"
|
||||
log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
|
||||
tmp_dropin="$(mktemp)"
|
||||
# flyedge is off by default, but its drop-in is written with the rest so that the day
|
||||
# it is enabled it serves the page from the page's CPUs, never from flysim's.
|
||||
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge; do
|
||||
case "$u" in
|
||||
flysim) cpus="$sim_cpus" ;;
|
||||
flycast) cpus="$encoder_cpus" ;;
|
||||
*) cpus="$page_cpus" ;;
|
||||
esac
|
||||
{
|
||||
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
|
||||
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
|
||||
echo "[Service]"
|
||||
echo "AllowedCPUs=${cpus}"
|
||||
} > "$tmp_dropin"
|
||||
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.service.d"
|
||||
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.service.d/cpuset.conf" 0644 root:root)"
|
||||
# it is enabled it serves the page from the page's CPUs, never from flysim's; likewise
|
||||
# flycontrol-edge (CTRL-01).
|
||||
# flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
|
||||
# (`fly-runtime session` runs it AS flysim.service, which already has them.)
|
||||
# flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
|
||||
# flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder
|
||||
# leave idle and never a cycle of the live fly's.
|
||||
# flysim.slice (PERF-02 review N1) is where flysim.service and flysim-session.service run;
|
||||
# its CPUs are the sim's alone, and bin/fly-cpu-confine (run by those units' ExecStartPre,
|
||||
# using /etc/fly/cpuset.env below) confines system.slice, user.slice and init.scope to
|
||||
# everything else. See that script's header for the cgroup semantics and the ordering rule.
|
||||
# A for loop over an array, not `while read` fed from the plan: `pct exec` reads stdin.
|
||||
mapfile -t plan_lines <<< "$plan"
|
||||
for plan_line in "${plan_lines[@]}"; do
|
||||
read -r u cpus <<< "$plan_line"
|
||||
case "$u" in *=) continue ;; esac
|
||||
cpuset_dropin_text "$u" "$cpus" "$ENV_LABEL" > "$tmp_dropin"
|
||||
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.d"
|
||||
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.d/cpuset.conf" 0644 root:root)"
|
||||
if [ "$changed" = changed ]; then
|
||||
NEED_RELOAD=1
|
||||
log "05-deploy: ${u}.service.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
|
||||
log "05-deploy: ${u}.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
|
||||
fi
|
||||
done
|
||||
{
|
||||
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
|
||||
echo "$plan" | awk '$1 ~ /=$/ {print $1 $2}'
|
||||
} > "$tmp_dropin"
|
||||
changed="$(converge_file "$CTID" "$tmp_dropin" /etc/fly/cpuset.env 0644 root:root)"
|
||||
[ "$changed" = changed ] && log "05-deploy: /etc/fly/cpuset.env changed — fly-cpu-confine applies it when flysim next (re)starts, by which time it runs in flysim.slice"
|
||||
rm -f "$tmp_dropin"
|
||||
fi
|
||||
else
|
||||
log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)"
|
||||
fi
|
||||
# No partition in force: nothing may stay confined by an earlier one, and the session runtime must
|
||||
# not pin (fly.env above says FLY_SESSION_PIN=0). A confinement already applied lasts until the next
|
||||
# boot or `fly-cpu-confine release`.
|
||||
if [ "$PARTITION_ACTIVE" -ne 1 ]; then
|
||||
ct_exec "$CTID" -- rm -f /etc/fly/cpuset.env
|
||||
log "05-deploy: no cpuset partition: /etc/fly/cpuset.env removed, FLY_SESSION_PIN=0 in fly.env (sweep workers float); run \`fly-cpu-confine release\` if an earlier partition is still applied"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not
|
||||
|
|
@ -707,10 +828,18 @@ fi
|
|||
# ---------------------------------------------------------------------------
|
||||
log "05-deploy: converging bin/ helpers to /opt/fly/bin"
|
||||
ct_exec "$CTID" -- mkdir -p /opt/fly/bin
|
||||
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
|
||||
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-feed fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
|
||||
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
|
||||
done
|
||||
|
||||
# A container already on the session runtime keeps it (see the policy note at the compat check
|
||||
# above), and its drop-in is rewritten in place from the current template (no restart) so that
|
||||
# the OnFailure= fallback and MALLOC_ARENA_MAX reach containers switched before they existed.
|
||||
if [ -n "${RELEASE_TARBALL:-}" ] && ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
|
||||
ct_exec "$CTID" -- /opt/fly/bin/fly-runtime session --no-restart \
|
||||
|| log "05-deploy: WARNING: could not refresh the session drop-in; it keeps its old content (no OnFailure= fallback until \`fly-runtime session\` is re-run)"
|
||||
fi
|
||||
|
||||
# The NOPASSWD surface those helpers use (config/fly-sudoers). 02-base installs it at
|
||||
# provision time; converging it here too means a release that adds a helper's line
|
||||
# (fly-loop-reset, v0.6.4) does not need a re-provision. Validated before install.
|
||||
|
|
|
|||
|
|
@ -267,6 +267,12 @@ refuses to write the drop-ins until the conf actually carries
|
|||
`CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves
|
||||
`cpuset.cpus.effective` empty and the unit unstartable.
|
||||
|
||||
The sim's CPUs are also kept exclusive to it (PERF-02 review N1, `infra/docs/runbook.md` "The sim's
|
||||
CPUs are exclusive to the sim"): the sim units run in `flysim.slice`, and `bin/fly-cpu-confine`
|
||||
confines `system.slice`, `user.slice`, `init.scope` and `/.lxc` (`pct exec`) to the other CPUs when the sim starts.
|
||||
Without a partition (`CPUSET` unset) none of this applies and the deploy turns the session
|
||||
runtime's worker pinning off (`FLY_SESSION_PIN=0`).
|
||||
|
||||
`CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local
|
||||
socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md`
|
||||
section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three
|
||||
|
|
|
|||
188
infra/bin/fly-cpu-confine
Executable file
188
infra/bin/fly-cpu-confine
Executable file
|
|
@ -0,0 +1,188 @@
|
|||
#!/usr/bin/env bash
|
||||
# infra/bin/fly-cpu-confine — keep every process that is not the sim off the sim's CPUs.
|
||||
#
|
||||
# Usage (INSIDE the container, as root):
|
||||
# fly-cpu-confine apply confine system.slice, user.slice, init.scope and /.lxc (where `pct exec`
|
||||
# lands) to the non-sim CPUs
|
||||
# fly-cpu-confine release undo `apply` (all of them go back to the container's whole cpuset)
|
||||
# fly-cpu-confine status what each of them is confined to, and where the sim runs
|
||||
# fly-cpu-confine check list every process that is not in flysim.slice but may run on a
|
||||
# sim CPU (exit 1 if there is one); this command's own process and its
|
||||
# parents (the shell it was started from) are noted, not failed
|
||||
#
|
||||
# Why. The session runtime pins its sweep workers one per CPU (PERF-02). A pinned worker cannot
|
||||
# leave its CPU, so any sustained CPU-bound process that may run there stalls every barrier:
|
||||
# measured 0.14x real time with a plain busy loop (0.68x at nice 19; SCHED_IDLE is harmless).
|
||||
# Priorities do not fix that; keeping the sim's CPUs to the sim does.
|
||||
#
|
||||
# How (cgroup v2). flysim.service and flysim-session.service run in flysim.slice, which has
|
||||
# AllowedCPUs= the sim's CPUs (a drop-in written by 05-deploy.sh). Its siblings under the root
|
||||
# cgroup are system.slice (every other service, cron, apt, sshd), user.slice (every login
|
||||
# session) and init.scope (PID 1 and what it forks). `apply` sets AllowedCPUs= the NON-sim CPUs
|
||||
# on those three, so nothing that systemd places anywhere else can reach a sim CPU. A child's
|
||||
# cpuset is bounded by its parent's, so the sim must never sit under a slice that excludes its
|
||||
# CPUs: that is why it has a slice of its own and is not left in system.slice.
|
||||
#
|
||||
# The CPU lists come from ${CPUSET_ENV} (written by 05-deploy.sh, from the same cpuset_partition
|
||||
# call as the AllowedCPUs= drop-ins). No file means no partition: nothing is confined.
|
||||
#
|
||||
# `apply` is runtime-only (systemctl set-property --runtime) and is run by flysim.service and
|
||||
# flysim-session.service's ExecStartPre, so it is re-applied after every boot and every restart
|
||||
# and can never run while the sim still sits in system.slice: shrinking system.slice under a
|
||||
# sim that has not been restarted into flysim.slice would silently make it float over the page
|
||||
# CPUs. `apply` refuses (exit 3, nothing changed) if a sim unit is outside flysim.slice.
|
||||
#
|
||||
# `pct exec` / `pct enter` (lxc-attach) put their processes in the cgroup `/.lxc` (or `/.lxc-N`),
|
||||
# a sibling of system.slice that systemd does not manage. It is written directly
|
||||
# (cpuset.cpus), only if it already exists (a cgroup lxc owns is never created here), and a
|
||||
# failure is a warning, never an error: it must not stop the sim from starting. If it cannot be
|
||||
# written, `check` lists what is running there; run long operator jobs with
|
||||
# `systemd-run --scope --slice=system.slice -- <cmd>` (or `... -- bash`).
|
||||
set -euo pipefail
|
||||
|
||||
: "${CPUSET_ENV:=/etc/fly/cpuset.env}"
|
||||
: "${SYSTEMCTL:=systemctl}"
|
||||
: "${PROC_ROOT:=/proc}"
|
||||
: "${CGROUP_ROOT:=/sys/fs/cgroup}"
|
||||
: "${SIM_SLICE:=flysim.slice}"
|
||||
: "${SIM_UNITS:=flysim.service flysim-session.service}"
|
||||
CONFINED_UNITS="system.slice user.slice init.scope"
|
||||
|
||||
# existing lxc attach cgroups (/.lxc, /.lxc-N) that have a cpuset
|
||||
lxc_cgroups() {
|
||||
local d
|
||||
for d in "$CGROUP_ROOT"/.lxc "$CGROUP_ROOT"/.lxc-*; do
|
||||
[ -d "$d" ] && [ -e "$d/cpuset.cpus" ] && echo "$d"
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
# set_lxc CPUS — write CPUS into every lxc attach cgroup; warn, never fail.
|
||||
set_lxc() {
|
||||
local d
|
||||
for d in $(lxc_cgroups); do
|
||||
if ! echo "$1" > "$d/cpuset.cpus" 2>/dev/null; then
|
||||
log "WARNING: cannot write ${d}/cpuset.cpus; processes started with pct exec stay unconfined (run long jobs with systemd-run --scope --slice=system.slice)"
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
log() { echo "fly-cpu-confine: $*" >&2; }
|
||||
|
||||
# read_env — set SIM_CPUS and OTHER_CPUS from ${CPUSET_ENV}, or return 1 when there is no partition.
|
||||
# Parsed as KEY=VALUE lines, never sourced.
|
||||
read_env() {
|
||||
SIM_CPUS="" OTHER_CPUS=""
|
||||
[ -r "$CPUSET_ENV" ] || return 1
|
||||
local k v
|
||||
while IFS='=' read -r k v; do
|
||||
case "$k" in
|
||||
FLY_SIM_CPUS) SIM_CPUS="$v" ;;
|
||||
FLY_OTHER_CPUS) OTHER_CPUS="$v" ;;
|
||||
esac
|
||||
done < "$CPUSET_ENV"
|
||||
[ -n "$SIM_CPUS" ] && [ -n "$OTHER_CPUS" ]
|
||||
}
|
||||
|
||||
# expand LIST — one cpu number per line for a list such as 1,3,5-7.
|
||||
expand() {
|
||||
echo "$1" | tr ',' '\n' | awk -F- 'NF==1 && $1 != "" {print $1} NF==2 {for (i=$1;i<=$2;i++) print i}'
|
||||
}
|
||||
|
||||
sim_outside_slice() {
|
||||
local u cg
|
||||
for u in $SIM_UNITS; do
|
||||
cg="$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
|
||||
[ -n "$cg" ] || continue
|
||||
case "$cg" in
|
||||
"/${SIM_SLICE}/"*) ;;
|
||||
*) echo "$u ($cg)"; return 0 ;;
|
||||
esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
cmd="${1:-}"
|
||||
case "$cmd" in
|
||||
apply)
|
||||
if ! read_env; then
|
||||
log "no partition configured (${CPUSET_ENV} missing or empty): nothing confined"
|
||||
exit 0
|
||||
fi
|
||||
if out="$(sim_outside_slice)"; then
|
||||
log "REFUSING to confine: $out runs outside ${SIM_SLICE}; restart it first (it would float over the page cpus otherwise)"
|
||||
exit 3
|
||||
fi
|
||||
for u in $CONFINED_UNITS; do
|
||||
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${OTHER_CPUS}"
|
||||
done
|
||||
set_lxc "$OTHER_CPUS"
|
||||
log "system.slice, user.slice, init.scope and /.lxc confined to ${OTHER_CPUS}; ${SIM_SLICE} keeps ${SIM_CPUS}"
|
||||
;;
|
||||
release)
|
||||
# Not `AllowedCPUs=` (empty): systemd leaves the cgroup's cpuset.cpus at its last value while
|
||||
# the cpuset controller stays enabled for some other unit (here flysim.slice), so the slices
|
||||
# would stay confined. Set the container's whole cpuset explicitly.
|
||||
all_cpus="$(cat "${CGROUP_ROOT}/cpuset.cpus.effective" 2>/dev/null || true)"
|
||||
for u in $CONFINED_UNITS; do
|
||||
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${all_cpus}"
|
||||
done
|
||||
set_lxc "$all_cpus"
|
||||
log "system.slice, user.slice, init.scope and /.lxc released to the container's whole cpuset (${all_cpus:-unknown})"
|
||||
;;
|
||||
status)
|
||||
for u in $CONFINED_UNITS $SIM_SLICE; do
|
||||
echo "$u AllowedCPUs=$("$SYSTEMCTL" show -p AllowedCPUs --value "$u" 2>/dev/null || true)"
|
||||
done
|
||||
for d in $(lxc_cgroups); do
|
||||
echo "${d#"$CGROUP_ROOT"} cpuset.cpus=$(cat "$d/cpuset.cpus" 2>/dev/null || true)"
|
||||
done
|
||||
for u in $SIM_UNITS; do
|
||||
echo "$u ControlGroup=$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
|
||||
done
|
||||
;;
|
||||
check)
|
||||
if ! read_env; then
|
||||
log "no partition configured: nothing to check"
|
||||
exit 0
|
||||
fi
|
||||
sim="$(expand "$SIM_CPUS" | sort -n | tr '\n' ' ')"
|
||||
bad=0
|
||||
# this process and its parents (the pct exec shell chain) are not a CPU hog
|
||||
self=" "
|
||||
p="${SELF_PID:-$$}"
|
||||
while [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && [ "${#self}" -lt 400 ]; do
|
||||
self="$self$p "
|
||||
p="$(sed -n 's/^PPid:[[:space:]]*//p' "$PROC_ROOT/$p/status" 2>/dev/null || true)"
|
||||
done
|
||||
for d in "$PROC_ROOT"/[0-9]*; do
|
||||
pid="${d##*/}"
|
||||
[ -r "$d/status" ] || continue
|
||||
cg="$(sed -n 's/^0:://p' "$d/cgroup" 2>/dev/null || true)"
|
||||
case "$cg" in "/${SIM_SLICE}/"* | "/${SIM_SLICE}") continue ;; esac
|
||||
# kernel threads have no cgroup of their own in this sense and are not a CPU hog
|
||||
if [ -z "$(readlink "$d/exe" 2>/dev/null || true)" ]; then continue; fi
|
||||
allowed="$(sed -n 's/^Cpus_allowed_list:[[:space:]]*//p' "$d/status")"
|
||||
[ -n "$allowed" ] || continue
|
||||
hit=""
|
||||
for c in $(expand "$allowed"); do
|
||||
for s in $sim; do [ "$c" = "$s" ] && hit="$hit$c,"; done
|
||||
done
|
||||
if [ -n "$hit" ]; then
|
||||
case "$self" in *" $pid "*)
|
||||
log "note: ${pid} ($(cat "$d/comm" 2>/dev/null)) is this check's own process chain in ${cg:-?} and may run on sim cpu ${hit%,}; not counted"
|
||||
continue ;;
|
||||
esac
|
||||
echo "process $pid ($(cat "$d/comm" 2>/dev/null)) in ${cg:-?} may run on sim cpu ${hit%,}"
|
||||
bad=1
|
||||
fi
|
||||
done
|
||||
[ "$bad" -eq 0 ] && log "ok: only ${SIM_SLICE} can run on ${SIM_CPUS}"
|
||||
exit "$bad"
|
||||
;;
|
||||
*)
|
||||
sed -n '2,11p' "$0" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
332
infra/bin/fly-feed
Executable file
332
infra/bin/fly-feed
Executable file
|
|
@ -0,0 +1,332 @@
|
|||
#!/usr/bin/env bash
|
||||
# infra/bin/fly-feed — who serves the feed WebSocket (ws://127.0.0.1:7400/feed): flysim itself
|
||||
# (`direct`) or fly-edge over flysim's feed bus (`bus`). EDGE-02; docs/design/flybus.md, "Feed over
|
||||
# the bus"; the runbook's "Feed over the bus".
|
||||
#
|
||||
# Usage (INSIDE the container, as root):
|
||||
# fly-feed status configured, running, the edge and its counters (any user)
|
||||
# fly-feed bus [--no-restart] [--no-rollback]
|
||||
# fly-feed direct [--no-restart] [--no-wait]
|
||||
#
|
||||
# One line decides: FLY_FEED_VIA in /etc/fly/fly.env. flysim reads it, flyedge.service's
|
||||
# ExecCondition= reads it, flysim.service has Wants=flyedge.service, so every start of flysim brings
|
||||
# up the edge in bus mode and skips it in direct mode, whoever started flysim and on whichever
|
||||
# runtime (flysim or flysim-session, `fly-runtime`): nothing else has to be enabled, started or
|
||||
# remembered. `fly-feed bus|direct` rewrites that line, restarts flysim.service (the feed changes
|
||||
# hands at the start, so the stream is down for the length of a flysim restart, exactly like the
|
||||
# unstick rule's) and waits until the page is on the feed again.
|
||||
#
|
||||
# What "healthy" means after a switch, in this order, within FLY_FEED_HEALTH_TIMEOUT (300 s):
|
||||
# 1. flysim's /healthz answers (a NEW invocation: the old process is not mistaken for it);
|
||||
# 2. bus: the edge's /healthz answers 200 (subscribed, snapshots arriving);
|
||||
# 3. if flystage.service is active: its page is on the feed (`fly_feed_clients` >= 1 on the
|
||||
# counters of whoever serves it) and `fly_frames_sent_total` advances. Without a page unit
|
||||
# (a box that only serves the feed) the wait ends at 2.
|
||||
# If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks
|
||||
# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it
|
||||
# only reports. `direct` is the safe terminal state: once the line says direct nothing, an
|
||||
# interrupted switch included (ssh drops, INT/TERM/HUP), puts bus back, and an interrupted
|
||||
# `direct` restarts flysim itself so the running process matches the line. An interrupted `bus`
|
||||
# rolls back the same way as a failed one.
|
||||
# `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts
|
||||
# flysim without blocking and does not wait for health or roll anything back: it is what the
|
||||
# watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up.
|
||||
#
|
||||
# 05-deploy.sh writes FLY_FEED_VIA into fly.env from the operator's env file on every deploy and
|
||||
# does not restart flysim. After a `fly-feed bus`, put FLY_FEED_VIA=bus in the env file too, or the
|
||||
# next deploy writes `direct` back (the next flysim start would then follow it) and says so.
|
||||
#
|
||||
# Restarts count against flysim.service's start limit (3 in 10 minutes while the session runtime is
|
||||
# selected, `fly-runtime`): a switch and its rollback are two.
|
||||
#
|
||||
# Every switch is logged to the journal (tag fly-feed) and ${FEED_LOG}.
|
||||
set -euo pipefail
|
||||
|
||||
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
|
||||
: "${FLY_SERVICE:=flysim.service}"
|
||||
: "${FLY_EDGE_SERVICE:=flyedge.service}"
|
||||
: "${FLY_PAGE_SERVICE:=flystage.service}"
|
||||
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
|
||||
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
|
||||
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
|
||||
: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}"
|
||||
: "${FLY_PROC_DIR:=/proc}"
|
||||
: "${FLY_FEED_HEALTH_TIMEOUT:=300}"
|
||||
: "${FLY_FEED_LOG:=/var/lib/fly/feed.log}"
|
||||
: "${FLY_FEED_LOCK:=/run/fly/feed.lock}"
|
||||
: "${FLY_FEED_SAMPLE_SECONDS:=3}"
|
||||
FEED_LOG="$FLY_FEED_LOG"
|
||||
|
||||
log() { echo "fly-feed: $*" >&2; }
|
||||
die() { log "$*"; exit 1; }
|
||||
|
||||
record() {
|
||||
if command -v logger >/dev/null 2>&1; then
|
||||
logger -t fly-feed -- "$*" || true
|
||||
fi
|
||||
mkdir -p "$(dirname "$FEED_LOG")" 2>/dev/null || true
|
||||
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >>"$FEED_LOG" 2>/dev/null || log "could not append to $FEED_LOG"
|
||||
}
|
||||
|
||||
usage() {
|
||||
echo "usage: fly-feed status | bus [--no-restart] [--no-rollback] [--no-wait] | direct [--no-restart] [--no-wait]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
# direct | bus | invalid:<value>. flysim reads the value case-insensitively; a missing line is direct.
|
||||
configured() {
|
||||
local value=""
|
||||
if [ -f "$FLY_ENV_FILE" ]; then
|
||||
value="$(awk -F= '/^FLY_FEED_VIA=/ { v=$0; sub(/^FLY_FEED_VIA=/, "", v); last=v } END { print last }' "$FLY_ENV_FILE" 2>/dev/null || true)"
|
||||
fi
|
||||
value="$(printf '%s' "$value" | tr -d ' \r"' | tr '[:upper:]' '[:lower:]')"
|
||||
case "$value" in
|
||||
""|direct) echo direct ;;
|
||||
bus) echo bus ;;
|
||||
*) echo "invalid:${value}" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# What the running flysim process started with (its environment, not the file): direct | bus |
|
||||
# stopped | unknown.
|
||||
running() {
|
||||
local pid value
|
||||
pid="$(systemctl show -p MainPID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
|
||||
if [ -z "$pid" ] || [ "$pid" = 0 ]; then echo stopped; return; fi
|
||||
if [ ! -r "${FLY_PROC_DIR}/${pid}/environ" ]; then echo unknown; return; fi
|
||||
value="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
case "$value" in
|
||||
bus) echo bus ;;
|
||||
*) echo direct ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# The counters of whoever serves the feed in `via` mode.
|
||||
metrics_url() {
|
||||
if [ "$1" = bus ]; then echo "$FLY_EDGE_METRICS_URL"; else echo "$FLY_METRICS_URL"; fi
|
||||
}
|
||||
|
||||
# metric URL NAME -> the value of the first sample of NAME, or empty.
|
||||
metric() {
|
||||
curl -fsS --max-time 5 "$1/metrics" 2>/dev/null | awk -v n="$2" '$1 == n { print $2; exit }' || true
|
||||
}
|
||||
|
||||
# Whole-number part of a Prometheus value ("3", "3.0", "1e+06" is not expected for these).
|
||||
whole() { printf '%.0f' "${1:-0}" 2>/dev/null || echo 0; }
|
||||
|
||||
# The page is on the feed: at least one client, and the frames counter moves over a sample.
|
||||
page_on_feed() {
|
||||
local url first second clients
|
||||
url="$(metrics_url "$1")"
|
||||
clients="$(metric "$url" fly_feed_clients)"
|
||||
[ "$(whole "$clients")" -ge 1 ] || return 1
|
||||
first="$(metric "$url" fly_frames_sent_total)"
|
||||
sleep "$FLY_FEED_SAMPLE_SECONDS"
|
||||
second="$(metric "$url" fly_frames_sent_total)"
|
||||
[ -n "$first" ] && [ -n "$second" ] && [ "$(whole "$second")" -gt "$(whole "$first")" ]
|
||||
}
|
||||
|
||||
page_unit_active() { systemctl is-active --quiet "$FLY_PAGE_SERVICE" 2>/dev/null; }
|
||||
|
||||
old_invocation=""
|
||||
# Print to stdout, exiting quietly once the reader has gone (`fly-feed status | head -1`).
|
||||
# Under `pct exec` SIGPIPE is ignored, so a write to a closed pipe fails with EPIPE and bash's
|
||||
# printf/echo print "write error: Broken pipe": silence that one write and stop printing.
|
||||
say() {
|
||||
printf '%s\n' "$*" 2>/dev/null || exit 0
|
||||
}
|
||||
# Wait for a NEW flysim invocation to be healthy and the feed to be flowing in `via` mode.
|
||||
healthy() {
|
||||
local via="$1" deadline
|
||||
deadline=$(( $(date +%s) + FLY_FEED_HEALTH_TIMEOUT ))
|
||||
while [ "$(date +%s)" -lt "$deadline" ]; do
|
||||
if [ -n "$old_invocation" ] \
|
||||
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
|
||||
sleep 1
|
||||
continue
|
||||
fi
|
||||
if curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
|
||||
if [ "$via" = bus ] && ! curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
|
||||
sleep 1
|
||||
continue
|
||||
fi
|
||||
if ! page_unit_active; then
|
||||
log "healthy (${via}): ${FLY_PAGE_SERVICE} is not active, so no page to wait for"
|
||||
return 0
|
||||
fi
|
||||
if page_on_feed "$via"; then
|
||||
log "healthy (${via}): the page is on the feed and frames are moving"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Rewrite (or add) the FLY_FEED_VIA line, keeping every other line, the mode and the owner.
|
||||
set_via() {
|
||||
local value="$1" tmp
|
||||
[ -f "$FLY_ENV_FILE" ] || die "no ${FLY_ENV_FILE}; deploy first (infra/05-deploy.sh writes it)"
|
||||
tmp="$(mktemp "${FLY_ENV_FILE}.XXXXXX")"
|
||||
awk -v v="$value" '
|
||||
/^FLY_FEED_VIA=/ { if (!done) { print "FLY_FEED_VIA=" v; done=1 } ; next }
|
||||
{ print }
|
||||
END { if (!done) print "FLY_FEED_VIA=" v }
|
||||
' "$FLY_ENV_FILE" >"$tmp"
|
||||
chmod --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || chmod 0640 "$tmp"
|
||||
chown --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || true
|
||||
mv -f "$tmp" "$FLY_ENV_FILE"
|
||||
}
|
||||
|
||||
locked=0
|
||||
take_lock() {
|
||||
[ "$locked" -eq 0 ] || return 0
|
||||
mkdir -p "$(dirname "$FLY_FEED_LOCK")" 2>/dev/null || true
|
||||
exec 8>>"$FLY_FEED_LOCK"
|
||||
flock -w 60 8 || die "another fly-feed holds ${FLY_FEED_LOCK}; not switching"
|
||||
locked=1
|
||||
}
|
||||
|
||||
restart_flysim() {
|
||||
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
|
||||
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
|
||||
log "restarting ${FLY_SERVICE}"
|
||||
# --no-block: a start that never becomes READY must not hold this process (and the lock);
|
||||
# `healthy` proves it is talking to the new invocation.
|
||||
systemctl restart --no-block "$FLY_SERVICE"
|
||||
}
|
||||
|
||||
status_report() {
|
||||
local conf run edge_state url
|
||||
conf="$(configured)"
|
||||
run="$(running)"
|
||||
say "configured: ${conf}"
|
||||
say "running: ${run}"
|
||||
if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then
|
||||
say " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
|
||||
fi
|
||||
edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)"
|
||||
say "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
|
||||
url="$(metrics_url "$run")"
|
||||
if [ "$run" = bus ]; then
|
||||
if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
|
||||
say "edge healthz: ok"
|
||||
else
|
||||
say "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
|
||||
fi
|
||||
say "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)"
|
||||
fi
|
||||
say "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)"
|
||||
if [ -f "$FEED_LOG" ]; then say "last switch: $(tail -n1 "$FEED_LOG")"; fi
|
||||
}
|
||||
|
||||
[ $# -ge 1 ] || usage
|
||||
command="$1"; shift
|
||||
restart=1
|
||||
rollback=1
|
||||
wait_for_health=1
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-restart) restart=0 ;;
|
||||
--no-rollback) rollback=0 ;;
|
||||
--no-wait) wait_for_health=0 ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
case "$command" in
|
||||
status) status_report; exit 0 ;;
|
||||
bus|direct) ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
|
||||
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${FLY_ENV_FILE} and restarts ${FLY_SERVICE})"
|
||||
before="$(configured)"
|
||||
[[ "$before" != invalid:* ]] || die "FLY_FEED_VIA in ${FLY_ENV_FILE} is '${before#invalid:}', not direct or bus; fix it (a deploy rewrites it) before switching"
|
||||
|
||||
if [ "$command" = bus ]; then
|
||||
[ -x "${FLY_RELEASE_DIR}/fly-edge" ] || die "this release has no ${FLY_RELEASE_DIR}/fly-edge; bus mode needs one (deploy a release that ships it)"
|
||||
fi
|
||||
|
||||
take_lock
|
||||
running_before="$(running)"
|
||||
if [ "$before" = "$command" ] && [ "$running_before" = "$command" ] && [ "$restart" -eq 1 ]; then
|
||||
log "already ${command}: fly.env says it and the running flysim started that way; nothing to do"
|
||||
status_report
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# An interrupted or failed `bus` puts the previous value back and restarts flysim on it. When
|
||||
# the line already said bus (a deploy wrote it, the running flysim never started that way), the
|
||||
# way back is direct: the state that worked.
|
||||
back="$before"
|
||||
if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi
|
||||
# Direct is where a failed bus ends up, so a switch TO direct has nowhere safer to go: it is never
|
||||
# undone (it used to roll back to `before`, which sent an operator escaping a bad bus back onto it).
|
||||
if [ "$command" = direct ]; then back=direct; fi
|
||||
switching=0
|
||||
restarted=0
|
||||
# shellcheck disable=SC2317 # runs from the EXIT trap
|
||||
on_exit() {
|
||||
local rc=$?
|
||||
trap - EXIT INT TERM HUP
|
||||
if [ "$switching" -eq 1 ]; then
|
||||
switching=0
|
||||
set_via "$back" || true
|
||||
if [ "$command" = direct ]; then
|
||||
record "direct (switch to direct interrupted (exit ${rc}); kept: direct is the safe state, flysim restarted to match)"
|
||||
else
|
||||
record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)"
|
||||
fi
|
||||
if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi
|
||||
fi
|
||||
exit "$rc"
|
||||
}
|
||||
trap on_exit EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
trap 'exit 129' HUP
|
||||
|
||||
switching=1
|
||||
set_via "$command"
|
||||
record "${command} (was ${before}; flysim was running ${running_before})"
|
||||
if [ "$restart" -ne 1 ]; then
|
||||
switching=0
|
||||
log "FLY_FEED_VIA=${command} written; the next start of ${FLY_SERVICE} applies it"
|
||||
exit 0
|
||||
fi
|
||||
restarted=1
|
||||
restart_flysim
|
||||
if [ "$wait_for_health" -ne 1 ]; then
|
||||
switching=0
|
||||
record "${command}: flysim restart queued (--no-wait); health not checked"
|
||||
log "restart queued; fly-feed status shows the result"
|
||||
exit 0
|
||||
fi
|
||||
if healthy "$command"; then
|
||||
switching=0
|
||||
if [ "$command" = direct ] && systemctl is-active --quiet "$FLY_EDGE_SERVICE" 2>/dev/null; then
|
||||
log "WARNING: ${FLY_EDGE_SERVICE} is still active in direct mode; stopping it"
|
||||
systemctl stop "$FLY_EDGE_SERVICE" || true
|
||||
fi
|
||||
record "${command}: healthy"
|
||||
log "the feed is served ${command}"
|
||||
exit 0
|
||||
fi
|
||||
log "the feed did not come up healthy (${command}) within ${FLY_FEED_HEALTH_TIMEOUT}s"
|
||||
if [ "$command" = bus ] && [ "$rollback" -eq 1 ]; then
|
||||
set_via "$back"
|
||||
switching=0
|
||||
record "${back} (automatic rollback: ${command} was not healthy within ${FLY_FEED_HEALTH_TIMEOUT}s)"
|
||||
restart_flysim
|
||||
if healthy "$back"; then
|
||||
log "rolled back to ${back}; it is healthy"
|
||||
else
|
||||
log "rolled back to ${back}, and it is NOT healthy either: journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE}"
|
||||
fi
|
||||
else
|
||||
switching=0
|
||||
record "${command}: NOT healthy; left as it is (journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE})"
|
||||
fi
|
||||
exit 1
|
||||
|
|
@ -3,8 +3,12 @@
|
|||
|
||||
Ladder (infra/docs/loop-recovery.md): restart flysim, then reset to the current rung's
|
||||
milestone, then to the rung below. It climbs one step per confirmed trap that outlives
|
||||
the previous step, and starts over once the fly reaches a new best rung or has been
|
||||
quiet for QUIET seconds. A router model can delay a step, never deny it.
|
||||
the previous step, and starts over once the fly reaches a new best rung, makes lasting
|
||||
progress after the last step that it had not made before (a reset's replay re-earns its
|
||||
archive's rewards, which is not progress), or has been quiet for QUIET seconds. A milestone reset
|
||||
never erases a species first owned within PROTECT seconds, and never repeats the last
|
||||
reset's archive (a restore replays it exactly); either is a restart instead. A router model can
|
||||
delay a step, never deny it.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
|
@ -29,6 +33,9 @@ QUIET = 6 * 3600 # this long without a suspected report starts the ladder ov
|
|||
HOLD = 3 * 3600 # restart-only spacing while the reset budget is spent
|
||||
DAY = 24 * 3600
|
||||
MAX_RESETS = 2 # milestone resets per DAY
|
||||
AGAIN = 12 * 3600 # after this long the last reset's archive may be restored again (row 70)
|
||||
PROTECT = 2 * 3600 # a species owned this recently is not reset away (row 70)
|
||||
SEEN = 2000 # lasting-progress names remembered, oldest dropped first (row 70 r3)
|
||||
VETO_LIMIT = 3 # model vetoes of one step before it goes ahead anyway
|
||||
MODEL_BUDGET = 90 # seconds across all models in one decision
|
||||
VERIFY_TIMEOUT = 240
|
||||
|
|
@ -142,16 +149,19 @@ def rungs():
|
|||
return sorted(found)
|
||||
|
||||
|
||||
def plan(level, rank, best, resets_left):
|
||||
def plan(level, rank, best, resets_left, last_reset=None):
|
||||
"""(action, target rung) for a ladder level; a spent budget or no restorable archive is a restart.
|
||||
|
||||
Level 1 resets to the current rung's archive; level 2 and beyond to the rung below the best,
|
||||
and never lower, so repeated days of a trap cannot walk the run down the ladder.
|
||||
and never lower, so repeated days of a trap cannot walk the run down the ladder. The archive
|
||||
the last reset restored is not restored again (`last_reset`, cleared by a new best rung): a
|
||||
restore is deterministic, so the same archive replays the same run into the same trap (row 70:
|
||||
the second reset to rung 11 matched the first event for event).
|
||||
"""
|
||||
if level == 0 or not resets_left or rank is None:
|
||||
return "restart", None
|
||||
target = rank if level == 1 else max(best, rank) - 1
|
||||
if target > rank or target not in restorable_rungs():
|
||||
if target > rank or target == last_reset or target not in restorable_rungs():
|
||||
return "restart", None
|
||||
return "reset", target
|
||||
|
||||
|
|
@ -226,7 +236,10 @@ def run(now=None, sleep=time.sleep, clock=None):
|
|||
if level:
|
||||
log({"at": now, "event": "ladder-reset", "why": "new best rung", "rank": rank})
|
||||
state.update(bestRank=rank, level=0)
|
||||
state.pop("lastReset", None)
|
||||
level = 0
|
||||
if "lastReset" in state and now - state.get("lastResetAt", 0) >= AGAIN:
|
||||
state.pop("lastReset", None)
|
||||
last = state.get("lastSuspectedAt")
|
||||
if level and last and now - last > QUIET:
|
||||
log({"at": now, "event": "ladder-reset", "why": "quiet", "rank": rank})
|
||||
|
|
@ -234,6 +247,46 @@ def run(now=None, sleep=time.sleep, clock=None):
|
|||
state["resets"] = [at for at in state.get("resets", []) if now - at < DAY]
|
||||
|
||||
at = report.get("at")
|
||||
# Row 70: lasting progress in the probe's window (a new rung, a species owned, a map entered,
|
||||
# a trainer or badge beaten; the watchdog's window.progress). The ladder climbs for a trap that
|
||||
# OUTLIVES its last step; one that follows real progress after that step is a new trap and
|
||||
# starts again from a restart. A species owned is also kept from a milestone reset for PROTECT.
|
||||
# A new trap means the old one let go: a clear probe more than SETTLE after the step, so a catch
|
||||
# made while the fly stays flagged does not start the ladder over.
|
||||
#
|
||||
# Progress is measured against everything the ladder has seen before, not against the
|
||||
# restored archive (row 70 review r3): a milestone reset restores the reward ledger, so the
|
||||
# replay pays the archive's areas, trainers, species and rungs again, and counting those
|
||||
# started the ladder over after every reset (a rung-12 replay re-earning an area and a
|
||||
# species cost two extra steps and a three-hour hold before the rung below). The watchdog
|
||||
# names each lasting reward (`window.progress.keys`, `kind:label`); only a name not in
|
||||
# `progressSeen` is progress, and only a species not in it is protected (the replayed catch
|
||||
# was the fly's before the reset too, and was protected then). A watchdog without names falls
|
||||
# back to the counts.
|
||||
progress = (report.get("window") or {}).get("progress") or {}
|
||||
fresh = type(at) is int and 0 <= now - at <= 600
|
||||
if fresh and report.get("suspected") == 0:
|
||||
state["clearAt"] = max(at, state.get("clearAt", 0))
|
||||
if fresh and type(progress) is dict:
|
||||
keys = progress.get("keys")
|
||||
if type(keys) is list:
|
||||
seen = state.get("progressSeen")
|
||||
seen = [key for key in seen if type(key) is str] if type(seen) is list else []
|
||||
known = set(seen)
|
||||
new = [key for key in dict.fromkeys(key for key in keys if type(key) is str) if key not in known]
|
||||
state["progressSeen"] = (seen + new)[-SEEN:]
|
||||
lasting, species = len(new), sum(key.startswith("pokedex:") for key in new)
|
||||
else:
|
||||
lasting, species = (progress.get(name) if type(progress.get(name)) is int else 0
|
||||
for name in ("lasting", "species"))
|
||||
if lasting > 0:
|
||||
state["progressAt"] = max(at, state.get("progressAt", 0))
|
||||
if species > 0:
|
||||
state["speciesAt"] = max(at, state.get("speciesAt", 0))
|
||||
since = state.get("actedAt", 0) + SETTLE
|
||||
if level and state.get("progressAt", 0) > since and state.get("clearAt", 0) > since:
|
||||
log({"at": now, "event": "ladder-reset", "why": "progress since the last step", "rank": rank})
|
||||
state["level"] = level = 0
|
||||
# The last probe that saw progress (new places, or a higher rung than the last probe), kept across
|
||||
# restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak.
|
||||
delta = (report.get("places") or {}).get("delta")
|
||||
|
|
@ -265,10 +318,25 @@ def run(now=None, sleep=time.sleep, clock=None):
|
|||
return "waiting for next probe"
|
||||
|
||||
resets_left = MAX_RESETS - len(state["resets"])
|
||||
action, target = plan(level, rank, state.get("bestRank", 0), resets_left)
|
||||
if action == "restart" and level and now - acted < HOLD:
|
||||
action, target = plan(level, rank, state.get("bestRank", 0), resets_left, state.get("lastReset"))
|
||||
protected = action == "reset" and now - state.get("speciesAt", -PROTECT) < PROTECT
|
||||
# Only a catch-protected reset is held (the level keeps its slot, so it never drops a rung deeper
|
||||
# while the window lasts, row 70). A step skipped because it would restore the archive just used
|
||||
# does climb, so the ladder reaches the rung below promptly.
|
||||
held_reset = protected
|
||||
if protected:
|
||||
action, target = "restart", None
|
||||
# Restarts are at least HOLD apart, also when the ladder has started over since the last one.
|
||||
if action == "restart" and (level or state.get("lastAction") == "restart") and now - acted < HOLD:
|
||||
write_json(STATE, state)
|
||||
return "holding: reset budget spent, next restart after the hold"
|
||||
if protected:
|
||||
return "holding: a species owned within the protection window, next restart after the hold"
|
||||
if not level:
|
||||
return "holding: the last restart was under three hours ago"
|
||||
return "holding: no reset to take, next restart after the hold"
|
||||
if protected:
|
||||
log({"at": now, "event": "protect", "why": "a species owned within the protection window",
|
||||
"speciesAt": state["speciesAt"], "rank": rank})
|
||||
|
||||
stuck, model = verdict(report)
|
||||
if stuck is False and state.get("vetoes", 0) < VETO_LIMIT:
|
||||
|
|
@ -289,15 +357,18 @@ def run(now=None, sleep=time.sleep, clock=None):
|
|||
notice(base, "countdown", now)
|
||||
sleep(COUNTDOWN)
|
||||
started = int(clock())
|
||||
# Recorded before acting, so a helper killed mid-step has still climbed and spent the reset.
|
||||
state.update(level=level + 1, actedAt=started, lastAction=action, vetoes=0)
|
||||
# Recorded before acting, so a helper killed mid-step has still climbed (unless held) and spent the reset.
|
||||
state.update(level=level if held_reset else level + 1, actedAt=started, lastAction=action, vetoes=0)
|
||||
state.pop("observedAt", None)
|
||||
if action == "reset":
|
||||
state["resets"].append(started)
|
||||
state.update(lastReset=target, lastResetAt=started)
|
||||
write_json(STATE, state)
|
||||
notice(base, "acting", started)
|
||||
ok = act(action, target)
|
||||
finished = int(clock())
|
||||
if action == "reset" and not ok:
|
||||
state.pop("lastReset", None) # not known to have been restored, so it may be tried again
|
||||
notice(base, "done" if ok else "failed", finished)
|
||||
state["actedAt"] = finished
|
||||
write_json(STATE, state)
|
||||
|
|
|
|||
501
infra/bin/fly-runtime
Executable file
501
infra/bin/fly-runtime
Executable file
|
|
@ -0,0 +1,501 @@
|
|||
#!/usr/bin/env bash
|
||||
# infra/bin/fly-runtime — which runtime the live fly runs: the legacy loop (`flysim`) or the
|
||||
# session runtime (`flysim-session`, SERVE-01).
|
||||
#
|
||||
# Usage (INSIDE the container, as root):
|
||||
# fly-runtime status print `legacy` or `session` (and the session's transport), and
|
||||
# what flysim.service runs
|
||||
# fly-runtime session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation]
|
||||
# fly-runtime session-bus [...] the same as `session --bus`
|
||||
# fly-runtime legacy [--no-restart]
|
||||
# fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent)
|
||||
#
|
||||
# CUT-01 calls `fly-runtime session` after its zero-divergence shadow; `fly-runtime legacy` is
|
||||
# the one-command rollback (port decisions, 2026-09-23). Neither migrates any data: both
|
||||
# binaries read and write the same FLYSIM01 stores, event log, sugar journal and chat sidecar.
|
||||
#
|
||||
# The session's transport (BUS-01). `--local` (the default for a first switch) runs the session's
|
||||
# participants in flysim-session's own process over the local lane. `--bus` runs them on the flybus
|
||||
# router over Unix sockets: flysim-session (the router, the coordinator, the listeners) starts the
|
||||
# agent and the world as child processes of the same unit (`fly-session legacy-agent`,
|
||||
# `fly-session legacy-environment`, from the same release), in flysim.slice, on flysim's cpuset.
|
||||
# The drop-in then carries `Environment=FLY_SESSION_TRANSPORT=bus`. Without either flag `session`
|
||||
# keeps the transport the drop-in already has, so 05-deploy's `session --no-restart` refresh never
|
||||
# changes it; `session --local` is the way back from the bus. Results, traces, checkpoints and the
|
||||
# compatibility string are the same in both: only where the participants run changes. A switch onto
|
||||
# the bus needs a shadow that ran the bus (`fly-shadow-run check --bus`), which the coordinator runs
|
||||
# before this command, as for the first cutover. Everything below applies to both transports: one
|
||||
# unit, OnFailure= falls back to LEGACY, the probation judges the session runtime either way.
|
||||
#
|
||||
# How the switch works. flysim.service stays the fly's one unit name, and the runtime it runs
|
||||
# is chosen by one drop-in, ${DROPIN}:
|
||||
#
|
||||
# [Service]
|
||||
# ExecStart=
|
||||
# ExecStart=/opt/fly/current/flysim-session
|
||||
# Environment=FLY_SESSION_DIR=/run/fly/session
|
||||
#
|
||||
# i.e. flysim-session.service's ExecStart and its one extra variable (the standalone unit and
|
||||
# this drop-in are kept identical by infra/tests/lint.sh). Everything else that names
|
||||
# flysim.service -- fly.target, flyedge.service's Requires=, fly-watchdog's checks and escalation,
|
||||
# fly-loop-recover's `sudo systemctl restart flysim.service` and its sudoers line,
|
||||
# fly-loop-reset, fly-reset-to-milestone, the unstick rule, `journalctl -u flysim`, the cpuset
|
||||
# drop-in -- therefore keeps working unchanged, a reboot keeps the choice, and 05-deploy.sh (which
|
||||
# converges unit files but never removes a drop-in) keeps it across deploys. 05-deploy.sh refuses
|
||||
# a release without flysim-session while the drop-in is present.
|
||||
#
|
||||
# `session` refuses unless the release has flysim-session and its --print-compatibility equals
|
||||
# flysim's (the store is shared, so the two must restore each other's checkpoints). After the
|
||||
# restart it waits for /healthz (FLY_RUNTIME_HEALTH_TIMEOUT, default 300 s: the connectome load and
|
||||
# the restore) and a snapshot that has advanced; if the session runtime does not come up healthy
|
||||
# it switches back to legacy by itself and exits 1 (--no-fallback leaves it to the operator).
|
||||
#
|
||||
# The fallback survives the invocation (C1 of the SERVE-01 review). The drop-in also carries
|
||||
#
|
||||
# [Unit]
|
||||
# OnFailure=fly-runtime-fallback.service
|
||||
# StartLimitIntervalSec=600
|
||||
# StartLimitBurst=3
|
||||
# [Service]
|
||||
# RestartMode=direct
|
||||
#
|
||||
# RestartMode=direct is essential (systemd >= 254; verified on 257): with the default
|
||||
# RestartMode=normal the unit passes through `failed` before every Restart=always restart and
|
||||
# OnFailure= fires on the FIRST crash, watchdog kill or start timeout. With `direct` the unit
|
||||
# goes from one start straight to the next and only the start limit puts it in `failed`. So while the session runtime is selected, three starts of flysim.service inside ten minutes
|
||||
# (crashes, watchdog kills, a start that never becomes ready, the restarts fly-watchdog and
|
||||
# fly-loop-recover make for a stream that does not come up) end in the failed state, and systemd
|
||||
# runs fly-runtime-fallback.service, i.e. `fly-runtime fallback`: write ${FELLBACK_FILE}, remove
|
||||
# the drop-in, daemon-reload, restart flysim.service (now the legacy binary) and log a line. That
|
||||
# holds across reboots, watchdog and loop-recover restarts and deploys, none of which go through
|
||||
# `fly-runtime session`. It is idempotent (a lock, and a no-op once the drop-in is gone) and it
|
||||
# keeps the drop-in when there is no executable legacy binary, so it never swaps one runtime that
|
||||
# cannot start for another. `fly-runtime session` deletes the reason file; `status` shows it.
|
||||
#
|
||||
# During a switch fly-runtime traps INT, TERM and HUP (and any failure): an interrupted `session`
|
||||
# puts the previous state back (drop-in removed, or the earlier one restored) and restarts
|
||||
# flysim.service on it, so a dropped ssh never leaves a drop-in that was not health-checked.
|
||||
#
|
||||
# The speed probation (CUT-01). Operator decision 2026-09-30: the session runtime stays only if it
|
||||
# sustains >= 1.0x real time on the release container. A `session` that restarted flysim and saw
|
||||
# it healthy therefore starts infra/bin/fly-runtime-probation (fly-runtime-probation.timer, every
|
||||
# 60 s for 30 minutes): a sustained speed failure ends in `fly-runtime fallback "speed: ..."`, the
|
||||
# same fallback as above under the same lock. `legacy` and every fallback cancel it. `--no-restart`
|
||||
# (05-deploy's refresh of the drop-in) and `--no-probation` (rehearsals) start none. If the
|
||||
# probation cannot be started, `session` falls back: an unguarded cutover is not allowed.
|
||||
#
|
||||
# `session` also stops a running shadow and its guard (fly-shadow-run stop, no flysim restart) once
|
||||
# flysim is healthy on the session runtime, so the procedure cannot be done wrong (review N1).
|
||||
#
|
||||
# Every switch is logged to the journal (tag fly-runtime) and appended to ${RUNTIME_LOG}.
|
||||
set -euo pipefail
|
||||
|
||||
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
|
||||
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
|
||||
: "${FLY_SERVICE:=flysim.service}"
|
||||
: "${FLY_RUNTIME_HEALTH_TIMEOUT:=300}"
|
||||
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
|
||||
: "${FLY_SYSTEMD_DIR:=/etc/systemd/system}"
|
||||
: "${FLY_RUNTIME_LOG:=/var/lib/fly/runtime.log}"
|
||||
: "${FLY_RUNTIME_FELLBACK:=/run/fly/runtime-fellback.json}"
|
||||
: "${FLY_RUNTIME_LOCK:=/run/fly/runtime.lock}"
|
||||
: "${FLY_RUNTIME_LOCK_WAIT:=150}"
|
||||
DROPIN_DIR="${FLY_SYSTEMD_DIR}/${FLY_SERVICE}.d"
|
||||
DROPIN="${DROPIN_DIR}/10-runtime.conf"
|
||||
RUNTIME_LOG="$FLY_RUNTIME_LOG"
|
||||
FELLBACK_FILE="$FLY_RUNTIME_FELLBACK"
|
||||
FALLBACK_UNIT=fly-runtime-fallback.service
|
||||
SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session"
|
||||
WORKER_BIN="${FLY_RELEASE_DIR}/fly-session"
|
||||
LEGACY_BIN="${FLY_RELEASE_DIR}/flysim"
|
||||
SESSION_DIR=/run/fly/session
|
||||
SHADOW_RUN_BIN="${FLY_SHADOW_RUN_BIN:-$(dirname "$(readlink -f "$0")")/fly-shadow-run}"
|
||||
PROBATION_BIN="${FLY_PROBATION_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime-probation}"
|
||||
|
||||
log() { echo "fly-runtime: $*" >&2; }
|
||||
|
||||
# The speed probation's hooks (best effort except `start`, which the caller checks).
|
||||
probation() {
|
||||
[ -x "$PROBATION_BIN" ] || return 0
|
||||
"$PROBATION_BIN" "$@" || log "fly-runtime-probation $1 failed"
|
||||
}
|
||||
die() { log "$*"; exit 1; }
|
||||
|
||||
# CUT-01 (review N1): once flysim runs the session runtime the shadow and its guard are over. The
|
||||
# guard would judge the session against the legacy baseline and restart flysim on a trip; the
|
||||
# session writes no trace. Stops both WITHOUT restarting flysim. Best effort, never fails the switch.
|
||||
stop_shadow() {
|
||||
if systemctl is-active --quiet flyshadow.service 2>/dev/null \
|
||||
|| systemctl is-active --quiet flyshadow-guard.timer 2>/dev/null; then
|
||||
if [ -x "$SHADOW_RUN_BIN" ] && "$SHADOW_RUN_BIN" stop; then
|
||||
log "the shadow and its guard are stopped (flysim.service not restarted)"
|
||||
else
|
||||
log "WARNING: could not stop the shadow; run: fly-shadow-run stop (never with --restart-flysim)"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
usage() {
|
||||
echo "usage: fly-runtime status | session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation] | session-bus [...] | legacy [--no-restart] | fallback [reason]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
current() {
|
||||
if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
|
||||
}
|
||||
|
||||
# The session's transport the drop-in selects: `bus` or `local` (also with no drop-in).
|
||||
current_transport() {
|
||||
if [ -f "$DROPIN" ] && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$DROPIN"; then
|
||||
echo bus
|
||||
else
|
||||
echo local
|
||||
fi
|
||||
}
|
||||
|
||||
# `legacy`, `session` or `session-bus`, for the runtime log.
|
||||
current_label() {
|
||||
if [ "$(current)" = session ] && [ "$(current_transport)" = bus ]; then echo session-bus; else current; fi
|
||||
}
|
||||
|
||||
record() {
|
||||
local line
|
||||
line="$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*"
|
||||
if command -v logger >/dev/null 2>&1; then
|
||||
logger -t fly-runtime -- "$*" || true
|
||||
fi
|
||||
mkdir -p "$(dirname "$RUNTIME_LOG")" 2>/dev/null || true
|
||||
echo "$line" >>"$RUNTIME_LOG" 2>/dev/null || log "could not append to $RUNTIME_LOG"
|
||||
}
|
||||
|
||||
# The compatibility string a binary would write, with the service's own environment: fly.env is
|
||||
# systemd's EnvironmentFile syntax, read as KEY=VALUE lines rather than sourced as shell.
|
||||
compat_of() {
|
||||
local -a vars=()
|
||||
local line key value
|
||||
if [ -f "$FLY_ENV_FILE" ]; then
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
|
||||
key="${line%%=*}"
|
||||
value="${line#*=}"
|
||||
value="${value%\"}"
|
||||
value="${value#\"}"
|
||||
vars+=("${key}=${value}")
|
||||
done <"$FLY_ENV_FILE"
|
||||
fi
|
||||
env "${vars[@]}" "$1" --print-compatibility 2>/dev/null | tr -d '\r'
|
||||
}
|
||||
|
||||
write_dropin() {
|
||||
mkdir -p "$DROPIN_DIR"
|
||||
local tmp="${DROPIN}.tmp.$$"
|
||||
cat >"$tmp" <<EOF
|
||||
# Written by fly-runtime session (SERVE-01): flysim.service runs the session runtime.
|
||||
# \`fly-runtime legacy\` removes this file, and so does fly-runtime-fallback.service (OnFailure=,
|
||||
# after three starts in ten minutes). RestartMode=direct is what makes OnFailure= wait for the start
|
||||
# limit: systemd >= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart.
|
||||
# Keep [Service] in step with units/flysim-session.service.
|
||||
[Unit]
|
||||
OnFailure=${FALLBACK_UNIT}
|
||||
StartLimitIntervalSec=600
|
||||
StartLimitBurst=3
|
||||
[Service]
|
||||
RestartMode=direct
|
||||
ExecStart=
|
||||
ExecStart=${SESSION_BIN}
|
||||
Environment=FLY_SESSION_DIR=${SESSION_DIR}
|
||||
Environment=MALLOC_ARENA_MAX=2
|
||||
EOF
|
||||
if [ "$transport" = bus ]; then
|
||||
cat >>"$tmp" <<EOF
|
||||
# BUS-01: the participants are child processes on the session router's Unix sockets.
|
||||
Environment=FLY_SESSION_TRANSPORT=bus
|
||||
EOF
|
||||
fi
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" "$DROPIN"
|
||||
}
|
||||
|
||||
# /healthz 200, then a snapshot whose frame moved: the loop is running, not just listening.
|
||||
healthy() {
|
||||
local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT ))
|
||||
local first=""
|
||||
while [ "$(date +%s)" -lt "$deadline" ]; do
|
||||
if [ -n "$old_invocation" ] \
|
||||
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
|
||||
sleep 1
|
||||
continue
|
||||
fi
|
||||
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
|
||||
local frame
|
||||
frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \
|
||||
| sed -n 's/.*"frame":\([0-9][0-9]*\).*/\1/p' | head -n1)"
|
||||
if [ -n "$frame" ]; then
|
||||
if [ -z "$first" ]; then
|
||||
first="$frame"
|
||||
elif [ "$frame" -gt "$first" ]; then
|
||||
log "healthy: frame ${first} -> ${frame}"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`,
|
||||
# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state
|
||||
# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so
|
||||
# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per
|
||||
# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s).
|
||||
locked=0
|
||||
take_lock() {
|
||||
if [ "$locked" -eq 1 ]; then return 0; fi
|
||||
mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true
|
||||
exec 9>>"$FLY_RUNTIME_LOCK"
|
||||
if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi
|
||||
log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s"
|
||||
return 1
|
||||
}
|
||||
drop_lock() {
|
||||
exec 9>&-
|
||||
locked=0
|
||||
}
|
||||
|
||||
restarted=0
|
||||
old_invocation=""
|
||||
restart_and_check() {
|
||||
systemctl daemon-reload
|
||||
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
|
||||
log "restarting ${FLY_SERVICE} on the $(current) runtime"
|
||||
restarted=1
|
||||
# --no-block: a blocking restart of a unit that never becomes READY holds this process (and
|
||||
# the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove
|
||||
# that it is talking to the NEW invocation, not the old process that is still shutting down.
|
||||
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
|
||||
systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; }
|
||||
drop_lock
|
||||
healthy
|
||||
}
|
||||
|
||||
# The fallback to legacy, shared by `fly-runtime session` (its own health check) and by
|
||||
# fly-runtime-fallback.service (OnFailure= in the drop-in). Idempotent and serialised: whoever
|
||||
# gets the lock second finds the drop-in gone and does nothing. It never removes the drop-in
|
||||
# unless legacy can start, and it puts the drop-in back if flysim.service cannot be restarted,
|
||||
# so at least one runtime is always startable. Restarts with --no-block: the caller (or the
|
||||
# watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start.
|
||||
do_fallback() {
|
||||
local reason="$1" result nrestarts saved
|
||||
take_lock || log "continuing without the lock"
|
||||
if [ ! -f "$DROPIN" ]; then
|
||||
log "fallback: the legacy runtime is already selected; nothing to do"
|
||||
return 0
|
||||
fi
|
||||
if [ ! -x "$LEGACY_BIN" ]; then
|
||||
record "fallback REFUSED (${reason}): no executable ${LEGACY_BIN}; the session drop-in stays"
|
||||
return 1
|
||||
fi
|
||||
result="$(systemctl show -p Result --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
|
||||
nrestarts="$(systemctl show -p NRestarts --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
|
||||
reason="${reason//[\"\\]/}"
|
||||
reason="${reason//$'\n'/ }"
|
||||
mkdir -p "$(dirname "$FELLBACK_FILE")" 2>/dev/null || true
|
||||
printf '{"at":"%s","from":"session","to":"legacy","reason":"%s","unitResult":"%s","nRestarts":"%s"}\n' \
|
||||
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$reason" "${result:-unknown}" "${nrestarts:-}" \
|
||||
>"${FELLBACK_FILE}.tmp.$$" 2>/dev/null || true
|
||||
mv -f "${FELLBACK_FILE}.tmp.$$" "$FELLBACK_FILE" 2>/dev/null || log "could not write ${FELLBACK_FILE}"
|
||||
saved="$(mktemp "${DROPIN}.saved.XXXXXX")"
|
||||
cp -f "$DROPIN" "$saved"
|
||||
rm -f "$DROPIN"
|
||||
rmdir "$DROPIN_DIR" 2>/dev/null || true
|
||||
probation cancel --quiet
|
||||
record "legacy (automatic fallback: ${reason}; was session)"
|
||||
systemctl daemon-reload || true
|
||||
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
|
||||
restarted=1
|
||||
if systemctl restart --no-block "$FLY_SERVICE"; then
|
||||
rm -f "$saved"
|
||||
return 0
|
||||
fi
|
||||
# Could not even queue the restart: keep what was running, and say so.
|
||||
mkdir -p "$DROPIN_DIR" && mv -f "$saved" "$DROPIN"
|
||||
systemctl daemon-reload || true
|
||||
rm -f "$FELLBACK_FILE"
|
||||
record "fallback FAILED (${reason}): could not restart ${FLY_SERVICE}; the session drop-in is back"
|
||||
return 1
|
||||
}
|
||||
|
||||
# An interrupted or failed switch puts the previous state back. `switching` is 1 from just
|
||||
# before the drop-in is touched until the switch has finished; `prev_dropin` is a copy of the
|
||||
# drop-in that was there before (empty: none, i.e. legacy). The rollback runs under the lock and
|
||||
# does nothing when a fallback has completed since the switch began (FELLBACK_FILE exists: the
|
||||
# switch deleted it under the lock, only a finished fallback writes it): restoring the older
|
||||
# drop-in then would strand the stream on the session runtime after it was taken off.
|
||||
switching=0
|
||||
switch_target=""
|
||||
prev_dropin=""
|
||||
# shellcheck disable=SC2317 # runs from the EXIT trap
|
||||
on_exit() {
|
||||
local rc=$?
|
||||
trap - EXIT INT TERM HUP
|
||||
if [ "$switching" -eq 1 ]; then
|
||||
switching=0
|
||||
take_lock || true
|
||||
if [ "$switch_target" = session ] && [ -f "$FELLBACK_FILE" ]; then
|
||||
record "legacy (switch to session interrupted or failed (exit ${rc}); a fallback completed meanwhile, not restoring the older drop-in)"
|
||||
restarted=0
|
||||
elif [ "$switch_target" = session ]; then
|
||||
if [ -n "$prev_dropin" ] && [ -f "$prev_dropin" ]; then
|
||||
mkdir -p "$DROPIN_DIR" && cp -f "$prev_dropin" "$DROPIN"
|
||||
else
|
||||
rm -f "$DROPIN"
|
||||
rmdir "$DROPIN_DIR" 2>/dev/null || true
|
||||
fi
|
||||
record "$(current) (switch to session interrupted or failed (exit ${rc}); rolled back)"
|
||||
else
|
||||
record "$(current) (switch to legacy interrupted (exit ${rc}))"
|
||||
fi
|
||||
systemctl daemon-reload || true
|
||||
if [ "$restarted" -eq 1 ]; then
|
||||
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
|
||||
systemctl restart --no-block "$FLY_SERVICE" || true
|
||||
fi
|
||||
fi
|
||||
[ -z "$prev_dropin" ] || rm -f "$prev_dropin"
|
||||
exit "$rc"
|
||||
}
|
||||
trap on_exit EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
trap 'exit 129' HUP
|
||||
|
||||
[ $# -ge 1 ] || usage
|
||||
command="$1"; shift
|
||||
restart=1
|
||||
fallback=1
|
||||
probe=1
|
||||
transport=""
|
||||
fallback_reason=""
|
||||
if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi
|
||||
if [ "$command" = session-bus ]; then command=session; transport=bus; fi
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-restart) restart=0 ;;
|
||||
--no-fallback) fallback=0 ;;
|
||||
--no-probation) probe=0 ;;
|
||||
--bus) [ "$command" = session ] || usage; transport=bus ;;
|
||||
--local) [ "$command" = session ] || usage; transport=local ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
# No flag: keep the drop-in's transport (05-deploy's refresh); local for a first switch.
|
||||
[ -n "$transport" ] || transport="$(current_transport)"
|
||||
|
||||
case "$command" in
|
||||
status)
|
||||
current
|
||||
if [ "$(current)" = session ]; then echo " transport: $(current_transport)"; fi
|
||||
if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi
|
||||
if [ -x "$PROBATION_BIN" ]; then "$PROBATION_BIN" status 2>/dev/null | sed 's/^/ /' || true; fi
|
||||
systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true
|
||||
exit 0
|
||||
;;
|
||||
session|session-bus|legacy) ;;
|
||||
fallback)
|
||||
[ "$(id -u)" -eq 0 ] || die "run as root"
|
||||
do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
|
||||
exit $?
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
|
||||
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${DROPIN} and restarts ${FLY_SERVICE})"
|
||||
|
||||
if [ "$command" = session ]; then
|
||||
[ -x "$SESSION_BIN" ] || die "this release has no ${SESSION_BIN}; the session runtime ships from SERVE-01 on"
|
||||
[ -x "$LEGACY_BIN" ] || die "no ${LEGACY_BIN}"
|
||||
if [ "$transport" = bus ] && [ ! -x "$WORKER_BIN" ]; then
|
||||
die "this release has no ${WORKER_BIN}: the bus transport starts its participants from it"
|
||||
fi
|
||||
legacy_compat="$(compat_of "$LEGACY_BIN")"
|
||||
session_compat="$(compat_of "$SESSION_BIN")"
|
||||
[ -n "$session_compat" ] || die "${SESSION_BIN} --print-compatibility printed nothing (see its stderr); not switching"
|
||||
if [ "$legacy_compat" != "$session_compat" ]; then
|
||||
die "the two runtimes would write different checkpoints; not switching.
|
||||
flysim: ${legacy_compat}
|
||||
flysim-session: ${session_compat}"
|
||||
fi
|
||||
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
|
||||
before="$(current_label)"
|
||||
if [ -f "$DROPIN" ]; then
|
||||
prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
|
||||
cp -f "$DROPIN" "$prev_dropin"
|
||||
fi
|
||||
switch_target=session
|
||||
switching=1
|
||||
rm -f "$FELLBACK_FILE"
|
||||
write_dropin
|
||||
record "$(current_label) (was ${before}); compatibility ${session_compat}"
|
||||
if [ "$restart" -ne 1 ]; then
|
||||
systemctl daemon-reload
|
||||
switching=0
|
||||
log "drop-in written; restart ${FLY_SERVICE} to apply"
|
||||
exit 0
|
||||
fi
|
||||
if restart_and_check; then
|
||||
# OnFailure= may have fallen back while we waited (a healthy legacy would pass the
|
||||
# check above too): only report success if the session drop-in is still what runs.
|
||||
if [ -f "$DROPIN" ] && [ ! -f "$FELLBACK_FILE" ]; then
|
||||
switching=0
|
||||
stop_shadow
|
||||
if [ "$probe" -eq 1 ]; then
|
||||
if [ ! -x "$PROBATION_BIN" ] || ! "$PROBATION_BIN" start; then
|
||||
log "the speed probation could not be started; an unguarded cutover is not allowed"
|
||||
if [ "$fallback" -eq 1 ]; then
|
||||
do_fallback "the speed probation could not be started" || true
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
log "flysim.service runs the session runtime, on probation: fly-runtime-probation status"
|
||||
else
|
||||
log "flysim.service runs the session runtime (no probation)"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
switching=0
|
||||
log "the session runtime failed and ${FALLBACK_UNIT} fell back to legacy: $(cat "$FELLBACK_FILE" 2>/dev/null)"
|
||||
exit 1
|
||||
fi
|
||||
log "the session runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s"
|
||||
if [ "$fallback" -eq 1 ]; then
|
||||
do_fallback "the session runtime was not healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s of the switch" || true
|
||||
switching=0
|
||||
if healthy; then
|
||||
log "fell back to the legacy runtime; it is healthy"
|
||||
else
|
||||
log "fell back to the legacy runtime, and it is NOT healthy either: check journalctl -u ${FLY_SERVICE}"
|
||||
fi
|
||||
else
|
||||
switching=0
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# legacy
|
||||
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
|
||||
before="$(current_label)"
|
||||
switch_target=legacy
|
||||
switching=1
|
||||
rm -f "$DROPIN"
|
||||
rmdir "$DROPIN_DIR" 2>/dev/null || true
|
||||
probation cancel
|
||||
record "legacy (was ${before})"
|
||||
[ "$restart" -eq 1 ] || { systemctl daemon-reload; switching=0; log "drop-in removed; restart ${FLY_SERVICE} to apply"; exit 0; }
|
||||
if restart_and_check; then
|
||||
switching=0
|
||||
log "flysim.service runs the legacy runtime"
|
||||
exit 0
|
||||
fi
|
||||
switching=0
|
||||
die "the legacy runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s: check journalctl -u ${FLY_SERVICE}"
|
||||
299
infra/bin/fly-runtime-probation
Executable file
299
infra/bin/fly-runtime-probation
Executable file
|
|
@ -0,0 +1,299 @@
|
|||
#!/usr/bin/env bash
|
||||
# infra/bin/fly-runtime-probation -- CUT-01's speed probation after `fly-runtime session`.
|
||||
# Pushed to /opt/fly/bin by 05-deploy.sh. Root, inside the container. Normally nobody runs it by
|
||||
# hand: `fly-runtime session` starts it, `fly-runtime legacy` and every fallback cancel it, and
|
||||
# fly-runtime-probation.timer runs `tick` every 60 s.
|
||||
#
|
||||
# fly-runtime-probation start begin a probation (enables and starts the timer)
|
||||
# fly-runtime-probation cancel end it without a verdict (disables the timer)
|
||||
# fly-runtime-probation status state, latest samples, result
|
||||
# fly-runtime-probation tick (timer) one sample and one decision
|
||||
# fly-runtime-probation simulate CHECKS.jsonl the rule over recorded samples (lint)
|
||||
#
|
||||
# Operator decision 2026-09-30: cut over only if the session runtime sustains >= 1.0x real time on
|
||||
# the release container. Only that box can measure it, so the switch is guarded. The rule:
|
||||
# - A sample is one fly_realtime_factor mean over 10 one-second reads of flysim's /metrics (the
|
||||
# same sampling as fly-shadow-run's guard), with fly_lag_seconds and fly_uptime_seconds.
|
||||
# - Warm-up: a flysim process is not judged before it has been up FLY_PROBATION_WARMUP (300 s:
|
||||
# the connectome load, the restore, the first minutes). A restart (uptime goes backwards)
|
||||
# starts the window again; so does a paused or not running fly: it is not judged.
|
||||
# - Window: the judged samples of the last FLY_PROBATION_WINDOW (600 s), at least
|
||||
# FLY_PROBATION_MIN_SAMPLES (8). FAIL when the window's MEDIAN realtime factor is below
|
||||
# FLY_PROBATION_MIN_RTF (0.97), or the lag grew by more than FLY_PROBATION_MAX_LAG_GROWTH
|
||||
# (30 s) between the start and the end of the window (median of the first and of the last 3
|
||||
# samples). The median is the same robust statistic fly-shadow-run's baseline uses: one
|
||||
# stalled sample, or two, never fails it.
|
||||
# - PASS when FLY_PROBATION_SECONDS (1800) have passed since `start` and the latest window is
|
||||
# full and healthy. A probation that cannot fill a window within FLY_PROBATION_MAX_SECONDS
|
||||
# (7200: a fly that never runs) fails as inconclusive: no proof of 1.0x, no cutover.
|
||||
# FAIL runs `fly-runtime fallback "speed: ..."` (the ordinary fallback: lock, reason file
|
||||
# /run/fly/runtime-fellback.json, journal line, flysim.service restarted on legacy). It is retried
|
||||
# every minute until it succeeds. PASS writes ${RESULT} (passed: true) and disables the timer.
|
||||
# Nothing judges the speed afterwards: the watchdog and the start-limit fallback are unchanged.
|
||||
#
|
||||
# State is ${DIR}/state.json (on disk, so a reboot resumes the probation: the timer is enabled,
|
||||
# and OnBootSec= runs it after boot); ${DIR}/last.json keeps the last verdict.
|
||||
set -euo pipefail
|
||||
|
||||
: "${FLY_PROBATION_DIR:=/var/lib/fly/probation}"
|
||||
: "${FLY_PROBATION_RESULT:=/run/fly/runtime-probation.json}"
|
||||
: "${FLY_PROBATION_TIMER:=fly-runtime-probation.timer}"
|
||||
: "${FLY_PROBATION_READS:=10}"
|
||||
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
|
||||
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
|
||||
RUNTIME_BIN="${FLY_RUNTIME_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime}"
|
||||
STATE="$FLY_PROBATION_DIR/state.json"
|
||||
LAST="$FLY_PROBATION_DIR/last.json"
|
||||
|
||||
log() { echo "fly-runtime-probation: $*" >&2; }
|
||||
die() { log "$*"; exit 1; }
|
||||
journal() {
|
||||
if command -v logger >/dev/null 2>&1; then logger -t fly-runtime -- "probation: $*" || true; fi
|
||||
log "$*"
|
||||
}
|
||||
need_root() { [ "$(id -u)" = 0 ] || die "run as root"; }
|
||||
|
||||
take_lock() {
|
||||
mkdir -p "$FLY_PROBATION_DIR"
|
||||
exec 8>>"$FLY_PROBATION_DIR/lock"
|
||||
flock -w 60 8 || die "could not take $FLY_PROBATION_DIR/lock"
|
||||
}
|
||||
drop_lock() { exec 8>&-; }
|
||||
|
||||
# One sample of the live fly: {t, status, rtMean, lag, uptime} (fly-shadow-run's format).
|
||||
sample() {
|
||||
python3 - "$FLY_METRICS_URL" "$FLY_CONTROL_URL" "$FLY_PROBATION_READS" <<'PY'
|
||||
import json, sys, time, urllib.request
|
||||
metrics_url, control_url, reads = sys.argv[1], sys.argv[2], int(sys.argv[3])
|
||||
def metrics():
|
||||
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
|
||||
out = {}
|
||||
for line in text.splitlines():
|
||||
if line.startswith("#"):
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) == 2:
|
||||
try:
|
||||
out[parts[0]] = float(parts[1])
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
factors = []
|
||||
for i in range(reads):
|
||||
factors.append(metrics().get("fly_realtime_factor", 0.0))
|
||||
if i + 1 < reads:
|
||||
time.sleep(1)
|
||||
m = metrics()
|
||||
try:
|
||||
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
|
||||
except Exception:
|
||||
status = None
|
||||
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
|
||||
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
|
||||
PY
|
||||
}
|
||||
|
||||
PROBATION_PY='
|
||||
import json, os, sys
|
||||
def env(name, default):
|
||||
return type(default)(os.environ.get(name, default))
|
||||
WARMUP = env("FLY_PROBATION_WARMUP", 300.0)
|
||||
WINDOW = env("FLY_PROBATION_WINDOW", 600.0)
|
||||
MIN_SAMPLES = env("FLY_PROBATION_MIN_SAMPLES", 8)
|
||||
MIN_RTF = env("FLY_PROBATION_MIN_RTF", 0.97)
|
||||
MAX_LAG_GROWTH = env("FLY_PROBATION_MAX_LAG_GROWTH", 30.0)
|
||||
DURATION = env("FLY_PROBATION_SECONDS", 1800.0)
|
||||
MAX_SECONDS = env("FLY_PROBATION_MAX_SECONDS", 7200.0)
|
||||
|
||||
def running(s):
|
||||
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
|
||||
|
||||
def median(xs):
|
||||
xs = sorted(xs)
|
||||
n = len(xs)
|
||||
return xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2
|
||||
|
||||
def step(state, s):
|
||||
"""Returns (state, verdict, detail): verdict is wait, ok, pass or fail."""
|
||||
started = state["startedAt"]
|
||||
history = state.get("history", [])
|
||||
elapsed = s["t"] - started
|
||||
if not running(s):
|
||||
return state, "wait", "flysim is %s: not judged" % s.get("status")
|
||||
if history and s["uptime"] < history[-1]["uptime"]:
|
||||
history = []
|
||||
if s["uptime"] < WARMUP:
|
||||
state["history"] = []
|
||||
return state, "wait", "warming up (flysim up %.0f of %.0f s)" % (s["uptime"], WARMUP)
|
||||
history = [h for h in history if h["t"] > s["t"] - WINDOW] + [s]
|
||||
state["history"] = history
|
||||
n = len(history)
|
||||
if n < MIN_SAMPLES:
|
||||
if elapsed >= MAX_SECONDS:
|
||||
return state, "fail", "speed: probation inconclusive after %.0f s (%d judged samples in the window): no proof of 1.0x" % (elapsed, n)
|
||||
return state, "wait", "collecting %d of %d samples" % (n, MIN_SAMPLES)
|
||||
rtf = median([h["rtMean"] for h in history])
|
||||
lag_growth = median([h["lag"] for h in history[-3:]]) - median([h["lag"] for h in history[:3]])
|
||||
detail = "median realtime factor %.3f over %d samples, lag growth %+.1f s over %.0f s" % (
|
||||
rtf, n, lag_growth, history[-1]["t"] - history[0]["t"])
|
||||
state["last"] = {"medianRtf": rtf, "lagGrowth": lag_growth, "samples": n}
|
||||
why = []
|
||||
if rtf < MIN_RTF:
|
||||
why.append("median realtime factor %.3f < %.2f" % (rtf, MIN_RTF))
|
||||
if lag_growth > MAX_LAG_GROWTH:
|
||||
why.append("lag grew %.1f s > %.0f s" % (lag_growth, MAX_LAG_GROWTH))
|
||||
if why:
|
||||
return state, "fail", "speed: " + ", ".join(why) + " over %d samples / %.0f s" % (
|
||||
n, history[-1]["t"] - history[0]["t"])
|
||||
if elapsed >= DURATION:
|
||||
return state, "pass", detail
|
||||
return state, "ok", detail + " (%.0f of %.0f s)" % (elapsed, DURATION)
|
||||
|
||||
mode = sys.argv[1]
|
||||
if mode == "step":
|
||||
state = json.load(open(sys.argv[2]))
|
||||
state, verdict, detail = step(state, json.loads(sys.argv[3]))
|
||||
json.dump(state, open(sys.argv[2], "w"))
|
||||
print(verdict + " " + detail)
|
||||
elif mode == "simulate":
|
||||
samples = [json.loads(l) for l in open(sys.argv[2]) if l.strip()]
|
||||
state = {"startedAt": samples[0]["t"] - 60, "history": []}
|
||||
verdict, detail = "wait", ""
|
||||
for n, s in enumerate(samples, 1):
|
||||
state, verdict, detail = step(state, s)
|
||||
if verdict in ("pass", "fail"):
|
||||
print("%s at check %d: %s" % (verdict, n, detail))
|
||||
sys.exit(0 if verdict == "pass" else 1)
|
||||
print("undecided after %d checks: %s %s" % (len(samples), verdict, detail))
|
||||
sys.exit(3)
|
||||
'
|
||||
|
||||
now_iso() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
|
||||
|
||||
enabled_timer() { systemctl "$1" --now "$FLY_PROBATION_TIMER" >/dev/null 2>&1; }
|
||||
|
||||
start() {
|
||||
need_root
|
||||
take_lock
|
||||
mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true
|
||||
rm -f "$FLY_PROBATION_RESULT"
|
||||
printf '{"startedAt":%s,"startedAtIso":"%s","history":[]}\n' "$(date +%s.%N)" "$(now_iso)" >"$STATE.tmp.$$"
|
||||
mv -f "$STATE.tmp.$$" "$STATE"
|
||||
if ! enabled_timer enable; then
|
||||
rm -f "$STATE"
|
||||
die "could not enable --now $FLY_PROBATION_TIMER (is the unit installed?)"
|
||||
fi
|
||||
journal "started: ${FLY_PROBATION_SECONDS:-1800} s, median realtime factor >= ${FLY_PROBATION_MIN_RTF:-0.97} over ${FLY_PROBATION_WINDOW:-600} s after ${FLY_PROBATION_WARMUP:-300} s warm-up, lag growth <= ${FLY_PROBATION_MAX_LAG_GROWTH:-30} s; else fallback to legacy"
|
||||
}
|
||||
|
||||
cancel() {
|
||||
local quiet=0
|
||||
[ "${1:-}" = --quiet ] && quiet=1
|
||||
need_root
|
||||
take_lock
|
||||
local had=0
|
||||
if [ -f "$STATE" ]; then had=1; fi
|
||||
rm -f "$STATE" "$FLY_PROBATION_RESULT"
|
||||
enabled_timer disable || true
|
||||
if [ "$had" -eq 1 ] || [ "$quiet" -eq 0 ]; then journal "cancelled"; fi
|
||||
}
|
||||
|
||||
# The verdict, persisted in last.json (and in ${RESULT} on a pass).
|
||||
finish() { # passed(true|false) detail state-file
|
||||
local tmp="$LAST.tmp.$$"
|
||||
python3 - "$1" "$2" "$3" >"$tmp" <<'PY'
|
||||
import json, sys, datetime
|
||||
passed, detail = sys.argv[1] == "true", sys.argv[2]
|
||||
st = {}
|
||||
try:
|
||||
st = json.load(open(sys.argv[3]))
|
||||
except Exception:
|
||||
pass
|
||||
out = {"passed": passed, "at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"startedAt": st.get("startedAtIso"), "detail": detail}
|
||||
out.update(st.get("last", {}))
|
||||
print(json.dumps(out))
|
||||
PY
|
||||
mv -f "$tmp" "$LAST"
|
||||
if [ "$1" = true ]; then
|
||||
mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true
|
||||
cp -f "$LAST" "$FLY_PROBATION_RESULT"
|
||||
fi
|
||||
}
|
||||
|
||||
tick() {
|
||||
need_root
|
||||
local sample_json="" now out verdict detail rc
|
||||
if [ "${1:-}" = --sample-json ]; then sample_json="$2"; fi # the test seam: a recorded sample
|
||||
if [ ! -f "$STATE" ]; then
|
||||
log "no probation: disabling $FLY_PROBATION_TIMER"
|
||||
enabled_timer disable || true
|
||||
exit 0
|
||||
fi
|
||||
# Only the session runtime is judged: a fallback, a legacy switch or a deploy that removed the
|
||||
# drop-in ended it.
|
||||
if [ "$("$RUNTIME_BIN" status 2>/dev/null | head -n1)" != session ]; then
|
||||
journal "the session runtime is not selected; probation ends"
|
||||
cancel --quiet
|
||||
exit 0
|
||||
fi
|
||||
if [ -n "$sample_json" ]; then now="$sample_json"; else now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }; fi
|
||||
take_lock
|
||||
[ -f "$STATE" ] || { log "cancelled while sampling"; exit 0; }
|
||||
rc=0
|
||||
out="$(python3 -c "$PROBATION_PY" step "$STATE" "$now")" || rc=$?
|
||||
[ "$rc" -eq 0 ] || die "probation rule failed: $out"
|
||||
verdict="${out%% *}"
|
||||
detail="${out#* }"
|
||||
case "$verdict" in
|
||||
wait|ok) drop_lock; log "$verdict: $detail" ;;
|
||||
pass)
|
||||
finish true "$detail" "$STATE"
|
||||
rm -f "$STATE"
|
||||
enabled_timer disable || true
|
||||
journal "PASSED: $detail"
|
||||
;;
|
||||
fail)
|
||||
cp -f "$STATE" "$STATE.failed.$$"
|
||||
drop_lock
|
||||
journal "FAILED: $detail; falling back to legacy"
|
||||
if "$RUNTIME_BIN" fallback "$detail"; then
|
||||
take_lock
|
||||
finish false "$detail" "$STATE.failed.$$"
|
||||
rm -f "$STATE" "$STATE.failed.$$"
|
||||
enabled_timer disable || true
|
||||
else
|
||||
rm -f "$STATE.failed.$$"
|
||||
log "fallback did not complete; probation stays and retries in a minute"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*) die "unexpected verdict: $out" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
status() {
|
||||
if [ -f "$STATE" ]; then
|
||||
python3 - "$STATE" <<'PY'
|
||||
import json, sys
|
||||
s = json.load(open(sys.argv[1]))
|
||||
print("probation running since %s; %d judged samples in the window; last %s" % (
|
||||
s.get("startedAtIso"), len(s.get("history", [])), json.dumps(s.get("last"))))
|
||||
PY
|
||||
else
|
||||
echo "no probation running"
|
||||
fi
|
||||
if [ -f "$LAST" ]; then echo "last verdict: $(cat "$LAST")"; fi
|
||||
if [ -f "$FLY_PROBATION_RESULT" ]; then echo "passed: $FLY_PROBATION_RESULT"; fi
|
||||
}
|
||||
|
||||
cmd="${1:-}"
|
||||
[ $# -gt 0 ] && shift
|
||||
case "$cmd" in
|
||||
start) start ;;
|
||||
cancel) cancel "$@" ;;
|
||||
tick) tick "$@" ;;
|
||||
status) status ;;
|
||||
simulate) [ $# = 1 ] || die "simulate CHECKS.jsonl"; python3 -c "$PROBATION_PY" simulate "$1" ;;
|
||||
*) echo "usage: fly-runtime-probation start|cancel|status|tick|simulate CHECKS.jsonl" >&2; exit 2 ;;
|
||||
esac
|
||||
630
infra/bin/fly-shadow-run
Executable file
630
infra/bin/fly-shadow-run
Executable file
|
|
@ -0,0 +1,630 @@
|
|||
#!/usr/bin/env bash
|
||||
# infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release
|
||||
# container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the
|
||||
# container, by the coordinator, with the container claimed in the host's agent claim log (one
|
||||
# agent at a time).
|
||||
#
|
||||
# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service
|
||||
# and the live-impact guard, restart flysim once. The shadow runs on a
|
||||
# build box (SHADOW-02, below); --local runs it on this container
|
||||
# instead, which the live fly paid for on 2026-09-30 (RTF 0.999 -> 0.93)
|
||||
# fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next
|
||||
# restart; --restart-flysim restarts it now), remove trace and spool
|
||||
# fly-shadow-run status the verdict in one screen
|
||||
# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
|
||||
# into the release /opt/fly/current points to, onto flysim-session.
|
||||
# --bus also requires that the shadow ran the bus topology (BUS-01)
|
||||
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
|
||||
# without the trace if the live fly pays for the shadow
|
||||
# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples
|
||||
# fly-shadow-run baseline SAMPLES.jsonl the baseline those samples give
|
||||
#
|
||||
# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once,
|
||||
# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the
|
||||
# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can
|
||||
# only follow a process from that process's own startup save.
|
||||
#
|
||||
# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a
|
||||
# minute, when the shadow's heartbeat (<trace dir>/consumer, every 30 s) is missing or older than
|
||||
# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file
|
||||
# it has compared.
|
||||
#
|
||||
# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run
|
||||
# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset
|
||||
# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed:
|
||||
# - `start` first samples the live fly over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means
|
||||
# of fly_realtime_factor and fly_lag_seconds. The BASELINE is robust: the median RTF, its
|
||||
# spread (1.4826 x the median absolute deviation) and the lag growth rate over the most recent
|
||||
# half (seconds of lag per wall second: about 1 - RTF when the loop is behind real time), so a
|
||||
# step within the window neither sets the baseline nor widens the margin. It refuses to start
|
||||
# on fewer than half the samples running.
|
||||
# - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim
|
||||
# process (a restart starts the window again) it compares the mean RTF and the lag growth
|
||||
# rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it
|
||||
# scales with how noisy this fly already was.
|
||||
# - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below
|
||||
# the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it.
|
||||
# A paused, booting or recovering fly is not judged.
|
||||
# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples;
|
||||
# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/).
|
||||
# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts
|
||||
# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow
|
||||
# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own
|
||||
# timer and changes nothing: it only ever acts against a running shadow. "No longer running" means
|
||||
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
|
||||
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
|
||||
#
|
||||
# THE BUS TOPOLOGY (BUS-01). `start --bus` runs the shadow's session the way `fly-runtime
|
||||
# session --bus` runs the live one: the router, the coordinator and the task in the shadow's own
|
||||
# process, the agent and the world as child processes (`fly-session legacy-agent`,
|
||||
# `fly-session legacy-environment`, from the same release) on the router's Unix sockets. It sets
|
||||
# FLY_SHADOW_MODE=bus/process in flyshadow.service's drop-in (mode.conf); a remote relay forwards it
|
||||
# to the box (live.env), whose shadow reads it. The verdict records the topology
|
||||
# (candidate.executionMode "process", candidate.transport "bus"), and `check --bus` refuses any
|
||||
# verdict that did not run it. The live fly must run the LEGACY runtime while a shadow runs: only
|
||||
# the legacy loop writes the trace (FLY_TRACE_DIR) the shadow follows, so `start` refuses while
|
||||
# flysim.service runs the session runtime (fly-runtime status: session).
|
||||
#
|
||||
# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
|
||||
# FLY_SHADOW_REMOTE=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
|
||||
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
|
||||
# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
|
||||
# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
|
||||
# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
|
||||
# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
|
||||
# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
|
||||
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
|
||||
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
|
||||
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
|
||||
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy, less than a minute old, of
|
||||
# this run (the drop-in's id, which the verdict must carry too), without coverageLost (flysim
|
||||
# stopped its trace for want of a consumer) and with a trace file written in the last 90 s.
|
||||
#
|
||||
# Files (all owned by fly):
|
||||
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all)
|
||||
# /srv/fly/shadow/trace/consumer the shadow's heartbeat
|
||||
# /srv/fly/shadow/spool/ copies of the live saves, bounded (512 MiB)
|
||||
# /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract)
|
||||
# /srv/fly/shadow/divergence.json the first divergence with its context
|
||||
# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl)
|
||||
# /srv/fly/shadow/guard-state.json the guard's recent samples
|
||||
# /srv/fly/shadow/relay.json remote mode: the relay's health
|
||||
set -euo pipefail
|
||||
|
||||
SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
|
||||
DROPIN_DIR=/etc/systemd/system/flysim.service.d
|
||||
DROPIN="$DROPIN_DIR/shadow-trace.conf"
|
||||
REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
|
||||
REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
|
||||
REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
|
||||
MODE_DROPIN="$REMOTE_DROPIN_DIR/mode.conf"
|
||||
RUNTIME_DROPIN="${FLY_RUNTIME_DROPIN:-$DROPIN_DIR/10-runtime.conf}"
|
||||
# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
|
||||
# restarts for the new run and the ingest hashes the release first).
|
||||
HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
|
||||
BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
|
||||
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
|
||||
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
|
||||
# The ledger digest period in transitions: about one a second. Every boundary is proved in the
|
||||
# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work.
|
||||
LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}"
|
||||
BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}"
|
||||
|
||||
die() { echo "fly-shadow-run: $*" >&2; exit 2; }
|
||||
log() { echo "fly-shadow-run: $*"; }
|
||||
|
||||
need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; }
|
||||
|
||||
# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged
|
||||
# over 10 one-second reads.
|
||||
sample() {
|
||||
python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY'
|
||||
import json, sys, time, urllib.request
|
||||
metrics_url, control_url = sys.argv[1], sys.argv[2]
|
||||
def metrics():
|
||||
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
|
||||
out = {}
|
||||
for line in text.splitlines():
|
||||
if line.startswith("#"):
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) == 2:
|
||||
try:
|
||||
out[parts[0]] = float(parts[1])
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
factors = []
|
||||
for _ in range(10):
|
||||
factors.append(metrics().get("fly_realtime_factor", 0.0))
|
||||
time.sleep(1)
|
||||
m = metrics()
|
||||
try:
|
||||
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
|
||||
except Exception:
|
||||
status = None
|
||||
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
|
||||
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
|
||||
PY
|
||||
}
|
||||
|
||||
# The guard's rule, one definition for `baseline`, `decide` and `simulate`.
|
||||
GUARD_PY='
|
||||
import json, math, sys
|
||||
WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05
|
||||
|
||||
def running(s):
|
||||
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
|
||||
|
||||
def rate(samples):
|
||||
"""Lag growth per wall second over the longest same-process run of samples."""
|
||||
best, run = None, []
|
||||
for s in samples:
|
||||
if run and s["uptime"] < run[-1]["uptime"]:
|
||||
run = []
|
||||
run.append(s)
|
||||
if len(run) >= 2 and (best is None or len(run) > len(best)):
|
||||
best = list(run)
|
||||
if not best or best[-1]["t"] <= best[0]["t"]:
|
||||
return None
|
||||
return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"]))
|
||||
|
||||
def baseline(samples):
|
||||
"""Robust statistics of the running samples: a step in the live fly within the window (its own
|
||||
warm-up, a load coming or going) must neither set the baseline nor widen the margin, as long
|
||||
as most of the window is on one side of it. The RTF is the median; its spread is 1.4826 x the
|
||||
median absolute deviation, which estimates the standard deviation without the step; the lag
|
||||
growth rate is taken over the most recent half, after any early step."""
|
||||
ok = [s for s in samples if running(s)]
|
||||
if len(ok) < max(3, len(samples) // 2):
|
||||
raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples)))
|
||||
recent = ok[len(ok) // 2:]
|
||||
rtf = sorted(s["rtMean"] for s in ok)
|
||||
median = rtf[len(rtf) // 2] if len(rtf) % 2 else (rtf[len(rtf) // 2 - 1] + rtf[len(rtf) // 2]) / 2
|
||||
dev = sorted(abs(x - median) for x in rtf)
|
||||
mad = dev[len(dev) // 2] if len(dev) % 2 else (dev[len(dev) // 2 - 1] + dev[len(dev) // 2]) / 2
|
||||
sd = 1.4826 * mad
|
||||
lag_rate = rate(recent)
|
||||
return {"rtfMean": median, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0,
|
||||
"samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))}
|
||||
|
||||
def decide(base, state, s):
|
||||
"""Returns (state, verdict); the verdict starts with ok or trip."""
|
||||
history, run = state.get("history", []), state.get("degradedRun", 0)
|
||||
if not running(s):
|
||||
return state, "ok (flysim is %s: not judged)" % s.get("status")
|
||||
if history and s["uptime"] < history[-1]["uptime"]:
|
||||
history, run = [], 0
|
||||
history = (history + [s])[-WINDOW:]
|
||||
state = {"history": history, "degradedRun": run}
|
||||
if len(history) < WINDOW:
|
||||
state["degradedRun"] = 0
|
||||
return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW)
|
||||
rtf = sum(h["rtMean"] for h in history) / WINDOW
|
||||
lag_rate = rate(history) or 0.0
|
||||
m = base["margin"]
|
||||
why = []
|
||||
if rtf < base["rtfMean"] - m:
|
||||
why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m))
|
||||
if lag_rate > base["lagRate"] + m:
|
||||
why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m))
|
||||
state["degradedRun"] = run + 1 if why else 0
|
||||
if state["degradedRun"] >= SUSTAIN:
|
||||
return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"]
|
||||
if why:
|
||||
return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why))
|
||||
return state, "ok"
|
||||
|
||||
def load_jsonl(path):
|
||||
return [json.loads(line) for line in open(path) if line.strip()]
|
||||
|
||||
mode = sys.argv[1]
|
||||
if mode == "baseline":
|
||||
print(json.dumps(baseline(load_jsonl(sys.argv[2]))))
|
||||
elif mode == "decide":
|
||||
base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3]))
|
||||
state, verdict = decide(base, state, json.load(open(sys.argv[4])))
|
||||
json.dump(state, open(sys.argv[3], "w"))
|
||||
print(verdict)
|
||||
sys.exit(1 if verdict.startswith("trip") else 0)
|
||||
elif mode == "simulate":
|
||||
base = baseline(load_jsonl(sys.argv[2]))
|
||||
state, n = {}, 0
|
||||
for n, s in enumerate(load_jsonl(sys.argv[3]), 1):
|
||||
state, verdict = decide(base, state, s)
|
||||
if verdict.startswith("trip"):
|
||||
print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base)))
|
||||
sys.exit(1)
|
||||
print("no trip over %d checks (baseline %s)" % (n, json.dumps(base)))
|
||||
'
|
||||
|
||||
# The shadow must never share a CPU with the live fly (review N2): refuse unless the unit's cpuset
|
||||
# drop-in exists (05-deploy skips every cpuset drop-in when the CT conf and CPUSET disagree) and its
|
||||
# AllowedCPUs is non-empty and disjoint from flysim.service's.
|
||||
check_cpuset() {
|
||||
local dropin="${FLY_SHADOW_CPUSET_DROPIN:-/etc/systemd/system/flyshadow.service.d/cpuset.conf}"
|
||||
[ -f "$dropin" ] || die "$dropin is missing: flyshadow would run on every CPU, including flysim's. Run 05-deploy with CPUSET set; nothing started"
|
||||
local shadow_cpus sim_cpus
|
||||
shadow_cpus="$(systemctl show -p AllowedCPUs --value flyshadow.service 2>/dev/null || true)"
|
||||
sim_cpus="$(systemctl show -p AllowedCPUs --value flysim.service 2>/dev/null || true)"
|
||||
[ -n "$shadow_cpus" ] || die "flyshadow.service has an empty AllowedCPUs; nothing started"
|
||||
[ -n "$sim_cpus" ] || die "flysim.service has an empty AllowedCPUs, so the shadow cannot be kept off it; nothing started"
|
||||
local overlap rc=0
|
||||
overlap="$(python3 -c '
|
||||
import sys
|
||||
def cpus(t):
|
||||
out = set()
|
||||
for part in t.replace(",", " ").split():
|
||||
a, _, b = part.partition("-")
|
||||
out.update(range(int(a), int(b or a) + 1))
|
||||
return out
|
||||
try:
|
||||
both = cpus(sys.argv[1]) & cpus(sys.argv[2])
|
||||
except ValueError:
|
||||
sys.exit(2)
|
||||
if both:
|
||||
print(",".join(str(c) for c in sorted(both)))
|
||||
sys.exit(1)
|
||||
' "$shadow_cpus" "$sim_cpus" 2>/dev/null)" || rc=$?
|
||||
case "$rc" in
|
||||
0) ;;
|
||||
1) die "flyshadow.service AllowedCPUs ($shadow_cpus) overlaps flysim.service's ($sim_cpus) on CPU $overlap; nothing started" ;;
|
||||
*) die "cannot parse AllowedCPUs (flyshadow '$shadow_cpus', flysim '$sim_cpus'); nothing started" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Remote mode's prerequisites, checked before anything changes.
|
||||
check_remote() {
|
||||
[ -r "$REMOTE_ENV" ] || die "$REMOTE_ENV is not readable"
|
||||
local target key known
|
||||
target="$(sed -n 's/^FLY_SHADOW_REMOTE=//p' "$REMOTE_ENV" | tail -n 1)"
|
||||
key="$(sed -n 's/^FLY_SHADOW_REMOTE_KEY=//p' "$REMOTE_ENV" | tail -n 1)"
|
||||
known="$(sed -n 's/^FLY_SHADOW_REMOTE_KNOWN_HOSTS=//p' "$REMOTE_ENV" | tail -n 1)"
|
||||
[ -n "$target" ] || die "$REMOTE_ENV sets no FLY_SHADOW_REMOTE"
|
||||
{ [ -n "$key" ] && [ -f "$key" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KEY ($key) is not a file"
|
||||
{ [ -n "$known" ] && [ -f "$known" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KNOWN_HOSTS ($known) is not a file"
|
||||
[ "$(stat -c %U "$key")" = "${FLY_SHADOW_KEY_OWNER:-fly}" ] || die "$key must be owned by fly (the relay runs as fly)"
|
||||
command -v ssh >/dev/null || die "no ssh client in this container (apt-get install openssh-client)"
|
||||
}
|
||||
|
||||
start() {
|
||||
need_root
|
||||
local mode=remote arm=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--local) mode=local ;;
|
||||
--bus) arm=bus/process ;;
|
||||
*) die "start: unknown option $arg" ;;
|
||||
esac
|
||||
done
|
||||
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
|
||||
# Only the legacy loop writes the trace the shadow follows (FLY_TRACE_DIR); the session runtime
|
||||
# ignores it, and every process it ran would be a coverage divergence.
|
||||
[ ! -f "$RUNTIME_DROPIN" ] || die "flysim.service runs the session runtime, which writes no trace for a shadow to follow. Switch the live fly to legacy for the shadow window first (fly-runtime legacy), then start the shadow"
|
||||
if [ -n "$arm" ]; then
|
||||
[ -x "$(dirname "$(readlink -f "$BIN")")/fly-session" ] || die "the bus topology needs fly-session beside $BIN"
|
||||
fi
|
||||
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
|
||||
if [ "$mode" = remote ]; then
|
||||
[ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
|
||||
check_remote
|
||||
fi
|
||||
check_cpuset
|
||||
install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace"
|
||||
# A previous run's verdict is kept beside, never read as this run's.
|
||||
if [ -f "$SHADOW_DIR/verdict.json" ]; then
|
||||
mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json"
|
||||
fi
|
||||
rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json"
|
||||
log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists"
|
||||
local n samples base
|
||||
n=$(( BASELINE_SECONDS / 10 ))
|
||||
[ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30"
|
||||
samples="$SHADOW_DIR/baseline-samples.jsonl"
|
||||
: > "$samples"
|
||||
for _ in $(seq 1 "$n"); do
|
||||
sample >> "$samples" || die "could not read flysim's metrics for the baseline"
|
||||
done
|
||||
base="$(python3 -c "$GUARD_PY" baseline "$samples")" \
|
||||
|| die "flysim did not run normally during the baseline; not starting the shadow"
|
||||
printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json"
|
||||
printf '{}\n' > "$SHADOW_DIR/guard-state.json"
|
||||
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
|
||||
log "baseline: $base"
|
||||
mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR"
|
||||
if [ -n "$arm" ]; then
|
||||
cat > "$MODE_DROPIN" <<EOF
|
||||
# written by fly-shadow-run start --bus (BUS-01); removed by fly-shadow-run stop and by its guard.
|
||||
# The shadow's session runs the bus topology; a remote relay forwards this to the box.
|
||||
[Service]
|
||||
Environment=FLY_SHADOW_MODE=$arm
|
||||
EOF
|
||||
log "the shadow runs the bus topology ($arm)"
|
||||
else
|
||||
rm -f "$MODE_DROPIN"
|
||||
fi
|
||||
if [ "$mode" = remote ]; then
|
||||
local run_id
|
||||
run_id="$(date +%s%3N)"
|
||||
[ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
|
||||
cat > "$REMOTE_DROPIN" <<EOF
|
||||
# written by fly-shadow-run start (SHADOW-02); removed by fly-shadow-run stop and by its guard.
|
||||
# The shadow runs on a build box; this unit is its relay: light, normal scheduling, off flysim's CPUs.
|
||||
[Service]
|
||||
EnvironmentFile=$REMOTE_ENV
|
||||
Environment=FLY_SHADOW_RUN_ID=$run_id
|
||||
ExecStart=
|
||||
ExecStart=$BIN relay
|
||||
CPUSchedulingPolicy=other
|
||||
Nice=5
|
||||
CPUWeight=50
|
||||
IOSchedulingClass=best-effort
|
||||
MemoryMax=1G
|
||||
EOF
|
||||
log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
|
||||
else
|
||||
rm -f "$REMOTE_DROPIN"
|
||||
log "LOCAL shadow on this container (--local)"
|
||||
fi
|
||||
cat > "$DROPIN" <<EOF
|
||||
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
|
||||
[Service]
|
||||
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
|
||||
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
|
||||
EOF
|
||||
systemctl daemon-reload
|
||||
rm -f "$SHADOW_DIR/relay.json" "$SHADOW_DIR/trace/consumer"
|
||||
systemctl start flyshadow.service
|
||||
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat (remote: the
|
||||
# relay writes it once the box's shadow of this run is alive and the sync is caught up).
|
||||
for _ in $(seq 1 "$HEARTBEAT_WAIT"); do
|
||||
[ -f "$SHADOW_DIR/trace/consumer" ] && break
|
||||
sleep 1
|
||||
done
|
||||
[ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up (remote: journalctl -u flyshadow; $SHADOW_DIR/relay.json)"; }
|
||||
log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
|
||||
systemctl restart flysim.service
|
||||
systemctl start flyshadow-guard.timer
|
||||
log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
|
||||
}
|
||||
|
||||
# Stops the shadow and the guard and turns the trace off. $1: why (logged).
|
||||
stop_all() {
|
||||
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||
systemctl stop flyshadow.service 2>/dev/null || true
|
||||
rm -f "$DROPIN" "$REMOTE_DROPIN" "$MODE_DROPIN"
|
||||
systemctl daemon-reload
|
||||
log "stopped the shadow: $1"
|
||||
}
|
||||
|
||||
stop() {
|
||||
need_root
|
||||
local restart_flysim=0 keep=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--restart-flysim) restart_flysim=1 ;;
|
||||
--keep) keep=1 ;;
|
||||
*) die "stop: unknown option $arg" ;;
|
||||
esac
|
||||
done
|
||||
stop_all "fly-shadow-run stop"
|
||||
if [ "$restart_flysim" = 1 ]; then
|
||||
systemctl restart flysim.service
|
||||
log "flysim.service restarted without the trace"
|
||||
else
|
||||
log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart"
|
||||
fi
|
||||
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
|
||||
if [ "$keep" = 0 ]; then
|
||||
rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work"
|
||||
find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true
|
||||
fi
|
||||
log "the verdict stays in $SHADOW_DIR/verdict.json"
|
||||
}
|
||||
|
||||
# "ActiveState/SubState" of a unit, from `systemctl show` (`is-active` cannot tell a crashed unit
|
||||
# waiting out its restart delay, activating/auto-restart, from a stopped one).
|
||||
unit_state() {
|
||||
local out active
|
||||
out="$(systemctl show -p ActiveState,SubState "$1" 2>/dev/null)" || true
|
||||
active="$(printf '%s\n' "$out" | sed -n 's/^ActiveState=//p')"
|
||||
# An unreadable state is not "stopped": the guard keeps running and judges the fly.
|
||||
case "$active" in
|
||||
active|inactive|failed|activating|deactivating|reloading) printf '%s\n' "$active" ;;
|
||||
*) printf 'unknown\n' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
guard() {
|
||||
need_root
|
||||
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
|
||||
log "no baseline: nothing to guard"
|
||||
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
# The guard acts only against a shadow that is up or on its way up. One that diverged, passed
|
||||
# and stopped, or was stopped costs the live fly nothing more (ActiveState inactive/failed), and
|
||||
# flysim stops its trace without the shadow's heartbeat. During the shadow's crash-restart delay
|
||||
# (Restart=on-failure, RestartSec=10) the unit is `activating` (auto-restart): the guard must
|
||||
# keep running, or the restarted shadow runs unguarded while `check` still allows a cutover
|
||||
# (SHADOW-01 review round 3, G1-a).
|
||||
local active_state
|
||||
active_state="$(unit_state flyshadow.service)"
|
||||
case "$active_state" in
|
||||
inactive|failed)
|
||||
log "flyshadow.service is $active_state: the guard stops itself and changes nothing"
|
||||
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
[ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json"
|
||||
local now tmp verdict
|
||||
now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }
|
||||
tmp="$(mktemp)"
|
||||
printf '%s\n' "$now" > "$tmp"
|
||||
if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then
|
||||
rm -f "$tmp"
|
||||
log "guard: $verdict ($now)"
|
||||
exit 0
|
||||
fi
|
||||
rm -f "$tmp"
|
||||
log "guard TRIPPED: $verdict ($now)"
|
||||
stop_all "guard: $verdict"
|
||||
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
|
||||
python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \
|
||||
"$verdict" "$now" "$SHADOW_DIR/guard-tripped.json"
|
||||
systemctl restart flysim.service
|
||||
log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json"
|
||||
}
|
||||
|
||||
status() {
|
||||
systemctl is-active flyshadow.service || true
|
||||
systemctl is-active flyshadow-guard.timer || true
|
||||
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
|
||||
if [ -f "$REMOTE_DROPIN" ] && [ -f "$SHADOW_DIR/relay.json" ]; then
|
||||
python3 - "$SHADOW_DIR/relay.json" <<'PY'
|
||||
import json, sys
|
||||
r = json.load(open(sys.argv[1]))
|
||||
print(f"remote relay: {'healthy' if r.get('healthy') else 'NOT HEALTHY'} (connected {r.get('connected')}, "
|
||||
f"box shadow alive {r.get('remoteAlive')} {r.get('remoteWhy') or ''}); caught up "
|
||||
f"{r.get('caughtUpSecondsAgo')} s ago; unsynced {r.get('unsyncedBytes')} B; updated {r.get('updatedAt')}")
|
||||
PY
|
||||
fi
|
||||
[ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
|
||||
python3 - "$SHADOW_DIR/verdict.json" <<'PY'
|
||||
import json, sys
|
||||
v = json.load(open(sys.argv[1]))
|
||||
c = v["compared"]
|
||||
print(f"verdict {v['status']}: {v['reason']}")
|
||||
print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s "
|
||||
f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}")
|
||||
print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, "
|
||||
f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}")
|
||||
print(f" checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}")
|
||||
print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}")
|
||||
if v["firstDivergence"]:
|
||||
print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
|
||||
PY
|
||||
}
|
||||
|
||||
check() {
|
||||
# `--bus` (BUS-01): the cutover goes onto the bus topology, so the shadow must have run it.
|
||||
local -a pass=()
|
||||
local arg
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--bus) pass+=(--require-arm bus/process) ;;
|
||||
*) pass+=("$arg") ;;
|
||||
esac
|
||||
done
|
||||
set -- "${pass[@]}"
|
||||
# Only the legacy loop writes the trace the shadow follows: if the live fly moved to the session
|
||||
# runtime during the window, the verdict no longer covers what would be cut over.
|
||||
if [ -f "$RUNTIME_DROPIN" ]; then
|
||||
echo "cutover refused: flysim.service runs the session runtime, which writes no trace for a shadow to follow (switch the live fly to legacy for the shadow window: fly-runtime legacy)"
|
||||
exit 1
|
||||
fi
|
||||
# A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
|
||||
# cutover, whatever the verdict file says: the guard timer must be active and its baseline
|
||||
# present (G1-a).
|
||||
if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then
|
||||
echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))"
|
||||
exit 1
|
||||
fi
|
||||
if ! systemctl is-active --quiet flyshadow.service; then
|
||||
echo "cutover refused: flyshadow.service is not running"
|
||||
exit 1
|
||||
fi
|
||||
if ! systemctl is-active --quiet flyshadow-guard.timer; then
|
||||
echo "cutover refused: flyshadow-guard.timer is not active (this run is not guarded)"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
|
||||
echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
|
||||
exit 1
|
||||
fi
|
||||
# Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
|
||||
# alive, the sync caught up), not just have relayed a pass lately; it must not have lost
|
||||
# coverage (flysim stopped its trace for want of a consumer: review B1); the live trace must be
|
||||
# being written; and the relay's, the verdict's and this run's drop-in's run ids must be one.
|
||||
# A verdict that carries a run id is a remote run's: it never stands for a local shadow.
|
||||
local why rc=0 run_id=""
|
||||
[ -f "$REMOTE_DROPIN" ] && run_id="$(sed -n 's/^Environment=FLY_SHADOW_RUN_ID=//p' "$REMOTE_DROPIN" | tail -n 1)"
|
||||
why="$(python3 - "$SHADOW_DIR/relay.json" "$SHADOW_DIR/verdict.json" "$([ -f "$REMOTE_DROPIN" ] && echo remote || echo local)" "$run_id" <<'PY'
|
||||
import datetime, json, sys
|
||||
relay_path, verdict_path, mode, run_id = sys.argv[1:5]
|
||||
def refuse(msg):
|
||||
print(msg); sys.exit(1)
|
||||
try:
|
||||
v = json.load(open(verdict_path))
|
||||
except Exception:
|
||||
v = {}
|
||||
if mode == "local":
|
||||
if v.get("runId") is not None:
|
||||
refuse("the verdict is a remote run's (run %s) but this run is local: no remote drop-in" % v.get("runId"))
|
||||
sys.exit(0)
|
||||
if not run_id:
|
||||
refuse("the remote drop-in names no FLY_SHADOW_RUN_ID")
|
||||
try:
|
||||
r = json.load(open(relay_path))
|
||||
t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
|
||||
except Exception as e:
|
||||
refuse("no readable relay.json (%s)" % e)
|
||||
# updatedAt is the container's own clock (the relay writes it here), so skew between the two hosts
|
||||
# does not reach this check; the verdict's own age check does (see the runbook: run NTP on both).
|
||||
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
|
||||
if not -60 <= age <= 60:
|
||||
refuse("relay.json is %.0f s old" % age)
|
||||
if r.get("runId") != run_id:
|
||||
refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id))
|
||||
if v.get("runId") != run_id:
|
||||
refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id))
|
||||
if v.get("window") is None:
|
||||
refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted")
|
||||
if r.get("coverageLost"):
|
||||
refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"]))
|
||||
if not r.get("healthy"):
|
||||
refuse("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or ""))
|
||||
ta = r.get("traceAgeSeconds")
|
||||
if ta is None:
|
||||
refuse("no live trace file of this run")
|
||||
if ta > 90:
|
||||
refuse("the live trace has not been written for %d s while the shadow claims to follow it (flysim paused, or its trace stopped)" % ta)
|
||||
PY
|
||||
)" || rc=$?
|
||||
if [ "$rc" != 0 ]; then
|
||||
echo "cutover refused: remote shadow: $why"
|
||||
exit 1
|
||||
fi
|
||||
[ -x "$BIN" ] || die "$BIN is missing"
|
||||
# The live service's configuration, for its compatibility string. fly.env is systemd's
|
||||
# EnvironmentFile syntax (GAME_TITLE=Pokemon Red is valid there), so it is read as KEY=VALUE
|
||||
# lines, as fly-runtime does, never sourced as shell.
|
||||
local line key value env_file="${FLY_ENV_FILE:-/etc/fly/fly.env}"
|
||||
if [ -f "$env_file" ]; then
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
|
||||
key="${line%%=*}"
|
||||
value="${line#*=}"
|
||||
value="${value%\"}"
|
||||
value="${value#\"}"
|
||||
export "${key}=${value}"
|
||||
done <"$env_file"
|
||||
fi
|
||||
# The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
|
||||
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current "${FLY_CURRENT_DIR:-/opt/fly/current}" \
|
||||
--binary flysim-session "$@"
|
||||
}
|
||||
|
||||
cmd="${1:-}"
|
||||
[ $# -gt 0 ] && shift
|
||||
case "$cmd" in
|
||||
start) start "$@" ;;
|
||||
stop) stop "$@" ;;
|
||||
status) status ;;
|
||||
check) check "$@" ;;
|
||||
guard) guard ;;
|
||||
baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;;
|
||||
simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;;
|
||||
*) echo "usage: fly-shadow-run start [--local]|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
|
||||
esac
|
||||
|
|
@ -48,6 +48,9 @@ log_info() {
|
|||
# encoder actually opened (docs/design/gpu.md section 5).
|
||||
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
|
||||
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
|
||||
# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick.
|
||||
: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}"
|
||||
: "${FLY_PROC_DIR:=/proc}"
|
||||
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
|
||||
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
|
||||
: "${FFMPEG:=/usr/bin/ffmpeg}"
|
||||
|
|
@ -156,7 +159,7 @@ write_textfile_metrics() {
|
|||
{
|
||||
echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)."
|
||||
echo "# TYPE fly_watchdog_restarts_total counter"
|
||||
for unit in flysim flystage flycast mediamtx flypush flystage-web; do
|
||||
for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do
|
||||
echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")"
|
||||
done
|
||||
# Check 7's own restart reason, kept as a separate labelset on the
|
||||
|
|
@ -174,6 +177,9 @@ write_textfile_metrics() {
|
|||
echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all."
|
||||
echo "# TYPE fly_watchdog_encoder_degraded gauge"
|
||||
echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)"
|
||||
echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend."
|
||||
echo "# TYPE fly_watchdog_backend_degraded gauge"
|
||||
echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)"
|
||||
# Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames
|
||||
# is -1 until the first probe completes, the same "unknown, not
|
||||
# broken" convention fly_watchdog_encoder_degraded uses; a value at or
|
||||
|
|
@ -326,9 +332,30 @@ is_enabled() {
|
|||
# ============================================================================
|
||||
# Check 1: flysim — /healthz 200 and hot-state mtime age < 30s.
|
||||
# ============================================================================
|
||||
# FLY_CONTROL_VIA from fly.env, lowercased ("direct" when absent).
|
||||
control_via() {
|
||||
local via=""
|
||||
if [ -f "$FLY_ENV_FILE" ]; then
|
||||
via="$(awk -F= '/^FLY_CONTROL_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
fi
|
||||
echo "${via:-direct}"
|
||||
}
|
||||
|
||||
# flysim's own /healthz: :7401 when flysim serves it, and with FLY_CONTROL_VIA=bus
|
||||
# (docs/design/flybus.md, "Control over the bus") flysim's read-only listener,
|
||||
# which flysim serves itself in both modes -- so an edge that is down is check
|
||||
# 1b's business and never restarts the fly.
|
||||
flysim_health_url() {
|
||||
if [ "$(control_via)" = "bus" ]; then
|
||||
echo "${FLY_METRICS_URL}/healthz"
|
||||
else
|
||||
echo "${FLY_CONTROL_URL}/healthz"
|
||||
fi
|
||||
}
|
||||
|
||||
check_flysim() {
|
||||
local ok=1
|
||||
if ! curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
|
||||
if ! curl -fsS -o /dev/null "$(flysim_health_url)"; then
|
||||
ok=0
|
||||
fi
|
||||
if [ -e "$FLY_STATE_HOT" ]; then
|
||||
|
|
@ -346,6 +373,24 @@ check_flysim() {
|
|||
fi
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Check 1b: flycontrol-edge -- only with FLY_CONTROL_VIA=bus. :7401/healthz
|
||||
# answered by the edge while flysim's own /healthz is fine; when the edge does
|
||||
# not answer, restart the edge (never flysim, never a reboot: the fly is fine
|
||||
# and the edge holds no state). With flysim itself down, check 1 owns it.
|
||||
# ============================================================================
|
||||
check_control_edge() {
|
||||
[ "$(control_via)" = "bus" ] || return 0
|
||||
curl -fsS -o /dev/null "${FLY_METRICS_URL}/healthz" || return 0
|
||||
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
|
||||
record_ok flycontrol-edge
|
||||
else
|
||||
record_fail flycontrol-edge
|
||||
log_err "flycontrol-edge: :7401 does not answer while flysim is healthy; restarting the edge"
|
||||
restart_unit flycontrol-edge
|
||||
fi
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Check 2: flystage — flysim's frames_sent_total / feed_clients from the
|
||||
# read-only metrics listener (infra.md section 5; not superseded by the
|
||||
|
|
@ -357,25 +402,86 @@ check_flysim() {
|
|||
# bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the
|
||||
# watchdog's own environment overrides both.
|
||||
# ============================================================================
|
||||
# `direct` or `bus`: who serves the feed RIGHT NOW. What fly.env says is what the next start of
|
||||
# flysim does; what the running flysim started with (its environment: `fly-feed status` reads the
|
||||
# same) is what is true. They differ between a deploy that changed FLY_FEED_VIA and the next
|
||||
# restart, and judging the edge in that window would restart a flysim that is serving the feed
|
||||
# itself. So: the running process when its environment can be read (flysim runs as the same user),
|
||||
# else the file. Lowercased, because flysim reads the value case-insensitively; anything else, or
|
||||
# no line, is direct.
|
||||
feed_via() {
|
||||
local via="" pid=""
|
||||
pid="$(systemctl show -p MainPID --value flysim.service 2>/dev/null | head -n1 || true)"
|
||||
if [ -n "$pid" ] && [ "$pid" != 0 ] && [ -r "${FLY_PROC_DIR}/${pid}/environ" ]; then
|
||||
via="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
elif [ -f "$FLY_ENV_FILE" ]; then
|
||||
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
fi
|
||||
if [ "$via" = "bus" ]; then echo bus; else echo direct; fi
|
||||
}
|
||||
|
||||
feed_metrics_url() {
|
||||
if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then
|
||||
echo "$FLY_FEED_METRICS_URL"
|
||||
return
|
||||
fi
|
||||
local via=""
|
||||
if [ -f "$FLY_ENV_FILE" ]; then
|
||||
# Lowercased: flysim reads the value case-insensitively, so `Bus` is bus mode.
|
||||
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
fi
|
||||
if [ "$via" = "bus" ]; then
|
||||
if [ "$(feed_via)" = "bus" ]; then
|
||||
echo "$FLY_EDGE_METRICS_URL"
|
||||
else
|
||||
echo "$FLY_METRICS_URL"
|
||||
fi
|
||||
}
|
||||
|
||||
# Check 2a (FLY_FEED_VIA=bus only): the edge itself. flyedge.service active and its /healthz 200
|
||||
# (subscribed to flysim's bus, a snapshot within the last 15 s). Not judged while flysim is down
|
||||
# or restarting (check 1's business: the edge follows it by itself), and one failed pass is let go:
|
||||
# a flysim that has only just answered may not have published yet. After that:
|
||||
# 2nd consecutive failure restart flyedge (the escalation's restart)
|
||||
# 3rd and the page and the encoder (escalate's chain)
|
||||
# 4th the edge cannot be kept up: the feed goes back to flysim, `fly-feed
|
||||
# direct --no-wait` (a restart of flysim, one stream gap, then the page
|
||||
# is served again by the process that always worked). It is logged as
|
||||
# an escalation and leaves FLY_FEED_VIA=direct until an operator
|
||||
# switches again; this check then does nothing.
|
||||
check_flyedge() {
|
||||
if [ "$(feed_via)" != "bus" ]; then
|
||||
record_ok flyedge
|
||||
return 0
|
||||
fi
|
||||
if ! curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
if is_active flyedge.service \
|
||||
&& curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
|
||||
record_ok flyedge
|
||||
return 0
|
||||
fi
|
||||
record_fail flyedge
|
||||
local n
|
||||
n="$(fail_count flyedge)"
|
||||
# From the 4th consecutive failure on, whatever the time the failures were spread over (passes
|
||||
# are skipped while flysim is down, so a flapping flysim stretches the run past any window): the
|
||||
# fallback to direct comes first and a reboot is never the answer to an edge fault. Only
|
||||
# n = 2 and 3 reach escalate (its reboot needs 5), and a failed `fly-feed direct` is retried on
|
||||
# the next pass instead of falling through to it.
|
||||
if [ "$n" -ge 4 ]; then
|
||||
log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)"
|
||||
inc_counter "escalations_total"
|
||||
sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down"
|
||||
record_ok flyedge
|
||||
elif [ "$n" -ge 2 ]; then
|
||||
escalate flyedge flystage flycast
|
||||
fi
|
||||
}
|
||||
|
||||
check_flystage() {
|
||||
local metrics frames clients ok=1
|
||||
local metrics frames clients ok=1 chain=(flycast)
|
||||
if [ "$(feed_via)" = "bus" ] && [ -z "${FLY_FEED_METRICS_URL:-}" ]; then
|
||||
# The edge serves the page. While it is down or silent that is check 2a's to fix, and a
|
||||
# restarted page would only reconnect to nothing (and count towards a reboot).
|
||||
curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null || return 0
|
||||
chain=(flyedge flycast)
|
||||
fi
|
||||
metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)"
|
||||
if [ -z "$metrics" ]; then
|
||||
ok=0
|
||||
|
|
@ -402,7 +508,7 @@ check_flystage() {
|
|||
record_ok flystage
|
||||
else
|
||||
record_fail flystage
|
||||
escalate flystage flycast
|
||||
escalate flystage "${chain[@]}"
|
||||
fi
|
||||
}
|
||||
|
||||
|
|
@ -610,6 +716,39 @@ check_encoder() {
|
|||
"and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv"
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the
|
||||
# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks
|
||||
# for the card and the CPU is what runs, the GPU fell back (operator decision
|
||||
# 2026-10-02: automatic, the stream keeps going, logged here, no paging).
|
||||
#
|
||||
# Like check 8 this takes NO remediation. A restart cannot repair a dead card
|
||||
# and costs the run its in-memory state; the fallback is a CPU run from the
|
||||
# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the
|
||||
# card to a human. fly_brain_backend is not duplicated into this file's own
|
||||
# .prom, for the reason check 8 gives.
|
||||
# ============================================================================
|
||||
check_backend() {
|
||||
local wanted live fallbacks
|
||||
if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then
|
||||
# No session worker has written it (the legacy loop, a CPU deploy, or not started yet).
|
||||
echo -1 > "${WD_RUN_DIR}/backend_degraded"
|
||||
return 0
|
||||
fi
|
||||
wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
|
||||
live="$(awk '/^fly_brain_backend\{/ && $NF == 1 {
|
||||
if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \
|
||||
"$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
|
||||
fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
|
||||
if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then
|
||||
echo 1 > "${WD_RUN_DIR}/backend_degraded"
|
||||
log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \
|
||||
"Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'"
|
||||
else
|
||||
echo 0 > "${WD_RUN_DIR}/backend_degraded"
|
||||
fi
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Check 9: capture freeze (infra/docs/capture-freeze.md).
|
||||
#
|
||||
|
|
@ -880,7 +1019,7 @@ loop_status_fields() {
|
|||
loop_macro_stream() {
|
||||
[ -f "$FLY_EVENT_LOG" ] || return 0
|
||||
tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \
|
||||
| jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \
|
||||
| jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward" or .kind == "milestone") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \
|
||||
|| true
|
||||
}
|
||||
|
||||
|
|
@ -888,13 +1027,22 @@ loop_macro_stream() {
|
|||
#
|
||||
# total US distinct US topCount US period US repeats US windowFrom US
|
||||
# windowTo US topName US block US tail US decisions US refused US blocked US
|
||||
# timeout US done US rewards US fights US wins
|
||||
# timeout US done US rewards US fights US wins US progress US species US keys
|
||||
#
|
||||
# `total` counts start events inside the window, `decisions` starts plus
|
||||
# refusals (the sequence, `distinct` and `topCount` are over decisions), and
|
||||
# the next four count each outcome in the window, and `rewards` the reward
|
||||
# events in it (row 58), `fights` the `MOVE n` decisions and `wins` the
|
||||
# rewards of kind wildwin/trainer/badge (row 67). `period`/`repeats` describe
|
||||
# rewards of kind wildwin/trainer/badge (row 67). `progress` counts the lasting
|
||||
# progress in the window (row 70): a `milestone` event (a new rung), or a reward of kind
|
||||
# pokedex (a species owned for the first time), area (a map entered for the first time),
|
||||
# trainer or badge -- each paid once per run, so a ring cannot earn them twice -- and
|
||||
# `species` the pokedex ones alone. `keys` names each of them once as `kind:label`
|
||||
# (`pokedex:OWNED #8`, `milestone:Reached MT. MOON`), RS-joined, at most 64: a milestone
|
||||
# reset restores the reward ledger, so its replay pays the same rewards again, and only
|
||||
# the names tell a replayed reward from a new one. They are reported, never read by a
|
||||
# rule here: the recovery ladder uses them to tell a trap that follows real progress from
|
||||
# one that outlived its last step. `period`/`repeats` describe
|
||||
# the shortest repeating block at the END of the sequence (0/0 when nothing
|
||||
# repeats), `block` is that block comma-joined, and `tail` is the last 12
|
||||
# names for context. The window ends at the newest macro event's own brain
|
||||
|
|
@ -903,17 +1051,28 @@ loop_analyze() {
|
|||
awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" '
|
||||
# Reward lines are counted and nothing else: the window still ends at the
|
||||
# newest macro event, as it always has.
|
||||
$3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; next }
|
||||
$3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; rlbl[nr] = $2; next }
|
||||
$3 == "milestone" { rms[++nr] = $1 + 0; rkind[nr] = "milestone"; rlbl[nr] = $2; next }
|
||||
{ ms[++n] = $1 + 0; lbl[n] = $2 }
|
||||
END {
|
||||
if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\n"; exit }
|
||||
if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\0370\0370\037\n"; exit }
|
||||
to = ms[n]; from = to - win
|
||||
k = 0; distinct = 0; topn = 0; top = ""
|
||||
starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0
|
||||
fights = 0; wins = 0
|
||||
fights = 0; wins = 0; progress = 0; species = 0; keys = ""; nkeys = 0
|
||||
for (q = 1; q <= nr; q++) if (rms[q] >= from) {
|
||||
lasting = rkind[q] == "milestone" || rkind[q] == "pokedex" || rkind[q] == "area" \
|
||||
|| rkind[q] == "trainer" || rkind[q] == "badge"
|
||||
if (lasting) {
|
||||
progress++
|
||||
key = rkind[q] ":" rlbl[q]
|
||||
gsub(/[\036\037]/, " ", key)
|
||||
if (!(key in seenkey) && nkeys < 64) { seenkey[key] = 1; keys = keys (nkeys++ ? "\036" : "") key }
|
||||
}
|
||||
if (rkind[q] == "milestone") continue
|
||||
rewards++
|
||||
if (rkind[q] == "wildwin" || rkind[q] == "trainer" || rkind[q] == "badge") wins++
|
||||
if (rkind[q] == "pokedex") species++
|
||||
}
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (ms[i] < from) continue
|
||||
|
|
@ -948,9 +1107,9 @@ loop_analyze() {
|
|||
tailstr = ""
|
||||
start = k - 11; if (start < 1) start = 1
|
||||
for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j]
|
||||
printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\n", \
|
||||
printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\n", \
|
||||
starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \
|
||||
k, refused, blocked, timeout, done, rewards, fights, wins
|
||||
k, refused, blocked, timeout, done, rewards, fights, wins, progress, species, keys
|
||||
}'
|
||||
}
|
||||
|
||||
|
|
@ -1008,15 +1167,15 @@ check_loop() {
|
|||
echo "$delta" > "${WD_RUN_DIR}/loop.places_delta"
|
||||
|
||||
local analysis total distinct topn period repeats win_from win_to top block tailstr
|
||||
local decisions refused blocked timeouts completed rewards fights wins
|
||||
local decisions refused blocked timeouts completed rewards fights wins progress species keys
|
||||
analysis="$(loop_macro_stream | loop_analyze)"
|
||||
IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \
|
||||
decisions refused blocked timeouts completed rewards fights wins <<< "$analysis"
|
||||
decisions refused blocked timeouts completed rewards fights wins progress species keys <<< "$analysis"
|
||||
total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}"
|
||||
period="${period:-0}"; repeats="${repeats:-0}"
|
||||
decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}"
|
||||
timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}"
|
||||
fights="${fights:-0}"; wins="${wins:-0}"
|
||||
fights="${fights:-0}"; wins="${wins:-0}"; progress="${progress:-0}"; species="${species:-0}"
|
||||
echo "$distinct" > "${WD_RUN_DIR}/loop.distinct"
|
||||
echo "$period" > "${WD_RUN_DIR}/loop.period"
|
||||
echo "$repeats" > "${WD_RUN_DIR}/loop.repeats"
|
||||
|
|
@ -1130,6 +1289,9 @@ check_loop() {
|
|||
--argjson rewards "$rewards" \
|
||||
--argjson fights "$fights" \
|
||||
--argjson wins "$wins" \
|
||||
--argjson progress "$progress" \
|
||||
--argjson species "$species" \
|
||||
--arg keys "${keys:-}" \
|
||||
--argjson windowFrom "${win_from:-0}" \
|
||||
--argjson windowTo "${win_to:-0}" \
|
||||
--argjson windowMs "$WD_LOOP_WINDOW_MS" \
|
||||
|
|
@ -1161,6 +1323,8 @@ check_loop() {
|
|||
rewards: $rewards,
|
||||
fights: $fights,
|
||||
wins: $wins,
|
||||
progress: { lasting: $progress, species: $species,
|
||||
keys: (if $keys == "" then [] else ($keys | split("\u001e")) end) },
|
||||
tail: (if $tail == "" then [] else ($tail | split(", ")) end)
|
||||
},
|
||||
dominant: { name: (if $dominant == "" then null else $dominant end),
|
||||
|
|
@ -1202,9 +1366,12 @@ check_loop() {
|
|||
|
||||
main() {
|
||||
check_flysim
|
||||
check_flyedge
|
||||
check_control_edge
|
||||
check_flystage
|
||||
check_flycast
|
||||
check_encoder
|
||||
check_backend
|
||||
check_mediamtx
|
||||
check_flypush
|
||||
check_disk
|
||||
|
|
|
|||
147
infra/box/fly-shadow-remote-setup
Executable file
147
infra/box/fly-shadow-remote-setup
Executable file
|
|
@ -0,0 +1,147 @@
|
|||
#!/usr/bin/env bash
|
||||
# infra/box/fly-shadow-remote-setup — prepare a BUILD BOX to run the remote shadow (SHADOW-02).
|
||||
# Run as root ON THE BOX (never on the release container, never on the host), by the coordinator.
|
||||
# Idempotent: re-run it for every release the container runs.
|
||||
#
|
||||
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]
|
||||
#
|
||||
# RELEASE_TARBALL the exact flybrain-<version>.tar.gz deployed to the release container. It is
|
||||
# installed at the SAME path, /opt/fly/releases/<version>, MANIFEST-verified,
|
||||
# root-owned, and /opt/fly/current points to it: the shadow's verdict names
|
||||
# that directory and the SHA-256 of its binaries, and `fly-shadow ingest`
|
||||
# refuses a relay whose release differs.
|
||||
# ROM_FILE the cartridge; its SHA-256 must be the container's ROM_SHA256.
|
||||
# RELAY_PUBKEY the public half of the relay's key (the private half lives only on the
|
||||
# release container, /etc/fly/shadow-remote/id_ed25519, owned by fly).
|
||||
# --from ADDRS REQUIRED: restricts the key to the container's address (authorized_keys from=).
|
||||
# --cpus LIST AllowedCPUs for the shadow, a drop-in: its own cores, never shared with the
|
||||
# live fly's NUMA node.
|
||||
# --threads N the shadow's sweep threads (default 4; one per core in --cpus). It must run
|
||||
# clearly faster than real time: see the runbook's "Which box".
|
||||
#
|
||||
# What it sets up:
|
||||
# - user flyshadow, the mirror /srv/fly-shadow-remote (flyshadow's; 0750) and, apart from it, the
|
||||
# user's home /srv/fly-shadow-remote-home, ROOT-owned with a root-owned .ssh: flyshadow can
|
||||
# neither change nor rename the key file (in a home it owned, it could rename .ssh);
|
||||
# - /srv/fly-shadow-remote-home/.ssh/authorized_keys, ROOT-owned, with one
|
||||
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="..." <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
|
||||
# ignores what the client asks for; the ingest writes nothing outside the mirror;
|
||||
# - /etc/fly/fly-shadow-remote.env: FLY_ROM, FLY_DATASET (this box's paths);
|
||||
# - flyshadow-remote.service and flyshadow-remote.path (enabled; the service starts at the first
|
||||
# run id the relay brings).
|
||||
# A re-run never follows a symlink under the mirror (flyshadow owns it and could plant one): it
|
||||
# refuses if any of the mirror's paths is a symlink, and leaves an existing directory as it is.
|
||||
# The release container's address is only in authorized_keys (from=); the relay dials out to the box.
|
||||
set -euo pipefail
|
||||
|
||||
die() { echo "fly-shadow-remote-setup: $*" >&2; exit 2; }
|
||||
log() { echo "fly-shadow-remote-setup: $*"; }
|
||||
|
||||
[ "$(id -u)" = 0 ] || die "run as root on the build box"
|
||||
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]"
|
||||
tarball="$1"; rom="$2"; pubkey="$3"; shift 3
|
||||
from=""; cpus=""; threads=4
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--from) from="$2"; shift 2 ;;
|
||||
--cpus) cpus="$2"; shift 2 ;;
|
||||
--threads) threads="$2"; shift 2 ;;
|
||||
*) die "unknown option $1" ;;
|
||||
esac
|
||||
done
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT=/srv/fly-shadow-remote
|
||||
HOME_DIR=/srv/fly-shadow-remote-home
|
||||
[ -n "$from" ] || die "--from is required: the relay key must be restricted to the container's address"
|
||||
[ -f "$tarball" ] || die "no tarball $tarball"
|
||||
[ -f "$rom" ] || die "no ROM $rom"
|
||||
[ -f "$pubkey" ] || die "no public key $pubkey"
|
||||
base="$(basename "$tarball")"; version="${base#flybrain-}"; version="${version%.tar.gz}"
|
||||
[[ "$version" =~ ^[A-Za-z0-9._-]+$ ]] || die "cannot parse a version from $base"
|
||||
[[ "$from" =~ ^[0-9A-Fa-f.:,/*]*$ ]] || die "--from takes addresses or patterns only"
|
||||
[[ "$cpus" =~ ^[0-9,-]*$ ]] || die "--cpus takes a CPU list"
|
||||
[[ "$threads" =~ ^[1-9][0-9]?$ ]] || die "--threads takes a number"
|
||||
key="$(head -n 1 "$pubkey")"
|
||||
[[ "$key" =~ ^ssh-(ed25519|rsa)\ [A-Za-z0-9+/=]+( [^\"]*)?$ ]] || die "$pubkey is not one ssh public key line"
|
||||
command -v sshd >/dev/null || [ -x /usr/sbin/sshd ] || die "this box has no sshd"
|
||||
|
||||
# The release, exactly as 05-deploy installs it on the container (but root-owned here).
|
||||
release="/opt/fly/releases/${version}"
|
||||
if [ -f "$release/MANIFEST" ]; then
|
||||
log "release $version already at $release"
|
||||
else
|
||||
install -d -m 0755 "$release"
|
||||
tar -xzf "$tarball" -C "$release"
|
||||
chown -R root:root "$release"
|
||||
fi
|
||||
(cd "$release" && sha256sum -c MANIFEST --quiet) || die "MANIFEST verification failed for $release"
|
||||
[ -x "$release/fly-shadow" ] || die "$release has no fly-shadow: this release predates SHADOW-01"
|
||||
# The bare subcommand exits 2 (usage); under pipefail a pipe into grep would fail on that, so capture.
|
||||
probe="$("$release/fly-shadow" ingest 2>&1 || true)"
|
||||
printf '%s' "$probe" | grep -q 'needs --root' \
|
||||
|| die "$release/fly-shadow has no ingest: this release predates SHADOW-02"
|
||||
ln -sfn "$release" /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current
|
||||
log "/opt/fly/current -> $release"
|
||||
|
||||
# The user, the mirror and the user's home. The home and its .ssh are root's; the mirror is
|
||||
# flyshadow's, so nothing in it is trusted: no symlink is followed there, as root.
|
||||
[ -L "$ROOT" ] && die "$ROOT is a symlink: refusing to follow it"
|
||||
[ -L "$HOME_DIR" ] && die "$HOME_DIR is a symlink: refusing to follow it"
|
||||
if id flyshadow >/dev/null 2>&1; then
|
||||
[ "$(getent passwd flyshadow | cut -d: -f6)" = "$HOME_DIR" ] || usermod --home "$HOME_DIR" flyshadow
|
||||
else
|
||||
useradd --system --home-dir "$HOME_DIR" --no-create-home --shell /bin/sh --user-group flyshadow
|
||||
fi
|
||||
if [ -e "$ROOT" ]; then
|
||||
[ -d "$ROOT" ] || die "$ROOT is not a directory"
|
||||
else
|
||||
mkdir -m 0750 "$ROOT"
|
||||
chown -h flyshadow:flyshadow "$ROOT"
|
||||
fi
|
||||
for d in trace hot durable out; do
|
||||
[ -L "$ROOT/$d" ] && die "$ROOT/$d is a symlink: refusing to follow it"
|
||||
if [ -e "$ROOT/$d" ]; then
|
||||
[ -d "$ROOT/$d" ] || die "$ROOT/$d is not a directory"
|
||||
else
|
||||
mkdir -m 0750 "$ROOT/$d"
|
||||
chown -h flyshadow:flyshadow "$ROOT/$d"
|
||||
fi
|
||||
done
|
||||
# An earlier version of this script kept .ssh in the mirror, where flyshadow could rename it.
|
||||
if [ -e "$ROOT/.ssh" ] || [ -L "$ROOT/.ssh" ]; then rm -rf "$ROOT/.ssh"; fi
|
||||
if [ -L "$HOME_DIR/.ssh" ]; then rm -f "$HOME_DIR/.ssh"; fi
|
||||
install -d -o root -g root -m 0755 "$HOME_DIR"
|
||||
install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"
|
||||
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\",from=\"$from\""
|
||||
printf '%s %s\n' "$line" "$key" > "$HOME_DIR/.ssh/authorized_keys.new"
|
||||
chown root:root "$HOME_DIR/.ssh/authorized_keys.new"; chmod 0644 "$HOME_DIR/.ssh/authorized_keys.new"
|
||||
mv -f "$HOME_DIR/.ssh/authorized_keys.new" "$HOME_DIR/.ssh/authorized_keys"
|
||||
log "authorized_keys: the relay key may run only the ingest"
|
||||
|
||||
# The cartridge and this box's paths.
|
||||
rom_sha="$(sha256sum "$rom" | cut -d' ' -f1)"
|
||||
install -d -m 0755 /srv/fly/rom
|
||||
install -o root -g flyshadow -m 0640 "$rom" "/srv/fly/rom/${rom_sha}.gb"
|
||||
install -d -m 0755 /etc/fly
|
||||
cat > /etc/fly/fly-shadow-remote.env <<ENV
|
||||
# written by infra/box/fly-shadow-remote-setup (SHADOW-02): this box's paths for the remote shadow.
|
||||
FLY_ROM=/srv/fly/rom/${rom_sha}.gb
|
||||
FLY_DATASET=/opt/fly/current/data/fafb-v783
|
||||
ENV
|
||||
log "ROM sha256 $rom_sha (must equal the container's ROM_SHA256)"
|
||||
|
||||
# The units.
|
||||
install -m 0644 "$here/flyshadow-remote.service" /etc/systemd/system/flyshadow-remote.service
|
||||
install -m 0644 "$here/flyshadow-remote.path" /etc/systemd/system/flyshadow-remote.path
|
||||
install -d -m 0755 /etc/systemd/system/flyshadow-remote.service.d
|
||||
{
|
||||
printf '# written by fly-shadow-remote-setup\n[Service]\nEnvironment=FLY_SHADOW_THREADS=%s\n' "$threads"
|
||||
[ -n "$cpus" ] && printf 'AllowedCPUs=%s\n' "$cpus"
|
||||
} > /etc/systemd/system/flyshadow-remote.service.d/10-cores.conf
|
||||
log "${threads} threads${cpus:+ on CPUs $cpus}"
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now flyshadow-remote.path
|
||||
systemctl enable flyshadow-remote.service
|
||||
# A running shadow of an older release restarts on this one (the relay's next run resets anyway).
|
||||
systemctl try-restart flyshadow-remote.service || true
|
||||
log "ready: the container's fly-shadow-run start brings the first run id"
|
||||
13
infra/box/flyshadow-remote.path
Normal file
13
infra/box/flyshadow-remote.path
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# infra/box/flyshadow-remote.path — installed on a BUILD BOX with flyshadow-remote.service
|
||||
# (SHADOW-02). A new run id (the container's `fly-shadow-run start`, written by the ingest) starts
|
||||
# the shadow when it is down: the first run, or after a divergence (exit 3 is not restarted). A
|
||||
# running shadow restarts itself on the change (exit 4, Restart=always).
|
||||
[Unit]
|
||||
Description=Start the remote shadow for a new run (SHADOW-02)
|
||||
|
||||
[Path]
|
||||
PathChanged=/srv/fly-shadow-remote/run-id
|
||||
Unit=flyshadow-remote.service
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
55
infra/box/flyshadow-remote.service
Normal file
55
infra/box/flyshadow-remote.service
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
|
||||
# by infra/box/fly-shadow-remote-setup (SHADOW-02).
|
||||
#
|
||||
# The shadow run (SHADOW-01, legacy-gameboy-v1 section 18) moved off the release container: there it
|
||||
# cost the live fly real time (2026-09-30: RTF 0.999 -> 0.93-0.98 with the shadow SCHED_IDLE on the
|
||||
# page and encoder CPUs, 27 ms of shadow per frame, falling further behind every hour). Here it runs
|
||||
# the SAME release (installed from the same tarball at the same /opt/fly/releases/<version> path,
|
||||
# so the verdict's release and binary hashes are the container's), on this box's own cores, at
|
||||
# normal priority.
|
||||
#
|
||||
# Its input is the mirror /srv/fly-shadow-remote, written by `fly-shadow ingest`, the forced
|
||||
# command of the one key the container's relay (`fly-shadow relay`, flyshadow.service there) holds;
|
||||
# the relay writes this shadow's verdict back to the container, where `fly-shadow-run check`, its
|
||||
# guard and CUT-01 read it as before. REPORT-ONLY: it reads the mirror, writes <root>/out and its
|
||||
# runtime directory, and serves nothing.
|
||||
#
|
||||
# The run: `fly-shadow-run start` on the container gives each run an id; the ingest writes it to
|
||||
# <root>/run-id (after resetting the mirror). A running shadow sees the change within 5 s and exits
|
||||
# with status 4, and Restart=always starts the new run; a shadow that is down (it diverged: exit 3,
|
||||
# which is not restarted, so the diverged verdict stays) is started by flyshadow-remote.path.
|
||||
[Unit]
|
||||
Description=flyshadow-remote: the session runtime shadowing the live fly from a build box (SHADOW-02, report only)
|
||||
ConditionPathExists=/opt/fly/current/fly-shadow
|
||||
ConditionPathExists=/srv/fly-shadow-remote/run-id
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=flyshadow
|
||||
# The live composition's settings, as the relay forwarded them (game, macro mode, accepted
|
||||
# adapters, pins; never a path or a secret), then this box's own paths: FLY_ROM (the cartridge,
|
||||
# with the container's ROM_SHA256) and FLY_DATASET (the release's connectome).
|
||||
EnvironmentFile=-/srv/fly-shadow-remote/live.env
|
||||
EnvironmentFile=/etc/fly/fly-shadow-remote.env
|
||||
Environment=FLY_TRACE_DIR=/srv/fly-shadow-remote/trace
|
||||
Environment=FLY_STATE_HOT=/srv/fly-shadow-remote/hot
|
||||
Environment=FLY_STATE=/srv/fly-shadow-remote/durable
|
||||
Environment=FLY_SHADOW_DIR=/srv/fly-shadow-remote/out
|
||||
Environment=FLY_SHADOW_WORK=/run/flyshadow-remote
|
||||
RuntimeDirectory=flyshadow-remote
|
||||
# 3 sweep threads (the SHADOW-01 measurements: 13-15 ms a frame against 16.7 ms of real time).
|
||||
Environment=FLY_SHADOW_THREADS=3
|
||||
# No lag back-off: the live fly is on another machine. The spool holds a long catch-up.
|
||||
ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0 --spool-max-mib 4096
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
RestartPreventExitStatus=3
|
||||
# Dedicated cores (fly-shadow-remote-setup --cpus writes AllowedCPUs= in a drop-in) at a weight
|
||||
# above anything else on the box: a build must not starve the shadow.
|
||||
CPUWeight=1000
|
||||
Nice=-5
|
||||
MemoryMax=6G
|
||||
TimeoutStopSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -85,6 +85,16 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
|
|||
# without a rebuild. It lands next to OUT_PATH, where package-release.sh
|
||||
# looks for it.
|
||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
|
||||
# fly-control-edge (FLY_CONTROL_VIA=bus, CTRL-01): the control API served from
|
||||
# flysim's control services on the bus. Same reasons, same place.
|
||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-control-edge
|
||||
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
|
||||
# that `fly-runtime session` points flysim.service at; fly-shadow (SHADOW-01,
|
||||
# infra/units/flyshadow.service): the session runtime shadowing the live fly; and
|
||||
# fly-session, their worker program (FLY_SESSION_MODE=process only). Same features as flysim,
|
||||
# built every time so a release can switch runtimes without a rebuild. All land next to
|
||||
# OUT_PATH, where package-release.sh looks for them.
|
||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-shadow --bin fly-session "${features_args[@]}"
|
||||
)
|
||||
|
||||
built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
|
||||
|
|
@ -118,4 +128,18 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
|
|||
cp "$edge_built" "$edge_out"
|
||||
chmod 0755 "$edge_out"
|
||||
log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
|
||||
control_edge_built="${crate_dir}/target/${CARGO_TARGET}/release/fly-control-edge"
|
||||
[ -x "$control_edge_built" ] || die "expected binary not found after build: $control_edge_built"
|
||||
control_edge_out="$(dirname "$OUT_PATH")/fly-control-edge"
|
||||
cp "$control_edge_built" "$control_edge_out"
|
||||
chmod 0755 "$control_edge_out"
|
||||
log "built $control_edge_out ($(du -h "$control_edge_out" | cut -f1))"
|
||||
for extra in flysim-session fly-shadow fly-session; do
|
||||
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
|
||||
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
|
||||
extra_out="$(dirname "$OUT_PATH")/${extra}"
|
||||
cp "$extra_built" "$extra_out"
|
||||
chmod 0755 "$extra_out"
|
||||
log "built $extra_out ($(du -h "$extra_out" | cut -f1))"
|
||||
done
|
||||
log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>"
|
||||
|
|
|
|||
|
|
@ -14,6 +14,14 @@
|
|||
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
|
||||
# left one beside FLYSIM_BIN; flyedge.service stays
|
||||
# inactive on a release without it)
|
||||
# fly-control-edge (the control-bus edge, CTRL-01, likewise;
|
||||
# flycontrol-edge.service stays inactive without it)
|
||||
# flysim-session (the session runtime, SERVE-01, and fly-session, its
|
||||
# fly-shadow worker program; mode 0755, when build-flysim.sh left
|
||||
# fly-session them beside FLYSIM_BIN. `fly-runtime session` refuses
|
||||
# a release without flysim-session. fly-shadow is
|
||||
# SHADOW-01's shadow; flyshadow.service stays inactive
|
||||
# on a release without it)
|
||||
# stage/... (apps/stage's build output)
|
||||
# bridge/... (services/bridge + node_modules)
|
||||
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
|
||||
|
|
@ -82,6 +90,25 @@ if [ -x "$EDGE_BIN" ]; then
|
|||
else
|
||||
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
|
||||
fi
|
||||
CONTROL_EDGE_BIN="$(dirname "$FLYSIM_BIN")/fly-control-edge"
|
||||
if [ -x "$CONTROL_EDGE_BIN" ]; then
|
||||
cp "$CONTROL_EDGE_BIN" "${release_dir}/fly-control-edge"
|
||||
chmod 0755 "${release_dir}/fly-control-edge"
|
||||
else
|
||||
log "no fly-control-edge beside $FLYSIM_BIN; packaging without it (FLY_CONTROL_VIA=bus unavailable in this release)"
|
||||
fi
|
||||
for extra in flysim-session fly-shadow fly-session; do
|
||||
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
|
||||
if [ -x "$EXTRA_BIN" ]; then
|
||||
cp "$EXTRA_BIN" "${release_dir}/${extra}"
|
||||
chmod 0755 "${release_dir}/${extra}"
|
||||
else
|
||||
case "$extra" in
|
||||
fly-shadow) log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" ;;
|
||||
*) log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)" ;;
|
||||
esac
|
||||
fi
|
||||
done
|
||||
cp -a "$STAGE_DIR" "${release_dir}/stage"
|
||||
cp -a "$BRIDGE_DIR" "${release_dir}/bridge"
|
||||
|
||||
|
|
|
|||
|
|
@ -6,17 +6,22 @@
|
|||
# <unit>` and, on the 5-consecutive-failure escalation, a container
|
||||
# reboot. This is the minimum NOPASSWD surface for exactly what
|
||||
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
|
||||
# mediamtx, flypush), plus reboot. No `systemctl stop`, no
|
||||
# mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
|
||||
# `enable`/`disable`, no arbitrary unit name, and no units this script
|
||||
# does not itself restart (xvfb, pulse, flystage-web are never touched by
|
||||
# fly-watchdog's checks, so they are not granted here).
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge.service
|
||||
fly ALL=(root) NOPASSWD: /usr/sbin/reboot
|
||||
# fly-loop-recover.service (also User=fly): its ladder restarts flysim (granted above) and
|
||||
# resets to a milestone archive through this one root wrapper, which validates the rung,
|
||||
# stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md).
|
||||
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset
|
||||
# Watchdog check 2a (FLY_FEED_VIA=bus): an edge that restarts cannot fix puts the feed back on
|
||||
# flysim, with exactly these arguments and nothing else (infra/bin/fly-feed).
|
||||
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ d /run/fly/wd 0750 fly fly -
|
|||
# ADDED: the feed bus (FLY_FEED_VIA=bus, docs/design/flybus.md): flysim's
|
||||
# router socket and artifact store. flysim also creates it, 0700, on start.
|
||||
d /run/fly/bus 0700 fly fly -
|
||||
# The session runtime's router store and worker sockets (SERVE-01, flysim-session).
|
||||
d /run/fly/session 0700 fly fly -
|
||||
d /var/lib/fly 0750 fly fly -
|
||||
d /var/lib/fly/chrome 0700 fly fly -
|
||||
d /srv/fly/state 0750 fly fly -
|
||||
|
|
|
|||
|
|
@ -16,9 +16,35 @@ a ladder one step per trap that outlives the previous step:
|
|||
their 10-brain-minute window lies after it. The helper waits that long after every step.
|
||||
- **Budget:** at most two milestone resets per 24 hours. With the budget spent the step is a
|
||||
restart, at most every three hours, until a reset is free again. The same three-hour spacing applies
|
||||
when a reset level finds no restorable rung and restarts instead.
|
||||
- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, or after
|
||||
six hours with no suspected report.
|
||||
when a reset level finds no restorable rung and restarts instead, and between any two restarts in a
|
||||
row, also when the ladder has started over in between.
|
||||
- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, after
|
||||
six hours with no suspected report, or when the fly makes new lasting progress more than
|
||||
20 minutes after the last step and a clear probe shows the old trap let go (row 70). Lasting
|
||||
progress is the watchdog's `window.progress`: a rung reached, a species owned, a map entered, or
|
||||
a trainer or badge beaten, each named in `window.progress.keys` as `kind:label` (`pokedex:OWNED
|
||||
#41`). A ring cannot earn them twice, but a milestone reset restores the reward ledger, so its
|
||||
replay pays the archive's rewards again. Progress is therefore measured against every name the
|
||||
ladder has seen (`progressSeen` in the state file, the last 2,000), not against the restored
|
||||
archive: a replay re-earning what the run had before the reset is not progress, and the ladder
|
||||
climbs on to the rung below as it did before row 70. A trap that follows new progress is a new
|
||||
trap, and it starts again from a restart. A catch made while the fly stays flagged is not a new
|
||||
trap. With a watchdog that reports no names, the counts are used as before.
|
||||
Names the ladder never saw (before this version was deployed, or while an older one ran) count
|
||||
as new once.
|
||||
- **Protected catches:** a milestone reset never erases a species first owned in the last two hours
|
||||
(`PROTECT`, a `pokedex:` name not seen before). A species a reset's replay owns again was the fly's
|
||||
before the reset and was protected then, so it does not open a second window. Within that window the step is a restart, spaced by
|
||||
the hold like a spent budget, and `history.jsonl` records a `protect` event. A reset turned into a
|
||||
restart this way does not climb the ladder: the level keeps its slot and the reset comes, at the
|
||||
same rung, once the window ends. Evolution also counts as a species owned.
|
||||
- **No archive twice in a row:** a reset never restores the same archive as the last reset,
|
||||
until a new best rung is reached or twelve hours have passed (`AGAIN`; a trap no restart clears
|
||||
is reset again in bounded time, no later than before this rule). Such a step does climb, so the rung below is reached promptly. A restore is deterministic, so the same archive replays the
|
||||
same run into the same trap. Row 70's second reset to rung 11 matched the first one event for
|
||||
event: the same Zubat caught, the same trap an hour later, and the catch erased. That step is
|
||||
a restart instead. A reset that fails does not mark its archive: it is not known to have been
|
||||
restored, so the next reset may try it again.
|
||||
|
||||
A milestone step only uses an archive the running build can restore. `fly-loop-reset --list`
|
||||
compares each archive's compatibility string with `flysim --print-compatibility` and accepts an
|
||||
|
|
|
|||
|
|
@ -3552,3 +3552,246 @@ starting state, as row 66's did: four rung-9 checkpoints with one ball each.
|
|||
after the keyboard because its frames after the catch differ from a69a258's (the keyboard took
|
||||
28 brain seconds instead of `NEXT`'s few), not because anything waited: 635 macros started, 633
|
||||
done, one refusal and one timeout, against 803, 802, one and one.
|
||||
|
||||
## 2026-09-29, row 68: the damage reward, the catalog's answer to row 67
|
||||
|
||||
Row 67 (the Pewter Gym's Jr. Trainer lost on repeat, TAIL WHIP 155 / BUBBLE 23 / TACKLE 0) is a
|
||||
readout choice, not a pad fault. The operator chose a catalog change over a pad rule: `damage`,
|
||||
adapter `pokered-unique8-v8` (`docs/rewards-learning.md`, "Damage rewards"). It pays for the HP the
|
||||
fly's own attack removes; it does not touch the pad.
|
||||
|
||||
### The survey
|
||||
|
||||
The real brain, macros mode, from the row 67 checkpoint, 120 brain minutes per arm, `v7` (main)
|
||||
against `v8` (the rule), on the stream's own frame (`LegacyFrame`). The palette seed turned out not
|
||||
to diversify a run (seeds 1, 2 and 3 were identical per arm), so the three pairs are three starts:
|
||||
the checkpoint as it is, and the checkpoint with the game run 7 and 19 frames ahead of the brain.
|
||||
Each pair is identical until the first damage payout.
|
||||
|
||||
| start | arm | trainer battles | won | BUBBLE share, first 40 / last 40 min | damage paid | rung |
|
||||
| --- | --- | ---: | ---: | --- | ---: | --- |
|
||||
| +0 | v7 | 68 | 0 | 14% / 17% | -- | 10 |
|
||||
| +0 | v8 | 58 | 3 (Jr. Trainer at 101 min, Brock at 107, a Route 3 trainer at 112) | 15% / 20% | 6.01 | **11, BOULDER BADGE** |
|
||||
| +7 | v7 | 65 | 0 | 16% / 21% | -- | 10 |
|
||||
| +7 | v8 | 67 | 0 | 14% / 14% | 3.41 | 10 |
|
||||
| +19 | v7 | 60 | 0 | 15% / 24% | -- | 10 |
|
||||
| +19 | v8 | 59 | 1 (Jr. Trainer at 119.6 min) | 16% / 22% | 6.74 | 10 |
|
||||
|
||||
TACKLE stayed at 0 to 2 choices a run in every arm.
|
||||
|
||||
**What it shows.** The rule fires where it should: every `v8` arm was paid for BUBBLE's hits and
|
||||
nothing for TAIL WHIP's, 3.4 to 6.7 over two hours, capped per battle. `v8` beat the trainer in 2
|
||||
of 3 starts and `v7` in 0 of 3 (and the live run 0 of 29). **What it does not show** is the
|
||||
mechanism the rule is for: the move choice did not move more under `v8` than under `v7`. BUBBLE
|
||||
drifted from about 15% to about 20% in both arms, and TAIL WHIP stayed near 80% everywhere. So
|
||||
inside two brain hours the wins are not explained by a learned preference; a paid hit also changes
|
||||
the brain's activity (the PAM stimulation) and the trajectory, and three starts cannot tell a small
|
||||
real effect from luck. Learning is too slow to show in this window, or not happening, and the
|
||||
survey cannot say which.
|
||||
|
||||
**Status: shipped as the operator decided, not a fix.** The trap is still possible under it: one of
|
||||
three `v8` starts never won. Row 67's watchdog check 10 (`unwon-battles`, on its branch) is the
|
||||
detector, and the pad rule the operator declined is the lever that still exists.
|
||||
|
||||
## 2026-09-30, row 70: Mt. Moon, the SHIFT offer's party list, and the ladder that took the catch
|
||||
|
||||
### What was live
|
||||
|
||||
On v0.7.0 with adapter v8, the ladder reset the run to rung 11 at 16:54Z. The rung-11 archive
|
||||
replayed deterministically: Route 3's trainers, Mt. Moon (rung 12) at 17:40, a Poké Ball bought,
|
||||
thrown, and a Zubat caught at 17:47 (`OWNED #41`, `CAUGHT #107`). At 17:52 a Lass's battle on 1F
|
||||
started. From then on the log was `NEXT start/done` every 0.8 brain seconds and nothing else: no
|
||||
reward and no other macro for 58 brain minutes. Check 10 flagged `dominant`/`sequence` (`NEXT`
|
||||
100%). At 18:50 the ladder, at level 2 since the 16:54 reset, reset the run to rung 11 again and
|
||||
erased the catch. The replay after that reset matched the one before it event for event (the same
|
||||
`brainMs`), so it was heading into the same trap at about 19:48.
|
||||
|
||||
### Reproduction (durable generation 250877, pulled from the reset's archive)
|
||||
|
||||
`wIsInBattle` 2 and the Lass (`wTrainerClass` 3), with Oddish beaten and Bellsprout L11 next.
|
||||
Wartortle L19 was at 0/58, Zubat L8 at 24/26 and out. The party list was open with
|
||||
`wPartyMenuTypeOrMessageID` = BATTLE_PARTY_MENU and the cursor on the Zubat. The screen read
|
||||
"ZUBAT is already out!". The seam read `forced_switch`, so the pad was `SWITCH, NEXT`, and `SWITCH`
|
||||
had no healthy Pokémon to go to. Driven from the checkpoint on v0.7.0, the pad was `NEXT` on
|
||||
6,000 of 6,000 frames: 125 `NEXT` starts, every one "already out" and the list again.
|
||||
|
||||
| # | trap | trigger | test | fix, or why it is left |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 70 | the SHIFT style's "Will <mon> change POKéMON?" offer opens the party list with BATTLE_PARTY_MENU, which the seam read as `ChooseNextMon`'s forced switch. Its pad `SWITCH, NEXT` had no B; `NEXT` on the Pokémon already out rings forever | any trainer battle with two or more Pokémon in the party, the fly answering YES (the first catch made it possible) | `the_shift_offers_party_list_is_the_flys_turn_and_its_way_out_is_back`, `row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` (`FLY_ROW70_CHECKPOINT`), `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered` (`FLY_ROW70_FORCED_CHECKPOINT`) | **fixed**: forced switch = BATTLE_PARTY_MENU **and** the active battler at 0 HP (`docs/design/macros.md` 12.33). The offer is the fly's turn, and its pad is `SWITCH` (when someone can go out) and `BACK` |
|
||||
|
||||
ROM tests on the build box (rom-env sourced):
|
||||
|
||||
| test | v0.7.0 | branch |
|
||||
| --- | --- | --- |
|
||||
| `row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` | 6,000 frames in the list, `NEXT` on all of them, `BACK` on none, never left. **Fails** | `BACK` from f3. "LASS sent out BELLSPROUT!", then the fly's turn at f194. Passes |
|
||||
| `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered` | passes | 881 forced frames, all read as forced, `SWITCH` on all of them, `BACK` on none. The Zubat goes out, and the fly's turn comes at f1,102. Passes |
|
||||
|
||||
The stub reaches row 70 by itself. From the live rung-12 archive (Mt. Moon's mouth, one ball),
|
||||
three uniform-stub seeds each catch a Zubat within 4,000 frames and meet the same Lass. There
|
||||
Wartortle faints at f27,361, f34,656 and f35,284.
|
||||
|
||||
### The watchdog and the ladder: every act was on a real trap
|
||||
|
||||
The day's six acts, replayed probe by probe through check 10 and the ladder from the live logs
|
||||
(open loop; uniqueLocations proxied from the tile rewards). The base replay reproduces the live
|
||||
history: restarts at 05:55, 08:55 and 11:55, and resets to rung 11 at 16:50 and 18:49 (live:
|
||||
16:54 and 18:50).
|
||||
|
||||
| live act | window | what the fly was doing |
|
||||
| --- | --- | --- |
|
||||
| restarts 05:57, 08:58, 11:59 (map 59) | `unwon-battles`, 05:50 to 13:50 | Row 67 again, against a Lass on Mt. Moon 1F. `MOVE 2` (TAIL WHIP) on six turns in seven, BUBBLE doing 5 to 8 to her Oddish, 34 to 48 moves per window, no battle won, whiteout and back. Beaten after the 11:59 restart (13:54, then the other 1F trainers, B2F's and the Super Nerd) |
|
||||
| reset to 11, 16:54 (map 61, B2F) | `unrewarded`, 15:05 to 16:50 | A wild encounter every ~20 s, `RUN` every time (220), `GO FRONTIER`/`GO WARP` between them, and no new tile or reward for 1 h 50 min. The battles were ending and the fly was moving between them, but on ground it had already covered. Mechanism not established: no checkpoint from before 16:54 survives (row 64/65 territory, B2F's far side) |
|
||||
| reset to 11, 18:50 (map 59) | `dominant`/`sequence`, 17:59 on | Row 70's list: `NEXT` alone for 58 brain minutes |
|
||||
|
||||
So check 10 read no cave as a trap. Healthy cave windows (17:04 to 17:54: Route 3 and Mt. Moon
|
||||
battles won, a catch, new areas) peaked at 94% `NEXT`, and the tile gate kept them clear. Two
|
||||
suggested relaxations are **not** supported by the evidence:
|
||||
|
||||
- "Battles ending and the fly moving between them": the 16:54 window was exactly that for
|
||||
1 h 50 min, with nothing new.
|
||||
- Counting the damage reward's KO as a win: the Lass ring had 45 KOs of her first Pokémon in
|
||||
eight hours and never won.
|
||||
|
||||
The watchdog's flags are unchanged. Every replayed log (rows 58, 60 to 64, 67, 70) flags on the
|
||||
same probes with the same reasons, base and branch.
|
||||
|
||||
What went wrong was the ladder. It stayed at level 3 to 4 from the morning's ring through a
|
||||
rung-11 reset and a full, rewarded climb back to Mt. Moon. The 18:50 reset then restored the
|
||||
same rung-11 archive as the 16:54 one. A restore is deterministic: the replay after it matched
|
||||
the one before event for event (1,138 of 1,138, same `brainMs`). So the reset erased the catch
|
||||
and walked back into the same list about an hour later. It also could not have helped: row 70's
|
||||
trap is in the game state, not the ledgers, so neither a restart nor a replay clears it.
|
||||
|
||||
| # | trap | trigger | test | fix, or why it is left |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 70b | the ladder never started over after real progress. A trap after a reset and a rewarded climb back was treated as the old trap outliving its step | a reset, then progress, then any trap | `test_progress_after_the_last_step_starts_the_ladder_over`, `test_progress_while_a_step_settles_does_not_start_the_ladder_over` | **fixed**: `window.progress` in loop.json (report only; `lint.sh` check 10 case 9). New lasting progress more than `SETTLE` after the step, once a clear probe shows the trap let go, returns the ladder to level 0 (see 70f) |
|
||||
| 70c | a reset restored the same archive as the last reset, which replays deterministically into the same trap | level 2 and above, where every step targets the rung below the best | `test_the_last_resets_archive_is_not_restored_again`, `test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it` | **fixed**: that step is a restart |
|
||||
| 70d | a reset erased a catch made an hour earlier | any reset after a catch | `test_a_species_owned_recently_is_never_reset_away`, `test_a_probe_that_owns_a_species_starts_the_protection` | **fixed**: within two hours of a species first owned, a reset is a restart (held three hours apart) |
|
||||
| 70f | (review r3) a reset's replay counted as progress. The restored reward ledger pays the archive's areas, trainers, species and rung again, so 70b started the ladder over after every reset, and a replayed catch opened a second protection window. A trap only the rung below escapes took 5.6 h (6.8 h after a catch) to reach it, against 2.1 h in v0.7.0 | a reset whose replay re-earns rewards, then traps | `test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over`, `test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected`, `test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over`, `test_a_trap_only_the_rung_below_escapes_is_reached_promptly`, `test_restarts_are_a_hold_apart_in_every_closed_loop` | **fixed**: `window.progress.keys` names each lasting reward (`lint.sh` check 10 case 9); progress and protection count only names the ladder has not seen (`progressSeen`). 2.1 h (3.3 h after a catch). Restarts stay three hours apart, and a failed reset does not mark its archive |
|
||||
| 70e | the B2F wander: `RUN` from every encounter, walks on covered ground, nothing new for 1 h 50 min | Mt. Moon B2F after the Super Nerd | -- | **left, named**: no checkpoint survived. The next occurrence should be pulled before any reset |
|
||||
|
||||
Ladder replay of the day (the same logs and the same start state, base against branch):
|
||||
|
||||
- **Base**: restarts at 01:30, 05:55, 08:55, 11:55 and 15:10; resets to 11 at 16:50 and 18:49.
|
||||
- **Branch**: restarts at 01:30, 05:55, 07:15, 10:30, 13:30 and 15:10; a reset to 12 (the
|
||||
current rung, not 11) at 16:50; a restart at 18:04.
|
||||
- 07:15: AREA 60 at 06:48 started the ladder over.
|
||||
- 18:04: the climb after 16:50 started the ladder over.
|
||||
- After 18:04, no reset. The Zubat was owned at 17:46 and rung 12 was the last reset's
|
||||
archive, so the branch holds to restarts three hours apart.
|
||||
|
||||
- **Review r3** (names, from a live-like 00:00 state, then the post-16:54 log with the state carried
|
||||
over): restarts at 01:30, 05:55, 08:55, 11:55 and 15:10, as live; a reset to 12 at 16:50 (the
|
||||
13:54 to 14:20 trainers were new, so the ladder had started over). After 16:54 the Route 3
|
||||
trainers, AREA 59, OWNED #8 and the rung are the replay's and do not count; OWNED #41 (the
|
||||
Zubat, 17:46) is new, so a restart at 18:04 and then the protection hold through 18:54, no reset.
|
||||
|
||||
The replay is open loop: the log after 16:50 is what the base's reset produced.
|
||||
|
||||
## 2026-10-01, row 71: Route 25, a ball past the bag's window
|
||||
|
||||
### What was live
|
||||
|
||||
v0.7.3 legacy, adapter v8, rung 15 (NUGGET BRIDGE), map 36 (Route 25), two badges. After the
|
||||
Route 25 trainers, a wild battle began. The pad held `THROW BALL` alone and every start was
|
||||
`blocked`: 131 of 131 in ten minutes, about two hours in all. A flysim restart restored a hot
|
||||
generation from inside the same battle with the same bag open, so the trap came back at once. The
|
||||
coordinator then reset the run to milestone 15.
|
||||
|
||||
### Reproduction (hot generation 263767, inside the trap)
|
||||
|
||||
- The state: `wIsInBattle` 1 (wild, not a trainer), a wild Oddish L13 at 8/36, Wartortle L35 at
|
||||
21/105 with PP left (only GROWL at 0).
|
||||
- The bag: TM34, HELIX FOSSIL, NUGGET, TM45, POKé BALL x2. Party of 2, Oddish not in it.
|
||||
- The bag was open with `wListScrollOffset` 3, so the window showed TM45, POKé BALL and CANCEL,
|
||||
with the arrow on row 1, the ball.
|
||||
- Row 69's rule (enemy HP low for the ball) withheld everything but the ball.
|
||||
- `THROW BALL` aims at bag index 4. The seam reported the window row (0..2) as the cursor, so the
|
||||
cursor step walked between rows 1 and 2 until its budget ran out.
|
||||
|
||||
The hypotheses in the brief were all checked:
|
||||
|
||||
- **A trainer battle.** No, it is wild.
|
||||
- **No balls in the bag.** No, there are two.
|
||||
- **The ball counted wrong.** Its index was right; the cursor reading was wrong.
|
||||
- **RUN, or PP.** Not involved.
|
||||
|
||||
| # | trap | trigger | test | fix, or why it is left |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 71 | the battle bag's cursor was read as the window's row, so a bag entry past the third could never be reached; with row 69's low-HP rule, `THROW BALL` alone on the pad and blocked for ever | any wild battle against a species not in the party at low HP, with the ball fourth or later in the bag (`ITEM`'s Potion likewise, without the trap) | `a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn`, `row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`), `row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` | **fixed**: cursor = `wCurrentMenuItem + wListScrollOffset` (`$CC36`, pinned from the cartridge; `docs/design/macros.md` 12.34). The mart's lists read the same way; `MART_CURSOR_ROWS` stays |
|
||||
|
||||
| test | 390d118 | branch |
|
||||
| --- | --- | --- |
|
||||
| `row71_a_ball_past_the_bags_window_is_thrown` | 11 starts, 10 `blocked`, nothing thrown in 3,000 frames. **Fails** | thrown, Oddish caught (`wCapturedMonSpecies`) by f350, 0 `blocked`. Passes |
|
||||
| `a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_label`, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | pass | pass (balls in the window's first rows, unscrolled) |
|
||||
|
||||
Trap hunt, 10 brain minutes with the real connectome from the trap checkpoint:
|
||||
|
||||
- **390d118:** 33 of 33 windows flagged, 1 tile, `THROW BALL` 131 starts and 131 `blocked`. That
|
||||
matches the live count exactly.
|
||||
- **Branch:** 1 of 33 flagged. That window is the opening battle text, with 71 tiles in it. The
|
||||
ball is thrown on the first hold and the Oddish is caught at 0.10 min. The fly ends the keyboard
|
||||
itself, and the run reaches 91 tiles.
|
||||
|
||||
The watchdog and the ladder flagged the trap correctly. The restart could not help, because the
|
||||
trap is in the game state and the hot checkpoint is inside it (row 70's lesson again). Only a reset
|
||||
or the fix ends it.
|
||||
|
||||
## 2026-10-02, row 73: Route 25 and Bill's house, a PC no macro could press, and Cerulean's south
|
||||
|
||||
### What was live
|
||||
|
||||
v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. After row 71's battle trap was fixed the fly kept a
|
||||
busy ring with no progress: `GO ROUTE` into Bill's house (`$58`, door (45, 3)), `GO OBJECTIVE` or
|
||||
`GO OUT` straight back out. Scout B3 measured it from the live checkpoint: on six seeds (2.8
|
||||
brain hours) the pad in the house was always `GO OBJECTIVE, GO OUT, GO NPC, GO FRONTIER`, `GO OUT`
|
||||
16-51 and `GO OBJECTIVE` 16-60 starts per ten brain minutes, `GO NPC` 0 in about 600 starts, and
|
||||
new tiles 2527 to 2531 in 35 minutes. Rung 16 was never earned.
|
||||
|
||||
### Mechanism
|
||||
|
||||
- **Rung 16's place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`. A fly on Route 25 was
|
||||
already there, so in the house `GO OBJECTIVE` was an exit into the objective's map: the same
|
||||
door as `GO OUT`.
|
||||
- **The errand's middle step was unpressable.** The ticket is Bill's errand
|
||||
(`scripts/BillsHouse.asm`): talk to Bill as a Pokémon, press the cell separator's PC at (1, 4)
|
||||
facing up, talk to Bill when he steps out. The PC is a hidden event (`wNumSigns` 0, one sprite),
|
||||
and no macro aimed at hidden events or dealt `TALK` in front of one. Scout B3 confirmed the
|
||||
press on the cartridge by hand.
|
||||
- **After the ticket, the town is two pieces.** Cerulean's town ground ends at row 28; Route 5 is
|
||||
on the ground behind the trashed house (`$3e`), in by its front door and out by the hole in its
|
||||
back wall. The house was off the map graph, so `GO OBJECTIVE` toward Vermilion ended `blocked`
|
||||
at (17, 28) and the fly rang between the town and its houses (scout: 0 of 6 seeds past row 28 in
|
||||
43 brain minutes each, from a carry-forward made by scripted presses).
|
||||
|
||||
| # | trap | trigger | test | fix, or why it is left |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 73 | rung 16's place was Route 25, so inside Bill's house `GO OBJECTIVE` and `GO OUT` were both the door; the errand's PC is a hidden event no macro could press; after the ticket, Cerulean's south was off the graph | rung 15 on Route 25 (live), and any fly with the ticket in Cerulean | `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`, `a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`, `a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`; `row73_*` in `rom_macros_mode.rs` (`FLY_ROW73_DOOR_CHECKPOINT`, `FLY_ROW73_PC_CHECKPOINT`, `FLY_ROW71_CHECKPOINT`, `FLY_ROW73_SOUTH_CHECKPOINT`, `FLY_ROW73_TRASHED_CHECKPOINT`, `FLY_ROW73_TICKET_CHECKPOINT`) | **fixed**: rung 16 is `errand(BILLS_HOUSE)`, people then things; hidden events read from the cartridge's own table (`$11:$6A40`/`$6A96`), only ever as the errand's next step, faced from the side the entry names (`docs/design/macros.md` 12.35, `macros-wram.md` 17); Cerulean's third piece and the trashed house on the graph |
|
||||
| 73a | the road from Route 5 to Vermilion is plain map edges through Saffron, whose gates are guarded until the drink; the Underground Path's houses are off the graph | a fly on Route 5 with rung 17 next | none yet | **left**: predicted, not reached by the scout; the branch hunt's flies reach Route 5's gate (`$46`) and the Underground Path house (`$47`). Needs its own checkpoint and row |
|
||||
|
||||
| test (stub rotation) | 74a3c12 | branch |
|
||||
| --- | --- | --- |
|
||||
| `row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door` | no ticket in 36,000 frames, out of the house and the Route 24/25 ring. **Fails** | ticket at 4,743 frames, never out of the house. Passes |
|
||||
| `row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket` | no ticket in 36,000 frames. **Fails** | ticket at 2,116 frames. Passes |
|
||||
| `row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket` | no ticket in 216,000 frames (60 brain minutes), 1,019 times into the house and 1,019 out. **Fails** | ticket at 9,876 frames. Passes |
|
||||
| `row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` | aims at the town's bottom row (unreachable). **Fails** | the house's front door, then the hole in its back wall. Passes |
|
||||
| `row73_the_fly_takes_the_trashed_house_south_to_route_5` | trashed house 54,442; ticket carry-forward not in 48,000 (63,880). **Fails** | 52,081 and 27,067. Passes |
|
||||
| `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` | does not compile (new seam) | passes |
|
||||
|
||||
Trap hunt, real connectome, 15 brain minutes per seed, six seeds per arm. The palette seed does not
|
||||
make runs differ (row 68), so the seeds are the game run 0, 7, 19, 41, 97 and 211 frames ahead of
|
||||
the brain before the first hold (scout B3's `FLY_TRAP_AHEAD`, a scratch patch, not committed):
|
||||
|
||||
| from | arm | rung 16 | distinct (map, tile) | Bill's-house ring (`GO ROUTE` / `GO OUT` / `GO OBJECTIVE` at net 0) | reached Route 5 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| live row-71 checkpoint (rung 15, Route 25) | 74a3c12 | 0 of 6 | 83-105 | 36-47 / 18-22 / 18-27 per seed | 0 of 6 |
|
||||
| live row-71 checkpoint | branch | **6 of 6**, at 2.0-2.3 brain minutes | 200-517 | 2-24 / 3-30 / none at net 0 (the walks go somewhere) | 3 of 6 inside the 15 minutes |
|
||||
| ticket carry-forward (rung 16, Bill's house) | 74a3c12 | (has it) | 328-400 | -- | 0 of 6 (ends in the town, the bike shop or the centre) |
|
||||
| ticket carry-forward | branch | (has it) | 273-439 | -- | **5 of 6**; four of them on into Route 5's gate (`$46`) or the Underground Path house (`$47`) |
|
||||
|
||||
The two-minute window flags do not measure this trap: the ring crosses more than four tiles, so
|
||||
the base arm flags only the opening battle text (1 of 53), and the branch arm's flags (28-49 of 53)
|
||||
are `NEXT` runs inside long battles it now reaches -- the Rocket in the yard behind the trashed
|
||||
house and Route 24/5 trainers (one battle 23,954 frames and 462 macros; the base's ticket seed 19
|
||||
has the same 17,235-frame battle). Every one ended; none is a ring. Route 5 is counted from the
|
||||
hunt's text-box maps and its final map, so it is a floor.
|
||||
|
|
|
|||
|
|
@ -282,7 +282,7 @@ pct exec $CTID -- /opt/fly/bin/fly-reset-to-milestone $N
|
|||
# (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5.
|
||||
# (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's
|
||||
# adapter so the gate and flysim both migrate instead of refusing:
|
||||
FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 infra/05-deploy.sh <release-env> <release-tarball>
|
||||
FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 infra/05-deploy.sh <release-env> <release-tarball>
|
||||
# The gate logs "the adapter version is the only difference, and it is named; the run is KEPT
|
||||
# and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the
|
||||
# same rule at restore. Anything else about the string differing is still a refusal.
|
||||
|
|
@ -443,6 +443,612 @@ One `ln -sfn` plus a restart, per `docs/design/infra.md` section 2. Nothing else
|
|||
touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`.
|
||||
On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above.
|
||||
|
||||
## Switch the runtime (legacy loop or session runtime)
|
||||
|
||||
Two binaries in every release from SERVE-01 on run the same fly: `flysim`, the legacy loop, and
|
||||
`flysim-session`, the same composition on the session framework (agent, Game Boy environment and
|
||||
macro task as participants). They read the same `/etc/fly/fly.env`, write the same checkpoint
|
||||
stores, event log, sugar journal and chat sidecar, and serve the same feed, control API and
|
||||
metrics through the same listener code, so nothing else on the container can tell them apart.
|
||||
`flysim.service` is the fly's one unit name either way; which binary it runs is one drop-in,
|
||||
written and removed by `fly-runtime` (`infra/bin/fly-runtime`, installed to `/opt/fly/bin`).
|
||||
|
||||
```
|
||||
pct exec $CTID -- /opt/fly/bin/fly-runtime status # legacy | session
|
||||
pct exec $CTID -- /opt/fly/bin/fly-runtime session # CUT-01, after the shadow's verdict (starts the speed probation)
|
||||
pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
|
||||
```
|
||||
|
||||
- **What it does.** `session` writes `/etc/systemd/system/flysim.service.d/10-runtime.conf`
|
||||
(`ExecStart=/opt/fly/current/flysim-session`, `FLY_SESSION_DIR=/run/fly/session`),
|
||||
daemon-reloads and restarts `flysim.service`; `legacy` deletes the file and does the same. No
|
||||
data moves: the store is shared, and each runtime restores the other's checkpoints.
|
||||
- **What it checks.** `session` refuses a release without `flysim-session`, and refuses when
|
||||
`flysim --print-compatibility` and `flysim-session --print-compatibility` differ. After the
|
||||
restart both wait for `/healthz` and a `/status` frame that advances
|
||||
(`FLY_RUNTIME_HEALTH_TIMEOUT`, 300 s). If the session runtime does not come up healthy, it
|
||||
switches back to legacy by itself and exits 1 (`--no-fallback` leaves it to the operator).
|
||||
Every switch is logged (`journalctl -t fly-runtime`, `/var/lib/fly/runtime.log`).
|
||||
- **The fallback outlives the switch (C1).** While the session runtime is selected, the drop-in
|
||||
also sets `OnFailure=fly-runtime-fallback.service`, `StartLimitBurst=3`,
|
||||
`StartLimitIntervalSec=600` and `RestartMode=direct`, and `MALLOC_ARENA_MAX=2` (glibc arena
|
||||
fragmentation was the whole of the 5-8 MB/h RSS growth). `RestartMode=direct` is what makes the
|
||||
limit real: since systemd 254 the default (`normal`) sends the unit through the `failed` state
|
||||
before every `Restart=always` restart, so `OnFailure=` would fire on the first crash, watchdog
|
||||
kill or start timeout (seen on systemd 257, the container's). With `direct` the unit goes from
|
||||
one start to the next and only hitting the start limit fails it. Three starts of `flysim.service` within ten minutes, from any
|
||||
cause and any caller (a reboot, the watchdog or `fly-loop-recover` restarting it, a deploy, a
|
||||
binary that crashes, hangs before READY or is killed by `WatchdogSec`) make systemd run
|
||||
`fly-runtime fallback`: it writes `/run/fly/runtime-fellback.json` (time, reason, unit result),
|
||||
deletes the drop-in, daemon-reloads and restarts `flysim.service` on the legacy binary, and logs
|
||||
a `fly-runtime` journal line. It is idempotent, and it does nothing if the release has no
|
||||
executable `flysim`. Look with `fly-runtime status` (it prints the reason) or
|
||||
`cat /run/fly/runtime-fellback.json`; the container is then on legacy until an operator runs
|
||||
`fly-runtime session` again, which clears the reason file. Restarts you make yourself count
|
||||
too, and once the limit is reached systemd refuses the next start and runs the fallback. Three legitimate restarts in ten
|
||||
minutes count the same as three crashes: after that many, prefer `fly-runtime legacy`, do the
|
||||
work, then switch back.
|
||||
- **Interrupted switches roll back.** `fly-runtime` traps INT, TERM and HUP (an ssh that drops
|
||||
mid-switch): an unfinished `session` removes the drop-in again (or restores the one that was
|
||||
there) and restarts `flysim.service` on that state, so a drop-in that never passed its health
|
||||
check is never left behind. `session`, `legacy`, `fallback` and that rollback all take one lock
|
||||
(`/run/fly/runtime.lock`); a switch holds it while it changes the drop-in and queues the restart
|
||||
(`systemctl restart --no-block`, so a unit that never becomes READY cannot hold it) and releases
|
||||
it for the health wait. The rollback does nothing when a fallback finished after the switch began (the
|
||||
reason file exists), so it can never put back an older drop-in over a fallback.
|
||||
- **What stays the same.** Everything that names `flysim.service` keeps working unchanged:
|
||||
`fly.target`, `flyedge.service`'s `Requires=`, the watchdog, `fly-loop-recover`'s restart and
|
||||
its sudoers line, `fly-loop-reset`, `fly-reset-to-milestone` (run with the service stopped, on
|
||||
the shared store), the unstick rule's `systemctl restart flysim.service`, `journalctl -u
|
||||
flysim`, the cpuset drop-in. The choice survives a reboot and a deploy: `05-deploy.sh`
|
||||
converges unit files but never removes a drop-in (it rewrites it in place from the current
|
||||
template, without a restart), and it refuses a release without `flysim-session` or with a
|
||||
different compatibility string while the drop-in is present (`fly-runtime legacy` first to
|
||||
deploy one). **Policy (C2, operator decision 2026-09-29, "Session stays, trust gates"):** a
|
||||
deploy keeps the chosen runtime on the new release's `flysim-session`, without re-running the
|
||||
shadow for it. The trust gates before the release vouch for the binary, and the persistent
|
||||
fallback above protects a bad one.
|
||||
- **What differs, by declaration.** `POST /reward` is always 403 on the session runtime (the
|
||||
operator pulse has no session-framework counterpart, `legacy-gameboy-v1` section 15); a
|
||||
fresh start publishes no audio for its one setup frame; `FLY_TRACE` and
|
||||
`FLY_PROFILE_SECONDS` are legacy-loop tools (the session runtime logs a `session profile`
|
||||
line of per-phase timings every minute instead). The sugar journal's boot header says
|
||||
`runtime: fly-session`.
|
||||
- **The standalone unit.** `flysim-session.service` is the same service as a unit of its own
|
||||
(flysim's limits, cpuset and environment; `Conflicts=flysim.service`; no `[Install]`, so it
|
||||
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
|
||||
stopped, not for switching the stream.
|
||||
- **The session on the bus (BUS-01).** `fly-runtime session --bus` (or `session-bus`) runs the
|
||||
session's participants on the flybus router over Unix sockets: `flysim-session` (the router, the
|
||||
coordinator, the listeners) starts `fly-session legacy-agent` and `fly-session legacy-environment`
|
||||
as children of the same unit, in `flysim.slice`, on flysim's CPUs. The drop-in gains
|
||||
`Environment=FLY_SESSION_TRANSPORT=bus`; `fly-runtime status` prints `session` and then
|
||||
` transport: bus`. `fly-runtime session` without a flag (05-deploy's refresh) keeps the transport
|
||||
the drop-in has; `fly-runtime session --local` goes back to the in-process lane, and
|
||||
`fly-runtime legacy` to legacy. The fallback, the probation, the watchdog and the unstick rule's
|
||||
restart are the same on either transport: one unit, restarted as a whole, children included
|
||||
(`ps -o pid,args --ppid $(systemctl show -p MainPID --value flysim)` lists them). A deploy
|
||||
refuses a release without `fly-session` while the drop-in says `bus`. **Before switching onto the
|
||||
bus, run a shadow of it** (Shadow run below): with the live fly on legacy (`fly-runtime legacy`),
|
||||
`fly-shadow-run start --bus`, three hours, then `fly-shadow-run check --bus && fly-runtime
|
||||
session --bus`. Watch `fly_frame_work_mean_ms` and `fly_frame_work_p99_ms` on `/metrics` (the
|
||||
loop's compute time per frame, without its pacing sleep, over the last 3,600 frames; the budget
|
||||
at real time is 16.74 ms): they show the headroom that a realtime factor of 1.0 hides.
|
||||
- **Per-frame compute time, both runtimes.** `/metrics` exports `fly_frame_work_mean_ms`,
|
||||
`fly_frame_work_p99_ms`, `fly_frame_work_max_ms` and `fly_frame_work_frames` for the legacy loop
|
||||
and the session runtime alike: everything one running iteration does except the pacing sleep.
|
||||
Headroom is `1 - mean / 16.74` at real time.
|
||||
|
||||
## Feed over the bus (EDGE-02)
|
||||
|
||||
`ws://127.0.0.1:7400/feed` is served either by `flysim` itself (`direct`, how every release before
|
||||
EDGE-01 did it, and the default) or by `fly-edge` from flysim's embedded feed bus (`bus`,
|
||||
`docs/design/flybus.md` "Feed over the bus"). The WebSocket contract is the same bytes either way
|
||||
(`docs/feed-protocol.md`); nothing about the fly, the readout or the compatibility string changes,
|
||||
on either runtime (`flysim` or `flysim-session`, `fly-runtime`). The stage, the bridge and the
|
||||
capture never see the difference.
|
||||
|
||||
**One switch, one line.** `FLY_FEED_VIA` in `/etc/fly/fly.env` (written by every deploy from the
|
||||
env file's `FLY_FEED_VIA`, default `direct`). flysim reads it, `flyedge.service` runs only when it
|
||||
says `bus` (`ExecCondition=`; in direct mode the unit starts as "skipped", inactive and not
|
||||
failed), and `flysim.service` has `Wants=flyedge.service`, so **every** start of flysim brings the
|
||||
edge up in bus mode, whoever starts it: a reboot, the unstick rule's restart, `fly-loop-reset`'s
|
||||
stop and start, `fly-reset-to-milestone`, a crash-restart. There is nothing to enable or start by
|
||||
hand, and flysim and the edge cannot disagree.
|
||||
|
||||
```
|
||||
pct exec $CTID -- /opt/fly/bin/fly-feed status # configured / running / the edge and its counters
|
||||
pct exec $CTID -- /opt/fly/bin/fly-feed bus # switch (restarts flysim; rolls itself back if unhealthy)
|
||||
pct exec $CTID -- /opt/fly/bin/fly-feed direct # the way back
|
||||
```
|
||||
|
||||
### The live procedure
|
||||
|
||||
Preconditions: the release has `fly-edge` (v0.7.6 and later; `ls /opt/fly/current/fly-edge`),
|
||||
`fly-feed` is installed (`/opt/fly/bin/fly-feed`, converged by the deploy), the container is
|
||||
claimed in the host log as for any host work, and `fly-feed status` says `configured: direct`,
|
||||
`running: direct`. Pick a moment you would also pick for the unstick rule's restart: **the switch
|
||||
restarts flysim**, so the stream shows the stage's reconnect screen for about a minute (the
|
||||
restore, the warm-up and the page's reconnect; the rehearsal measured it, below), and the run
|
||||
continues from the last checkpoint. It counts as one start against `flysim.service`'s start limit
|
||||
(3 in 10 minutes on the session runtime), two if it rolls back: do not switch within ten minutes
|
||||
of two other restarts.
|
||||
|
||||
```
|
||||
# 1. Before: the baseline to compare with (keep the output).
|
||||
pct exec $CTID -- /opt/fly/bin/fly-feed status
|
||||
pct exec $CTID -- sh -c 'curl -s 127.0.0.1:9101/metrics | grep -E "^fly_(realtime_factor|lag_seconds|feed_clients|frames_sent_total) "'
|
||||
pct exec $CTID -- fly-cpu-confine status # PERF-02: the sim's cpus are the sim's
|
||||
# 2. Switch. Blocks until the page is on the feed again (FLY_FEED_HEALTH_TIMEOUT, 300 s) and prints
|
||||
# "healthy (bus): the page is on the feed and frames are moving", exit 0.
|
||||
pct exec $CTID -- /opt/fly/bin/fly-feed bus
|
||||
# 3. Make it permanent for the next deploy: FLY_FEED_VIA=bus in the operator's env file for this
|
||||
# container. (A deploy that finds fly.env and the env file disagreeing warns loudly and writes the
|
||||
# env file's value; flysim applies it at its next restart.)
|
||||
# 4. Look at it (below) for a few minutes, then at the end of the first hour and the first day.
|
||||
pct exec $CTID -- /opt/fly/bin/fly-feed status
|
||||
```
|
||||
|
||||
What `fly-feed bus` does, in order: refuses unless the release has `fly-edge`, takes
|
||||
`/run/fly/feed.lock`, rewrites the one `FLY_FEED_VIA` line (every other line, the mode and the owner
|
||||
kept), restarts `flysim.service` (`--no-block`, then waits for a **new** invocation's `/healthz`),
|
||||
waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) and, while
|
||||
`flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with
|
||||
`fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA`
|
||||
back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback`
|
||||
leaves the failed switch in place for the operator; an interrupted `bus`, ssh dropped or INT, TERM
|
||||
or HUP, rolls back too). `direct` is the safe terminal state and is never rolled back: an interrupted
|
||||
`fly-feed direct` leaves `FLY_FEED_VIA=direct` and restarts flysim so the running process matches. Every switch is in the journal (`journalctl -t fly-feed`) and
|
||||
`/var/lib/fly/feed.log`.
|
||||
|
||||
### What to watch
|
||||
|
||||
| Where | Healthy in bus mode | Wrong looks like |
|
||||
| --- | --- | --- |
|
||||
| `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` |
|
||||
| edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) |
|
||||
| flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` |
|
||||
| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is about 2 ms of CPU per snapshot (10x the direct websocket write), so with `SESSION_AUX_CPUS=1` it runs on its own CPU and the number is unchanged; without it, expect a loss of 1 to 2 ms of the 3.7 to 5.7 ms of headroom per frame | a drop that persists for the hour: switch back (`fly-feed direct`) and compare |
|
||||
| `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy |
|
||||
| `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back |
|
||||
| `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` |
|
||||
| the stream | the page is up, frames moving | the page on its reconnect screen: `fly-feed status`; if the edge is down `systemctl status flyedge`; `fly-feed direct` is the one-command answer |
|
||||
|
||||
The watchdog follows the **running** mode (the running flysim's own environment, so a deploy that
|
||||
changed `FLY_FEED_VIA` but has not restarted flysim is not an outage). Check 2 reads the feed
|
||||
counters from the edge in bus mode; a new check 2a judges the edge itself, only while flysim answers
|
||||
`/healthz` (a down flysim is check 1's): active and `/healthz` 200, one failed pass let go, then
|
||||
the second pass restarts `flyedge`, the third restarts the page and the encoder as well, and the
|
||||
fourth **puts the feed back on flysim** (`fly-feed direct --no-wait`, granted in sudoers with exactly
|
||||
those arguments): one more flysim restart, and `FLY_FEED_VIA=direct` stays until an operator
|
||||
switches again (put it in the env file too). Check 2 in bus mode leaves a silent edge to 2a rather
|
||||
than restarting a page that has nothing to connect to, and its chain ends with the edge and the
|
||||
encoder.
|
||||
|
||||
### Rolling back
|
||||
|
||||
- `fly-feed direct`: writes `direct`, restarts flysim, waits until the page is on flysim's own
|
||||
feed, stops a lingering edge. It needs nothing from the release (it works on one without
|
||||
`fly-edge`), and it is the way back if anything above looks wrong. It restarts flysim again, so
|
||||
count it against the start limit.
|
||||
- Automatic: a switch that does not become healthy (above), the watchdog's fourth failed pass, and
|
||||
`fly-runtime fallback` (to legacy) all leave `FLY_FEED_VIA` alone: the setting is the same on both
|
||||
runtimes.
|
||||
- A deploy of a release **without** `fly-edge` is refused (before `/opt/fly/current` moves) while
|
||||
the env file says `bus` or the container is in bus mode: `fly-feed direct` and set
|
||||
`FLY_FEED_VIA=direct` in the env file first, then roll back or deploy.
|
||||
- A reboot keeps whatever `fly.env` says.
|
||||
|
||||
### What the rehearsal measured
|
||||
|
||||
Before the first live switch (EDGE-02, 2026-10-02): the real fly (session runtime, real connectome,
|
||||
macros mode, sim on four CPUs and the page and edge on two others, as on the container), the real
|
||||
stage page in headless Chromium consuming through `fly-edge`, plus the repo's own units, `fly-feed`
|
||||
and watchdog under a real systemd. The build box was shared and loaded (load average 8 to 30), so
|
||||
**real-time factor is not comparable between the two runs**; the numbers below are the ones load does
|
||||
not move much. The live switch is the real A/B: take the step 1 baseline and compare.
|
||||
|
||||
| Measure | direct | bus |
|
||||
| --- | --- | --- |
|
||||
| WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs |
|
||||
| Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) |
|
||||
| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher: on the aux CPU with `SESSION_AUX_CPUS`, else on the host CPU with the sim's dispatcher, about 7% of a CPU at 30 Hz and on the critical path) and 1.1 ms in the edge (page CPUs) |
|
||||
| Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs |
|
||||
| Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run |
|
||||
| Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both |
|
||||
| Snapshots dropped on the way (heavy load) | none seen by a local client | 0.28% sequence gaps at the recorder (the edge sits on CPUs Chromium saturates); none on a quiet box |
|
||||
| Page | 0 decode errors | 0 decode errors, gaps only under that load |
|
||||
|
||||
Recovery, with the page (a reconnecting stage) as the witness: `kill -9 fly-edge`, a SIGTERM
|
||||
restart of it, and two kills 0.1 s apart (the router's one seat for the edge is released at once)
|
||||
each had the page streaming again in 0.7 to 0.9 s; a `kill -9` of flysim (router, publisher and
|
||||
sim) had the edge serving the new router 3 s later and the page 3.4 s later; a SIGTERM restart of
|
||||
flysim (the unstick rule) 4 and 5.3 s (the page's retries are 0.3 to 1 s apart, the sim restores
|
||||
from its hot ring). Under the real systemd: `fly-feed bus` took 6 s from command to "page on the
|
||||
feed", `fly-feed direct` 6 s, a `fly-feed bus` with a broken `fly-edge` rolled itself back after
|
||||
the 40 s test timeout and left the page on flysim, a stop and start of flysim brought the edge
|
||||
back by itself, and the watchdog's fourth failed pass switched a permanently broken edge back to
|
||||
direct with the page connected again. The live restart is longer than these 6 s by the real
|
||||
restore and warm-up; use the unstick rule's usual time.
|
||||
|
||||
### Notes
|
||||
|
||||
- **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and
|
||||
`fly_frames_sent_total` as 0. Scrape the edge's `:9102` too (same names, plus the `fly_edge_*`
|
||||
series); the metrics address is on every interface, as `:9101` is, and exposes nothing but
|
||||
counters.
|
||||
- **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and
|
||||
the publisher run inside flysim, on its `flysim-bus` runtime: two threads plus tokio's blocking
|
||||
pool, which does the artifact copies. **Give it a CPU of its own** (`SESSION_AUX_CPUS=1` in the
|
||||
operator's env file, a page CPU added to `flysim.slice`; the deploy writes it to `fly.env` as
|
||||
`FLY_SESSION_AUX_CPUS`, and the session pins the bus runtime there and the sweep and dispatcher to
|
||||
the rest). Without it the runtime shares the host CPU with the sim's dispatcher, which costs about
|
||||
1 ms per frame measured (the publisher is 1.3 to 2.5 ms of CPU per snapshot, 30 a second, on the
|
||||
critical path; the barrier stalls behind it). Check: `grep Cpus_allowed_list /proc/$(pidof
|
||||
flysim-session)/task/*/status` for the `flysim-bus` threads shows the aux CPU alone. Set it, run the
|
||||
deploy, restart flysim, and only then `fly-feed bus`.
|
||||
- **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A
|
||||
reboot empties it; a crashed flysim's directory is removed by the next one.
|
||||
- **Control (`:7401`)** stays in flysim and is not part of this switch.
|
||||
|
||||
## Shadow run (SHADOW-01)
|
||||
|
||||
The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The
|
||||
contract is `docs/design/session-framework/legacy-gameboy-v1.md` section 18. The shadow is
|
||||
report-only: it presses no button, serves no port, and only reads flysim's stores and trace. Claim
|
||||
the release container in the host log first, as for any host work.
|
||||
|
||||
```
|
||||
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, remote shadow + guard, one flysim restart
|
||||
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict, the relay (and a guard trip) in one screen
|
||||
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
|
||||
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
|
||||
```
|
||||
|
||||
- **A shadow of the bus topology (BUS-01).** `start --bus` runs the box's shadow session with its
|
||||
agent and world as child processes on its router's sockets (`FLY_SHADOW_MODE=bus/process`, which
|
||||
the relay forwards); `check --bus` also requires that the verdict ran that topology
|
||||
(`candidate.transport` `bus`, `executionMode` `process`). The live fly must be on the legacy
|
||||
runtime for any shadow: only the legacy loop writes the trace, and `start` refuses otherwise.
|
||||
|
||||
- **Where it runs (SHADOW-02).** On a build box, not on the release container: there it cost the
|
||||
live fly real time (2026-09-30: the realtime factor fell from 0.9998 to 0.93-0.98 and came back
|
||||
to 0.999-1.0 the moment the shadow stopped), and at about 27 ms a frame on shared CPUs it fell
|
||||
further behind every hour. `start` refuses without the remote configuration below; `start --local`
|
||||
runs it on the container anyway. In remote mode `flyshadow.service` on the container is the
|
||||
*relay* (`fly-shadow relay`, from a drop-in `start` writes): normal scheduling off flysim's CPUs,
|
||||
a few file reads and one outbound ssh stream that carries the trace, the new saves and the sugar
|
||||
journal to the box and brings the box shadow's verdict back to `/srv/fly/shadow/verdict.json`.
|
||||
The guard, `check` and CUT-01 see the unit and the files they always did. Set-up below
|
||||
("Remote shadow set-up").
|
||||
- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty
|
||||
10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth
|
||||
rate. It refuses unless flysim ran normally for most of that time. Then it:
|
||||
1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
|
||||
`FLY_TRACE_LEDGERS=60`) and, remote, `flyshadow.service.d/remote.conf` (the relay, and this
|
||||
run's id: the start's Unix ms);
|
||||
2. starts `flyshadow.service` and waits for its heartbeat (remote: up to 5 minutes, while the
|
||||
box resets its mirror, restarts its shadow for the new run and reports it alive);
|
||||
3. restarts `flysim.service` once;
|
||||
4. starts `flyshadow-guard.timer`.
|
||||
|
||||
`FLY_SHADOW_BASELINE_SECONDS` shortens the baseline, for tests only. The restart is the same one
|
||||
the unstick rule uses: the rung is kept and the ledgers are cleared. A previous `verdict.json`
|
||||
is kept beside the new one, renamed with its time.
|
||||
- **The guard** runs every 60 s, automatically, and judges the live fly against its own baseline,
|
||||
not against real time. A fly that already ran at 0.66 is fine at 0.66. It trips only on a
|
||||
sustained degradation: 3 checks in a row in which the last 5 samples of the same flysim process
|
||||
fall below the baseline, or grow lag faster than it, by more than the margin. The margin is
|
||||
max(0.05, 4 x the baseline spread / sqrt 5). A trip is at the earliest about 7 minutes after a
|
||||
real degradation begins. A tripped guard stops the shadow and the guard, removes the drop-in and
|
||||
restarts flysim without the trace. It records why in `/srv/fly/shadow/guard-tripped.json`, and
|
||||
`status` shows it. A paused fly is not judged, and a restarted one starts its window again.
|
||||
Once the shadow is down for good (`ActiveState` inactive or failed: diverged, stopped, given up),
|
||||
the guard stops itself and changes nothing. While the shadow waits out its 10-s crash-restart delay
|
||||
(`activating`) the guard keeps running. A trip is not a divergence: fix the resources, then `start` again.
|
||||
- **While it runs**, every later flysim restart (the unstick rule, the watchdog,
|
||||
`fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on
|
||||
its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes.
|
||||
Stopping or restarting `flyshadow.service` itself starts the window again.
|
||||
- **Pass**: `status` shows `verdict pass` once both of these hold with zero divergence:
|
||||
- 10,800 brain seconds are compared;
|
||||
- at least one live save per 10 brain minutes has been compared byte for byte.
|
||||
|
||||
The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01
|
||||
runs `check` at the moment it cuts over. `check` also requires all of these:
|
||||
- at least 10,800 brain seconds, whatever window the shadow was started with;
|
||||
- the guard has not tripped, `flyshadow.service` is running, `flyshadow-guard.timer` is active and
|
||||
`baseline.json` exists (a run no guard watched is never cut over);
|
||||
- remote: `/srv/fly/shadow/relay.json` is less than a minute old and `healthy` (connected, the
|
||||
box's shadow of this run alive, the sync caught up), and the verdict is this run's (`runId`);
|
||||
its `lagTransitions` counts the live trace not yet on the box as well;
|
||||
- the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
|
||||
other shadowed binary unchanged;
|
||||
- the shadow is caught up (at most about a minute behind);
|
||||
- remote: `relay.json` is this run's (its `runId`, the verdict's and the drop-in's are one), has
|
||||
no `coverageLost`, and its `traceAgeSeconds` (the newest live trace file's age) is at most 90 s:
|
||||
a trace that is not being written while the shadow claims to follow refuses the check (a paused
|
||||
flysim refuses too, until it runs);
|
||||
- remote, the two hosts' clocks agree: the verdict's `updatedAt` is the box's clock and the check
|
||||
bounds its age to within 60 s, so clock skew between the container and the box makes `check`
|
||||
refuse (safe, not silent). Run NTP on both;
|
||||
- the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future
|
||||
(a clock stepped back must not keep an old pass fresh);
|
||||
- no segment was skipped for a reason other than the live side's own.
|
||||
- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). A failure
|
||||
of the session runtime itself counts: it did not start, the restore gate refused the live save,
|
||||
or a step failed. The shadow leaves `verdict.json` at `diverged` and
|
||||
`/srv/fly/shadow/divergence.json` with the field, both values and the 30 transitions before it.
|
||||
On a checkpoint difference it also leaves both checkpoint files. It removes its heartbeat, so
|
||||
flysim stops tracing within a minute. The live fly is untouched. Run `stop --keep`, pull the
|
||||
files for the review, and do not cut over.
|
||||
- **The trace cannot outlive the shadow.** flysim starts no trace without the shadow's fresh
|
||||
heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the
|
||||
heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was
|
||||
stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
|
||||
deletes every file it has compared (remote: the box deletes its copy, and the relay then deletes
|
||||
the container's). Remote, the heartbeat is the relay's, and it is written only while the relay is
|
||||
healthy: a dead box, a dead box shadow, a broken link or a sync more than a minute behind all stop
|
||||
it, and flysim then stops its trace as for a dead local shadow. A trace that stops that way while
|
||||
the shadow follows it is a `coverage` divergence: that process can no longer be compared. A
|
||||
network blip shorter than the 10 minutes costs nothing for the trace: the relay resumes where
|
||||
the box's copy ends. The hot saves queued in the relay (400 MiB, about 12 minutes) cover the same
|
||||
window; beyond it a save may be missed, which the unavailable-checkpoint allowance absorbs.
|
||||
**A stop that did happen is never forgotten** (review B1): after an outage of more than 10 minutes
|
||||
flysim stops its trace (`no-consumer`) and runs on untraced. When the link heals the box is alive
|
||||
and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay
|
||||
therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in
|
||||
`/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses
|
||||
until the box's shadow reaches the stop and diverges (`coverage`), or ends its window at that
|
||||
stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage
|
||||
gap, never a skip. The shadow discards the brain time and saves compared before it
|
||||
(`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the
|
||||
last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops
|
||||
the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while
|
||||
`coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or
|
||||
a later one) and for a verdict without a `window`. Catching up and restarting never clear it.
|
||||
The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
|
||||
does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
|
||||
the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
|
||||
new window has compared the required time.
|
||||
**After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
|
||||
would have to restart while the stopped trace is still the newest file and reach its stop before
|
||||
any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
|
||||
(`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
|
||||
container, `pct exec <release-ctid> --` in front): `/opt/fly/bin/fly-shadow-run stop
|
||||
--restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
|
||||
one.
|
||||
**Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
|
||||
restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
|
||||
and the run is lost (safe: start a new run as above); do not rely on the fast case.
|
||||
`coverageLost` is synced to disk before the chunk with the stop is forwarded.
|
||||
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame.
|
||||
Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the
|
||||
container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network:
|
||||
the hot save every 5 s is 2.7 MB, the trace about 140 MB an hour) and the trace writer inside
|
||||
flysim: about 1.3 ms of the sim thread a frame (measured unpaced on a build box's Haswell, 3
|
||||
threads: 11.1 to 12.5 ms). The guard's baseline is taken before the trace is on, so that cost
|
||||
counts against it; if the guard trips on a remote run, the trace alone is too much for the live
|
||||
fly's headroom. `--local` runs it `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh
|
||||
writes its `cpuset.conf`), pausing for a minute while flysim's lag grows faster than its
|
||||
baseline rate. Disk on the container: the trace until the box has compared it (under 8 GiB);
|
||||
on the box: the mirrored saves (under 3 GiB) and a spool of at most 4 GiB.
|
||||
- **Start** refuses, and starts nothing, unless `flyshadow.service.d/cpuset.conf` exists and the
|
||||
unit's `AllowedCPUs` (`systemctl show`) is disjoint from flysim.service's (05-deploy skips every
|
||||
cpuset drop-in when the CT conf and CPUSET disagree).
|
||||
- **Stop** stops the unit and the guard, removes the drop-ins, and deletes the trace and the spool
|
||||
(`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
|
||||
within a minute, because its consumer is gone. Remote, the box's shadow keeps running idle until
|
||||
the next `start`, which resets its mirror and restarts it for the new run.
|
||||
- **Remote divergence**: the box's shadow stops (exit 3); the relay brings `divergence.json` and
|
||||
both checkpoint files back to `/srv/fly/shadow/`, writes the diverged verdict and exits with
|
||||
status 3 (the unit stays stopped, the guard stops itself). Pull the files from the container as
|
||||
for a local divergence.
|
||||
|
||||
### Remote shadow set-up (SHADOW-02)
|
||||
|
||||
Once per build box, and again for every release the container runs. The real values (the box's
|
||||
address, the key's path) go in the operator's private files, never in this repository. Nothing
|
||||
on the build box can reach the release container: the container dials out.
|
||||
|
||||
1. **The relay's key**, on the release container (as root, claimed):
|
||||
`install -d -o root -g fly -m 0750 /etc/fly/shadow-remote`, then
|
||||
`ssh-keygen -t ed25519 -N '' -C fly-shadow-relay -f /etc/fly/shadow-remote/id_ed25519` and
|
||||
`chown fly:fly /etc/fly/shadow-remote/id_ed25519*`. The private half never leaves the container.
|
||||
The container needs an ssh client (`openssh-client`; `02-base.sh` installs it) and no sshd.
|
||||
2. **The box** (as root on the box): copy the release tarball the container runs, the cartridge,
|
||||
`infra/box/` and the public key there, then
|
||||
`infra/box/fly-shadow-remote-setup flybrain-<version>.tar.gz <rom> id_ed25519.pub --from <container address> --cpus <its cores> --threads <one per core>`.
|
||||
It installs the release at the same `/opt/fly/releases/<version>` path (MANIFEST-verified,
|
||||
root-owned), a `flyshadow` user whose home is a root-owned `/srv/fly-shadow-remote-home` (so the
|
||||
user cannot rename `.ssh`; the mirror `/srv/fly-shadow-remote` is the user's and is never
|
||||
followed through a symlink on a re-run), a root-owned `authorized_keys` whose only line is
|
||||
`restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" <key>`,
|
||||
`/etc/fly/fly-shadow-remote.env` (the box's `FLY_ROM`, `FLY_DATASET`), and
|
||||
`flyshadow-remote.service` + `.path` (enabled). Put the box's host key into
|
||||
`/etc/fly/shadow-remote/known_hosts` on the container (`ssh-keyscan` from the host, checked by
|
||||
hand).
|
||||
3. **The container's remote file**, `/etc/fly/shadow-remote.env` (root, 0600):
|
||||
`FLY_SHADOW_REMOTE=flyshadow@<box address>`,
|
||||
`FLY_SHADOW_REMOTE_KEY=/etc/fly/shadow-remote/id_ed25519`,
|
||||
`FLY_SHADOW_REMOTE_KNOWN_HOSTS=/etc/fly/shadow-remote/known_hosts`
|
||||
(and `FLY_SHADOW_REMOTE_PORT` if the box's sshd is not on 22). `fly-shadow-run start` finds
|
||||
it and runs in remote mode.
|
||||
4. `fly-shadow-run start` as above. **Then watch the live fly's realtime factor by hand for the
|
||||
first hour** (`fly_realtime_factor` on the metrics endpoint): stop the shadow if its 30-minute
|
||||
median is below 0.99. The guard's floor is a 5 % margin on the baseline and cannot see the
|
||||
trace's cost (about 1.3 ms a frame, 2 to 3 %); on the rehearsal it tripped only by chance,
|
||||
after an hour. The ingest refuses a relay whose release directory or binaries
|
||||
differ from the box's (another release on the container: re-run step 2 with its tarball);
|
||||
`journalctl -u flyshadow` on the container shows it.
|
||||
|
||||
Which box: never one on the live fly's NUMA node (flysim is memory-bandwidth-bound: in the
|
||||
SHADOW-02 rehearsal an unpaced flysim on a neighbouring box of the same node took a paced one from
|
||||
1.0 to 0.68-0.88). The shadow must also run clearly faster than real time (16.7 ms a frame) to
|
||||
catch up after a restart; measured per frame (mean, unthrottled replay): 11.8 ms on the second
|
||||
host's box with 4 threads, 11.9-12.2 ms on the build boxes of the release host's other node with
|
||||
6 threads (13-14 ms with 3-4). Give it 4 cores (second host) or all 6 (same host, other node)
|
||||
with `--cpus` and `--threads`; keep other heavy work (bx) off that box
|
||||
for the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`).
|
||||
|
||||
## Cutover to the session runtime (CUT-01)
|
||||
|
||||
Operator decision (2026-09-30): the stream moves to the session runtime only if that runtime
|
||||
sustains at least 1.0x real time on the release container, otherwise it stays on legacy. Only the
|
||||
release container can measure that, so the switch is guarded by a **probation**. Claim the
|
||||
container in the host log first, as for any host work.
|
||||
|
||||
```
|
||||
# 1. Deploy v0.7.0 with flysim-session installed but NOT selected (no drop-in): the ordinary deploy.
|
||||
# The container keeps running legacy; nothing else changes. (fly-runtime status: legacy)
|
||||
# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact; on a build box
|
||||
# (Remote shadow set-up above, once per box and release):
|
||||
pct exec $CTID -- /opt/fly/bin/fly-shadow-run start
|
||||
pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass
|
||||
# 3. Cutover: the shadow's gate, then the switch. One command line:
|
||||
pct exec $CTID -- sh -c '/opt/fly/bin/fly-shadow-run check && /opt/fly/bin/fly-runtime session'
|
||||
# 4. Watch the probation (30 minutes after the switch):
|
||||
pct exec $CTID -- /opt/fly/bin/fly-runtime-probation status
|
||||
pct exec $CTID -- /opt/fly/bin/fly-runtime status
|
||||
# 5. Pass, or automatic fallback (below). Nothing to stop: step 3 already stopped the shadow.
|
||||
# Manual rollback, any time (cancels the probation too):
|
||||
pct exec $CTID -- /opt/fly/bin/fly-runtime legacy
|
||||
```
|
||||
|
||||
- **Step 3 in detail.** `check` refuses unless the verdict, the guard and the release all line
|
||||
up (Shadow run above). `session` then does what "Switch the runtime" describes (compatibility
|
||||
check, drop-in, restart, health wait) and, once flysim is healthy on the session runtime, starts
|
||||
the probation. `session` returns 0 at that point: the probation is judged later, by the timer.
|
||||
`session` also stops the shadow and its guard (`fly-shadow-run stop`, never
|
||||
`--restart-flysim`) as soon as flysim is healthy on the session runtime, before the probation
|
||||
starts. A guard left running would judge the session runtime against the legacy baseline and
|
||||
restart flysim on a trip (a second start inside the 600 s start-limit window, and a reset
|
||||
warm-up), and the session writes no trace, so the shadow has nothing to follow. If you stop the
|
||||
shadow by hand at any time during the probation, do it without `--restart-flysim`.
|
||||
- **The probation** (`infra/bin/fly-runtime-probation`, `fly-runtime-probation.timer` every 60 s,
|
||||
root). Each tick takes one sample of flysim's `/metrics` (`fly_realtime_factor` averaged over 10
|
||||
one-second reads, `fly_lag_seconds`, `fly_uptime_seconds`; the same sampling as the shadow
|
||||
guard). It judges the session runtime only:
|
||||
- *Warm-up.* A flysim process is not judged before it has been up 300 s (connectome load,
|
||||
restore, first minutes). A restart, a pause or a fly that is not `running` starts the window
|
||||
again; it is never counted as slow.
|
||||
- *Failure*, sustained and not one sample: over the judged samples of the last 10 minutes (at
|
||||
least 8 of them) the **median** realtime factor is below **0.97**, or the lag grew by more than
|
||||
**30 s** from the window's start to its end (median of the first and of the last three
|
||||
samples). The median is the robust statistic the shadow guard's baseline uses: one or two
|
||||
stalled minutes do not fail it, a steady 0.85x does, at the earliest about 13 minutes after the
|
||||
switch (5 min warm-up, 8 samples). A lag step of more than 30 s inside the window counts as
|
||||
lag growth.
|
||||
- *Pass*: 30 minutes since the switch, and the latest window is full and healthy. A probation
|
||||
that cannot fill a window within 2 h (a fly that never runs) fails as inconclusive: no proof
|
||||
of 1.0x, no cutover. `FLY_PROBATION_*` variables tune every number (tests and rehearsals only).
|
||||
- **On failure** it runs `fly-runtime fallback "speed: ..."`, exactly the fallback of "Switch
|
||||
the runtime": under the same lock, `/run/fly/runtime-fellback.json` with the reason
|
||||
(`"speed: median realtime factor 0.850 < 0.97 ..."`), the drop-in removed, flysim restarted on
|
||||
legacy, a `fly-runtime` journal line (`journalctl -t fly-runtime`,
|
||||
`/var/lib/fly/runtime.log`), and the probation ended (`/var/lib/fly/probation/last.json`
|
||||
says `passed: false`). If that fallback cannot complete (no executable `flysim`) it is retried
|
||||
every minute. The container is then on legacy and the decision is "no cutover": do not retry
|
||||
`session` without a fix (or a new measurement) for the cause.
|
||||
- **On pass** it writes `/run/fly/runtime-probation.json` (`{"passed": true, "at", "startedAt",
|
||||
"medianRtf", "lagGrowth", "samples", "detail"}`; also kept in
|
||||
`/var/lib/fly/probation/last.json` because `/run` is cleared by a reboot) and disables its
|
||||
timer. **Nothing judges the speed afterwards.** A continuous guard would make a passing
|
||||
cutover fall back at 03:00 on one noisy hour, on a stream that has proven itself, and the
|
||||
watchdog already covers a stuck or dead loop. The start-limit fallback also stays as it is.
|
||||
- **Cancel and resume.** `fly-runtime legacy` cancels the probation, as does every fallback
|
||||
(including the start-limit one), and a tick that finds the legacy runtime selected ends it
|
||||
without a verdict. The state is `/var/lib/fly/probation/state.json` and the timer is enabled while
|
||||
a probation runs (`[Install] WantedBy=timers.target`; nothing else enables it), so a reboot
|
||||
during the probation resumes it: `OnBootSec=90s` runs the first tick, flysim's new process
|
||||
starts a new warm-up and window, and the 30 minutes keep counting from the original switch.
|
||||
`fly-runtime session --no-restart` (05-deploy's refresh of the drop-in) starts no probation;
|
||||
`fly-runtime session --no-probation` is for rehearsals. A `session` that cannot start the
|
||||
probation (helper or timer unit missing) falls back: an unguarded cutover is not allowed.
|
||||
- **Reading the result honestly.** The probation is absolute, as decided: a container on which the
|
||||
legacy loop itself runs below 0.97x (the release container has been measured at 0.66, and 0.77-0.99
|
||||
after its cpuset rebalance) will fail it, and the session runtime was measured at 1.25-1.35x
|
||||
legacy's time per frame on the dev box. A fallback with reason `speed` therefore means "this box
|
||||
cannot hold real time on the session runtime", not necessarily "the session runtime is
|
||||
broken"; compare with `fly-shadow-run`'s baseline (`/srv/fly/shadow/baseline.json`) before
|
||||
anything else. The `check` before it measures the live fly against itself; this measures it
|
||||
against the clock.
|
||||
- **Rehearsal** without a host: `fly-runtime-probation simulate CHECKS.jsonl` runs the rule over
|
||||
recorded samples (`{t, status, rtMean, lag, uptime}`, one a minute); `infra/tests/lint.sh` drives
|
||||
the real `fly-runtime` and the probation over synthetic traces (healthy, 0.85x, a stall, lag
|
||||
growth, a restore, a restart, legacy cancel), and the unit wiring has been run under a real
|
||||
systemd 257 user manager (state, timer enable/disable, `OnFailure`-style fallback, resume).
|
||||
|
||||
## Control over the bus (CTRL-01)
|
||||
|
||||
`FLY_CONTROL_VIA` picks who serves `http://127.0.0.1:7401`: `direct` (the default; flysim binds
|
||||
it) or `bus`. In bus mode flysim registers the control API as RPC services on its embedded flybus
|
||||
router, and `flycontrol-edge.service` serves the same HTTP bytes on `:7401` by calling them
|
||||
(`docs/design/flybus.md`, "Control over the bus"). Clients do not change: the bridge, the stage's
|
||||
health wait, the watchdog, `fly-runtime`, the probation and shadow guards, `fly-loop-recover`,
|
||||
the stream check and `curl` still talk to `:7401`. It works under either runtime, independently
|
||||
of `FLY_FEED_VIA`. Claim the container in the host log first, as for any host work.
|
||||
|
||||
**Prerequisites.** The release ships `fly-control-edge` (`ls /opt/fly/current/fly-control-edge`).
|
||||
The env file has `FLY_CONTROL_VIA=bus`, deployed with `05-deploy.sh`. The deploy only rewrites
|
||||
`/etc/fly/fly.env` and pushes the unit; it neither enables the edge nor restarts flysim, so the
|
||||
box keeps serving `:7401` directly until step 2.
|
||||
|
||||
```
|
||||
# 1. Before: what the switch must preserve.
|
||||
pct exec $CTID -- grep -E '^FLY_(CONTROL|FEED)_VIA=' /etc/fly/fly.env # FLY_CONTROL_VIA=bus
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status, .checkpoint'
|
||||
pct exec $CTID -- curl -s -X POST 127.0.0.1:7401/checkpoint # a fresh generation to restart from
|
||||
# 2. The switch: flysim stops binding :7401 and registers the services; the edge (Wants= of
|
||||
# flysim.service, started with it because fly.env says bus) binds :7401 once they answer.
|
||||
# Between the two, :7401 refuses connections, exactly as during any flysim restart.
|
||||
# There is nothing to enable: the unit has no [Install] section.
|
||||
pct exec $CTID -- systemctl restart flysim.service
|
||||
# 3. Verify.
|
||||
pct exec $CTID -- ss -ltnp | grep ':7401' # users:(("fly-control-edg"...
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # {"status":"ok"}
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status' # the frame moves
|
||||
pct exec $CTID -- curl -s 127.0.0.1:9103/metrics | grep -E '^fly_control_edge_(bus_connected|calls_total|call_failures_total)'
|
||||
pct exec $CTID -- journalctl -u flysim -b --since -5min | grep -E 'control services registered|bus listening'
|
||||
pct exec $CTID -- ls /run/fly/bus/control-edge.sock /run/fly/bus/control/
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7410/health | jq . # the bridge: sim reachable
|
||||
```
|
||||
|
||||
- **Healthy looks like:** `fly_control_edge_bus_connected 1`, `calls_total` rising (the bridge and
|
||||
the watchdog poll it), `call_failures_total` flat, no `fly-watchdog:` restart lines, and the next
|
||||
real channel-points sugar fulfilled as before. Do not fire a test sugar or chat line on the live
|
||||
stream to prove it; both are visible on screen.
|
||||
- **Watchdog.** With `FLY_CONTROL_VIA=bus`, check 1 reads flysim's own `/healthz` on `:9101`, so a
|
||||
dead edge never restarts the fly. Check 1b restarts `flycontrol-edge` alone when `:7401` fails
|
||||
while flysim is healthy (the sudoers file grants exactly that restart).
|
||||
- **Restarts.** `flysim.service` has `Wants=flycontrol-edge.service` and the edge has `Requires=`
|
||||
on flysim plus an `ExecCondition=` on `FLY_CONTROL_VIA`, so the edge follows flysim in bus mode
|
||||
and stays off ("skipped", not failed) in direct mode. A `restart`, and a `stop` then `start`
|
||||
(`fly-loop-reset`, `fly-reset-to-milestone`, the milestone-reset rung of the unstick rule) all
|
||||
bring `:7401` back with flysim; nothing needs a separate `start` of the edge. A crash-restart of flysim needs nothing: the edge
|
||||
unbinds `:7401`, reconnects every 500 ms and binds again once the new services answer.
|
||||
|
||||
**Rollback** (any time, no release change):
|
||||
|
||||
```
|
||||
pct exec $CTID -- sed -i 's/^FLY_CONTROL_VIA=.*/FLY_CONTROL_VIA=direct/' /etc/fly/fly.env
|
||||
pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself; the edge is skipped
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz
|
||||
# then set FLY_CONTROL_VIA=direct in the env file too, or the next 05-deploy.sh writes bus back.
|
||||
```
|
||||
|
||||
- **Rolling back to a release from before CTRL-01 while in bus mode** is safe. The older flysim
|
||||
does not know `FLY_CONTROL_VIA`, so it binds `:7401` itself. The edge unit's
|
||||
`ConditionPathExists=` keeps it inactive on a release without the binary, and the older
|
||||
watchdog reads `:7401` as before. Switch to direct first anyway, so the env file says what
|
||||
runs.
|
||||
- **If the edge cannot bind** (`fly_control_edge_bind_failures_total` rising, "the control port
|
||||
cannot be bound" in its journal), flysim is still in direct mode. `fly.env` says bus but flysim
|
||||
was not restarted after the deploy. Restart flysim (step 2).
|
||||
- **Upgrading a container that had the edge enabled** (before this wiring): an
|
||||
old `fly.target.wants/flycontrol-edge.service` symlink is harmless (the condition decides), but
|
||||
run `systemctl disable flycontrol-edge.service` once so `systemctl is-enabled` says what is true.
|
||||
|
||||
## CPU partition (cpuset)
|
||||
|
||||
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
|
||||
|
|
@ -492,6 +1098,78 @@ not a constant, and live in the operator's infra repo
|
|||
ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh`
|
||||
checks it against both the current shape and the earlier, narrower one.
|
||||
|
||||
### The sim's CPUs are exclusive to the sim (PERF-02 review N1)
|
||||
|
||||
The session runtime pins its sweep workers one per CPU. A pinned worker cannot leave its CPU, so
|
||||
any sustained CPU-bound process that is allowed on a worker's CPU stalls every barrier: measured
|
||||
**0.14x real time** with a plain busy loop (0.68x at nice 19; `SCHED_IDLE` was harmless; the
|
||||
floating, unpinned runtimes held 0.86-0.94x under the same hog). Priorities cannot fix that, so
|
||||
the partition above is completed by making the sim's CPUs exclusive:
|
||||
|
||||
- `flysim.service` and `flysim-session.service` run in **`flysim.slice`** (`units/flysim.slice`),
|
||||
whose `AllowedCPUs=` is the sim's set (`flysim.slice.d/cpuset.conf`, written by `05-deploy.sh` from
|
||||
`lib/common.sh`'s `cpuset_dropin_plan`, the same call that writes every other drop-in).
|
||||
- `bin/fly-cpu-confine apply` sets `AllowedCPUs=` the **non-sim** CPUs on `system.slice` (every
|
||||
other service, cron, apt, sshd), `user.slice` (every login session) and `init.scope`, and writes
|
||||
the same list to `/sys/fs/cgroup/.lxc/cpuset.cpus` (where `pct exec` / `pct enter` processes land,
|
||||
see below). It runs as
|
||||
both sim units' `ExecStartPre` (root, failure never blocks the start), so it is re-applied after
|
||||
every boot and every restart. The lists come from `/etc/fly/cpuset.env`, which the deploy writes.
|
||||
- The slice is named without a dash on purpose: systemd nests `a-b.slice` under `a.slice`, and a
|
||||
child's cpuset is bounded by its parent's (cgroup v2: effective cpus = own cpus intersected with
|
||||
the parent's, and the parent's when that is empty). `flysim.slice` sits beside `system.slice`
|
||||
under the root slice, so nothing above it excludes its CPUs.
|
||||
- **Ordering rule.** Shrinking `system.slice` under a flysim that still sits in `system.slice` (a
|
||||
unit started before this change, not yet restarted) would leave its own `AllowedCPUs=` outside the
|
||||
parent's set and silently make it float over the page CPUs. So `apply` refuses (exit 3, nothing
|
||||
changed) while a sim unit's cgroup is not under `/flysim.slice/`. A deploy therefore changes
|
||||
nothing on a running sim; the confinement starts with the next `flysim` (re)start, which is the
|
||||
first moment it is safe. `fly-cpu-confine status` shows the result.
|
||||
- `fly-recap` and `fly-retention` also run at `CPUSchedulingPolicy=idle`, which the review measured
|
||||
harmless beside the pinned workers (defence in depth for the batch jobs).
|
||||
- **No partition, no pinning.** With `CPUSET` unset (or the container conf not matching it) there
|
||||
is no confinement, so `05-deploy.sh` writes `FLY_SESSION_PIN=0` to `/etc/fly/fly.env` and the
|
||||
session runtime's threads float, as before PERF-02. With the partition in force it writes
|
||||
`FLY_SESSION_PIN=1`. (The runtime treats exactly `0` as off.)
|
||||
- **`pct exec` / `pct enter`:** `lxc-attach` puts its processes in the cgroup `/.lxc` (or
|
||||
`/.lxc-N`), a sibling of `system.slice` that systemd does not manage. `apply` writes the non-sim
|
||||
list into the `cpuset.cpus` of every such cgroup that already exists (it never creates one; lxc
|
||||
owns it). Where that file is not writable it logs a warning and carries on: `apply` never fails
|
||||
the sim's start. In that case run long operator jobs through
|
||||
`pct exec <ctid> -- systemd-run --scope --slice=system.slice -- <command>`. A `.lxc-N` created
|
||||
after `apply` is not covered until the next sim start. `fly-cpu-confine check` lists every
|
||||
process outside `flysim.slice` that may run on a sim CPU (exit 1 if there is one); its own
|
||||
process and the shell chain it was started from are printed as a note and not counted, so it
|
||||
exits 0 on a healthy container when run through `pct exec`.
|
||||
- **After the first deploy (once):** restart the sim so the confinement is applied, then read it.
|
||||
`apply` is refused while flysim still runs outside `flysim.slice`, so nothing changes until then.
|
||||
```
|
||||
pct exec <ctid> -- systemctl restart flysim.service
|
||||
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine status # system.slice, user.slice, init.scope and /.lxc = the non-sim cpus; flysim.slice = the sim's; flysim ControlGroup under /flysim.slice/
|
||||
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine check # exit 0: "ok: only flysim.slice can reach ..."
|
||||
pct exec <ctid> -- systemctl show -p AllowedCPUs flycast.service xvfb.service # still the drop-in values
|
||||
```
|
||||
Then watch the probation RTF. A `check` that names a process is a hog to move or stop.
|
||||
- **If lag grows on the session runtime**: `fly-cpu-confine check`, then `top -H` for a stray hog on
|
||||
the sim's CPUs. `FLY_SESSION_PIN=0` (a drop-in) restores floating.
|
||||
- `fly-cpu-confine release` undoes the runtime confinement (until the next sim start); it sets
|
||||
`system.slice`, `user.slice`, `init.scope` and `/.lxc` back to the container's whole cpuset
|
||||
explicitly, because systemd keeps the old mask for an empty `AllowedCPUs=` while the cpuset
|
||||
controller stays on for another unit. (Tested in `tests/lint.sh` against a fake cgroup tree.)
|
||||
- **Rollback by re-running an older infra tree's `05-deploy.sh`** (rather than the symlink flip in
|
||||
"Roll back a release", which is fine): an infra tree older than this change has no
|
||||
`Slice=flysim.slice`, so flysim restarts into `system.slice`, which is still confined to the
|
||||
non-sim CPUs. Its `AllowedCPUs=` then does not intersect that set and it floats over the page and
|
||||
encoder CPUs while the sim's own CPUs sit idle (the slow shape again, not a black stream). After
|
||||
such a rollback run `pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine release` (or reboot), then
|
||||
restart flysim.
|
||||
|
||||
Verified on a real-systemd box (4 CPUs, the sim as a unit in `flysim.slice` on 3 of them, 3 sweep
|
||||
threads, paced at 0.55x): confined or not, with no hog the session holds 0.55; five busy loops (three
|
||||
as system services, two from a user shell) unconfined sit on the sim's CPUs and the session drops to
|
||||
0.37; confined by the unit's own `ExecStartPre`, every loop samples on CPU 0 only, the sim's threads
|
||||
keep their CPUs and the session holds 0.54-0.55.
|
||||
|
||||
### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition
|
||||
|
||||
`FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into
|
||||
|
|
@ -504,13 +1182,49 @@ loud which backend is configured. Two separate switches, deliberately:
|
|||
| build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed |
|
||||
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
|
||||
|
||||
A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
|
||||
A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
|
||||
backend from flysim's own log, not from the env file:
|
||||
|
||||
```sh
|
||||
pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend'
|
||||
```
|
||||
|
||||
The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables
|
||||
(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without
|
||||
the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with
|
||||
`BACKEND_FAILURE`; a build with it logs `LIF backend cuda:<n> attached, device-owned state` when
|
||||
the worker starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the
|
||||
card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual
|
||||
drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the
|
||||
feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too.
|
||||
|
||||
**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no
|
||||
paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches
|
||||
a dead card in a loop:
|
||||
|
||||
- A CUDA error on a frame whose host state was current (the first frame after a start or a
|
||||
restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there.
|
||||
- Any other CUDA error mid-run fails the agent (the device held the only current copy of the
|
||||
membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on
|
||||
the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact,
|
||||
so the CPU run equals one that never had a GPU.
|
||||
- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and
|
||||
a CPU worker, not a failed `Agent.Initialize`.
|
||||
- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still
|
||||
dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU.
|
||||
|
||||
Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure,
|
||||
with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs),
|
||||
`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the
|
||||
textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and
|
||||
`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises
|
||||
`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It
|
||||
takes no remediation and pages no one (a restart cannot fix a dead card and would cost the
|
||||
run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host,
|
||||
and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2`
|
||||
(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0`
|
||||
and redeploy if the card is not coming back soon.
|
||||
|
||||
It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the
|
||||
container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
|
||||
targets, `sm_75`.
|
||||
|
|
@ -749,6 +1463,50 @@ The card is shared with **the neighbouring GPU container (`ml`, the GPU workload
|
|||
mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let
|
||||
whichever container got there first lock the card out from under the other.
|
||||
|
||||
## GPU on a build box (dev and benchmarks)
|
||||
|
||||
A build box is a container with the host's `/dev/nvidia*` device nodes passed through but no
|
||||
userspace driver installed — used for the `cuda` feature tests and the GPU benchmarks. The
|
||||
release container follows the lockstep runbook above; this path is only for build boxes,
|
||||
no root, no system install, one userspace per test run.
|
||||
|
||||
**Get the host's module version** — the .run must match exactly:
|
||||
|
||||
```sh
|
||||
ssh the host cat /proc/driver/nvidia/version # the "Kernel Module" line
|
||||
# or: ssh the host cat /sys/module/nvidia/version
|
||||
```
|
||||
|
||||
**Install under your home.** Download the matching `NVIDIA-Linux-x86_64-<ver>.run`, verify
|
||||
its SHA256 against the checksum NVIDIA publishes, and `--extract-only`:
|
||||
|
||||
```sh
|
||||
VER=580.76.05 # whatever the host module reports
|
||||
mkdir -p ~/tmp/nvidia-$VER && cd ~/tmp/nvidia-$VER
|
||||
U=https://download.nvidia.com/XFree86/Linux-x86_64/$VER/NVIDIA-Linux-x86_64-$VER.run
|
||||
curl -fSLO $U && curl -fSLO $U.sha256sum
|
||||
sha256sum -c NVIDIA-Linux-x86_64-$VER.run.sha256sum # must print OK
|
||||
sh NVIDIA-Linux-x86_64-$VER.run --extract-only --target ~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
|
||||
```
|
||||
|
||||
**Use it only for the test run.** Prepend the extracted directory to `LD_LIBRARY_PATH`
|
||||
(`libcuda.so`, `libnvidia-ptxjitcompiler.so`) and `PATH` (`nvidia-smi`); the kernel
|
||||
modules are the host's, so nothing else is needed:
|
||||
|
||||
```sh
|
||||
NV=~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
|
||||
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH FLY_CARGO_FEATURES=cuda \
|
||||
cargo test --release -p flybrain-core --features cuda
|
||||
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH \
|
||||
cargo run --release -p flybrain-core --features cuda --example cuda_bench
|
||||
```
|
||||
|
||||
**Shared card.** The build box shares the GPU with the LLM workload. Before and after each
|
||||
timing run, `nvidia-smi` for other compute processes on the device; re-run flagged timings
|
||||
(benchmarks yield to the other workload — a contended run is not a measurement).
|
||||
|
||||
**Never on the release container** — that path is the lockstep one above.
|
||||
|
||||
## The host reboot order
|
||||
|
||||
Fly containers have no special reboot ordering requirement relative to each other
|
||||
|
|
|
|||
32
infra/env/example.env
vendored
32
infra/env/example.env
vendored
|
|
@ -138,6 +138,12 @@ RAYON_THREADS=3
|
|||
# cpuset_partition (default 2 when unset). flycast gets its own group rather
|
||||
# than sharing the page group — see lib/common.sh's cpuset_partition header.
|
||||
ENCODER_CORES=2
|
||||
# SESSION_AUX_CPUS: how many page cpus (taken from the end of the page group) flysim.slice gets in
|
||||
# addition to the sim's, for the session runtime's bus threads (the feed publisher and router when
|
||||
# FLY_FEED_VIA / FLY_CONTROL_VIA is bus). The sweep and its dispatcher never use them, the page and the
|
||||
# encoder never see them. Default 0 (none): the bus threads then share the sim's host cpu, which costs
|
||||
# +1 to 2 ms per frame (EDGE-02 review N1). Set 1 on a partitioned container before `fly-feed bus`.
|
||||
SESSION_AUX_CPUS=0
|
||||
|
||||
# --- CUDA LIF backend -------------------------------------------------------
|
||||
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what
|
||||
|
|
@ -321,9 +327,21 @@ FLY_MACRO_MODE=raw
|
|||
# Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the
|
||||
# bus"). direct: flysim binds it, as always. bus: flysim publishes every
|
||||
# snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves
|
||||
# the same bytes; enable that unit by hand (its header has the steps).
|
||||
# Watchdog check 2 follows this setting to the edge's counters by itself.
|
||||
# the same bytes. This line (written into fly.env by every deploy) is the only
|
||||
# switch: flysim.service wants the edge, which starts only in bus mode.
|
||||
# On a live container switch with `fly-feed bus` / `fly-feed direct` (restarts
|
||||
# flysim, checks the page is back, rolls back by itself) and put the same value
|
||||
# here afterwards, or the next deploy warns that it writes the old one back.
|
||||
# Watchdog check 2 follows the running mode to the edge's counters by itself.
|
||||
# Runbook: "Feed over the bus".
|
||||
FLY_FEED_VIA=direct
|
||||
# --- control path -------------------------------------------------------------
|
||||
# Who serves http://127.0.0.1:7401 (docs/control-api.md; docs/design/flybus.md,
|
||||
# "Control over the bus"). direct: flysim binds it, as always. bus: flysim
|
||||
# registers the control services on its embedded bus (/run/fly/bus) and
|
||||
# flycontrol-edge.service serves the same bytes; enable that unit by hand
|
||||
# (infra/docs/runbook.md, "Control over the bus"). Independent of FLY_FEED_VIA.
|
||||
FLY_CONTROL_VIA=direct
|
||||
# How long a macro leaves a target alone after a walk to it aborted "blocked" or
|
||||
# "timeout" (macros.md section 12.1). Session state, so a restart offers every
|
||||
# target once more. Unset means the default, 10.
|
||||
|
|
@ -340,9 +358,13 @@ FLY_FEED_VIA=direct
|
|||
# two strings AND the new build's adapter declares a migration from that one. A
|
||||
# dataset, kernel, plasticity, emulator or state-format difference is still a
|
||||
# refusal. Set it for the one deploy that needs it and leave it out afterwards;
|
||||
# 05-deploy writes it into /etc/fly/fly.env only while it is set. The v0.6.0
|
||||
# deploy (pokered-unique8-v7, the engagement rewards) is the one that needs:
|
||||
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v6
|
||||
# 05-deploy writes it into /etc/fly/fly.env only while it is set. The deploy
|
||||
# of pokered-unique8-v8 (the damage reward) over the live v7 run needs:
|
||||
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7
|
||||
# and, to keep the milestone archives written before v0.6.0 restorable as
|
||||
# fallbacks and fly-reset-to-milestone targets, also names v6 (v8 reads both):
|
||||
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7,pokered-unique8-v6
|
||||
# (v0.6.0's, pokered-unique8-v7 over v6, needed pokered-unique8-v6.)
|
||||
|
||||
# --- push mode --------------------------------------------------------------
|
||||
# local: flypush.service stays disabled, everything else identical to prod.
|
||||
|
|
|
|||
|
|
@ -168,6 +168,19 @@ feed_via_normalize() {
|
|||
esac
|
||||
}
|
||||
|
||||
# control_via_normalize VALUE — FLY_CONTROL_VIA as feed_via_normalize does FLY_FEED_VIA:
|
||||
# lowercased (empty means "direct"), or return 1 for anything but direct|bus. flysim refuses
|
||||
# anything else at boot; 05-deploy.sh refuses it at deploy and writes the lowercased word, which
|
||||
# the watchdog reads to know who serves :7401 (docs/design/flybus.md, "Control over the bus").
|
||||
control_via_normalize() {
|
||||
local via
|
||||
via="$(printf '%s' "${1:-direct}" | tr '[:upper:]' '[:lower:]')"
|
||||
case "$via" in
|
||||
direct|bus) printf '%s\n' "$via" ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
cpuset_partition() {
|
||||
local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}"
|
||||
local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus
|
||||
|
|
@ -189,6 +202,69 @@ cpuset_partition() {
|
|||
echo "$sim_cpus $page_cpus $encoder_cpus"
|
||||
}
|
||||
|
||||
# cpuset_aux_split PAGE_CPUS COUNT — take the LAST COUNT cpus of the page group for flysim's
|
||||
# auxiliary threads (EDGE-02 review N1: the bus runtime, which must not share the sim's
|
||||
# dispatcher cpu). Echoes "PAGE_REST AUX"; dies if that would leave no page cpu.
|
||||
cpuset_aux_split() {
|
||||
local page="$1" count="$2" n
|
||||
n="$(echo "$page" | awk -F, '{print NF}')"
|
||||
if [ "$count" -ge "$n" ]; then
|
||||
die "cpuset_aux_split: SESSION_AUX_CPUS=${count} leaves no page cpu out of '${page}'. Widen CPUSET or lower SESSION_AUX_CPUS."
|
||||
fi
|
||||
echo "$(echo "$page" | cut -d, -f1-"$(( n - count ))") $(echo "$page" | cut -d, -f"$(( n - count + 1 ))"-)"
|
||||
}
|
||||
|
||||
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] [AUX_COUNT] — print one "UNIT-NAME CPUS" line for every
|
||||
# AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service,
|
||||
# flysim.slice), and then the two lines that name the confinement lists for bin/fly-cpu-confine:
|
||||
#
|
||||
# flysim.slice the sim's CPUs plus AUX_COUNT page cpus (default 0) taken from the end of the
|
||||
# page group for flysim's bus threads, exclusive to flysim like the rest (flysim.service and flysim-session.service run in it);
|
||||
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
|
||||
# slice is still bounded);
|
||||
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
|
||||
# flycast the encoder CPUs;
|
||||
# flyshadow page + encoder (never the sim's);
|
||||
# FLY_AUX_CPUS= only with AUX_COUNT > 0: the aux cpus (fly.env's FLY_SESSION_AUX_CPUS);
|
||||
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU
|
||||
# of CPUSET that is not the sim's, in CPUSET order.
|
||||
#
|
||||
# One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like
|
||||
# cpuset_partition does.
|
||||
cpuset_dropin_plan() {
|
||||
local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus
|
||||
local out
|
||||
out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
|
||||
read -r sim page enc <<< "$out"
|
||||
if [ "$aux_count" -gt 0 ]; then
|
||||
# not `read <<< "$(...)"`: die inside the substitution would only end the subshell
|
||||
out="$(cpuset_aux_split "$page" "$aux_count")" || return 1
|
||||
read -r page aux <<< "$out"
|
||||
fi
|
||||
slice_cpus="$sim"
|
||||
[ -n "$aux" ] && slice_cpus="${sim},${aux}"
|
||||
echo "flysim.slice $slice_cpus"
|
||||
for u in flysim flysim-session; do echo "${u}.service $slice_cpus"; done
|
||||
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done
|
||||
echo "flycast.service $enc"
|
||||
echo "flyshadow.service ${page},${enc}"
|
||||
echo "FLY_SIM_CPUS= $slice_cpus"
|
||||
echo "FLY_OTHER_CPUS= ${page},${enc}"
|
||||
[ -n "$aux" ] && echo "FLY_AUX_CPUS= $aux"
|
||||
return 0
|
||||
}
|
||||
|
||||
# cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to
|
||||
# /etc/systemd/system/UNIT-NAME.d/cpuset.conf ([Slice] for a .slice, [Service] otherwise).
|
||||
cpuset_dropin_text() {
|
||||
local unit="$1" cpus="$2" label="$3" section="Service"
|
||||
case "$unit" in *.slice) section="Slice" ;; esac
|
||||
echo "# generated by infra/05-deploy.sh from CPUSET in ${label} — do not hand-edit."
|
||||
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
|
||||
echo "[${section}]"
|
||||
echo "AllowedCPUs=${cpus}"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# operator-box guard
|
||||
# ---------------------------------------------------------------------------
|
||||
|
|
|
|||
19
infra/tests/fixtures/shadow-guard/README.md
vendored
Normal file
19
infra/tests/fixtures/shadow-guard/README.md
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# Recorded live-fly samples for `fly-shadow-run`'s guard
|
||||
|
||||
These samples come from a real `flysim` (legacy, FAFB, macros mode, at real time) on a shared build
|
||||
box on 2026-09-30. They are in `fly-shadow-run`'s own format and cadence:
|
||||
|
||||
- `baseline.jsonl` holds 60 samples 10 s apart;
|
||||
- `checks.jsonl` holds 20 samples a minute apart, after the same flysim restart that `start` does.
|
||||
|
||||
`lint.sh` runs `fly-shadow-run simulate` over each case and holds it to `expect`:
|
||||
|
||||
| Case | Setup | Expect |
|
||||
| --- | --- | --- |
|
||||
| `slow-alone` | 1 cpu, 1 thread; no shadow | pass |
|
||||
| `slow-shadow-same` | the same fly, with a real `fly-shadow` following it at normal priority on the same cpu. The live fly dropped from 0.66 to 0.44-0.60 | trip |
|
||||
| `fast-shadow-idle` | 3 cpus, 3 threads; a real `fly-shadow` at `SCHED_IDLE` on other cpus. The box was already loaded, and the fly ran at 0.4-0.85 | pass |
|
||||
| `fast-alone` | 3 cpus, 3 threads; no shadow | pass |
|
||||
|
||||
The box's own load moved the fly between 0.4 and 1.0 during some baselines. Those steps are why
|
||||
the baseline is robust: the median, and the spread taken as the MAD.
|
||||
60
infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
{"t": 1790738128.362942, "status": "running", "rtMean": 0.7588339770286441, "lag": 33.479, "uptime": 71.223399881}
|
||||
{"t": 1790738138.4285393, "status": "running", "rtMean": 1.0036906365382738, "lag": 33.479, "uptime": 81.293069051}
|
||||
{"t": 1790738148.4962938, "status": "running", "rtMean": 0.9970303099114692, "lag": 33.479, "uptime": 91.408291997}
|
||||
{"t": 1790738158.5748143, "status": "running", "rtMean": 0.9957513747669762, "lag": 33.479, "uptime": 101.483131764}
|
||||
{"t": 1790738168.9591897, "status": "running", "rtMean": 0.819013893871745, "lag": 35.496, "uptime": 111.869185712}
|
||||
{"t": 1790738179.0497794, "status": "running", "rtMean": 0.955720505211804, "lag": 35.496, "uptime": 121.957242118}
|
||||
{"t": 1790738189.13739, "status": "running", "rtMean": 0.8799930137133124, "lag": 36.498, "uptime": 132.018380479}
|
||||
{"t": 1790738199.2148638, "status": "running", "rtMean": 0.8902680060117365, "lag": 37.521, "uptime": 142.113434378}
|
||||
{"t": 1790738209.3021023, "status": "running", "rtMean": 0.8803874146669992, "lag": 38.524, "uptime": 152.181022738}
|
||||
{"t": 1790738219.3764796, "status": "running", "rtMean": 0.8658710279839296, "lag": 40.54, "uptime": 162.284831945}
|
||||
{"t": 1790738229.4663715, "status": "running", "rtMean": 0.8894453486450183, "lag": 41.541, "uptime": 172.367967371}
|
||||
{"t": 1790738239.553954, "status": "running", "rtMean": 0.9052554309116678, "lag": 42.543, "uptime": 182.460932044}
|
||||
{"t": 1790738249.6388013, "status": "running", "rtMean": 0.9129316585556161, "lag": 43.544, "uptime": 192.526870399}
|
||||
{"t": 1790738259.7050216, "status": "running", "rtMean": 0.9999965689074697, "lag": 43.544, "uptime": 202.609470103}
|
||||
{"t": 1790738269.7767544, "status": "running", "rtMean": 0.9378600900744024, "lag": 43.544, "uptime": 212.690426315}
|
||||
{"t": 1790738279.8516681, "status": "running", "rtMean": 0.7973579434723355, "lag": 45.556, "uptime": 222.761268128}
|
||||
{"t": 1790738289.9210968, "status": "running", "rtMean": 0.9352522067409303, "lag": 46.571, "uptime": 232.836669514}
|
||||
{"t": 1790738300.0552127, "status": "running", "rtMean": 0.7150556877963433, "lag": 49.584, "uptime": 242.963564523}
|
||||
{"t": 1790738310.2007082, "status": "running", "rtMean": 1.0059437251512073, "lag": 49.584, "uptime": 253.109498917}
|
||||
{"t": 1790738320.2790272, "status": "running", "rtMean": 1.00373183915971, "lag": 49.584, "uptime": 263.195154054}
|
||||
{"t": 1790738330.3444412, "status": "running", "rtMean": 0.9972521469939926, "lag": 49.584, "uptime": 273.255265175}
|
||||
{"t": 1790738340.4204133, "status": "running", "rtMean": 0.8495939168264007, "lag": 50.586, "uptime": 283.330032566}
|
||||
{"t": 1790738350.5301325, "status": "running", "rtMean": 0.7839208383476353, "lag": 52.599, "uptime": 293.439062795}
|
||||
{"t": 1790738360.6693776, "status": "running", "rtMean": 0.9653471893141468, "lag": 53.6, "uptime": 303.576346295}
|
||||
{"t": 1790738370.8137631, "status": "running", "rtMean": 0.6241158180206947, "lag": 57.623, "uptime": 313.699656832}
|
||||
{"t": 1790738380.9961703, "status": "running", "rtMean": 0.5687473149333804, "lag": 61.68, "uptime": 323.912074763}
|
||||
{"t": 1790738391.089262, "status": "running", "rtMean": 0.5804323097526403, "lag": 65.706, "uptime": 333.967914558}
|
||||
{"t": 1790738401.19394, "status": "running", "rtMean": 0.5362910197658861, "lag": 70.779, "uptime": 344.048343544}
|
||||
{"t": 1790738411.3023837, "status": "running", "rtMean": 0.5510464052357773, "lag": 74.845, "uptime": 354.205680506}
|
||||
{"t": 1790738421.4007213, "status": "running", "rtMean": 0.5652293538813947, "lag": 79.905, "uptime": 364.315364667}
|
||||
{"t": 1790738431.503473, "status": "running", "rtMean": 0.57359026862898, "lag": 83.964, "uptime": 374.377908576}
|
||||
{"t": 1790738441.6479023, "status": "running", "rtMean": 0.5540343187796515, "lag": 87.999, "uptime": 384.55919851}
|
||||
{"t": 1790738451.7651033, "status": "running", "rtMean": 0.6037429716311573, "lag": 92.018, "uptime": 394.673360423}
|
||||
{"t": 1790738461.8663146, "status": "running", "rtMean": 0.6985130182613225, "lag": 95.095, "uptime": 404.755070174}
|
||||
{"t": 1790738471.9642298, "status": "running", "rtMean": 0.7594984860121092, "lag": 98.14, "uptime": 414.851205955}
|
||||
{"t": 1790738482.0506132, "status": "running", "rtMean": 0.8166532570546075, "lag": 99.145, "uptime": 424.958463239}
|
||||
{"t": 1790738492.1384304, "status": "running", "rtMean": 0.8807780226062987, "lag": 100.145, "uptime": 434.992925627}
|
||||
{"t": 1790738502.2033277, "status": "running", "rtMean": 1.0802703218851182, "lag": 100.145, "uptime": 445.108112717}
|
||||
{"t": 1790738512.273309, "status": "running", "rtMean": 0.9857221768324773, "lag": 100.145, "uptime": 455.179728346}
|
||||
{"t": 1790738522.3412535, "status": "running", "rtMean": 1.0008941796078314, "lag": 100.145, "uptime": 465.243065017}
|
||||
{"t": 1790738532.4065015, "status": "running", "rtMean": 1.0144037951650158, "lag": 100.145, "uptime": 475.316217749}
|
||||
{"t": 1790738542.4878814, "status": "running", "rtMean": 0.995240358864496, "lag": 100.145, "uptime": 485.400446119}
|
||||
{"t": 1790738552.5522985, "status": "running", "rtMean": 0.9958695819760208, "lag": 100.145, "uptime": 495.331048011}
|
||||
{"t": 1790738562.6135433, "status": "running", "rtMean": 0.9990484834746928, "lag": 100.145, "uptime": 505.518260558}
|
||||
{"t": 1790738572.6848962, "status": "running", "rtMean": 0.9999101070487516, "lag": 100.145, "uptime": 515.603359756}
|
||||
{"t": 1790738582.7517495, "status": "running", "rtMean": 1.0067915374872096, "lag": 100.145, "uptime": 525.63843004}
|
||||
{"t": 1790738592.8203006, "status": "running", "rtMean": 0.9933226593909843, "lag": 100.145, "uptime": 535.714625602}
|
||||
{"t": 1790738602.8871908, "status": "running", "rtMean": 0.9997146956682066, "lag": 100.145, "uptime": 545.76592055}
|
||||
{"t": 1790738612.9580173, "status": "running", "rtMean": 0.9995574815559497, "lag": 100.145, "uptime": 555.842376949}
|
||||
{"t": 1790738623.0309892, "status": "running", "rtMean": 1.0009077839472587, "lag": 100.145, "uptime": 565.932440918}
|
||||
{"t": 1790738633.1058488, "status": "running", "rtMean": 0.905700103566834, "lag": 101.148, "uptime": 576.014824329}
|
||||
{"t": 1790738643.2241693, "status": "running", "rtMean": 0.9002632818253182, "lag": 102.159, "uptime": 586.12547679}
|
||||
{"t": 1790738653.3037221, "status": "running", "rtMean": 1.001384402969126, "lag": 102.159, "uptime": 596.212798092}
|
||||
{"t": 1790738663.377194, "status": "running", "rtMean": 1.0025847949946505, "lag": 102.159, "uptime": 606.291720522}
|
||||
{"t": 1790738673.450081, "status": "running", "rtMean": 0.9982495351402143, "lag": 102.159, "uptime": 616.368169968}
|
||||
{"t": 1790738683.5147092, "status": "running", "rtMean": 1.000470259093377, "lag": 102.159, "uptime": 626.427550974}
|
||||
{"t": 1790738693.5863135, "status": "running", "rtMean": 0.9966639708181871, "lag": 102.159, "uptime": 636.458204371}
|
||||
{"t": 1790738703.651422, "status": "running", "rtMean": 0.9994712074317433, "lag": 102.159, "uptime": 646.54138456}
|
||||
{"t": 1790738713.7201247, "status": "running", "rtMean": 0.9965700494189607, "lag": 102.159, "uptime": 656.631814013}
|
||||
{"t": 1790738723.7912498, "status": "running", "rtMean": 1.0007973265331749, "lag": 102.159, "uptime": 666.694264297}
|
||||
20
infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{"t": 1790738735.0354905, "status": "running", "rtMean": 0.999484237762719, "lag": 0.0, "uptime": 11.07355663}
|
||||
{"t": 1790738795.1101537, "status": "running", "rtMean": 0.998153021033785, "lag": 0.0, "uptime": 71.129215866}
|
||||
{"t": 1790738855.1800184, "status": "running", "rtMean": 0.9926228160612285, "lag": 0.0, "uptime": 131.202241399}
|
||||
{"t": 1790738915.249556, "status": "running", "rtMean": 0.9992177109183569, "lag": 0.0, "uptime": 191.273914994}
|
||||
{"t": 1790738975.3090174, "status": "running", "rtMean": 1.0004807207169564, "lag": 0.0, "uptime": 251.312728385}
|
||||
{"t": 1790739035.3770518, "status": "running", "rtMean": 0.99729025135176, "lag": 0.0, "uptime": 311.41256314}
|
||||
{"t": 1790739095.4512274, "status": "running", "rtMean": 0.9963104110487839, "lag": 0.0, "uptime": 371.442377297}
|
||||
{"t": 1790739155.5106263, "status": "running", "rtMean": 0.9986795197502222, "lag": 0.0, "uptime": 431.514951288}
|
||||
{"t": 1790739215.5753255, "status": "running", "rtMean": 0.998777006263299, "lag": 0.0, "uptime": 491.615126509}
|
||||
{"t": 1790739275.6377265, "status": "running", "rtMean": 0.9993828850549406, "lag": 0.0, "uptime": 551.643819315}
|
||||
{"t": 1790739335.6982403, "status": "running", "rtMean": 0.9998689452246822, "lag": 0.0, "uptime": 611.710123532}
|
||||
{"t": 1790739395.7690253, "status": "running", "rtMean": 1.0066090326463777, "lag": 0.0, "uptime": 671.806084883}
|
||||
{"t": 1790739455.8361878, "status": "running", "rtMean": 0.9991477060779191, "lag": 0.0, "uptime": 731.837495033}
|
||||
{"t": 1790739515.8999934, "status": "running", "rtMean": 0.9968497132252894, "lag": 0.0, "uptime": 791.918687829}
|
||||
{"t": 1790739575.9599848, "status": "running", "rtMean": 0.9993416499626159, "lag": 0.0, "uptime": 851.966694729}
|
||||
{"t": 1790739636.031231, "status": "running", "rtMean": 0.9997509681411471, "lag": 0.0, "uptime": 912.047324838}
|
||||
{"t": 1790739696.1082256, "status": "running", "rtMean": 0.9993880587210896, "lag": 0.0, "uptime": 972.143571488}
|
||||
{"t": 1790739756.1715124, "status": "running", "rtMean": 0.9978257533955007, "lag": 0.0, "uptime": 1032.192931507}
|
||||
{"t": 1790739816.2371426, "status": "running", "rtMean": 1.0003866207887322, "lag": 0.0, "uptime": 1092.269950437}
|
||||
{"t": 1790739876.297765, "status": "running", "rtMean": 0.9997339122145353, "lag": 0.0, "uptime": 1152.311864977}
|
||||
1
infra/tests/fixtures/shadow-guard/fast-alone/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/fast-alone/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
pass
|
||||
60
infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
{"t": 1790736255.1832466, "status": "running", "rtMean": 0.44899475378270337, "lag": 40.531, "uptime": 71.111642723}
|
||||
{"t": 1790736265.3486006, "status": "running", "rtMean": 0.40737226174421837, "lag": 46.58, "uptime": 81.296028671}
|
||||
{"t": 1790736275.462523, "status": "running", "rtMean": 0.43926524622884744, "lag": 51.607, "uptime": 91.41614284}
|
||||
{"t": 1790736285.5483737, "status": "running", "rtMean": 0.4992672422167786, "lag": 57.668, "uptime": 101.49334599}
|
||||
{"t": 1790736295.691844, "status": "running", "rtMean": 0.4722833612045654, "lag": 62.729, "uptime": 111.631919513}
|
||||
{"t": 1790736305.8359153, "status": "running", "rtMean": 0.49364414852989763, "lag": 67.756, "uptime": 121.766530366}
|
||||
{"t": 1790736316.0044537, "status": "running", "rtMean": 0.4592358802945983, "lag": 72.814, "uptime": 131.934151579}
|
||||
{"t": 1790736326.1091528, "status": "running", "rtMean": 0.4414601438247983, "lag": 78.84, "uptime": 142.0534588}
|
||||
{"t": 1790736336.2525842, "status": "running", "rtMean": 0.4540765983005316, "lag": 83.88, "uptime": 152.198379259}
|
||||
{"t": 1790736346.4600585, "status": "running", "rtMean": 0.4173426800525677, "lag": 89.957, "uptime": 162.413446602}
|
||||
{"t": 1790736356.5611305, "status": "running", "rtMean": 0.4606621035712305, "lag": 96.016, "uptime": 172.491203687}
|
||||
{"t": 1790736366.7702422, "status": "running", "rtMean": 0.46203321509514217, "lag": 101.071, "uptime": 182.696019242}
|
||||
{"t": 1790736376.9394329, "status": "running", "rtMean": 0.4863329297033063, "lag": 106.126, "uptime": 192.889038592}
|
||||
{"t": 1790736387.0649624, "status": "running", "rtMean": 0.4495199219435465, "lag": 112.232, "uptime": 203.013465866}
|
||||
{"t": 1790736397.1682742, "status": "running", "rtMean": 0.42863654848005284, "lag": 118.286, "uptime": 213.12621802}
|
||||
{"t": 1790736407.2758026, "status": "running", "rtMean": 0.4139101392220675, "lag": 123.367, "uptime": 223.208709667}
|
||||
{"t": 1790736417.43286, "status": "running", "rtMean": 0.43302060621434524, "lag": 129.445, "uptime": 233.357393123}
|
||||
{"t": 1790736427.5712192, "status": "running", "rtMean": 0.43801120859089393, "lag": 135.505, "uptime": 243.507406013}
|
||||
{"t": 1790736437.7151752, "status": "running", "rtMean": 0.4402615997407782, "lag": 140.554, "uptime": 253.661724645}
|
||||
{"t": 1790736447.85799, "status": "running", "rtMean": 0.48112727487436235, "lag": 146.635, "uptime": 263.813400946}
|
||||
{"t": 1790736458.0452223, "status": "running", "rtMean": 0.4318712743090674, "lag": 151.707, "uptime": 273.954505321}
|
||||
{"t": 1790736468.1886797, "status": "running", "rtMean": 0.42247469989908265, "lag": 157.751, "uptime": 284.121781118}
|
||||
{"t": 1790736478.3070867, "status": "running", "rtMean": 0.414255858741203, "lag": 163.851, "uptime": 294.242313229}
|
||||
{"t": 1790736488.4334955, "status": "running", "rtMean": 0.42798509497809467, "lag": 169.928, "uptime": 304.374179381}
|
||||
{"t": 1790736498.598869, "status": "running", "rtMean": 0.6973435620918129, "lag": 171.95, "uptime": 314.520569518}
|
||||
{"t": 1790736508.6862988, "status": "running", "rtMean": 0.8506385364177339, "lag": 173.964, "uptime": 324.645689838}
|
||||
{"t": 1790736518.7639382, "status": "running", "rtMean": 0.6393757799420648, "lag": 176.98, "uptime": 334.702167477}
|
||||
{"t": 1790736528.8444629, "status": "running", "rtMean": 0.7563780548037421, "lag": 179.995, "uptime": 344.767409573}
|
||||
{"t": 1790736538.9335213, "status": "running", "rtMean": 0.7299449362518324, "lag": 183.099, "uptime": 354.892773648}
|
||||
{"t": 1790736549.0587013, "status": "running", "rtMean": 0.7495898580324455, "lag": 185.1, "uptime": 365.018206452}
|
||||
{"t": 1790736559.125795, "status": "running", "rtMean": 0.7466250548943967, "lag": 188.191, "uptime": 375.072270628}
|
||||
{"t": 1790736569.2290745, "status": "running", "rtMean": 0.7135159366386999, "lag": 191.217, "uptime": 385.16395309}
|
||||
{"t": 1790736579.3221574, "status": "running", "rtMean": 0.6444057032246826, "lag": 194.311, "uptime": 395.24551542}
|
||||
{"t": 1790736589.387774, "status": "running", "rtMean": 0.7078500629057103, "lag": 197.356, "uptime": 405.328315223}
|
||||
{"t": 1790736599.457208, "status": "running", "rtMean": 0.7724222621426244, "lag": 199.41, "uptime": 415.395630334}
|
||||
{"t": 1790736609.5669358, "status": "running", "rtMean": 0.7238637707089501, "lag": 202.432, "uptime": 425.523861591}
|
||||
{"t": 1790736619.667222, "status": "running", "rtMean": 0.636988015566429, "lag": 206.491, "uptime": 435.596000401}
|
||||
{"t": 1790736629.7565455, "status": "running", "rtMean": 0.6846194839249449, "lag": 209.511, "uptime": 445.705233095}
|
||||
{"t": 1790736639.9320571, "status": "running", "rtMean": 0.5775285955158141, "lag": 213.527, "uptime": 455.875805326}
|
||||
{"t": 1790736650.1127295, "status": "running", "rtMean": 0.6874672985502784, "lag": 216.574, "uptime": 466.047794887}
|
||||
{"t": 1790736660.23605, "status": "running", "rtMean": 0.7980788454806589, "lag": 218.599, "uptime": 476.191578571}
|
||||
{"t": 1790736670.3181207, "status": "running", "rtMean": 0.8373465907575423, "lag": 220.629, "uptime": 486.259561672}
|
||||
{"t": 1790736680.5240602, "status": "running", "rtMean": 0.5739965775984952, "lag": 224.72, "uptime": 496.479775337}
|
||||
{"t": 1790736690.6629243, "status": "running", "rtMean": 0.5286072075517942, "lag": 229.778, "uptime": 506.594493598}
|
||||
{"t": 1790736700.8302114, "status": "running", "rtMean": 0.6743407053708753, "lag": 232.792, "uptime": 516.784837195}
|
||||
{"t": 1790736710.9810565, "status": "running", "rtMean": 0.4833175202797613, "lag": 237.843, "uptime": 526.927338551}
|
||||
{"t": 1790736721.1076307, "status": "running", "rtMean": 0.5049205359243616, "lag": 242.912, "uptime": 537.054603691}
|
||||
{"t": 1790736731.2034523, "status": "running", "rtMean": 0.4861911891792873, "lag": 248.95, "uptime": 547.101045326}
|
||||
{"t": 1790736741.3109553, "status": "running", "rtMean": 0.4845765517462596, "lag": 254.061, "uptime": 557.246782973}
|
||||
{"t": 1790736751.4774404, "status": "running", "rtMean": 0.5333230355802153, "lag": 258.103, "uptime": 567.418066384}
|
||||
{"t": 1790736761.652144, "status": "running", "rtMean": 0.49627891829609305, "lag": 264.173, "uptime": 577.572329582}
|
||||
{"t": 1790736771.8544915, "status": "running", "rtMean": 0.5215276573927089, "lag": 268.2, "uptime": 587.79709649}
|
||||
{"t": 1790736781.9649491, "status": "running", "rtMean": 0.5216891717973449, "lag": 273.234, "uptime": 597.898939598}
|
||||
{"t": 1790736792.0599647, "status": "running", "rtMean": 0.5310205891816586, "lag": 278.266, "uptime": 607.982986102}
|
||||
{"t": 1790736802.1870968, "status": "running", "rtMean": 0.49618279364312484, "lag": 283.316, "uptime": 618.117053029}
|
||||
{"t": 1790736812.290842, "status": "running", "rtMean": 0.49072671618430486, "lag": 288.404, "uptime": 628.23818419}
|
||||
{"t": 1790736822.4333866, "status": "running", "rtMean": 0.5402747673446865, "lag": 292.418, "uptime": 638.367153256}
|
||||
{"t": 1790736832.613669, "status": "running", "rtMean": 0.8329938906374317, "lag": 294.42, "uptime": 648.537882771}
|
||||
{"t": 1790736842.6835933, "status": "running", "rtMean": 0.7430173560600793, "lag": 297.448, "uptime": 658.629022047}
|
||||
{"t": 1790736852.755823, "status": "running", "rtMean": 0.8578215877131159, "lag": 298.448, "uptime": 668.694834509}
|
||||
20
infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{"t": 1790736864.4256852, "status": "running", "rtMean": 0.6099898319965826, "lag": 3.091, "uptime": 11.07909019}
|
||||
{"t": 1790736924.501681, "status": "running", "rtMean": 0.5411932741082821, "lag": 20.265, "uptime": 71.155545456}
|
||||
{"t": 1790736984.5807962, "status": "running", "rtMean": 0.7295306018507262, "lag": 35.328, "uptime": 131.199399778}
|
||||
{"t": 1790737044.6489198, "status": "running", "rtMean": 0.8067884564857175, "lag": 46.47, "uptime": 191.29805351}
|
||||
{"t": 1790737104.7270966, "status": "running", "rtMean": 0.8192565712279218, "lag": 58.542, "uptime": 251.37716607}
|
||||
{"t": 1790737164.7932363, "status": "running", "rtMean": 0.8487114702728498, "lag": 69.618, "uptime": 311.44889619}
|
||||
{"t": 1790737224.91049, "status": "running", "rtMean": 0.42516908835738415, "lag": 101.107, "uptime": 371.522769005}
|
||||
{"t": 1790737285.0996652, "status": "running", "rtMean": 0.41299332249218484, "lag": 136.493, "uptime": 431.719907398}
|
||||
{"t": 1790737345.3437996, "status": "running", "rtMean": 0.4410892921905215, "lag": 171.04, "uptime": 491.980527036}
|
||||
{"t": 1790737405.5281327, "status": "running", "rtMean": 0.4454430216668691, "lag": 204.353, "uptime": 552.14783058}
|
||||
{"t": 1790737465.838257, "status": "running", "rtMean": 0.5991416565682315, "lag": 227.769, "uptime": 612.473422449}
|
||||
{"t": 1790737525.9655414, "status": "running", "rtMean": 0.6857160494879407, "lag": 246.844, "uptime": 672.619024119}
|
||||
{"t": 1790737586.045057, "status": "running", "rtMean": 0.6537634570200577, "lag": 265.963, "uptime": 732.678449214}
|
||||
{"t": 1790737646.1301575, "status": "running", "rtMean": 0.6473194011694912, "lag": 290.309, "uptime": 792.775859726}
|
||||
{"t": 1790737706.2470899, "status": "running", "rtMean": 0.474484017045933, "lag": 319.566, "uptime": 852.890865845}
|
||||
{"t": 1790737766.4071772, "status": "running", "rtMean": 0.5316840402693012, "lag": 349.947, "uptime": 913.037081082}
|
||||
{"t": 1790737826.488124, "status": "running", "rtMean": 0.7651768950839182, "lag": 371.253, "uptime": 973.141837869}
|
||||
{"t": 1790737886.652113, "status": "running", "rtMean": 0.4461005912444415, "lag": 403.681, "uptime": 1033.302886448}
|
||||
{"t": 1790737946.764796, "status": "running", "rtMean": 0.4610048048396617, "lag": 438.093, "uptime": 1093.383696514}
|
||||
{"t": 1790738006.857649, "status": "running", "rtMean": 0.44882468186134916, "lag": 471.382, "uptime": 1153.477095415}
|
||||
1
infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
pass
|
||||
60
infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
{"t": 1790732513.9182734, "status": "running", "rtMean": 0.8924521636213212, "lag": 14.055, "uptime": 71.036299234}
|
||||
{"t": 1790732524.0150237, "status": "running", "rtMean": 0.8353274823796196, "lag": 16.062, "uptime": 81.13323077}
|
||||
{"t": 1790732534.1210978, "status": "running", "rtMean": 0.8500748093099013, "lag": 17.063, "uptime": 91.228242756}
|
||||
{"t": 1790732544.215337, "status": "running", "rtMean": 0.8468167790642429, "lag": 19.065, "uptime": 101.324762382}
|
||||
{"t": 1790732554.322073, "status": "running", "rtMean": 0.8195776032071418, "lag": 21.069, "uptime": 111.432768959}
|
||||
{"t": 1790732564.4171112, "status": "running", "rtMean": 0.8132396801449534, "lag": 23.128, "uptime": 121.51184336}
|
||||
{"t": 1790732574.6153316, "status": "running", "rtMean": 0.7620145427014579, "lag": 25.169, "uptime": 131.725135168}
|
||||
{"t": 1790732584.921327, "status": "running", "rtMean": 0.8332397110903376, "lag": 27.171, "uptime": 142.033873438}
|
||||
{"t": 1790732595.01128, "status": "running", "rtMean": 0.870312035539666, "lag": 28.172, "uptime": 152.095917692}
|
||||
{"t": 1790732605.1342888, "status": "running", "rtMean": 0.8533222405905535, "lag": 29.174, "uptime": 162.233917268}
|
||||
{"t": 1790732615.2172267, "status": "running", "rtMean": 0.8613640091999233, "lag": 31.183, "uptime": 172.332574842}
|
||||
{"t": 1790732625.292268, "status": "running", "rtMean": 0.8522988744218247, "lag": 32.186, "uptime": 182.413805105}
|
||||
{"t": 1790732635.3641157, "status": "running", "rtMean": 0.9357131448898743, "lag": 33.188, "uptime": 192.485818904}
|
||||
{"t": 1790732645.4261112, "status": "running", "rtMean": 1.0206119648139633, "lag": 33.188, "uptime": 202.528181723}
|
||||
{"t": 1790732655.4861393, "status": "running", "rtMean": 0.9996233335893017, "lag": 33.188, "uptime": 212.597230658}
|
||||
{"t": 1790732665.5481722, "status": "running", "rtMean": 0.9988689561123472, "lag": 33.188, "uptime": 222.643138786}
|
||||
{"t": 1790732675.6082208, "status": "running", "rtMean": 0.9720518244342236, "lag": 33.188, "uptime": 232.688977534}
|
||||
{"t": 1790732685.6701753, "status": "running", "rtMean": 0.9535516201508779, "lag": 33.188, "uptime": 242.776975854}
|
||||
{"t": 1790732695.7341325, "status": "running", "rtMean": 1.0629078918872632, "lag": 33.188, "uptime": 252.850174728}
|
||||
{"t": 1790732705.8101525, "status": "running", "rtMean": 0.9727389888242601, "lag": 33.188, "uptime": 262.903659566}
|
||||
{"t": 1790732715.8741817, "status": "running", "rtMean": 1.0273735099933976, "lag": 33.188, "uptime": 272.974337275}
|
||||
{"t": 1790732725.938133, "status": "running", "rtMean": 1.0004052294537187, "lag": 33.188, "uptime": 283.049608446}
|
||||
{"t": 1790732735.998134, "status": "running", "rtMean": 0.9949238477466771, "lag": 33.188, "uptime": 293.095921712}
|
||||
{"t": 1790732746.058181, "status": "running", "rtMean": 1.001717860791771, "lag": 33.188, "uptime": 303.168958273}
|
||||
{"t": 1790732756.1181643, "status": "running", "rtMean": 0.9904886517209306, "lag": 33.188, "uptime": 313.212038344}
|
||||
{"t": 1790732766.1781104, "status": "running", "rtMean": 1.0019464588045806, "lag": 33.188, "uptime": 323.27335596}
|
||||
{"t": 1790732776.2361557, "status": "running", "rtMean": 0.9964762908263903, "lag": 33.188, "uptime": 333.345377532}
|
||||
{"t": 1790732786.2971303, "status": "running", "rtMean": 0.9919143606076284, "lag": 33.188, "uptime": 343.415231522}
|
||||
{"t": 1790732796.356171, "status": "running", "rtMean": 0.9987406877370043, "lag": 33.188, "uptime": 353.453194803}
|
||||
{"t": 1790732806.4211473, "status": "running", "rtMean": 0.9606955955830612, "lag": 33.188, "uptime": 363.51066889}
|
||||
{"t": 1790732816.4811146, "status": "running", "rtMean": 1.0365607476649523, "lag": 33.188, "uptime": 373.577335699}
|
||||
{"t": 1790732826.5412261, "status": "running", "rtMean": 0.9998410565989371, "lag": 33.188, "uptime": 383.641038325}
|
||||
{"t": 1790732836.6022642, "status": "running", "rtMean": 1.0000077033831407, "lag": 33.188, "uptime": 393.71493795}
|
||||
{"t": 1790732846.66412, "status": "running", "rtMean": 1.000194713414025, "lag": 33.188, "uptime": 403.778353067}
|
||||
{"t": 1790732856.7631304, "status": "running", "rtMean": 0.9963137515722961, "lag": 33.188, "uptime": 413.843209009}
|
||||
{"t": 1790732866.8251379, "status": "running", "rtMean": 1.0024279700647742, "lag": 33.188, "uptime": 423.939536235}
|
||||
{"t": 1790732876.8881218, "status": "running", "rtMean": 0.9998292141625301, "lag": 33.188, "uptime": 434.00196051}
|
||||
{"t": 1790732886.9481704, "status": "running", "rtMean": 1.000376047514638, "lag": 33.188, "uptime": 444.041568588}
|
||||
{"t": 1790732897.0131807, "status": "running", "rtMean": 0.9650577242433412, "lag": 33.188, "uptime": 454.116318252}
|
||||
{"t": 1790732907.0751567, "status": "running", "rtMean": 1.0144244685102852, "lag": 33.188, "uptime": 464.167010558}
|
||||
{"t": 1790732917.135163, "status": "running", "rtMean": 1.0205380747863821, "lag": 33.188, "uptime": 474.251702386}
|
||||
{"t": 1790732927.2051454, "status": "running", "rtMean": 1.0000612465292147, "lag": 33.188, "uptime": 484.315901269}
|
||||
{"t": 1790732937.2681184, "status": "running", "rtMean": 0.9994207833538337, "lag": 33.188, "uptime": 494.376673004}
|
||||
{"t": 1790732947.3331046, "status": "running", "rtMean": 1.000304521129079, "lag": 33.188, "uptime": 504.439961234}
|
||||
{"t": 1790732957.3971682, "status": "running", "rtMean": 1.0002162260543621, "lag": 33.188, "uptime": 514.506681195}
|
||||
{"t": 1790732967.4561813, "status": "running", "rtMean": 0.9940778699094166, "lag": 33.188, "uptime": 524.546264956}
|
||||
{"t": 1790732977.5141263, "status": "running", "rtMean": 0.9996073475880696, "lag": 33.188, "uptime": 534.609522709}
|
||||
{"t": 1790732987.574194, "status": "running", "rtMean": 1.0002335793712973, "lag": 33.188, "uptime": 544.681525736}
|
||||
{"t": 1790732997.63819, "status": "running", "rtMean": 0.9719075938039292, "lag": 33.188, "uptime": 554.746296519}
|
||||
{"t": 1790733007.6981711, "status": "running", "rtMean": 0.9642994644579728, "lag": 33.188, "uptime": 564.819180783}
|
||||
{"t": 1790733017.758178, "status": "running", "rtMean": 1.018785781616432, "lag": 33.188, "uptime": 574.863920385}
|
||||
{"t": 1790733027.8201568, "status": "running", "rtMean": 1.0126053016171566, "lag": 33.188, "uptime": 584.931657624}
|
||||
{"t": 1790733037.8801777, "status": "running", "rtMean": 1.0288813388578921, "lag": 33.188, "uptime": 595.000913192}
|
||||
{"t": 1790733047.9401584, "status": "running", "rtMean": 0.9993726786826045, "lag": 33.188, "uptime": 605.062362454}
|
||||
{"t": 1790733058.0032334, "status": "running", "rtMean": 1.0003288362459641, "lag": 33.188, "uptime": 615.100685166}
|
||||
{"t": 1790733068.0701303, "status": "running", "rtMean": 0.996323054395049, "lag": 33.188, "uptime": 625.182391179}
|
||||
{"t": 1790733078.1311688, "status": "running", "rtMean": 0.9986121232113987, "lag": 33.188, "uptime": 635.237969741}
|
||||
{"t": 1790733088.194169, "status": "running", "rtMean": 0.9998456257825143, "lag": 33.188, "uptime": 645.294446623}
|
||||
{"t": 1790733098.254364, "status": "running", "rtMean": 0.9990527607429407, "lag": 33.188, "uptime": 655.371233565}
|
||||
{"t": 1790733108.3171723, "status": "running", "rtMean": 0.9801059046785113, "lag": 33.188, "uptime": 665.424268239}
|
||||
20
infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{"t": 1790733119.441622, "status": "running", "rtMean": 0.999626145847037, "lag": 0.0, "uptime": 11.03453719}
|
||||
{"t": 1790733179.5021126, "status": "running", "rtMean": 0.996429238965645, "lag": 0.0, "uptime": 71.109465871}
|
||||
{"t": 1790733239.563163, "status": "running", "rtMean": 1.0001344530283525, "lag": 0.0, "uptime": 131.161767319}
|
||||
{"t": 1790733299.6230712, "status": "running", "rtMean": 1.0051819085367752, "lag": 0.0, "uptime": 191.213566544}
|
||||
{"t": 1790733359.684059, "status": "running", "rtMean": 0.9994857841966536, "lag": 0.0, "uptime": 251.305985353}
|
||||
{"t": 1790733419.744106, "status": "running", "rtMean": 0.9309339263307287, "lag": 1.016, "uptime": 311.343539702}
|
||||
{"t": 1790733479.8072605, "status": "running", "rtMean": 0.9914113663325995, "lag": 1.016, "uptime": 371.420558771}
|
||||
{"t": 1790733539.874109, "status": "running", "rtMean": 1.0150616406858766, "lag": 1.016, "uptime": 431.469758515}
|
||||
{"t": 1790733599.934255, "status": "running", "rtMean": 0.9990854925925501, "lag": 1.016, "uptime": 491.554715659}
|
||||
{"t": 1790733659.998115, "status": "running", "rtMean": 0.9992033155394792, "lag": 1.016, "uptime": 551.614612008}
|
||||
{"t": 1790733720.0581028, "status": "running", "rtMean": 1.0002394824346315, "lag": 1.016, "uptime": 611.653389874}
|
||||
{"t": 1790733780.121188, "status": "running", "rtMean": 1.002487894172868, "lag": 1.016, "uptime": 671.727773294}
|
||||
{"t": 1790733840.1851053, "status": "running", "rtMean": 1.000530724113054, "lag": 1.016, "uptime": 731.80678409}
|
||||
{"t": 1790733900.2461364, "status": "running", "rtMean": 1.000644782810976, "lag": 1.016, "uptime": 791.842628622}
|
||||
{"t": 1790733960.3072183, "status": "running", "rtMean": 0.999652205983927, "lag": 1.016, "uptime": 851.922688196}
|
||||
{"t": 1790734020.3681173, "status": "running", "rtMean": 0.9946548155046125, "lag": 1.016, "uptime": 911.968050417}
|
||||
{"t": 1790734080.4291067, "status": "running", "rtMean": 1.0009058823044212, "lag": 1.016, "uptime": 972.041325345}
|
||||
{"t": 1790734140.4912531, "status": "running", "rtMean": 0.9902809817215064, "lag": 1.016, "uptime": 1032.085088126}
|
||||
{"t": 1790734200.550132, "status": "running", "rtMean": 1.0136589528338944, "lag": 1.016, "uptime": 1092.153292688}
|
||||
{"t": 1790734260.6101415, "status": "running", "rtMean": 0.997751864835789, "lag": 1.016, "uptime": 1152.230885469}
|
||||
1
infra/tests/fixtures/shadow-guard/slow-alone/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/slow-alone/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
pass
|
||||
60
infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
{"t": 1790734381.7911441, "status": "running", "rtMean": 0.9991690302798031, "lag": 0.0, "uptime": 71.04094778}
|
||||
{"t": 1790734391.863173, "status": "running", "rtMean": 0.9995511232186312, "lag": 0.0, "uptime": 81.137648009}
|
||||
{"t": 1790734401.9251318, "status": "running", "rtMean": 1.004411393451764, "lag": 0.0, "uptime": 91.179846024}
|
||||
{"t": 1790734411.9851615, "status": "running", "rtMean": 1.0061548832920237, "lag": 0.0, "uptime": 101.244880286}
|
||||
{"t": 1790734422.045158, "status": "running", "rtMean": 1.0009389826422062, "lag": 0.0, "uptime": 111.322533823}
|
||||
{"t": 1790734432.1231213, "status": "running", "rtMean": 0.9994054188236428, "lag": 0.0, "uptime": 121.386590467}
|
||||
{"t": 1790734442.1821327, "status": "running", "rtMean": 1.0019091973172163, "lag": 0.0, "uptime": 131.434675409}
|
||||
{"t": 1790734452.2411315, "status": "running", "rtMean": 1.0003511147658264, "lag": 0.0, "uptime": 141.510042108}
|
||||
{"t": 1790734462.3011394, "status": "running", "rtMean": 0.9998128330113216, "lag": 0.0, "uptime": 151.571854176}
|
||||
{"t": 1790734472.3611345, "status": "running", "rtMean": 0.9995342276541852, "lag": 0.0, "uptime": 161.611024691}
|
||||
{"t": 1790734482.435045, "status": "running", "rtMean": 0.9922858838781137, "lag": 0.0, "uptime": 171.712414098}
|
||||
{"t": 1790734492.4924283, "status": "running", "rtMean": 1.0077000502536002, "lag": 0.0, "uptime": 181.768296008}
|
||||
{"t": 1790734502.590251, "status": "running", "rtMean": 0.688659978029653, "lag": 3.02, "uptime": 191.845836083}
|
||||
{"t": 1790734512.7063384, "status": "running", "rtMean": 0.6918570039489707, "lag": 6.031, "uptime": 201.972741056}
|
||||
{"t": 1790734522.8416302, "status": "running", "rtMean": 0.6636996350321189, "lag": 9.061, "uptime": 212.118463031}
|
||||
{"t": 1790734532.9413493, "status": "running", "rtMean": 0.677691555064422, "lag": 13.117, "uptime": 222.217638708}
|
||||
{"t": 1790734543.0511246, "status": "running", "rtMean": 0.6687714298956552, "lag": 16.132, "uptime": 232.330293687}
|
||||
{"t": 1790734553.214297, "status": "running", "rtMean": 0.6610843395024606, "lag": 19.139, "uptime": 242.48895228}
|
||||
{"t": 1790734563.3515842, "status": "running", "rtMean": 0.652060892547814, "lag": 23.162, "uptime": 252.608110328}
|
||||
{"t": 1790734573.4900045, "status": "running", "rtMean": 0.6695512645097088, "lag": 26.172, "uptime": 262.753496555}
|
||||
{"t": 1790734583.676419, "status": "running", "rtMean": 0.672729094430949, "lag": 30.189, "uptime": 272.933415929}
|
||||
{"t": 1790734593.8542893, "status": "running", "rtMean": 0.6751609713074462, "lag": 33.199, "uptime": 283.119763313}
|
||||
{"t": 1790734603.9855552, "status": "running", "rtMean": 0.6532184360045333, "lag": 36.247, "uptime": 293.24006575}
|
||||
{"t": 1790734614.107205, "status": "running", "rtMean": 0.6660828397073446, "lag": 40.264, "uptime": 303.373977854}
|
||||
{"t": 1790734624.218526, "status": "running", "rtMean": 0.6077386619823459, "lag": 44.344, "uptime": 313.467368475}
|
||||
{"t": 1790734634.3447165, "status": "running", "rtMean": 0.6539609074261248, "lag": 47.354, "uptime": 323.602496592}
|
||||
{"t": 1790734644.4728997, "status": "running", "rtMean": 0.6660933740022716, "lag": 50.368, "uptime": 333.740179276}
|
||||
{"t": 1790734654.5995867, "status": "running", "rtMean": 0.6500636748816758, "lag": 54.395, "uptime": 343.847346535}
|
||||
{"t": 1790734664.7299855, "status": "running", "rtMean": 0.6705859566600052, "lag": 57.409, "uptime": 354.005911843}
|
||||
{"t": 1790734674.917639, "status": "running", "rtMean": 0.6740430368306463, "lag": 61.419, "uptime": 364.191797413}
|
||||
{"t": 1790734685.0660818, "status": "running", "rtMean": 0.6643961460479318, "lag": 64.428, "uptime": 374.341795785}
|
||||
{"t": 1790734695.265925, "status": "running", "rtMean": 0.6579653102367324, "lag": 68.437, "uptime": 384.519988281}
|
||||
{"t": 1790734705.472841, "status": "running", "rtMean": 0.6547900490878023, "lag": 71.446, "uptime": 394.730676243}
|
||||
{"t": 1790734715.6600814, "status": "running", "rtMean": 0.6530533406133286, "lag": 75.466, "uptime": 404.896364288}
|
||||
{"t": 1790734725.7730033, "status": "running", "rtMean": 0.6672820515708326, "lag": 78.47, "uptime": 415.037219103}
|
||||
{"t": 1790734735.8823855, "status": "running", "rtMean": 0.6604279690960906, "lag": 81.507, "uptime": 425.141484166}
|
||||
{"t": 1790734746.0059605, "status": "running", "rtMean": 0.669876056664904, "lag": 85.525, "uptime": 435.241624797}
|
||||
{"t": 1790734756.16065, "status": "running", "rtMean": 0.6669554325713298, "lag": 88.532, "uptime": 445.424510067}
|
||||
{"t": 1790734766.2961965, "status": "running", "rtMean": 0.6789691324390087, "lag": 91.546, "uptime": 455.562624387}
|
||||
{"t": 1790734776.4270732, "status": "running", "rtMean": 0.6764526659523141, "lag": 95.567, "uptime": 465.699227051}
|
||||
{"t": 1790734786.5895793, "status": "running", "rtMean": 0.6530891711548452, "lag": 98.603, "uptime": 475.850685381}
|
||||
{"t": 1790734796.7317367, "status": "running", "rtMean": 0.6406146952722656, "lag": 102.675, "uptime": 486.00189116}
|
||||
{"t": 1790734806.8721528, "status": "running", "rtMean": 0.6453060329257198, "lag": 105.69, "uptime": 496.149729812}
|
||||
{"t": 1790734817.0070937, "status": "running", "rtMean": 0.6454966448957478, "lag": 109.706, "uptime": 506.283307741}
|
||||
{"t": 1790734827.1343982, "status": "running", "rtMean": 0.6448485469528062, "lag": 112.72, "uptime": 516.409124389}
|
||||
{"t": 1790734837.2881198, "status": "running", "rtMean": 0.6535926679887758, "lag": 116.748, "uptime": 526.560442848}
|
||||
{"t": 1790734847.4209673, "status": "running", "rtMean": 0.6425044322629614, "lag": 119.784, "uptime": 536.693837434}
|
||||
{"t": 1790734857.5829508, "status": "running", "rtMean": 0.6452458464522223, "lag": 123.802, "uptime": 546.8305001}
|
||||
{"t": 1790734867.7133708, "status": "running", "rtMean": 0.6302281366614498, "lag": 127.82, "uptime": 556.984448186}
|
||||
{"t": 1790734877.8158286, "status": "running", "rtMean": 0.6629500748501092, "lag": 130.844, "uptime": 567.072718764}
|
||||
{"t": 1790734887.943275, "status": "running", "rtMean": 0.6648674424022735, "lag": 133.854, "uptime": 577.200347159}
|
||||
{"t": 1790734898.06847, "status": "running", "rtMean": 0.6593429199106378, "lag": 137.876, "uptime": 587.328798352}
|
||||
{"t": 1790734908.210695, "status": "running", "rtMean": 0.662979366140112, "lag": 140.891, "uptime": 597.465073525}
|
||||
{"t": 1790734918.3496716, "status": "running", "rtMean": 0.6614754105222075, "lag": 144.914, "uptime": 607.619842905}
|
||||
{"t": 1790734928.486646, "status": "running", "rtMean": 0.6692348242211306, "lag": 147.924, "uptime": 617.724273337}
|
||||
{"t": 1790734938.6051722, "status": "running", "rtMean": 0.6733974004623173, "lag": 150.942, "uptime": 627.874978882}
|
||||
{"t": 1790734948.703509, "status": "running", "rtMean": 0.6484292959854895, "lag": 154.965, "uptime": 637.96851242}
|
||||
{"t": 1790734958.9605355, "status": "running", "rtMean": 0.6326829212607562, "lag": 158.977, "uptime": 648.224285288}
|
||||
{"t": 1790734969.0924904, "status": "running", "rtMean": 0.6743317584475094, "lag": 162.001, "uptime": 658.352731683}
|
||||
{"t": 1790734979.512936, "status": "running", "rtMean": 0.66105927868997, "lag": 165.016, "uptime": 668.754929041}
|
||||
20
infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{"t": 1790734991.7640753, "status": "running", "rtMean": 0.6359105463426694, "lag": 3.008, "uptime": 11.070042764}
|
||||
{"t": 1790735051.931584, "status": "running", "rtMean": 0.4413866438713924, "lag": 31.225, "uptime": 71.270223818}
|
||||
{"t": 1790735112.0636158, "status": "running", "rtMean": 0.528275325797771, "lag": 56.478, "uptime": 131.388274947}
|
||||
{"t": 1790735172.2191246, "status": "running", "rtMean": 0.5653650170639056, "lag": 85.705, "uptime": 191.513860632}
|
||||
{"t": 1790735232.3440776, "status": "running", "rtMean": 0.598275320104138, "lag": 110.037, "uptime": 251.674657096}
|
||||
{"t": 1790735292.5060995, "status": "running", "rtMean": 0.6030301486902879, "lag": 134.326, "uptime": 311.836161733}
|
||||
{"t": 1790735352.646486, "status": "running", "rtMean": 0.6475849197046364, "lag": 156.459, "uptime": 371.966818709}
|
||||
{"t": 1790735412.780515, "status": "running", "rtMean": 0.5770778494664259, "lag": 179.892, "uptime": 432.08998512}
|
||||
{"t": 1790735472.8577662, "status": "running", "rtMean": 0.6886656579593289, "lag": 198.051, "uptime": 492.201636495}
|
||||
{"t": 1790735532.9329088, "status": "running", "rtMean": 0.7616039578620443, "lag": 210.17, "uptime": 552.275859184}
|
||||
{"t": 1790735592.995646, "status": "running", "rtMean": 0.8492741277663118, "lag": 225.508, "uptime": 612.316843322}
|
||||
{"t": 1790735653.0601382, "status": "running", "rtMean": 0.8233088403353765, "lag": 232.541, "uptime": 672.386139571}
|
||||
{"t": 1790735713.1299574, "status": "running", "rtMean": 0.8821898469526929, "lag": 239.649, "uptime": 732.468014006}
|
||||
{"t": 1790735773.1924357, "status": "running", "rtMean": 0.9074726134753647, "lag": 243.655, "uptime": 792.527038261}
|
||||
{"t": 1790735833.2571187, "status": "running", "rtMean": 0.899453016514728, "lag": 250.877, "uptime": 852.593245225}
|
||||
{"t": 1790735893.3221343, "status": "running", "rtMean": 0.6620087337657867, "lag": 258.043, "uptime": 912.634830266}
|
||||
{"t": 1790735953.5102656, "status": "running", "rtMean": 0.4740061480416233, "lag": 290.508, "uptime": 972.827598732}
|
||||
{"t": 1790736013.6372716, "status": "running", "rtMean": 0.552244625226687, "lag": 321.774, "uptime": 1032.942900792}
|
||||
{"t": 1790736073.7192469, "status": "running", "rtMean": 0.5496939405024359, "lag": 348.997, "uptime": 1093.015463153}
|
||||
{"t": 1790736133.779931, "status": "running", "rtMean": 0.8831947829035597, "lag": 362.15, "uptime": 1153.096169148}
|
||||
1
infra/tests/fixtures/shadow-guard/slow-shadow-same/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/slow-shadow-same/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
trip
|
||||
1760
infra/tests/lint.sh
1760
infra/tests/lint.sh
File diff suppressed because it is too large
Load diff
136
infra/tests/shadow_guard_traces.py
Normal file
136
infra/tests/shadow_guard_traces.py
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Synthetic live-fly RTF traces for fly-shadow-run's guard (SHADOW-01 review round 2, G1).
|
||||
|
||||
shadow_guard_traces.py OUTDIR
|
||||
|
||||
Writes <case>/baseline.jsonl and <case>/checks.jsonl in fly-shadow-run's sample format
|
||||
({t, status, rtMean, lag, uptime}) and prints one line per case: `<case> <expect>`, where
|
||||
<expect> is `pass` (the guard must not trip) or `trip` (it must). The baseline is 60 samples 10 s
|
||||
apart (start's 10 minutes); the checks are one sample a minute for the given length.
|
||||
|
||||
The lag follows flysim's pacer: a fly behind real time owes (1 - rtf) seconds per second, and the
|
||||
pacer books it as lag only in chunks of more than a second (`pacing::MAX_CATCHUP`).
|
||||
|
||||
The cases come from the release container's own numbers (the coordinator's samples, agents.log
|
||||
2026-09-30 00:08Z): a flat 0.66 before the cpuset rebalance, 0.77-0.99 noisy after it, plus a fly
|
||||
at real time; each alone (must pass), and each with a genuine degradation after the start (must
|
||||
trip).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
|
||||
class Fly:
|
||||
def __init__(self, seed):
|
||||
self.rng = random.Random(seed)
|
||||
self.t, self.uptime, self.lag, self.debt = 1_790_000_000.0, 3600.0, 12.0, 0.0
|
||||
|
||||
def run(self, seconds, rtf_of):
|
||||
"""Advances `seconds` of wall time at the realtime factors `rtf_of()` gives per second."""
|
||||
rtfs = []
|
||||
for _ in range(int(seconds)):
|
||||
rtf = rtf_of(self.rng)
|
||||
rtfs.append(rtf)
|
||||
self.debt += max(0.0, 1.0 - rtf)
|
||||
if self.debt > 1.0:
|
||||
self.lag += self.debt
|
||||
self.debt = 0.0
|
||||
self.t += 1
|
||||
self.uptime += 1
|
||||
return rtfs
|
||||
|
||||
def sample(self, rtf_of, status="running"):
|
||||
rtfs = self.run(10, rtf_of)
|
||||
return {"t": self.t, "status": status, "rtMean": sum(rtfs) / len(rtfs),
|
||||
"lag": round(self.lag, 3), "uptime": self.uptime}
|
||||
|
||||
def restart(self):
|
||||
self.uptime, self.lag, self.debt = 5.0, 0.0, 0.0
|
||||
|
||||
|
||||
def flat(v, jitter=0.01):
|
||||
return lambda rng: v + rng.uniform(-jitter, jitter)
|
||||
|
||||
|
||||
def noisy(lo, hi):
|
||||
return lambda rng: rng.uniform(lo, hi)
|
||||
|
||||
|
||||
def noisy_windows(lo, hi):
|
||||
"""Noise at the sample level: each 10 s holds one value in [lo, hi], so the 10-s means the
|
||||
guard reads spread over the whole range (the coordinator's samples)."""
|
||||
state = {"n": 0, "v": None}
|
||||
|
||||
def pace(rng):
|
||||
if state["n"] % 10 == 0:
|
||||
state["v"] = rng.uniform(lo, hi)
|
||||
state["n"] += 1
|
||||
return state["v"]
|
||||
|
||||
return pace
|
||||
|
||||
|
||||
def realtime(rng):
|
||||
return min(1.0, 1.0 + rng.uniform(-0.004, 0.002))
|
||||
|
||||
|
||||
def case(seed, before, after, checks=180, degrade_at=None, events=None):
|
||||
fly = Fly(seed)
|
||||
baseline = [fly.sample(before) for _ in range(60)]
|
||||
fly.restart() # start's own flysim restart
|
||||
rows = []
|
||||
for n in range(checks):
|
||||
pace = after if degrade_at is not None and n >= degrade_at else before
|
||||
status = "running"
|
||||
if events and n in events:
|
||||
kind = events[n]
|
||||
if kind == "restart":
|
||||
fly.restart()
|
||||
elif kind == "paused":
|
||||
status = "paused"
|
||||
elif kind == "hiccup":
|
||||
fly.lag += 1.3 # one pacing shortfall of 1.3 s, nothing more
|
||||
rows.append(fly.sample(pace, status))
|
||||
fly.run(50, pace)
|
||||
return baseline, rows
|
||||
|
||||
|
||||
CASES = {
|
||||
# The release CT before the rebalance: a flat 0.66, 3 hours, with a restart and a pause.
|
||||
"ct-flat-0.66": (case(1, flat(0.66), None, events={40: "restart", 90: "paused", 91: "paused"}), "pass"),
|
||||
# After the rebalance: 0.77-0.99 noisy, 3 hours, a restart.
|
||||
"ct-noisy-0.77-0.99": (case(2, noisy(0.77, 0.99), None, events={120: "restart"}), "pass"),
|
||||
"ct-noisy-0.77-0.99-seed3": (case(3, noisy(0.77, 0.99), None), "pass"),
|
||||
# The same spread at the level of the 10-s samples themselves, the harder case.
|
||||
"ct-samples-0.77-0.99": (case(8, noisy_windows(0.77, 0.99), None, events={60: "restart"}), "pass"),
|
||||
"ct-samples-0.77-0.99-seed9": (case(9, noisy_windows(0.77, 0.99), None), "pass"),
|
||||
"ct-samples-0.77-0.99-seed10": (case(10, noisy_windows(0.77, 0.99), None), "pass"),
|
||||
# At real time, with single pacing hiccups: never a trip.
|
||||
"realtime-hiccups": (case(4, realtime, None, events={30: "hiccup", 100: "hiccup", 150: "hiccup"}), "pass"),
|
||||
# A shadow that costs the fly real time.
|
||||
"ct-flat-0.66-then-0.55": (case(5, flat(0.66), flat(0.55), checks=40, degrade_at=15), "trip"),
|
||||
"ct-noisy-then-0.60-0.75": (case(6, noisy(0.77, 0.99), noisy(0.60, 0.75), checks=40, degrade_at=15), "trip"),
|
||||
"realtime-then-0.90": (case(7, realtime, flat(0.90), checks=40, degrade_at=15), "trip"),
|
||||
"ct-samples-then-0.55-0.75": (
|
||||
case(11, noisy_windows(0.77, 0.99), noisy_windows(0.55, 0.75), checks=40, degrade_at=15),
|
||||
"trip",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
out = sys.argv[1]
|
||||
for name, ((baseline, checks), expect) in CASES.items():
|
||||
d = os.path.join(out, name)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
for fname, rows in (("baseline.jsonl", baseline), ("checks.jsonl", checks)):
|
||||
with open(os.path.join(d, fname), "w") as f:
|
||||
for r in rows:
|
||||
f.write(json.dumps(r) + "\n")
|
||||
print(name, expect)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -117,6 +117,143 @@ class RecoveryTests(unittest.TestCase):
|
|||
self.confirm(T0, rank=13)
|
||||
self.assertEqual(self.acts, [("restart", None)])
|
||||
|
||||
# Row 70: the rung-11 reset replayed the run exactly (1,138 of 1,138 events), caught the Zubat
|
||||
# again and walked into the same trap; the next step reset to rung 11 again and erased the catch.
|
||||
def test_progress_after_the_last_step_starts_the_ladder_over(self):
|
||||
recover.write_json(recover.STATE, {"level": 4, "bestRank": 12, "resets": [], "actedAt": T0 - 7200})
|
||||
# an area and a species inside the windows of probes well after the step
|
||||
self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 2, "species": 0}})
|
||||
self.assertIn("flysim restarted", self.confirm(T0))
|
||||
self.assertEqual(self.acts, [("restart", None)])
|
||||
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
|
||||
self.assertIn("progress since the last step", [event.get("why") for event in history])
|
||||
|
||||
def test_progress_while_a_step_settles_does_not_start_the_ladder_over(self):
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 1500})
|
||||
self.tick(T0 - 1400, suspected=0, window={"progress": {"lasting": 3, "species": 0}})
|
||||
self.confirm(T0)
|
||||
self.assertEqual(self.acts, [("reset", 11)])
|
||||
|
||||
def test_a_species_owned_recently_is_never_reset_away(self):
|
||||
owned = T0 - 1200
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [],
|
||||
"actedAt": T0 - recover.HOLD - 300, "speciesAt": owned})
|
||||
self.assertIn("flysim restarted", self.confirm(T0))
|
||||
self.assertEqual(self.acts, [("restart", None)])
|
||||
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
|
||||
self.assertIn("protect", [event.get("event") for event in history])
|
||||
# the hold still spaces the restarts, and says why
|
||||
self.assertIn("protection window", self.confirm(T0 + 300 + recover.SETTLE + 10))
|
||||
# the protection lasts PROTECT from the species; then the ladder resets as before
|
||||
self.assertIn("reset to rung 11", self.tick(owned + recover.PROTECT + 60))
|
||||
|
||||
def test_a_probe_that_owns_a_species_starts_the_protection(self):
|
||||
self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 1}})
|
||||
self.assertEqual(recover.load(recover.STATE, {}).get("speciesAt"), T0)
|
||||
self.assertEqual(recover.load(recover.STATE, {}).get("progressAt"), T0)
|
||||
|
||||
def test_the_last_resets_archive_is_not_restored_again(self):
|
||||
acted = T0 - recover.HOLD - 100
|
||||
recover.write_json(recover.STATE, {"level": 3, "bestRank": 12, "resets": [acted],
|
||||
"actedAt": acted, "lastReset": 11, "lastResetAt": acted})
|
||||
self.confirm(T0)
|
||||
self.assertEqual(self.acts, [("restart", None)])
|
||||
|
||||
def test_a_protected_reset_does_not_climb_but_the_archive_just_used_does(self):
|
||||
# protected: the restart keeps the level's slot, so the reset comes at the same rung later
|
||||
owned = T0 - 600
|
||||
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": 0,
|
||||
"speciesAt": owned})
|
||||
self.confirm(T0)
|
||||
self.assertEqual(self.acts, [("restart", None)])
|
||||
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 1)
|
||||
# the archive just restored: a restart that climbs, and the marker is forgotten after AGAIN
|
||||
self.acts.clear()
|
||||
reset_at = T0 - recover.HOLD - 100
|
||||
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [reset_at], "actedAt": reset_at,
|
||||
"lastReset": 12, "lastResetAt": reset_at})
|
||||
self.confirm(T0 + 1000)
|
||||
self.assertEqual(self.acts, [("restart", None)])
|
||||
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2)
|
||||
self.acts.clear()
|
||||
self.tick(reset_at + recover.AGAIN + 60)
|
||||
self.assertNotIn("lastReset", recover.load(recover.STATE, {}))
|
||||
|
||||
def test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it(self):
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
|
||||
self.confirm(T0)
|
||||
self.assertEqual(recover.load(recover.STATE, {}).get("lastReset"), 11)
|
||||
self.tick(T0 + 300 + recover.SETTLE + 10, suspected=0, rank=13)
|
||||
self.assertNotIn("lastReset", recover.load(recover.STATE, {}))
|
||||
|
||||
# Row 70 review r3: a reset restores the reward ledger, so its replay pays the archive's rewards
|
||||
# again. Progress is a reward name the ladder has not seen before, not a count.
|
||||
def test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over(self):
|
||||
seen = ["area:AREA 59", "pokedex:OWNED #8", "trainer:BEAT ROUTE 3 TRAINER 0", "milestone:Reached MT. MOON"]
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
|
||||
"progressSeen": seen})
|
||||
replay = {"progress": {"lasting": 4, "species": 1, "keys": seen}}
|
||||
self.tick(T0 - 3000, suspected=0, window=replay)
|
||||
state = recover.load(recover.STATE, {})
|
||||
self.assertNotIn("progressAt", state)
|
||||
self.assertNotIn("speciesAt", state) # the replayed catch was protected before the reset
|
||||
self.assertEqual(state["progressSeen"], seen)
|
||||
self.confirm(T0)
|
||||
self.assertEqual(self.acts, [("reset", 11)])
|
||||
|
||||
def test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected(self):
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
|
||||
"progressSeen": ["area:AREA 59"]})
|
||||
self.tick(T0 - 3000, suspected=0,
|
||||
window={"progress": {"lasting": 2, "species": 1, "keys": ["area:AREA 59", "pokedex:OWNED #41"]}})
|
||||
state = recover.load(recover.STATE, {})
|
||||
self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000))
|
||||
self.assertEqual(state["progressSeen"], ["area:AREA 59", "pokedex:OWNED #41"])
|
||||
self.assertIn("flysim restarted", self.confirm(T0))
|
||||
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
|
||||
self.assertIn("progress since the last step", [event.get("why") for event in history])
|
||||
|
||||
def test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over(self):
|
||||
acted = T0 - recover.HOLD - 600
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": acted,
|
||||
"clearAt": acted + 60})
|
||||
catch = {"progress": {"lasting": 1, "species": 1, "keys": ["pokedex:OWNED #41"]}}
|
||||
self.assertIn("flysim restarted", self.confirm(T0, window=catch))
|
||||
self.assertEqual(self.acts, [("restart", None)]) # the rung-11 reset, held for the new species
|
||||
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2)
|
||||
|
||||
def test_without_reward_names_the_counts_still_count(self):
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
|
||||
"progressSeen": ["pokedex:OWNED #8"]})
|
||||
self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 1, "species": 1}})
|
||||
state = recover.load(recover.STATE, {})
|
||||
self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000))
|
||||
|
||||
def test_the_names_remembered_are_bounded(self):
|
||||
recover.write_json(recover.STATE, {"progressSeen": [f"area:AREA {n}" for n in range(recover.SEEN)]})
|
||||
self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA X"]}})
|
||||
seen = recover.load(recover.STATE, {})["progressSeen"]
|
||||
self.assertEqual((len(seen), seen[0], seen[-1]), (recover.SEEN, "area:AREA 1", "area:AREA X"))
|
||||
# a malformed list is ignored item by item
|
||||
self.tick(T0 + 300, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": [{}, ["x"], 3]}})
|
||||
self.assertEqual(recover.load(recover.STATE, {})["progressSeen"][-1], "area:AREA X")
|
||||
|
||||
def test_restarts_stay_a_hold_apart_after_the_ladder_starts_over(self):
|
||||
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": T0 - 3600,
|
||||
"lastAction": "restart"})
|
||||
self.tick(T0 - 2000, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA 60"]}})
|
||||
self.assertIn("last restart was under three hours ago", self.confirm(T0))
|
||||
self.assertEqual(self.acts, [])
|
||||
self.assertIn("flysim restarted", self.tick(T0 - 3600 + recover.HOLD))
|
||||
|
||||
def test_a_failed_reset_does_not_block_its_archive(self):
|
||||
recover.act.side_effect = lambda action, target: self.acts.append((action, target)) or False
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
|
||||
self.assertIn("reset FAILED", self.confirm(T0))
|
||||
state = recover.load(recover.STATE, {})
|
||||
self.assertNotIn("lastReset", state)
|
||||
self.assertEqual((state["level"], len(state["resets"])), (3, 1)) # it still climbed and spent the reset
|
||||
|
||||
def test_quiet_hours_start_the_ladder_over(self):
|
||||
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "actedAt": 0,
|
||||
"lastSuspectedAt": T0 - recover.QUIET - 1})
|
||||
|
|
@ -268,6 +405,139 @@ BUILD = "lif-1ms-f64-v2/pokered-unique8-v7/abc/fly-kc-mbon-rstdp-v2"
|
|||
|
||||
|
||||
@unittest.skipIf(recover.os.geteuid() == 0, "the wrapper ignores test overrides as root")
|
||||
class ClosedLoopTests(unittest.TestCase):
|
||||
"""Row 70 review L1: a trap no restart clears, every reset replaying it exactly (closed loop)."""
|
||||
M = 60
|
||||
R11 = dict(events=[(20, "pokedex"), (21, "trainer"), (35, "trainer"), (44, "area"), (46, "milestone"),
|
||||
(52, "pokedex")], trap=58, rank_after=[(46, 12)], start_rank=11)
|
||||
R12 = dict(events=[(7, "pokedex")], trap=12, rank_after=[], start_rank=12)
|
||||
R10 = dict(events=[(30, "area"), (60, "milestone"), (90, "milestone"), (100, "pokedex")], trap=110,
|
||||
rank_after=[(60, 11), (90, 12)], start_rank=10)
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
root = Path(self.temp.name)
|
||||
for name, value in (("REPORT", "loop.json"), ("STATE", "s.json"), ("HISTORY", "h.jsonl"),
|
||||
("NOTICE", "n.json")):
|
||||
patcher = patch.object(recover, name, root / value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
for name, value in (("restorable_rungs", lambda: {9, 10, 11, 12}), ("verdict", lambda report: (None, None))):
|
||||
patcher = patch.object(recover, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.env = patch.dict("os.environ", {}, clear=False)
|
||||
self.env.start()
|
||||
self.addCleanup(self.env.stop)
|
||||
for key in ("FLY_LOOP_ROUTER_URL", "FLY_LOOP_MODELS", "FLY_LOOP_MODEL", "FLY_LOOP_ROUTER_KEY"):
|
||||
recover.os.environ.pop(key, None)
|
||||
|
||||
def simulate(self, archives, hours, species_before=None, names=True):
|
||||
"""The fly is trapped from T0; returns [(hours, action, target)]. A reset replays its archive.
|
||||
|
||||
Every lasting reward has a name (window.progress.keys): the fly earned each archive's rewards
|
||||
once before the trap, in clear probes the ladder saw, and a replay pays the same names again.
|
||||
"""
|
||||
M = self.M
|
||||
sim = dict(events=[(T0 - species_before * M, "pokedex", "pokedex:pre")] if species_before else [],
|
||||
rank=12, rank_changes=[], trap_from=T0, now=T0, acts=[])
|
||||
history = [f"{k}:{rung}/{o}" for rung, a in sorted(archives.items()) for o, k in a["events"]]
|
||||
for i in range(0, len(history), 3) if names else ():
|
||||
recover.REPORT.write_text(json.dumps({
|
||||
"at": T0 - 86400 + i * 300, "suspected": 0, "action": "none", "milestone": {"rank": 12},
|
||||
"window": {"progress": {"lasting": 3, "species": 0, "keys": history[i:i + 3]}}}))
|
||||
recover.run(now=T0 - 86400 + i * 300 + 5, sleep=lambda s: None)
|
||||
seen = recover.load(recover.STATE, {}).get("progressSeen")
|
||||
|
||||
def act(action, target):
|
||||
sim["acts"].append((sim["now"], action, target))
|
||||
if action == "reset":
|
||||
a = archives[target]
|
||||
sim["rank"] = a["start_rank"]
|
||||
sim["events"] = [(sim["now"] + o * M, k, f"{k}:{target}/{o}") for o, k in a["events"]]
|
||||
sim["rank_changes"] = [(sim["now"] + o * M, r) for o, r in a["rank_after"]]
|
||||
sim["trap_from"] = None if a["trap"] is None else sim["now"] + a["trap"] * M
|
||||
return True
|
||||
|
||||
recover.write_json(recover.STATE, dict({"bestRank": 12, "rank": 12, "level": 0},
|
||||
**({"progressSeen": seen} if seen else {})))
|
||||
recover.HISTORY.write_text("")
|
||||
with patch.object(recover, "act", side_effect=act):
|
||||
t = T0
|
||||
while t < T0 + hours * 3600:
|
||||
for change in list(sim["rank_changes"]):
|
||||
if change[0] <= t:
|
||||
sim["rank"] = change[1]
|
||||
sim["rank_changes"].remove(change)
|
||||
win = [(k, name) for at, k, name in sim["events"] if t - 600 <= at <= t]
|
||||
trapped = sim["trap_from"] is not None and t - sim["trap_from"] >= 600
|
||||
recover.REPORT.write_text(json.dumps({
|
||||
"at": t, "suspected": 1 if trapped else 0, "action": "none", "reason": "dominant",
|
||||
"sequence": ["NEXT"], "milestone": {"rank": sim["rank"], "label": "X"}, "map": 59,
|
||||
"window": {"progress": dict({
|
||||
"lasting": sum(k in ("pokedex", "area", "trainer", "badge", "milestone") for k, _ in win),
|
||||
"species": sum(k == "pokedex" for k, _ in win)},
|
||||
**({"keys": [name for _, name in win]} if names else {}))}}))
|
||||
sim["now"] = t + 5
|
||||
recover.run(now=t + 5, sleep=lambda s: None)
|
||||
t += 300
|
||||
return [((at - T0) / 3600, action, target) for at, action, target in sim["acts"]]
|
||||
|
||||
def test_a_restart_proof_trap_is_reset_in_bounded_time_and_again(self):
|
||||
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 72, species_before=6)
|
||||
resets = [a for a in acts if a[1] == "reset"]
|
||||
# v0.7.0 resets again at 24.75 h; the ladder is no worse, and keeps resetting
|
||||
self.assertTrue(resets and resets[0][0] <= 25, acts)
|
||||
self.assertTrue(len([a for a in resets if a[0] <= 25]) >= 1, acts)
|
||||
self.assertTrue(len(resets) >= 3, acts)
|
||||
gaps = [b[0] - a[0] for a, b in zip(resets, resets[1:])]
|
||||
self.assertTrue(all(g <= 25 for g in gaps), acts)
|
||||
# the first step is a restart; the catch stays protected for 2 h
|
||||
self.assertEqual(acts[0][1], "restart")
|
||||
self.assertTrue(all(a[0] >= 2 - 0.2 for a in resets[:1]), acts)
|
||||
|
||||
def test_the_held_reset_is_the_rung_12_one_not_a_deeper_rung(self):
|
||||
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24, species_before=6)
|
||||
self.assertEqual([a[2] for a in acts if a[1] == "reset"][:1], [12], acts)
|
||||
|
||||
def test_a_trap_the_rung_12_archive_escapes_ends_there(self):
|
||||
clean = dict(self.R12, trap=None)
|
||||
acts = self.simulate({11: self.R11, 12: clean, 10: self.R10, 9: self.R10}, 24, species_before=6)
|
||||
self.assertEqual([a[1:] for a in acts if a[1] == "reset"], [("reset", 12)], acts)
|
||||
self.assertEqual(len(acts), 2, acts)
|
||||
|
||||
def test_without_a_catch_the_ladder_resets_early(self):
|
||||
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24)
|
||||
self.assertLessEqual(next(a[0] for a in acts if a[1] == "reset"), 1, acts)
|
||||
|
||||
def test_a_trap_only_the_rung_below_escapes_is_reached_promptly(self):
|
||||
# review r2 N1: the rung-12 replay re-earns progress, then traps; only rung 11 escapes.
|
||||
# v0.7.0 reset to 11 at 2.08 h; holding the level on the archive just used took 24.75 h, and
|
||||
# counting the replay's area and species as progress took 5.58 h (6.83 h after a catch).
|
||||
late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12)
|
||||
archives = {11: dict(self.R11, trap=None), 12: late12, 10: self.R10, 9: self.R10}
|
||||
for species_before, bound in ((None, 2.1), (6, 2.1 + 2)): # a catch 6 min before the trap: +2 h at most
|
||||
with self.subTest(species_before=species_before):
|
||||
self.setUp()
|
||||
acts = self.simulate(archives, 96, species_before=species_before)
|
||||
resets = [a for a in acts if a[1] == "reset"]
|
||||
self.assertEqual([a[2] for a in resets], [12, 11], acts)
|
||||
self.assertLessEqual(resets[-1][0], bound, acts)
|
||||
|
||||
def test_restarts_are_a_hold_apart_in_every_closed_loop(self):
|
||||
late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12)
|
||||
for archives in ({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10},
|
||||
{11: self.R11, 12: late12, 10: self.R10, 9: self.R10}):
|
||||
for species_before in (None, 6):
|
||||
self.setUp()
|
||||
acts = self.simulate(archives, 72, species_before=species_before)
|
||||
restarts = [a[0] for a in acts if a[1] == "restart"]
|
||||
self.assertTrue(all(b - a >= 3 - 1e-6 for a, b in zip(restarts, restarts[1:])), acts)
|
||||
resets = [a[0] for a in acts if a[1] == "reset"]
|
||||
self.assertTrue(all(sum(1 for y in resets if x <= y < x + 24) <= 2 for x in resets), acts)
|
||||
|
||||
|
||||
class WrapperTests(unittest.TestCase):
|
||||
"""infra/bin/fly-loop-reset against a fake flysim, systemctl, reset tool and archives."""
|
||||
|
||||
|
|
|
|||
|
|
@ -13,3 +13,7 @@ ExecStart=/opt/fly/bin/fly-recap
|
|||
Nice=19
|
||||
IOSchedulingClass=idle
|
||||
CPUWeight=20
|
||||
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
|
||||
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
|
||||
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
|
||||
CPUSchedulingPolicy=idle
|
||||
|
|
|
|||
|
|
@ -11,3 +11,7 @@ Environment=FLY_MEDIA_DIR=/srv/fly/media
|
|||
ExecStart=/opt/fly/bin/fly-retention
|
||||
Nice=15
|
||||
IOSchedulingClass=idle
|
||||
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
|
||||
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
|
||||
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
|
||||
CPUSchedulingPolicy=idle
|
||||
|
|
|
|||
19
infra/units/fly-runtime-fallback.service
Normal file
19
infra/units/fly-runtime-fallback.service
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# infra/units/fly-runtime-fallback.service — pushed to /etc/systemd/system/.
|
||||
#
|
||||
# The persistent fallback from the session runtime to the legacy loop (SERVE-01 review, C1).
|
||||
# It is never enabled and in no target: the drop-in that `fly-runtime session` writes on
|
||||
# flysim.service (10-runtime.conf) carries `OnFailure=fly-runtime-fallback.service` together with
|
||||
# StartLimitIntervalSec=600, StartLimitBurst=3 and RestartMode=direct (without it OnFailure= fires on
|
||||
# every crash, not at the start limit), so three starts of flysim.service on the
|
||||
# session binary inside ten minutes -- from any cause, and from any caller: a reboot, the
|
||||
# watchdog, fly-loop-recover, a deploy -- run this unit once. `fly-runtime fallback` removes the
|
||||
# drop-in (which removes this OnFailure= too), daemon-reloads, restarts flysim.service on the
|
||||
# legacy binary and writes /run/fly/runtime-fellback.json plus a journal line (tag fly-runtime).
|
||||
# It is idempotent and refuses to act without an executable legacy binary. Runs as root.
|
||||
[Unit]
|
||||
Description=fly-runtime-fallback: flysim.service failed on the session runtime, back to legacy
|
||||
# Its own start limit stays the default; a fallback that has already happened is a no-op.
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/opt/fly/bin/fly-runtime fallback
|
||||
13
infra/units/fly-runtime-probation.service
Normal file
13
infra/units/fly-runtime-probation.service
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# infra/units/fly-runtime-probation.service -- triggered by fly-runtime-probation.timer.
|
||||
#
|
||||
# One sample (10 s of flysim's /metrics) and one decision of CUT-01's speed probation: see
|
||||
# infra/bin/fly-runtime-probation. On a sustained speed failure it runs `fly-runtime fallback
|
||||
# "speed: ..."`. With no probation running it disables its own timer. Root: the fallback removes a
|
||||
# drop-in in /etc/systemd and restarts flysim.
|
||||
[Unit]
|
||||
Description=fly-runtime-probation: is the session runtime at real time? (CUT-01)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/opt/fly/bin/fly-runtime-probation tick
|
||||
TimeoutStartSec=240
|
||||
18
infra/units/fly-runtime-probation.timer
Normal file
18
infra/units/fly-runtime-probation.timer
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# infra/units/fly-runtime-probation.timer -- CUT-01's speed probation, every 60 s.
|
||||
#
|
||||
# Not enabled by provisioning or deploy. `fly-runtime session` runs `fly-runtime-probation start`
|
||||
# (systemctl enable --now), which is why this unit has an [Install] section: the enablement is
|
||||
# what makes a probation survive a reboot (OnBootSec= then runs the first tick). The probation
|
||||
# disables the timer when it passes, fails over to legacy, or is cancelled (`fly-runtime legacy`).
|
||||
[Unit]
|
||||
Description=fly-runtime-probation: the session runtime's speed probation, every minute (CUT-01)
|
||||
|
||||
[Timer]
|
||||
OnBootSec=90s
|
||||
OnActiveSec=60s
|
||||
OnUnitActiveSec=60s
|
||||
AccuracySec=5s
|
||||
Unit=fly-runtime-probation.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
56
infra/units/flycontrol-edge.service
Normal file
56
infra/units/flycontrol-edge.service
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# infra/units/flycontrol-edge.service — pushed to /etc/systemd/system/flycontrol-edge.service.
|
||||
#
|
||||
# The control API (http://127.0.0.1:7401, docs/control-api.md) served from
|
||||
# flysim's control services on the bus (docs/design/flybus.md, "Control over
|
||||
# the bus"; services/flysim/crates/fly-control-edge). Whether it runs is decided
|
||||
# by one line, FLY_CONTROL_VIA in /etc/fly/fly.env (05-deploy.sh writes it from
|
||||
# the env file's FLY_CONTROL_VIA, default `direct`):
|
||||
#
|
||||
# direct flysim binds 127.0.0.1:7401 itself. ExecCondition= below fails, so
|
||||
# this unit starts as "skipped" (inactive, no failure, no restart).
|
||||
# bus flysim registers the control services on its router and leaves
|
||||
# :7401 to this unit.
|
||||
#
|
||||
# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick
|
||||
# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a
|
||||
# crash-restart, a reboot through fly.target) starts the edge in bus mode and
|
||||
# skips it in direct mode; fly.env alone decides, and flysim and the edge can
|
||||
# never disagree. This unit is in no target and has no [Install] section:
|
||||
# `systemctl enable` has nothing to do. The switch and the way back are
|
||||
# infra/docs/runbook.md, "Control over the bus": edit FLY_CONTROL_VIA, run
|
||||
# 05-deploy.sh, restart flysim.
|
||||
#
|
||||
# Ordering: flysim owns the router (/run/fly/bus, shared with the feed when
|
||||
# that rides the bus too), so it starts first and the edge follows it.
|
||||
# Requires= makes an explicit stop or restart of flysim stop or restart the
|
||||
# edge with it (and Wants= on the other side brings it back after a plain
|
||||
# start). A crash-restart of flysim is covered by the edge itself: it unbinds
|
||||
# :7401 and reconnects every 500 ms, so to every client it looks exactly like
|
||||
# flysim restarting. The edge holds no state.
|
||||
[Unit]
|
||||
Description=flycontrol-edge: the control API served from flysim's control services on the bus
|
||||
After=flysim.service
|
||||
Requires=flysim.service
|
||||
# A release that predates fly-control-edge has no binary; stay cleanly
|
||||
# inactive rather than restart-looping.
|
||||
ConditionPathExists=/opt/fly/current/fly-control-edge
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=fly
|
||||
# FLY_CONTROL_VIA, FLY_BUS_DIR and the rest of flysim's configuration: the
|
||||
# edge reads the same file, so the two cannot disagree about the port or the bus.
|
||||
EnvironmentFile=/etc/fly/fly.env
|
||||
Environment=FLY_CONTROL_BIND=127.0.0.1:7401
|
||||
Environment=FLY_BUS_DIR=/run/fly/bus
|
||||
# Its own /metrics and /healthz. Loopback only.
|
||||
Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127.0.0.1:9103
|
||||
# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value
|
||||
# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means
|
||||
# "skip": the unit goes inactive without failing and without being restarted.
|
||||
ExecCondition=/bin/sh -c 'case "$$FLY_CONTROL_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac'
|
||||
ExecStart=/opt/fly/current/fly-control-edge
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
# Small JSON requests; an /events page is the largest thing it ever holds.
|
||||
MemoryMax=128M
|
||||
|
|
@ -1,30 +1,41 @@
|
|||
# infra/units/flyedge.service — pushed to /etc/systemd/system/flyedge.service.
|
||||
#
|
||||
# The feed WebSocket served from flysim's feed bus (docs/design/flybus.md,
|
||||
# "Feed over the bus"; services/flysim/crates/fly-edge). DISABLED BY DEFAULT:
|
||||
# it is in no target's Wants=/Requires= and 07-enable.sh does not enable it.
|
||||
# With FLY_FEED_VIA=direct (the default, written into /etc/fly/fly.env by
|
||||
# 05-deploy.sh) flysim binds 127.0.0.1:7400 itself and this unit has nothing
|
||||
# to do. To move the feed onto the bus on one container:
|
||||
# "Feed over the bus"; services/flysim/crates/fly-edge). Whether it runs is
|
||||
# decided by one line, FLY_FEED_VIA in /etc/fly/fly.env (05-deploy.sh writes it
|
||||
# from the env file's FLY_FEED_VIA, default `direct`):
|
||||
#
|
||||
# 1. FLY_FEED_VIA=bus in the env file, then 05-deploy.sh (rewrites fly.env);
|
||||
# 2. systemctl enable --now flyedge.service; systemctl restart flysim.service
|
||||
# (flysim stops binding :7400, the edge binds it once the first snapshot
|
||||
# is on the bus);
|
||||
# 3. nothing for the watchdog: check 2 reads FLY_FEED_VIA from fly.env and
|
||||
# follows the feed counters to this unit's loopback /metrics.
|
||||
# direct flysim binds 127.0.0.1:7400 itself. ExecCondition= below fails, so
|
||||
# this unit starts as "skipped" (inactive, no failure, no restart).
|
||||
# bus flysim publishes on its feed bus and leaves :7400 to this unit.
|
||||
#
|
||||
# Back: FLY_FEED_VIA=direct, deploy, systemctl disable --now flyedge.service,
|
||||
# restart flysim.
|
||||
# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick
|
||||
# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a
|
||||
# crash-restart, a reboot through fly.target) starts the edge in bus mode and
|
||||
# skips it in direct mode; fly.env alone decides, and flysim and the edge can
|
||||
# never disagree. This unit is in no target and has no [Install] section:
|
||||
# `systemctl enable` has nothing to do.
|
||||
#
|
||||
# Switching a running container (infra/bin/fly-feed, "Feed over the bus" in
|
||||
# docs/runbook.md; it is the whole procedure, with a health check and its own
|
||||
# rollback):
|
||||
#
|
||||
# fly-feed bus FLY_FEED_VIA=bus in fly.env, restart flysim, wait for
|
||||
# the edge and a client
|
||||
# fly-feed direct the way back
|
||||
#
|
||||
# Ordering (docs/design/flybus.md, amendment "Feed store lifecycle"): flysim
|
||||
# owns the router and its store under /run/fly/bus, so it starts first and
|
||||
# the edge follows it. Requires= makes an explicit stop or restart of flysim
|
||||
# (the unstick rule's `systemctl restart flysim.service` included) stop or
|
||||
# restart the edge with it. A crash-restart of flysim is covered by the edge
|
||||
# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms,
|
||||
# so nothing here has to be restarted by hand. The edge holds no state; the
|
||||
# store is flysim's and a new router removes the previous one's directory.
|
||||
# owns the router and its store under /run/fly/bus, so it starts first and the
|
||||
# edge follows it. Requires= makes an explicit stop or restart of flysim stop
|
||||
# or restart the edge with it. A crash-restart of flysim is covered by the edge
|
||||
# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms, so
|
||||
# nothing here has to be restarted by hand. The edge holds no state; the store
|
||||
# is flysim's and a new router removes the previous one's directory.
|
||||
#
|
||||
# CPUs: 05-deploy.sh writes this unit's cpuset drop-in on the page CPUs, never
|
||||
# flysim's (the sim's CPUs are the sim's alone, docs/runbook.md "CPU partition").
|
||||
# The router and the publisher run inside flysim, on its own two-thread bus
|
||||
# runtime.
|
||||
[Unit]
|
||||
Description=flyedge: the feed WebSocket served from flysim's feed bus
|
||||
After=flysim.service
|
||||
|
|
@ -42,15 +53,17 @@ User=fly
|
|||
EnvironmentFile=/etc/fly/fly.env
|
||||
Environment=FLY_FEED_BIND=127.0.0.1:7400
|
||||
Environment=FLY_BUS_DIR=/run/fly/bus
|
||||
# Its own read-only /metrics and /healthz, for watchdog check 2 in bus mode.
|
||||
# Loopback only: nothing off the container needs the edge's counters.
|
||||
Environment=FLY_EDGE_METRICS_ADDR=127.0.0.1:9102
|
||||
# Its own read-only /metrics and /healthz: watchdog check 2 reads them in bus mode (over
|
||||
# loopback), and so can the metrics dashboard, as a second target beside flysim's :9101, which
|
||||
# reads 0 for the feed counters in bus mode. Same exposure as :9101 (the container's network).
|
||||
Environment=FLY_EDGE_METRICS_ADDR=0.0.0.0:9102
|
||||
# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value
|
||||
# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means
|
||||
# "skip": the unit goes inactive without failing and without being restarted.
|
||||
ExecCondition=/bin/sh -c 'case "$$FLY_FEED_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac'
|
||||
ExecStart=/opt/fly/current/fly-edge
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
# A few snapshots in flight and a WebSocket per client; the store itself is
|
||||
# flysim's (tmpfs, bounded by feedbus::limits at 32 MiB).
|
||||
MemoryMax=256M
|
||||
|
||||
[Install]
|
||||
WantedBy=fly.target
|
||||
|
|
|
|||
15
infra/units/flyshadow-guard.service
Normal file
15
infra/units/flyshadow-guard.service
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# infra/units/flyshadow-guard.service — triggered by flyshadow-guard.timer.
|
||||
#
|
||||
# `fly-shadow-run guard` compares the live fly with the 10-minute baseline `fly-shadow-run start`
|
||||
# recorded before it started the shadow: on a sustained degradation of the realtime factor or the
|
||||
# lag growth rate against that baseline (3 checks in a row, 5-sample windows), it stops
|
||||
# flyshadow.service, removes the trace drop-in and restarts flysim without the trace. The live
|
||||
# stream never pays for the shadow. It stops itself when the shadow is not running. Root, because it installs no file but
|
||||
# removes one in /etc/systemd and restarts flysim.
|
||||
[Unit]
|
||||
Description=fly-shadow-run guard: the live-impact check of the shadow run (SHADOW-01)
|
||||
ConditionPathExists=/srv/fly/shadow/baseline.json
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/opt/fly/bin/fly-shadow-run guard
|
||||
11
infra/units/flyshadow-guard.timer
Normal file
11
infra/units/flyshadow-guard.timer
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# infra/units/flyshadow-guard.timer — SHADOW-01's live-impact guard, every 60 s while a shadow
|
||||
# runs. Started by `fly-shadow-run start`, stopped by `fly-shadow-run stop` and by the guard
|
||||
# itself when it trips. No [Install]: it is never enabled, so a reboot does not start it.
|
||||
[Unit]
|
||||
Description=Stop the shadow run if the live fly pays for it (SHADOW-01)
|
||||
|
||||
[Timer]
|
||||
OnActiveSec=60s
|
||||
OnUnitActiveSec=60s
|
||||
AccuracySec=5s
|
||||
Unit=flyshadow-guard.service
|
||||
66
infra/units/flyshadow.service
Normal file
66
infra/units/flyshadow.service
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
# infra/units/flyshadow.service — pushed to /etc/systemd/system/flyshadow.service.
|
||||
#
|
||||
# SHADOW-01 (docs/design/session-framework/legacy-gameboy-v1.md section 18): the
|
||||
# session runtime run beside the live fly. REPORT-ONLY: it presses no button,
|
||||
# serves no port, and only READS flysim's stores and trace; it writes nothing
|
||||
# but /srv/fly/shadow (verdict.json, divergence.json, its spool) and its
|
||||
# runtime directory. DISABLED BY DEFAULT: in no target's Wants=/Requires=,
|
||||
# not in 07-enable.sh. `fly-shadow-run start` (infra/bin) starts it, turns
|
||||
# flysim's trace on and restarts flysim once so the shadow follows a process
|
||||
# from its first frame; `fly-shadow-run stop` undoes both.
|
||||
#
|
||||
# Deliberately NOT bound to flysim (no Requires=/BindsTo=/PartOf=): every
|
||||
# flysim restart (the unstick rule, the watchdog, fly-loop-recover, a
|
||||
# milestone reset) is a new trace file the shadow follows on its own, so the
|
||||
# shadow must outlive them. It stops itself on the first divergence with exit
|
||||
# status 3 and a `diverged` verdict; RestartPreventExitStatus keeps it
|
||||
# stopped so the verdict stays for the coordinator to read.
|
||||
#
|
||||
# Resources (the SHADOW-01 report, "resource plan"): a second whole brain,
|
||||
# about the live fly's own CPU per frame. It must never take a cycle the live
|
||||
# fly, the page or the encoder wants, so it runs SCHED_IDLE (it only gets CPU
|
||||
# nobody else is using), off flysim's cpuset (05-deploy.sh writes
|
||||
# AllowedCPUs= for it from the page and encoder groups). It pauses for a minute
|
||||
# while flysim's lag grows faster than its pre-start baseline rate (and stops
|
||||
# pausing when that does not help: then it is not the cause).
|
||||
# flyshadow-guard.timer (fly-shadow-run guard) stops it and restarts flysim
|
||||
# without the trace on a sustained degradation against that baseline. It is lag-tolerant: the trace and the
|
||||
# spool are on disk, so running behind real time only delays the verdict (the
|
||||
# 512 MiB spool covers about 15 minutes of lag for hot saves).
|
||||
#
|
||||
# Its heartbeat (<trace dir>/consumer, every 30 s, removed when it stops) is
|
||||
# what keeps flysim tracing: a stopped, diverged or crashed shadow turns the
|
||||
# live trace off within a minute of a stale heartbeat, with no root action.
|
||||
[Unit]
|
||||
Description=flyshadow: the session runtime shadowing the live fly (SHADOW-01, report only)
|
||||
After=flysim.service
|
||||
# A release that predates SHADOW-01 has no binary; stay cleanly inactive.
|
||||
ConditionPathExists=/opt/fly/current/fly-shadow
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=fly
|
||||
# The live service's configuration, read the way flysim reads it: the
|
||||
# cartridge, the dataset, the macro mode, the speed. The store paths and the
|
||||
# metrics listener are flysim.service's own Environment= lines, repeated.
|
||||
EnvironmentFile=/etc/fly/fly.env
|
||||
Environment=FLY_STATE_HOT=/run/fly/state
|
||||
Environment=FLY_STATE=/srv/fly/state
|
||||
Environment=FLY_METRICS_ADDR=0.0.0.0:9101
|
||||
# What flysim writes with the shadow's drop-in (fly-shadow-run), and where the
|
||||
# verdict goes. The session's sockets and artifacts live on tmpfs.
|
||||
Environment=FLY_TRACE_DIR=/srv/fly/shadow/trace
|
||||
Environment=FLY_SHADOW_DIR=/srv/fly/shadow
|
||||
Environment=FLY_SHADOW_WORK=/run/fly-shadow
|
||||
RuntimeDirectory=fly-shadow
|
||||
# The shadow agent's sweep threads (the report's measurements).
|
||||
Environment=FLY_SHADOW_THREADS=2
|
||||
ExecStart=/opt/fly/current/fly-shadow run
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
RestartPreventExitStatus=3
|
||||
CPUSchedulingPolicy=idle
|
||||
Nice=19
|
||||
CPUWeight=1
|
||||
IOSchedulingClass=idle
|
||||
MemoryMax=3G
|
||||
66
infra/units/flysim-session.service
Normal file
66
infra/units/flysim-session.service
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
# infra/units/flysim-session.service — pushed to /etc/systemd/system/flysim-session.service.
|
||||
#
|
||||
# The live fly on the session runtime (SERVE-01): `flysim-session`, a drop-in for `flysim` that
|
||||
# reads the same /etc/fly/fly.env, writes the same checkpoint stores, event log, sugar journal and
|
||||
# chat sidecar, and serves the same feed (:7400, or the feed bus for fly-edge), control API
|
||||
# (:7401) and metrics (:9101) -- through flysim's own listener code, so the binding contracts
|
||||
# (docs/feed-protocol.md, docs/control-api.md) are the same bytes.
|
||||
#
|
||||
# NOT ENABLED, IN NO TARGET, and it Conflicts= with flysim.service: the two own the same ports
|
||||
# and the same stores, so at most one of them runs. It is not how the stream is switched either.
|
||||
# `fly-runtime session` (infra/bin/fly-runtime; the runbook's "Switch the runtime") points
|
||||
# flysim.service itself at this unit's ExecStart and Environment with a drop-in, so that every
|
||||
# consumer that names flysim.service -- fly.target, flyedge.service's Requires=, the watchdog,
|
||||
# fly-loop-recover's restart (and its sudoers line), fly-loop-reset, fly-reset-to-milestone, the
|
||||
# unstick rule, `journalctl -u flysim` -- keeps working unchanged, a reboot keeps the choice, and
|
||||
# `fly-runtime legacy` is one command back. This unit is the standalone form of the same
|
||||
# service: for a rehearsal or a soak on a container whose flysim.service is stopped
|
||||
# (`systemctl stop flysim.service && systemctl start flysim-session.service`).
|
||||
#
|
||||
# Everything below except ExecStart, FLY_SESSION_DIR, MALLOC_ARENA_MAX, Conflicts= and the missing [Install] is
|
||||
# flysim.service's, line for line (infra/tests/lint.sh checks it), and so are the limits and the cpuset: 05-deploy.sh writes
|
||||
# flysim-session.service.d/cpuset.conf with flysim's set (docs/design/infra.md section 3 and
|
||||
# flysim.service's own notes on RAYON_NUM_THREADS, Nice, CPUWeight and AllowedCPUs apply as they
|
||||
# stand).
|
||||
[Unit]
|
||||
Description=flysim-session: the fly brain and its Game Boy on the session runtime
|
||||
After=network.target
|
||||
Conflicts=flysim.service
|
||||
StartLimitIntervalSec=300
|
||||
StartLimitBurst=5
|
||||
|
||||
[Service]
|
||||
Type=notify
|
||||
NotifyAccess=main
|
||||
WatchdogSec=30
|
||||
User=fly
|
||||
EnvironmentFile=/etc/fly/fly.env
|
||||
Environment=FLY_FEED_BIND=127.0.0.1:7400
|
||||
Environment=FLY_BUS_DIR=/run/fly/bus
|
||||
Environment=FLY_CONTROL_BIND=127.0.0.1:7401
|
||||
Environment=FLY_METRICS_ADDR=0.0.0.0:9101
|
||||
Environment=FLY_STATE_HOT=/run/fly/state
|
||||
Environment=FLY_STATE=/srv/fly/state
|
||||
# The session's own router store and worker sockets (tmpfs, fly 0700, config/fly-tmpfiles.conf).
|
||||
Environment=FLY_SESSION_DIR=/run/fly/session
|
||||
# glibc per-thread arenas fragment under the session's MB-sized capture/encode buffers: without
|
||||
# this RSS grows about 5-8 MB/h (SERVE-01 review); with it the growth plateaus. Legacy is unaffected.
|
||||
Environment=MALLOC_ARENA_MAX=2
|
||||
ExecStart=/opt/fly/current/flysim-session
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
Nice=-5
|
||||
CPUWeight=400
|
||||
# The sim's CPUs are the sim's alone (PERF-02 review N1). The session runtime pins its sweep
|
||||
# workers one per CPU, and a pinned worker cannot leave a CPU that something else is hogging:
|
||||
# measured 0.14x real time. So flysim runs in its own slice, flysim.slice, whose AllowedCPUs=
|
||||
# 05-deploy.sh writes (the same set as this unit's cpuset drop-in), and `fly-cpu-confine apply`
|
||||
# confines its siblings under the root cgroup (system.slice, user.slice, init.scope) to the other
|
||||
# CPUs. It must NOT sit under a slice that excludes its CPUs: a child's cpuset is bounded by its
|
||||
# parent's. The ExecStartPre refuses to confine anything while a sim unit is still outside the
|
||||
# slice, and a failure of it never blocks the start (the `-`); `+` runs it as root.
|
||||
Slice=flysim.slice
|
||||
ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply
|
||||
MemoryMax=4G
|
||||
# No [Install] section, deliberately: `systemctl enable flysim-session.service` has nothing to
|
||||
# do, so it can never be pulled in beside flysim.service by fly.target.
|
||||
|
|
@ -14,6 +14,15 @@
|
|||
[Unit]
|
||||
Description=flysim: the fly brain, emulator, and control/feed APIs
|
||||
After=network.target
|
||||
# Every start of flysim starts the feed edge when fly.env says FLY_FEED_VIA=bus, and skips it in
|
||||
# direct mode (units/flyedge.service decides): a stop and start of flysim (fly-loop-reset,
|
||||
# fly-reset-to-milestone) would otherwise leave the stage with nothing on :7400, because
|
||||
# flyedge.service's Requires= stops the edge with flysim but does not bring it back.
|
||||
# Every start of flysim starts the control edge when fly.env says FLY_CONTROL_VIA=bus, and skips
|
||||
# it in direct mode (units/flycontrol-edge.service decides): a stop and start of flysim
|
||||
# (fly-loop-reset, fly-reset-to-milestone) would otherwise leave :7401 dead, because the edge's
|
||||
# Requires= stops it with flysim but does not bring it back.
|
||||
Wants=flyedge.service flycontrol-edge.service
|
||||
StartLimitIntervalSec=300
|
||||
StartLimitBurst=5
|
||||
|
||||
|
|
@ -79,6 +88,16 @@ RestartSec=2
|
|||
# bandwidth-bound sweep that is fighting its own SMT siblings.
|
||||
Nice=-5
|
||||
CPUWeight=400
|
||||
# The sim's CPUs are the sim's alone (PERF-02 review N1). The session runtime pins its sweep
|
||||
# workers one per CPU, and a pinned worker cannot leave a CPU that something else is hogging:
|
||||
# measured 0.14x real time. So flysim runs in its own slice, flysim.slice, whose AllowedCPUs=
|
||||
# 05-deploy.sh writes (the same set as this unit's cpuset drop-in), and `fly-cpu-confine apply`
|
||||
# confines its siblings under the root cgroup (system.slice, user.slice, init.scope) to the other
|
||||
# CPUs. It must NOT sit under a slice that excludes its CPUs: a child's cpuset is bounded by its
|
||||
# parent's. The ExecStartPre refuses to confine anything while a sim unit is still outside the
|
||||
# slice, and a failure of it never blocks the start (the `-`); `+` runs it as root.
|
||||
Slice=flysim.slice
|
||||
ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply
|
||||
# The encoder, the browser and the sim must not share physical cores.
|
||||
# AllowedCPUs is per-host and per-container (PVE picks the container's
|
||||
# cpuset at `pct create` time and it is NOT a set of whole cores — on this
|
||||
|
|
|
|||
11
infra/units/flysim.slice
Normal file
11
infra/units/flysim.slice
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# infra/units/flysim.slice — the sim's own slice (PERF-02 review N1).
|
||||
# Named without a dash on purpose: systemd nests a slice named a-b.slice under a.slice, and a child's
|
||||
# cpuset is bounded by its parent's; flysim.slice sits directly under the root slice, beside system.slice.
|
||||
# flysim.service and flysim-session.service run here. 05-deploy.sh writes the drop-in
|
||||
# flysim.slice.d/cpuset.conf (AllowedCPUs= the sim's CPUs) when the container has a cpuset
|
||||
# partition; bin/fly-cpu-confine keeps every other slice off those CPUs. Nothing else belongs in
|
||||
# this slice.
|
||||
[Unit]
|
||||
Description=The live sim (its CPUs are exclusive to it)
|
||||
|
||||
[Slice]
|
||||
63
services/flysim/Cargo.lock
generated
63
services/flysim/Cargo.lock
generated
|
|
@ -416,6 +416,23 @@ dependencies = [
|
|||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-control-edge"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"flybus",
|
||||
"flysim",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-edge"
|
||||
version = "0.1.1"
|
||||
|
|
@ -435,6 +452,49 @@ dependencies = [
|
|||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-legacy-session"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"fly-control-edge",
|
||||
"fly-edge",
|
||||
"fly-session",
|
||||
"flybrain-core",
|
||||
"flybrain-gb",
|
||||
"flybus",
|
||||
"flysim",
|
||||
"futures-util",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"toml",
|
||||
"tower",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-scorecard"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"fly-legacy-session",
|
||||
"fly-session",
|
||||
"flybrain-core",
|
||||
"flybrain-gb",
|
||||
"flysim",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-session"
|
||||
version = "0.1.1"
|
||||
|
|
@ -445,6 +505,7 @@ dependencies = [
|
|||
"flybrain-gb",
|
||||
"flybus",
|
||||
"flysim-store",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
|
|
@ -468,11 +529,13 @@ dependencies = [
|
|||
"cudarc",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"libc",
|
||||
"libm",
|
||||
"ryu-js",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/fly-control-edge",
|
||||
"crates/fly-edge",
|
||||
"crates/fly-legacy-session",
|
||||
"crates/fly-session",
|
||||
"crates/fly-session-types",
|
||||
"crates/flybrain-core",
|
||||
|
|
@ -9,6 +11,7 @@ members = [
|
|||
"crates/flybus",
|
||||
"crates/flysim",
|
||||
"crates/flysim-store",
|
||||
"crates/fly-scorecard",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
|
|
|
|||
35
services/flysim/crates/fly-control-edge/Cargo.toml
Normal file
35
services/flysim/crates/fly-control-edge/Cargo.toml
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
[package]
|
||||
name = "fly-control-edge"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "The control API (:7401) served from flysim's control services on the bus (FLY_CONTROL_VIA=bus)."
|
||||
|
||||
[lib]
|
||||
name = "fly_control_edge"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "fly-control-edge"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# The HTTP layer, the request/reply types and the bus encoding are flysim's own modules (`api`,
|
||||
# `control`, `controlbus`), so the edge writes the :7401 bytes with the code flysim uses in direct
|
||||
# mode and cannot disagree with the services about the encoding.
|
||||
flysim = { path = "../flysim" }
|
||||
flybus = { path = "../flybus" }
|
||||
|
||||
anyhow = "1.0"
|
||||
axum = "0.8"
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "time", "signal", "macros"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
462
services/flysim/crates/fly-control-edge/src/lib.rs
Normal file
462
services/flysim/crates/fly-control-edge/src/lib.rs
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
//! `fly-control-edge`: the control API on `:7401`, answered by flysim's control services on the
|
||||
//! bus (CTRL-01, `docs/design/flybus.md`, "Control over the bus").
|
||||
//!
|
||||
//! With `FLY_CONTROL_VIA=bus` flysim (either runtime) does not bind `control.bind`. It registers
|
||||
//! the control services on its embedded router (`flysim::controlbus`), and this process serves the
|
||||
//! HTTP surface of `docs/control-api.md` to the bridge, the stage, the infra scripts and the
|
||||
//! operator's `curl` by calling them. The HTTP layer is flysim's own `api::router_with`, so the
|
||||
//! routes, the 404s, the extractors, the headers and the body encoding are the code direct mode
|
||||
//! runs; this crate only adds a [`BusBackend`] that carries each request across the bus.
|
||||
//!
|
||||
//! Lifecycle (as `fly-edge` for the feed):
|
||||
//!
|
||||
//! - the control port is bound only once the control services answer, so before that a client
|
||||
//! is refused exactly as it is by a flysim that has not started;
|
||||
//! - when the bus goes away (flysim stopped or restarted) the edge unbinds the port, again what a
|
||||
//! stopped flysim looks like, and reconnects every `retry` until a router answers.
|
||||
//!
|
||||
//! Failures on the bus side map onto the 503s direct mode answers for the same failure (the
|
||||
//! words are `flysim::control::unavailable`), so a client cannot tell which side was in trouble.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::get;
|
||||
use flybus::{BusError, Client, ClientConfig, Dispatch, ErrorCode};
|
||||
use flysim::api::ControlBackend;
|
||||
use flysim::control::{COMMAND_TIMEOUT, ControlReply, ControlRequest, unavailable};
|
||||
use flysim::controlbus::{self, Role, Scope};
|
||||
use flysim::feedbus;
|
||||
use flysim::metrics::metric;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// How much longer than the services' own [`COMMAND_TIMEOUT`] the edge waits before it gives up
|
||||
/// on a timed request and cancels it. The services answer a wedged loop with their own 503 at
|
||||
/// [`COMMAND_TIMEOUT`]; this guard only covers a bus or a host that stopped answering at all.
|
||||
pub const DEADLINE_MARGIN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// What the edge needs to know, from flysim's own configuration.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EdgeConfig {
|
||||
/// `feed.bus_dir`: the router's sockets and store root.
|
||||
pub bus_dir: PathBuf,
|
||||
/// `control.bind`, the port flysim leaves alone in bus mode.
|
||||
pub control_bind: SocketAddr,
|
||||
/// `FLY_CONTROL_EDGE_METRICS_ADDR`: the edge's own `/metrics` and `/healthz`, when set.
|
||||
pub metrics_bind: Option<SocketAddr>,
|
||||
/// Delay between attempts to reach the bus.
|
||||
pub retry: Duration,
|
||||
/// The session and agents whose services `:7401` addresses.
|
||||
pub scope: Scope,
|
||||
}
|
||||
|
||||
impl EdgeConfig {
|
||||
pub fn from_flysim(config: &flysim::config::Config, metrics_bind: Option<SocketAddr>) -> Self {
|
||||
Self {
|
||||
bus_dir: config.feed.bus_dir.clone(),
|
||||
control_bind: config.control.bind,
|
||||
metrics_bind,
|
||||
retry: Duration::from_millis(500),
|
||||
scope: Scope::live(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edge's counters.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct EdgeMetrics {
|
||||
/// 1 while connected and serving.
|
||||
pub connected: AtomicU64,
|
||||
/// Requests carried across the bus.
|
||||
pub calls: AtomicU64,
|
||||
/// Requests that ended in a bus failure rather than a reply (each a 503 or 403 to the
|
||||
/// client).
|
||||
pub call_failures: AtomicU64,
|
||||
/// Requests the edge cancelled at its own deadline.
|
||||
pub cancelled: AtomicU64,
|
||||
/// Serving sessions ended by the bus going away.
|
||||
pub bus_lost: AtomicU64,
|
||||
/// Sessions that reached the bus but could not bind the control port.
|
||||
pub bind_failures: AtomicU64,
|
||||
}
|
||||
|
||||
impl EdgeMetrics {
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::with_capacity(1_024);
|
||||
for (name, kind, help, value) in [
|
||||
(
|
||||
"fly_control_edge_bus_connected",
|
||||
"gauge",
|
||||
"1 while the edge is connected to the control bus and serving.",
|
||||
&self.connected,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_calls_total",
|
||||
"counter",
|
||||
"Control requests carried across the bus.",
|
||||
&self.calls,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_call_failures_total",
|
||||
"counter",
|
||||
"Control requests that ended in a bus failure instead of a reply.",
|
||||
&self.call_failures,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_cancelled_total",
|
||||
"counter",
|
||||
"Control requests the edge cancelled at its own deadline.",
|
||||
&self.cancelled,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_bus_lost_total",
|
||||
"counter",
|
||||
"Serving sessions ended by the control bus going away.",
|
||||
&self.bus_lost,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_bind_failures_total",
|
||||
"counter",
|
||||
"Times the bus was reachable but the control port could not be bound.",
|
||||
&self.bind_failures,
|
||||
),
|
||||
] {
|
||||
metric(&mut out, name, kind, help, value.load(Ordering::Relaxed));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ControlBackend`] that answers each request by calling the control services on the bus.
|
||||
#[derive(Clone)]
|
||||
pub struct BusBackend {
|
||||
client: Client,
|
||||
scope: Scope,
|
||||
metrics: Arc<EdgeMetrics>,
|
||||
}
|
||||
|
||||
impl BusBackend {
|
||||
pub fn new(client: Client, scope: Scope, metrics: Arc<EdgeMetrics>) -> BusBackend {
|
||||
BusBackend {
|
||||
client,
|
||||
scope,
|
||||
metrics,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bus connection.
|
||||
pub fn client(&self) -> &Client {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// The service a request goes to: the session's, or the first agent's for the agent-scoped
|
||||
/// families (`:7401` addresses the one live fly; a second fly has no HTTP surface).
|
||||
fn service(&self, family: controlbus::Family) -> String {
|
||||
let agent = self.scope.agent_ids().next().unwrap_or("");
|
||||
self.scope.service(family, agent)
|
||||
}
|
||||
|
||||
/// Carry one request across the bus and wait for its reply, under the edge's deadline.
|
||||
pub async fn call(&self, request: ControlRequest) -> ControlReply {
|
||||
self.metrics.calls.fetch_add(1, Ordering::Relaxed);
|
||||
let deadline = if request.waits_for_a_write() {
|
||||
None
|
||||
} else {
|
||||
Some(COMMAND_TIMEOUT + DEADLINE_MARGIN)
|
||||
};
|
||||
let (family, method, mut payload) = controlbus::encode_request(&request);
|
||||
let service = self.service(family);
|
||||
// A body over the envelope travels as an artifact, so a large request gets the answer
|
||||
// direct mode gives it.
|
||||
let sealed = match controlbus::take_out_of_line_request(&mut payload) {
|
||||
None => None,
|
||||
Some(bytes) => match seal(&self.client, &bytes, "application/json").await {
|
||||
Ok(artifact) => Some(artifact),
|
||||
Err(error) => return self.failed(&error),
|
||||
},
|
||||
};
|
||||
let attachments: Vec<(&str, &flybus::Artifact)> = sealed
|
||||
.iter()
|
||||
.map(|artifact| (controlbus::REQUEST_ARTIFACT, artifact))
|
||||
.collect();
|
||||
let mut pending = match self
|
||||
.client
|
||||
.call(&service, None, method, payload, &attachments)
|
||||
.await
|
||||
{
|
||||
Ok(pending) => pending,
|
||||
Err(error) => return self.failed(&error),
|
||||
};
|
||||
let result = match deadline {
|
||||
None => pending.result().await,
|
||||
Some(deadline) => match tokio::time::timeout(deadline, pending.result()).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
// Cancelled before dispatch, the loop never sees it; dispatched, it may still
|
||||
// act, exactly as a direct request whose caller timed out.
|
||||
let state = pending.cancel().await;
|
||||
self.metrics.cancelled.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::warn!(method, ?state, "a control call passed the edge's deadline");
|
||||
return ControlReply::error(503, unavailable::TIMED_OUT);
|
||||
}
|
||||
},
|
||||
};
|
||||
let result = match result {
|
||||
Ok(result) => result,
|
||||
Err(error) => return self.failed(&error),
|
||||
};
|
||||
let artifact = if controlbus::has_body_artifact(result.outcome()) {
|
||||
match result.artifact(controlbus::BODY_ARTIFACT) {
|
||||
Ok(artifact) => match artifact.read_all().await {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(error) => return self.failed(&error),
|
||||
},
|
||||
Err(error) => return self.failed(&error),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match controlbus::decode_reply(result.outcome(), artifact) {
|
||||
Ok(reply) => reply,
|
||||
Err(error) => {
|
||||
self.metrics.call_failures.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::warn!(%error, method, "an undecodable control reply");
|
||||
ControlReply::error(502, format!("the control service answered badly: {error}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(&self, error: &BusError) -> ControlReply {
|
||||
self.metrics.call_failures.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::debug!(%error, "a control call failed on the bus");
|
||||
bus_failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl ControlBackend for BusBackend {
|
||||
fn handle(
|
||||
&self,
|
||||
request: ControlRequest,
|
||||
) -> impl std::future::Future<Output = ControlReply> + Send {
|
||||
let backend = self.clone();
|
||||
async move { backend.call(request).await }
|
||||
}
|
||||
}
|
||||
|
||||
async fn seal(
|
||||
client: &Client,
|
||||
bytes: &[u8],
|
||||
content_type: &str,
|
||||
) -> Result<flybus::Artifact, BusError> {
|
||||
let mut writer = client
|
||||
.artifacts()
|
||||
.allocate(bytes.len() as u64, content_type)
|
||||
.await?;
|
||||
writer
|
||||
.write_all(bytes)
|
||||
.map_err(|error| BusError::new(ErrorCode::StoreFailure, error.to_string()))?;
|
||||
writer.seal().await
|
||||
}
|
||||
|
||||
/// The reply a client gets for a request the bus did not deliver, in the words direct mode uses
|
||||
/// for the same failure.
|
||||
pub fn bus_failure(error: &BusError) -> ControlReply {
|
||||
match error.code {
|
||||
// The service's queue and in-flight slots are full: the direct API's full command queue.
|
||||
ErrorCode::Backpressure => ControlReply::error(503, unavailable::QUEUE_FULL),
|
||||
// Nobody is serving it: before dispatch the loop never saw it, as a closed command queue.
|
||||
ErrorCode::NoService if error.dispatch == Dispatch::NotDispatched => {
|
||||
ControlReply::error(503, unavailable::STOPPED)
|
||||
}
|
||||
ErrorCode::NoService | ErrorCode::CallGone | ErrorCode::RouterLost => {
|
||||
ControlReply::error(503, unavailable::DROPPED)
|
||||
}
|
||||
ErrorCode::NotAuthorized => ControlReply::error(
|
||||
403,
|
||||
format!("not authorized on the control bus: {}", error.message),
|
||||
),
|
||||
code => ControlReply::error(
|
||||
503,
|
||||
format!("the control bus refused the request: {}", code.as_str()),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve until the process is stopped. Only a metrics listener that cannot bind is fatal;
|
||||
/// everything about the bus is retried.
|
||||
pub async fn run(config: EdgeConfig, metrics: Arc<EdgeMetrics>) -> Result<()> {
|
||||
config.scope.validate()?;
|
||||
if let Some(addr) = config.metrics_bind {
|
||||
let listener = tokio::net::TcpListener::bind(addr)
|
||||
.await
|
||||
.with_context(|| format!("binding the edge metrics listener on {addr}"))?;
|
||||
let app = axum::Router::new()
|
||||
.route("/metrics", get(prometheus))
|
||||
.route("/healthz", get(healthz))
|
||||
.with_state(Arc::clone(&metrics));
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = axum::serve(listener, app).await {
|
||||
tracing::error!(%error, "the edge metrics listener stopped");
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut last: Option<&'static str> = None;
|
||||
loop {
|
||||
let end = session(&config, &metrics).await;
|
||||
match &end {
|
||||
SessionEnd::BusLost => {
|
||||
tracing::warn!("the control bus went away; :7401 unbound, reconnecting");
|
||||
}
|
||||
SessionEnd::Unreachable(error) if last != Some(end.kind()) => {
|
||||
tracing::info!(error = format!("{error:#}"), "waiting for the control bus");
|
||||
}
|
||||
SessionEnd::BindFailed(error) if last != Some(end.kind()) => {
|
||||
// The bus is fine; the port is not ours. Most likely flysim is still in direct
|
||||
// mode and holds it (FLY_CONTROL_VIA is not bus), or another process does.
|
||||
tracing::warn!(
|
||||
error = format!("{error:#}"),
|
||||
"the bus is up but the control port cannot be bound; retrying"
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
last = match end {
|
||||
SessionEnd::BusLost => None,
|
||||
other => Some(other.kind()),
|
||||
};
|
||||
tokio::time::sleep(config.retry).await;
|
||||
}
|
||||
}
|
||||
|
||||
enum SessionEnd {
|
||||
Unreachable(anyhow::Error),
|
||||
BindFailed(anyhow::Error),
|
||||
BusLost,
|
||||
}
|
||||
|
||||
impl SessionEnd {
|
||||
fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unreachable(_) => "unreachable",
|
||||
Self::BindFailed(_) => "bind",
|
||||
Self::BusLost => "lost",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn prometheus(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
|
||||
(
|
||||
[(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/plain; version=0.0.4",
|
||||
)],
|
||||
metrics.render(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn healthz(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
|
||||
if metrics.connected.load(Ordering::Relaxed) == 1 {
|
||||
(StatusCode::OK, "ok")
|
||||
} else {
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"waiting for the control bus",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect as [`controlbus::EDGE`] and wait until the control services answer.
|
||||
pub async fn connect(config: &EdgeConfig, metrics: &Arc<EdgeMetrics>) -> Result<BusBackend> {
|
||||
let client = Client::connect_unix(
|
||||
controlbus::socket_path(&config.bus_dir, Role::Edge),
|
||||
ClientConfig::new(controlbus::EDGE, feedbus::store_root(&config.bus_dir)),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| anyhow!("connecting to the control bus: {error}"))?;
|
||||
let backend = BusBackend::new(client, config.scope.clone(), Arc::clone(metrics));
|
||||
// The host registers its services right after the router starts; until it has, a call is
|
||||
// NO_SERVICE. Bind :7401 only once one is answered, whatever it answers.
|
||||
let (family, method, payload) = controlbus::encode_request(&ControlRequest::Healthz);
|
||||
let service = backend.service(family);
|
||||
for _ in 0..20 {
|
||||
match backend
|
||||
.client
|
||||
.call(&service, None, method, payload.clone(), &[])
|
||||
.await
|
||||
{
|
||||
Ok(mut pending) => match pending.result().await {
|
||||
Ok(_) => return Ok(backend),
|
||||
Err(error) if error.code == ErrorCode::NoService => {}
|
||||
Err(error) => return Err(anyhow!("the control services did not answer: {error}")),
|
||||
},
|
||||
Err(error) if error.code == ErrorCode::NoService => {}
|
||||
Err(error) => return Err(anyhow!("calling the control services: {error}")),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(anyhow!(
|
||||
"the control services are not registered on the bus"
|
||||
))
|
||||
}
|
||||
|
||||
async fn session(config: &EdgeConfig, metrics: &Arc<EdgeMetrics>) -> SessionEnd {
|
||||
let backend = match connect(config, metrics).await {
|
||||
Ok(backend) => backend,
|
||||
Err(error) => return SessionEnd::Unreachable(error),
|
||||
};
|
||||
let listener = match tokio::net::TcpListener::bind(config.control_bind).await {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
metrics.bind_failures.fetch_add(1, Ordering::Relaxed);
|
||||
return SessionEnd::BindFailed(anyhow::Error::new(error).context(format!(
|
||||
"binding the control listener on {}",
|
||||
config.control_bind
|
||||
)));
|
||||
}
|
||||
};
|
||||
serve(config, metrics, backend, listener).await;
|
||||
SessionEnd::BusLost
|
||||
}
|
||||
|
||||
/// Serve `listener` until the bus connection closes.
|
||||
async fn serve(
|
||||
config: &EdgeConfig,
|
||||
metrics: &EdgeMetrics,
|
||||
backend: BusBackend,
|
||||
listener: tokio::net::TcpListener,
|
||||
) {
|
||||
tracing::info!(control = %config.control_bind, bus = %config.bus_dir.display(), "serving the control API from the bus");
|
||||
metrics.connected.store(1, Ordering::Relaxed);
|
||||
let client = backend.client.clone();
|
||||
let (stop, stopped) = oneshot::channel::<()>();
|
||||
let server = tokio::spawn(async move {
|
||||
let result = axum::serve(listener, flysim::api::router_with(backend))
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = stopped.await;
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
tracing::error!(%error, "the control listener stopped");
|
||||
}
|
||||
});
|
||||
while client.closed().is_none() {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
metrics.connected.store(0, Ordering::Relaxed);
|
||||
metrics.bus_lost.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = stop.send(());
|
||||
if tokio::time::timeout(Duration::from_secs(5), server)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("the control listener took more than 5 s to stop");
|
||||
}
|
||||
}
|
||||
81
services/flysim/crates/fly-control-edge/src/main.rs
Normal file
81
services/flysim/crates/fly-control-edge/src/main.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
//! `fly-control-edge`: serve the control API (`:7401`) from flysim's control services on the bus.
|
||||
//!
|
||||
//! ```sh
|
||||
//! FLY_CONTROL_VIA=bus flysim-session &
|
||||
//! fly-control-edge
|
||||
//! ```
|
||||
//!
|
||||
//! Configured through the same environment as flysim (`FLY_CONTROL_BIND`, `FLY_BUS_DIR`, or
|
||||
//! `--config flysim.toml`), plus `FLY_CONTROL_EDGE_METRICS_ADDR` for its own `/metrics` and
|
||||
//! `/healthz`. `infra/units/flycontrol-edge.service` runs it with no arguments.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use fly_control_edge::{EdgeConfig, EdgeMetrics};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "fly-control-edge",
|
||||
about = "The control API, served from flysim's control services on the bus.",
|
||||
version
|
||||
)]
|
||||
struct Args {
|
||||
/// Path to `flysim.toml`, read for `[control]` and `[feed] bus_dir`. Environment overrides
|
||||
/// apply as they do for flysim.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
config: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
init_tracing();
|
||||
let config = flysim::config::Config::load(args.config.as_deref())?;
|
||||
let metrics_bind = match std::env::var("FLY_CONTROL_EDGE_METRICS_ADDR") {
|
||||
Ok(value) if !value.is_empty() => Some(value.parse().with_context(|| {
|
||||
format!("FLY_CONTROL_EDGE_METRICS_ADDR: {value:?} is not a host:port address")
|
||||
})?),
|
||||
_ => None,
|
||||
};
|
||||
let edge = EdgeConfig::from_flysim(&config, metrics_bind);
|
||||
if config.control.via != flysim::config::ControlVia::Bus {
|
||||
tracing::warn!(
|
||||
"FLY_CONTROL_VIA is not \"bus\": flysim serves the control API itself and binds {}; \
|
||||
this edge will wait for control services that are not there",
|
||||
edge.control_bind
|
||||
);
|
||||
}
|
||||
tracing::info!(config = ?edge, "fly-control-edge starting");
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_name("fly-control-edge")
|
||||
.enable_all()
|
||||
.build()
|
||||
.context("building the tokio runtime")?;
|
||||
runtime.block_on(async move {
|
||||
let metrics = Arc::new(EdgeMetrics::default());
|
||||
let mut terminate =
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.context("installing the SIGTERM handler")?;
|
||||
tokio::select! {
|
||||
result = fly_control_edge::run(edge, metrics) => result,
|
||||
_ = tokio::signal::ctrl_c() => { tracing::info!("SIGINT: shutting down"); Ok(()) }
|
||||
_ = terminate.recv() => { tracing::info!("SIGTERM: shutting down"); Ok(()) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Logs to stderr, like flysim, under `FLY_CONTROL_EDGE_LOG` (or `RUST_LOG`).
|
||||
fn init_tracing() {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_env("FLY_CONTROL_EDGE_LOG")
|
||||
.or_else(|_| EnvFilter::try_from_default_env())
|
||||
.unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.with_writer(std::io::stderr)
|
||||
.with_target(false)
|
||||
.init();
|
||||
}
|
||||
313
services/flysim/crates/fly-control-edge/tests/backpressure.rs
Normal file
313
services/flysim/crates/fly-control-edge/tests/backpressure.rs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
//! Backpressure, cancellation and the edge's lifecycle.
|
||||
//!
|
||||
//! - a family whose service is full refuses with the direct API's "queue is full" 503, and the
|
||||
//! other families keep answering;
|
||||
//! - a call cancelled before dispatch never reaches the loop; a caller that goes away, or a call
|
||||
//! past the edge's deadline, leaves no call on the router;
|
||||
//! - the edge unbinds `:7401` when the bus goes away and binds it again when a router is back.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use common::{exchange, rig};
|
||||
use flybus::{CancelState, Client, ClientConfig, Policy, Router, RouterConfig};
|
||||
use flysim::control::{ControlRequest, unavailable};
|
||||
use flysim::controlbus::{self, Family, Role, Scope};
|
||||
use serde_json::json;
|
||||
|
||||
async fn until(what: &str, mut check: impl FnMut() -> bool) {
|
||||
let started = Instant::now();
|
||||
while !check() {
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(30),
|
||||
"timed out waiting for {what}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_full_service_is_a_503_and_the_other_families_still_answer() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.sim.hold.store(true, Ordering::SeqCst);
|
||||
let slots =
|
||||
(controlbus::SERVICE_CONFIG.max_in_flight + controlbus::SERVICE_CONFIG.max_queued) as usize;
|
||||
// The first 16 fill the service's in-flight slots and reach the (wedged) loop; only then
|
||||
// the next 16 fill its queue. (Sent as one burst, the queue bound can be met before the
|
||||
// router has dispatched the first ones: a bounded queue refuses what it cannot hold at that
|
||||
// instant, which is the point, but not what this test counts.)
|
||||
let in_flight = controlbus::SERVICE_CONFIG.max_in_flight as usize;
|
||||
let mut pauses = Vec::new();
|
||||
for batch in [in_flight, slots - in_flight] {
|
||||
for _ in 0..batch {
|
||||
let edge = rig.edge.clone();
|
||||
pauses.push(tokio::spawn(async move {
|
||||
edge.call(ControlRequest::Pause).await
|
||||
}));
|
||||
}
|
||||
until("the in-flight pauses", || rig.sim.received("pause") == in_flight).await;
|
||||
}
|
||||
let started = Instant::now();
|
||||
while (rig.bus.router.stats().calls as usize) < slots {
|
||||
if started.elapsed() > Duration::from_secs(30) {
|
||||
let mut finished = Vec::new();
|
||||
for pause in pauses.iter_mut().filter(|p| p.is_finished()) {
|
||||
finished.push(format!("{:?}", pause.await.unwrap()));
|
||||
}
|
||||
panic!(
|
||||
"not every pause admitted: {:?}, received {}, finished {finished:?}",
|
||||
rig.bus.router.stats(),
|
||||
rig.sim.received("pause")
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
|
||||
// One more is refused at once, in the direct API's words.
|
||||
let started = Instant::now();
|
||||
let refused = exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]).await;
|
||||
assert_eq!(refused.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(refused.json(), json!({"error": unavailable::QUEUE_FULL}));
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(1),
|
||||
"a full service made the caller wait"
|
||||
);
|
||||
|
||||
// Reads, sugar and chat are other services: they answer while ops is saturated.
|
||||
let status = exchange(rig.via_edge(), &Method::GET, "/status", None, &[]).await;
|
||||
assert_eq!(status.status, StatusCode::OK);
|
||||
let healthz = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await;
|
||||
assert_eq!(healthz.status, StatusCode::OK);
|
||||
|
||||
// A queued pause cancelled before dispatch never reaches the loop.
|
||||
let operator = Client::connect_unix(
|
||||
controlbus::socket_path(&rig.config.bus_dir, Role::Operator),
|
||||
ClientConfig::new(
|
||||
Role::Operator.participant(),
|
||||
flysim::feedbus::store_root(&rig.config.bus_dir),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Let the loop go: the held pauses are dropped (503 "dropped"), the queued ones answered.
|
||||
rig.sim.hold.store(false, Ordering::SeqCst);
|
||||
rig.sim.release_held();
|
||||
for pause in pauses {
|
||||
let reply = pause.await.unwrap();
|
||||
// The 16 the wedged loop dropped answer "dropped"; the 16 queued ones were answered.
|
||||
assert!(
|
||||
reply.status == 200 || reply.json_error() == Some(unavailable::DROPPED),
|
||||
"{reply:?}"
|
||||
);
|
||||
}
|
||||
let answered = rig.sim.received("pause");
|
||||
assert_eq!(answered, slots);
|
||||
|
||||
// Wedge it again with 16 of the operator's own in flight; the 17th waits in the queue and
|
||||
// is cancelled there.
|
||||
rig.sim.hold.store(true, Ordering::SeqCst);
|
||||
let (family, method, payload) = controlbus::encode_request(&ControlRequest::Pause);
|
||||
let service = Scope::live().service(family, "");
|
||||
let mut holders = Vec::new();
|
||||
for _ in 0..controlbus::SERVICE_CONFIG.max_in_flight {
|
||||
holders.push(
|
||||
operator
|
||||
.call(&service, None, method, payload.clone(), &[])
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
until("the in-flight pauses", || {
|
||||
rig.sim.received("pause") == slots + controlbus::SERVICE_CONFIG.max_in_flight as usize
|
||||
})
|
||||
.await;
|
||||
let queued = operator
|
||||
.call(&service, None, method, payload.clone(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
queued.cancel().await.unwrap(),
|
||||
CancelState::CancelledBeforeDispatch
|
||||
);
|
||||
rig.sim.hold.store(false, Ordering::SeqCst);
|
||||
rig.sim.release_held();
|
||||
for mut holder in holders {
|
||||
let _ = holder.result().await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(
|
||||
rig.sim.received("pause"),
|
||||
slots + controlbus::SERVICE_CONFIG.max_in_flight as usize,
|
||||
"the cancelled pause reached the loop"
|
||||
);
|
||||
until("no calls left on the router", || {
|
||||
rig.bus.router.stats().calls == 0
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
trait ErrorText {
|
||||
fn json_error(&self) -> Option<&str>;
|
||||
}
|
||||
|
||||
impl ErrorText for flysim::control::ControlReply {
|
||||
fn json_error(&self) -> Option<&str> {
|
||||
match &self.body {
|
||||
flysim::control::ReplyBody::Json(value) => value["error"].as_str(),
|
||||
flysim::control::ReplyBody::Text(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_client_that_goes_away_leaves_no_call_behind() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.sim.hold.store(true, Ordering::SeqCst);
|
||||
// An HTTP client that gives up on a pause (which waits for a durable write, so has no
|
||||
// deadline of its own): axum drops the handler, the edge drops the pending call.
|
||||
let gave_up = tokio::time::timeout(
|
||||
Duration::from_millis(300),
|
||||
exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]),
|
||||
)
|
||||
.await;
|
||||
assert!(gave_up.is_err());
|
||||
until("the dropped call to be dispatched", || {
|
||||
rig.sim.received("pause") == 1
|
||||
})
|
||||
.await;
|
||||
// The host still holds it (the loop has it), so the router keeps the correlation until the
|
||||
// host answers; then the detached result is discarded and nothing is left.
|
||||
rig.sim.hold.store(false, Ordering::SeqCst);
|
||||
rig.sim.release_held();
|
||||
until("no calls left on the router", || {
|
||||
rig.bus.router.stats().calls == 0
|
||||
})
|
||||
.await;
|
||||
// And the edge is fine afterwards.
|
||||
let ok = exchange(rig.via_edge(), &Method::POST, "/resume", None, &[]).await;
|
||||
assert_eq!(ok.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
/// A host that registered the services but never answers: the edge gives up at its own deadline,
|
||||
/// cancels, and answers the direct API's timeout 503.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_edge_cancels_at_its_deadline_when_the_host_never_answers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scope = Scope::live();
|
||||
let mut config = RouterConfig::new(dir.path());
|
||||
config.policy = controlbus::policy(Policy::closed(), &scope);
|
||||
let router = Router::new(config).unwrap();
|
||||
let silent = Client::connect(
|
||||
router.connect_in_memory_as(controlbus::HOST),
|
||||
ClientConfig::new(controlbus::HOST, router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let name = scope.service(Family::Sugar, controlbus::LIVE_AGENT);
|
||||
let mut service = silent
|
||||
.register(&name, controlbus::SERVICE_CONFIG)
|
||||
.await
|
||||
.unwrap();
|
||||
let held = tokio::spawn(async move {
|
||||
let mut kept = Vec::new();
|
||||
while let Some(request) = service.next().await {
|
||||
kept.push(request);
|
||||
}
|
||||
});
|
||||
let edge_client = Client::connect(
|
||||
router.connect_in_memory_as(controlbus::EDGE),
|
||||
ClientConfig::new(controlbus::EDGE, router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let backend = fly_control_edge::BusBackend::new(edge_client, scope, Arc::clone(&metrics));
|
||||
let started = Instant::now();
|
||||
let reply = exchange(
|
||||
flysim::api::router_with(backend),
|
||||
&Method::POST,
|
||||
"/stimulate",
|
||||
Some("application/json"),
|
||||
&serde_json::to_vec(&json!({"by": "v", "source": "chat"})).unwrap(),
|
||||
)
|
||||
.await;
|
||||
let waited = started.elapsed();
|
||||
assert_eq!(reply.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(reply.json(), json!({"error": unavailable::TIMED_OUT}));
|
||||
let deadline = flysim::control::COMMAND_TIMEOUT + fly_control_edge::DEADLINE_MARGIN;
|
||||
assert!(
|
||||
waited >= deadline && waited < deadline + Duration::from_secs(2),
|
||||
"{waited:?}"
|
||||
);
|
||||
assert_eq!(metrics.cancelled.load(Ordering::Relaxed), 1);
|
||||
held.abort();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_edge_unbinds_when_the_bus_goes_and_binds_again_when_it_is_back() {
|
||||
let mut rig = rig(|_| {}).await;
|
||||
// The edge process connects as the edge participant, which the router admits once.
|
||||
rig.close_edge().await;
|
||||
let addr = common::free_port();
|
||||
let config = fly_control_edge::EdgeConfig {
|
||||
control_bind: addr,
|
||||
..rig.config.clone()
|
||||
};
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let edge = tokio::spawn(fly_control_edge::run(config, Arc::clone(&metrics)));
|
||||
until("the edge to bind", || {
|
||||
metrics.connected.load(Ordering::Relaxed) == 1
|
||||
})
|
||||
.await;
|
||||
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
let served = common::raw_http(addr, request).await.unwrap();
|
||||
assert!(
|
||||
served.starts_with(b"HTTP/1.1 200"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&served)
|
||||
);
|
||||
|
||||
// flysim stops: its router goes, and the port with it.
|
||||
rig.host.take();
|
||||
rig.bus.router.shutdown();
|
||||
until("the edge to notice", || {
|
||||
metrics.bus_lost.load(Ordering::Relaxed) == 1
|
||||
})
|
||||
.await;
|
||||
let started = Instant::now();
|
||||
while common::raw_http(addr, request).await.is_some() {
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
":7401 stayed bound"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
|
||||
// flysim is back: a new router on the same directory, the services registered again.
|
||||
let scope = Scope::live();
|
||||
let uses = flysim::bus::Uses {
|
||||
feed: false,
|
||||
control: true,
|
||||
};
|
||||
let bus = flysim::bus::start(&rig.config.bus_dir, uses, &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let _host = controlbus::serve(&bus.router, rig.state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
until("the edge to bind again", || {
|
||||
metrics.connected.load(Ordering::Relaxed) == 1
|
||||
})
|
||||
.await;
|
||||
let served = common::raw_http(addr, request).await.unwrap();
|
||||
assert!(
|
||||
served.starts_with(b"HTTP/1.1 200"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&served)
|
||||
);
|
||||
edge.abort();
|
||||
}
|
||||
320
services/flysim/crates/fly-control-edge/tests/common/mod.rs
Normal file
320
services/flysim/crates/fly-control-edge/tests/common/mod.rs
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
//! A control rig: flysim's control state with a scripted stand-in for the loop behind it, the
|
||||
//! embedded router with the control services registered, and the edge connected over its socket.
|
||||
//! Every request can be sent to both sides — `direct` (flysim's own `:7401` router) and `edge`
|
||||
//! (the same router over the bus) — and the answers compared byte for byte.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{HeaderMap, Method, Request, StatusCode};
|
||||
use fly_control_edge::{BusBackend, EdgeConfig, EdgeMetrics};
|
||||
use flysim::AppState;
|
||||
use flysim::bus::{EmbeddedBus, Uses};
|
||||
use flysim::chat::{ChatRefusal, RejectReason};
|
||||
use flysim::controlbus::{ControlHost, Scope};
|
||||
use flysim::eventlog::{EventLog, EventRing, NewEvent};
|
||||
use flysim::ratelimit::Refusal;
|
||||
use flysim::simloop::{Command, Shared, booting_snapshot};
|
||||
use flysim::snapshot::{FeedEventKind, FeedStatus, MacroMode, Snapshot};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tower::ServiceExt;
|
||||
|
||||
/// The stand-in loop: answers every command deterministically from what the request says, so
|
||||
/// the same request gets the same answer however often (and from whichever side) it is sent.
|
||||
#[derive(Default)]
|
||||
pub struct FakeSim {
|
||||
/// Commands received, by kind.
|
||||
pub received: Mutex<Vec<&'static str>>,
|
||||
/// Hold every command without answering (a wedged loop).
|
||||
pub hold: AtomicBool,
|
||||
/// Answer `/checkpoint` with a failure.
|
||||
pub fail_checkpoint: AtomicBool,
|
||||
/// Held commands: kept so their reply channels stay open.
|
||||
pub held: Mutex<Vec<Command>>,
|
||||
pub answered: AtomicU64,
|
||||
}
|
||||
|
||||
impl FakeSim {
|
||||
pub fn received(&self, kind: &str) -> usize {
|
||||
self.received
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|k| **k == kind)
|
||||
.count()
|
||||
}
|
||||
|
||||
pub fn release_held(&self) {
|
||||
self.held.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
fn answer(&self, command: Command) {
|
||||
let kind = match &command {
|
||||
Command::Stimulate { .. } => "stimulate",
|
||||
Command::Reward { .. } => "reward",
|
||||
Command::Chat { .. } => "chat",
|
||||
Command::Checkpoint { .. } => "checkpoint",
|
||||
Command::Pause { .. } => "pause",
|
||||
Command::Resume { .. } => "resume",
|
||||
Command::Shutdown { .. } => "shutdown",
|
||||
};
|
||||
self.received.lock().unwrap().push(kind);
|
||||
if self.hold.load(Ordering::SeqCst) {
|
||||
self.held.lock().unwrap().push(command);
|
||||
return;
|
||||
}
|
||||
self.answered.fetch_add(1, Ordering::SeqCst);
|
||||
match command {
|
||||
Command::Stimulate { by, reply, .. } => {
|
||||
let answer = match by.as_str() {
|
||||
"pulse" => Err(Refusal::PulseActive {
|
||||
retry_after_ms: 250,
|
||||
}),
|
||||
"spent" => Err(Refusal::RateLimited {
|
||||
retry_after_ms: 41_500,
|
||||
}),
|
||||
"drop" => return,
|
||||
"hang" => {
|
||||
self.held.lock().unwrap().push(Command::Stimulate {
|
||||
duration_ms: None,
|
||||
by,
|
||||
source: String::new(),
|
||||
reply,
|
||||
});
|
||||
return;
|
||||
}
|
||||
_ => Ok(41),
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Command::Reward { reply, .. } => {
|
||||
let _ = reply.send(42);
|
||||
}
|
||||
Command::Chat {
|
||||
by, text, reply, ..
|
||||
} => {
|
||||
let answer = if text.contains("http") {
|
||||
Err(ChatRefusal::Rejected(RejectReason::Url))
|
||||
} else if by == "fast" {
|
||||
Err(ChatRefusal::RateLimited {
|
||||
retry_after_ms: 1_999,
|
||||
})
|
||||
} else {
|
||||
Ok(43)
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Command::Checkpoint { reply } => {
|
||||
let answer = if self.fail_checkpoint.load(Ordering::SeqCst) {
|
||||
Err("disk full".to_owned())
|
||||
} else {
|
||||
Ok(12)
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Command::Pause { reply } => {
|
||||
let _ = reply.send(FeedStatus::Paused);
|
||||
}
|
||||
Command::Resume { reply } => {
|
||||
let _ = reply.send(FeedStatus::Running);
|
||||
}
|
||||
Command::Shutdown { reply } => {
|
||||
let _ = reply.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Rig {
|
||||
pub state: AppState,
|
||||
pub sim: Arc<FakeSim>,
|
||||
pub snapshots: watch::Sender<Arc<Snapshot>>,
|
||||
pub bus: EmbeddedBus,
|
||||
pub host: Option<ControlHost>,
|
||||
pub edge: BusBackend,
|
||||
pub metrics: Arc<EdgeMetrics>,
|
||||
pub config: EdgeConfig,
|
||||
pub dir: tempfile::TempDir,
|
||||
_log: EventLog,
|
||||
}
|
||||
|
||||
/// A snapshot with a few fields that are not the boot defaults, so `/status` has content.
|
||||
fn snapshot() -> Snapshot {
|
||||
let mut snapshot = booting_snapshot(4_242, 1_757_000_000_000, MacroMode::Raw);
|
||||
let header = &mut snapshot.header;
|
||||
header.status = FeedStatus::Running;
|
||||
header.realtime_factor = 1.0312;
|
||||
header.uptime_seconds = 612.5;
|
||||
header.brain_ms = 3_600_250.0;
|
||||
header.frame = 215_089;
|
||||
header.population_rate = 12.375;
|
||||
header.learning.signal = -0.125;
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// The rig, with `configure` applied to flysim's configuration.
|
||||
pub async fn rig(configure: impl FnOnce(&mut flysim::config::Config)) -> Rig {
|
||||
rig_with(
|
||||
configure,
|
||||
Uses {
|
||||
feed: false,
|
||||
control: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn rig_with(configure: impl FnOnce(&mut flysim::config::Config), uses: Uses) -> Rig {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut config = flysim::config::Config::default();
|
||||
config.feed.bus_dir = dir.path().join("bus");
|
||||
config.control.via = flysim::config::ControlVia::Bus;
|
||||
configure(&mut config);
|
||||
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
|
||||
let (commands, mut command_rx) = mpsc::channel::<Command>(flysim::simloop::COMMAND_QUEUE);
|
||||
let (snapshots, receiver) = watch::channel(Arc::new(snapshot()));
|
||||
let state = AppState {
|
||||
shared: Arc::clone(&shared),
|
||||
commands,
|
||||
snapshots: receiver,
|
||||
};
|
||||
// A short event log, so `/events` has pages to turn.
|
||||
let mut log = EventLog::open(&dir.path().join("events"), state.shared.events.clone()).unwrap();
|
||||
for index in 0..7u64 {
|
||||
log.append(
|
||||
1_000 + index,
|
||||
index as f64 * 0.5,
|
||||
NewEvent::new(FeedEventKind::System, format!("event {index}")).value(index as f64),
|
||||
);
|
||||
}
|
||||
state.shared.beat();
|
||||
|
||||
let sim = Arc::new(FakeSim::default());
|
||||
{
|
||||
let sim = Arc::clone(&sim);
|
||||
tokio::spawn(async move {
|
||||
while let Some(command) = command_rx.recv().await {
|
||||
sim.answer(command);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let scope = Scope::live();
|
||||
let bus = flysim::bus::start(&config.feed.bus_dir, uses, &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let edge_config = EdgeConfig {
|
||||
retry: Duration::from_millis(50),
|
||||
..EdgeConfig::from_flysim(&config, None)
|
||||
};
|
||||
let metrics = Arc::new(EdgeMetrics::default());
|
||||
let edge = fly_control_edge::connect(&edge_config, &metrics)
|
||||
.await
|
||||
.unwrap();
|
||||
Rig {
|
||||
state,
|
||||
sim,
|
||||
snapshots,
|
||||
bus,
|
||||
host: Some(host),
|
||||
edge,
|
||||
metrics,
|
||||
config: edge_config,
|
||||
dir,
|
||||
_log: log,
|
||||
}
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
pub fn direct(&self) -> axum::Router {
|
||||
flysim::api::router(self.state.clone())
|
||||
}
|
||||
|
||||
/// Close the rig's own edge connection, so an edge process can connect as the edge (the
|
||||
/// router admits one live connection per participant).
|
||||
pub async fn close_edge(&self) {
|
||||
self.edge.client().clone().close().await;
|
||||
}
|
||||
|
||||
pub fn via_edge(&self) -> axum::Router {
|
||||
flysim::api::router_with(self.edge.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// One HTTP exchange as the bytes a client sees: status, every header, body.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Exchange {
|
||||
pub status: StatusCode,
|
||||
pub headers: Vec<(String, Vec<u8>)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn json(&self) -> serde_json::Value {
|
||||
serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn exchange(
|
||||
router: axum::Router,
|
||||
method: &Method,
|
||||
uri: &str,
|
||||
content_type: Option<&str>,
|
||||
body: &[u8],
|
||||
) -> Exchange {
|
||||
let mut request = Request::builder().method(method.clone()).uri(uri);
|
||||
if let Some(content_type) = content_type {
|
||||
request = request.header("content-type", content_type);
|
||||
}
|
||||
let request = request.body(Body::from(body.to_vec())).unwrap();
|
||||
let response = router.oneshot(request).await.unwrap();
|
||||
let status = response.status();
|
||||
let headers = sorted(response.headers());
|
||||
let body = axum::body::to_bytes(response.into_body(), 64 << 20)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
Exchange {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted(headers: &HeaderMap) -> Vec<(String, Vec<u8>)> {
|
||||
let mut out: Vec<(String, Vec<u8>)> = headers
|
||||
.iter()
|
||||
.map(|(name, value)| (name.as_str().to_owned(), value.as_bytes().to_vec()))
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// A free loopback port (bound, read, released).
|
||||
pub fn free_port() -> std::net::SocketAddr {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.local_addr().unwrap()
|
||||
}
|
||||
|
||||
/// A raw HTTP/1.1 exchange over TCP: the whole response, with the `date` header line removed
|
||||
/// (the one header that differs from second to second). `None` when nothing listens.
|
||||
pub async fn raw_http(addr: std::net::SocketAddr, request: &str) -> Option<Vec<u8>> {
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
||||
let mut stream = tokio::net::TcpStream::connect(addr).await.ok()?;
|
||||
stream.write_all(request.as_bytes()).await.ok()?;
|
||||
let mut out = Vec::new();
|
||||
stream.read_to_end(&mut out).await.ok()?;
|
||||
let text = String::from_utf8_lossy(&out).into_owned();
|
||||
let kept: Vec<&str> = text
|
||||
.split("\r\n")
|
||||
.filter(|line| !line.to_ascii_lowercase().starts_with("date:"))
|
||||
.collect();
|
||||
Some(kept.join("\r\n").into_bytes())
|
||||
}
|
||||
388
services/flysim/crates/fly-control-edge/tests/grants.rs
Normal file
388
services/flysim/crates/fly-control-edge/tests/grants.rs
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
//! The grant table refuses what it should, over the router's real sockets.
|
||||
//!
|
||||
//! - each native role calls exactly its families, and a refused call never reaches the loop;
|
||||
//! - no role can register a service (so none can stand in for the control host), publish,
|
||||
//! subscribe or manage a topic;
|
||||
//! - a socket is bound to its role: claiming another identity on it is refused at hello;
|
||||
//! - on a router shared with a service that does take input (an environment's, say), no control
|
||||
//! participant can call it: "nothing can press buttons" holds for the grant table, not only for
|
||||
//! the list of control methods;
|
||||
//! - per-agent scoping: a player may sugar their own fly and not another.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use common::{exchange, rig, rig_with};
|
||||
use flybus::{
|
||||
BusError, Client, ClientConfig, Dispatch, ErrorCode, Grants, Pattern, Policy, Retained, Router,
|
||||
RouterConfig, ServiceConfig,
|
||||
};
|
||||
use flysim::bus::Uses;
|
||||
use flysim::control::ControlRequest;
|
||||
use flysim::controlbus::{self, Family, Role, Scope};
|
||||
use serde_json::{Map, json};
|
||||
|
||||
fn request_of(family: Family) -> ControlRequest {
|
||||
match family {
|
||||
Family::Read | Family::Status => ControlRequest::Status,
|
||||
Family::Sugar => ControlRequest::Stimulate {
|
||||
body: Some(json!({"by": "viewer", "source": "points"})),
|
||||
},
|
||||
Family::Reward => ControlRequest::Reward {
|
||||
body: Some(json!({"value": 1.0, "by": "op", "source": "operator"})),
|
||||
},
|
||||
Family::Chat => ControlRequest::Chat {
|
||||
body: Some(json!({"by": "viewer", "text": "hi"})),
|
||||
},
|
||||
Family::Ops => ControlRequest::Resume,
|
||||
}
|
||||
}
|
||||
|
||||
async fn call(
|
||||
client: &Client,
|
||||
scope: &Scope,
|
||||
family: Family,
|
||||
agent: &str,
|
||||
) -> Result<Map<String, serde_json::Value>, BusError> {
|
||||
let (encoded_family, method, payload) = controlbus::encode_request(&request_of(family));
|
||||
// An agent's status service answers the same method the session's read does.
|
||||
if family != Family::Status {
|
||||
assert_eq!(encoded_family, family);
|
||||
}
|
||||
let service = scope.service(family, agent);
|
||||
let result = client
|
||||
.call_and_wait(&service, None, method, payload, &[])
|
||||
.await?;
|
||||
Ok(result.outcome().clone())
|
||||
}
|
||||
|
||||
fn assert_refused(result: Result<impl std::fmt::Debug, BusError>, what: &str) {
|
||||
let error = result.expect_err(what);
|
||||
assert_eq!(error.code, ErrorCode::NotAuthorized, "{what}: {error}");
|
||||
assert_eq!(error.dispatch, Dispatch::NotDispatched, "{what}");
|
||||
}
|
||||
|
||||
async fn connect_role(
|
||||
bus_dir: &std::path::Path,
|
||||
role: Role,
|
||||
claimed: &str,
|
||||
) -> Result<Client, BusError> {
|
||||
Client::connect_unix(
|
||||
controlbus::socket_path(bus_dir, role),
|
||||
ClientConfig::new(claimed, flysim::feedbus::store_root(bus_dir)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn each_role_calls_exactly_its_families_and_nothing_else() {
|
||||
let rig = rig_with(
|
||||
|_| {},
|
||||
Uses {
|
||||
feed: true,
|
||||
control: true,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
rig.close_edge().await;
|
||||
let bus_dir = rig.config.bus_dir.clone();
|
||||
let scope = Scope::live();
|
||||
for role in Role::ALL {
|
||||
let client = connect_role(&bus_dir, role, role.participant())
|
||||
.await
|
||||
.unwrap();
|
||||
for family in Family::ALL {
|
||||
let before = rig.sim.received.lock().unwrap().len();
|
||||
let result = call(&client, &scope, family, controlbus::LIVE_AGENT).await;
|
||||
if role.families().contains(&family) {
|
||||
let outcome = result.unwrap_or_else(|e| panic!("{role:?} {family:?}: {e}"));
|
||||
assert!(outcome["status"].as_u64().is_some(), "{role:?} {family:?}");
|
||||
} else {
|
||||
assert_refused(result, &format!("{role:?} {family:?}"));
|
||||
assert_eq!(
|
||||
rig.sim.received.lock().unwrap().len(),
|
||||
before,
|
||||
"{role:?} {family:?}: a refused call reached the loop"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Nobody but the in-process host may register anything, a control name least of all.
|
||||
for name in [
|
||||
scope.service(Family::Ops, ""),
|
||||
scope.service(Family::Sugar, controlbus::LIVE_AGENT),
|
||||
"fly.control.s.main.buttons".to_owned(),
|
||||
"anything".to_owned(),
|
||||
] {
|
||||
assert_refused(
|
||||
client
|
||||
.register(&name, ServiceConfig::default())
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} registering {name}"),
|
||||
);
|
||||
}
|
||||
// No topics: not the feed, not a new one.
|
||||
assert_refused(
|
||||
client
|
||||
.subscribe(flysim::feedbus::TOPIC, flybus::SubscriptionConfig::latest())
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} subscribing to the feed"),
|
||||
);
|
||||
assert_refused(
|
||||
client
|
||||
.declare_topic("fly.control.events", Retained::None)
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} declaring a topic"),
|
||||
);
|
||||
assert_refused(
|
||||
client
|
||||
.publish(flysim::feedbus::TOPIC, Map::new(), &[])
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} publishing on the feed"),
|
||||
);
|
||||
client.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_socket_admits_only_its_own_role() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let bus_dir = rig.config.bus_dir.clone();
|
||||
for (socket, claimed) in [
|
||||
(Role::Stage, Role::Operator.participant()),
|
||||
(Role::Bridge, controlbus::HOST),
|
||||
(Role::Watchdog, controlbus::EDGE),
|
||||
(Role::Edge, Role::Operator.participant()),
|
||||
] {
|
||||
let result = connect_role(&bus_dir, socket, claimed).await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"{claimed} was admitted on {socket:?}'s socket"
|
||||
);
|
||||
}
|
||||
// No socket is bound to the host.
|
||||
assert!(
|
||||
!bus_dir.join("control").join("flysim-control.sock").exists()
|
||||
&& std::fs::read_dir(bus_dir.join("control")).unwrap().count() == Role::NATIVE.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn on_a_shared_router_no_control_participant_can_reach_an_input_service() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scope = Scope::live();
|
||||
// An environment that takes input lives on the same router as the control services.
|
||||
let input = "fly.env.s.main.input";
|
||||
let policy = controlbus::policy(
|
||||
Policy::closed().client(
|
||||
"env",
|
||||
Grants {
|
||||
register: vec![Pattern::exact(input)],
|
||||
..Grants::default()
|
||||
},
|
||||
),
|
||||
&scope,
|
||||
);
|
||||
let mut config = RouterConfig::new(dir.path());
|
||||
config.policy = policy;
|
||||
let router = Router::new(config).unwrap();
|
||||
let env = Client::connect(
|
||||
router.connect_in_memory_as("env"),
|
||||
ClientConfig::new("env", router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut service = env.register(input, ServiceConfig::default()).await.unwrap();
|
||||
let pressed = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
{
|
||||
let pressed = Arc::clone(&pressed);
|
||||
tokio::spawn(async move {
|
||||
while let Some(request) = service.next().await {
|
||||
pressed.fetch_add(1, Ordering::SeqCst);
|
||||
let _ = request.reply(Map::new(), &[]).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
for role in Role::ALL {
|
||||
let client = Client::connect(
|
||||
router.connect_in_memory_as(role.participant()),
|
||||
ClientConfig::new(role.participant(), router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for method in ["Environment.Step", "Control.Stimulate", "Press"] {
|
||||
let mut payload = Map::new();
|
||||
payload.insert("buttons".into(), json!(1));
|
||||
assert_refused(
|
||||
client
|
||||
.call(input, None, method, payload, &[])
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} calling {input} {method}"),
|
||||
);
|
||||
}
|
||||
client.close().await;
|
||||
}
|
||||
assert_eq!(pressed.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_player_sugars_their_own_fly_and_no_other() {
|
||||
// Two flies on two controller ports; one player backs the fly on port 1 and another is
|
||||
// granted by id. Single-fly is the same table with one agent.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scope = Scope {
|
||||
session: "arena".to_owned(),
|
||||
agents: vec![
|
||||
controlbus::AgentScope::new("fly-a", Some(1)),
|
||||
controlbus::AgentScope::new("fly-b", Some(2)),
|
||||
],
|
||||
};
|
||||
let policy = controlbus::policy(Policy::closed(), &scope)
|
||||
.client(
|
||||
"player-a",
|
||||
controlbus::player_grants(&scope, controlbus::Agents::Port(1)),
|
||||
)
|
||||
.client(
|
||||
"player-b",
|
||||
controlbus::player_grants(&scope, controlbus::Agents::Id("fly-b")),
|
||||
);
|
||||
let mut config = RouterConfig::new(dir.path());
|
||||
config.policy = policy;
|
||||
let router = Router::new(config).unwrap();
|
||||
let rig = rig(|_| {}).await;
|
||||
let _host = controlbus::serve(&router, rig.state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let player = Client::connect(
|
||||
router.connect_in_memory_as("player-a"),
|
||||
ClientConfig::new("player-a", router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let other = Client::connect(
|
||||
router.connect_in_memory_as("player-b"),
|
||||
ClientConfig::new("player-b", router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
call(&other, &scope, Family::Sugar, "fly-b").await.unwrap()["status"],
|
||||
json!(202)
|
||||
);
|
||||
assert_refused(
|
||||
call(&other, &scope, Family::Sugar, "fly-a").await,
|
||||
"player-b sugar on fly-a",
|
||||
);
|
||||
assert_eq!(
|
||||
call(&player, &scope, Family::Status, "fly-a").await.unwrap()["status"],
|
||||
json!(200)
|
||||
);
|
||||
assert_refused(
|
||||
call(&player, &scope, Family::Status, "fly-b").await,
|
||||
"status of fly-b",
|
||||
);
|
||||
let outcome = call(&player, &scope, Family::Sugar, "fly-a").await.unwrap();
|
||||
assert_eq!(outcome["status"], json!(202));
|
||||
assert_eq!(outcome["body"], json!({"eventId": 41}));
|
||||
assert_eq!(
|
||||
call(&player, &scope, Family::Read, "").await.unwrap()["status"],
|
||||
json!(200)
|
||||
);
|
||||
assert_refused(
|
||||
call(&player, &scope, Family::Sugar, "fly-b").await,
|
||||
"sugar on fly-b",
|
||||
);
|
||||
assert_refused(
|
||||
call(&player, &scope, Family::Reward, "fly-a").await,
|
||||
"reward on fly-a",
|
||||
);
|
||||
assert_refused(call(&player, &scope, Family::Chat, "").await, "chat");
|
||||
assert_refused(call(&player, &scope, Family::Ops, "").await, "ops");
|
||||
// The live session's names are not the arena's.
|
||||
assert_refused(
|
||||
call(&player, &Scope::live(), Family::Read, "").await,
|
||||
"another session's read",
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_method_the_service_does_not_have_is_a_404_and_reaches_nothing() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let operator = connect_role(
|
||||
&rig.config.bus_dir,
|
||||
Role::Operator,
|
||||
Role::Operator.participant(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let scope = Scope::live();
|
||||
for (family, method) in [
|
||||
(Family::Read, "Control.Pause"),
|
||||
(Family::Sugar, "Control.Press"),
|
||||
(Family::Ops, "Control.Buttons"),
|
||||
(Family::Chat, "Control.Stimulate"),
|
||||
] {
|
||||
let result = operator
|
||||
.call_and_wait(
|
||||
&scope.service(family, controlbus::LIVE_AGENT),
|
||||
None,
|
||||
method,
|
||||
Map::new(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
result.outcome()["status"],
|
||||
json!(404),
|
||||
"{family:?} {method}"
|
||||
);
|
||||
}
|
||||
assert!(rig.sim.received.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// An HTTP edge holding a narrower role answers what the role may not do with a 403, and the
|
||||
/// loop never sees it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn an_edge_on_a_narrow_role_refuses_over_http() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let stage = connect_role(&rig.config.bus_dir, Role::Stage, Role::Stage.participant())
|
||||
.await
|
||||
.unwrap();
|
||||
let backend = fly_control_edge::BusBackend::new(stage, Scope::live(), Arc::clone(&rig.metrics));
|
||||
let router = || flysim::api::router_with(backend.clone());
|
||||
let ok = exchange(router(), &Method::GET, "/healthz", None, &[]).await;
|
||||
assert_eq!(ok.status, StatusCode::OK);
|
||||
for (uri, body) in [
|
||||
("/stimulate", json!({"by": "v", "source": "chat"})),
|
||||
("/chat", json!({"by": "v", "text": "hi"})),
|
||||
("/pause", json!({})),
|
||||
("/checkpoint", json!({})),
|
||||
] {
|
||||
let refused = exchange(
|
||||
router(),
|
||||
&Method::POST,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
&serde_json::to_vec(&body).unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(refused.status, StatusCode::FORBIDDEN, "{uri}");
|
||||
assert!(
|
||||
refused.json()["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("not authorized on the control bus"),
|
||||
"{uri}"
|
||||
);
|
||||
}
|
||||
assert!(rig.sim.received.lock().unwrap().is_empty());
|
||||
}
|
||||
427
services/flysim/crates/fly-control-edge/tests/parity.rs
Normal file
427
services/flysim/crates/fly-control-edge/tests/parity.rs
Normal file
|
|
@ -0,0 +1,427 @@
|
|||
//! Every `docs/control-api.md` endpoint through the edge equals direct, byte for byte.
|
||||
//!
|
||||
//! Each case is sent twice, to flysim's own `:7401` router (`control.via = direct`) and to the
|
||||
//! same router over the bus (`fly-control-edge`'s [`BusBackend`]), and the status, every header
|
||||
//! and the body bytes must be equal. The stand-in loop answers each command from what the request
|
||||
//! says, so both sends get the same answer. The last test does it over real TCP sockets against
|
||||
//! the running edge, where the whole HTTP response must be equal but for its `date` line.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use common::{exchange, rig};
|
||||
use serde_json::json;
|
||||
|
||||
/// `(method, uri, content type, body)`.
|
||||
type Case = (Method, &'static str, Option<&'static str>, Vec<u8>);
|
||||
|
||||
fn json_case(method: Method, uri: &'static str, body: serde_json::Value) -> Case {
|
||||
(
|
||||
method,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
serde_json::to_vec(&body).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn bare(method: Method, uri: &'static str) -> Case {
|
||||
(method, uri, None, Vec::new())
|
||||
}
|
||||
|
||||
fn raw(method: Method, uri: &'static str, body: &str) -> Case {
|
||||
(
|
||||
method,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
body.as_bytes().to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The cases every configuration runs: each endpoint, its validation and its refusals.
|
||||
fn cases() -> Vec<Case> {
|
||||
use Method as M;
|
||||
vec![
|
||||
bare(M::GET, "/status"),
|
||||
bare(M::GET, "/status.json"),
|
||||
bare(M::GET, "/healthz"),
|
||||
bare(M::GET, "/metrics"),
|
||||
// /events: the page, its parameters and the lenient defaults.
|
||||
bare(M::GET, "/events"),
|
||||
bare(M::GET, "/events?since=3"),
|
||||
bare(M::GET, "/events?since=0&limit=2"),
|
||||
bare(M::GET, "/events?since=99"),
|
||||
bare(M::GET, "/events?since=abc&limit=abc"),
|
||||
bare(M::GET, "/events?since=&limit="),
|
||||
bare(M::GET, "/events?limit=0"),
|
||||
bare(M::GET, "/events?since=-1&limit=100000"),
|
||||
bare(M::GET, "/events?since=1&since=2"),
|
||||
bare(M::GET, "/events?unknown=1"),
|
||||
// /stimulate: accepted, both refusals, every malformed shape.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "points"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "chat", "durationMs": 300}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "op", "source": "operator", "durationMs": null}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "pulse", "source": "points"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "spent", "source": "chat"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "bridge"}),
|
||||
),
|
||||
json_case(M::POST, "/stimulate", json!({"by": "viewer"})),
|
||||
json_case(M::POST, "/stimulate", json!({"source": "points"})),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "points", "durationMs": -5}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "points", "durationMs": "400"}),
|
||||
),
|
||||
json_case(M::POST, "/stimulate", json!([1, 2, 3])),
|
||||
raw(M::POST, "/stimulate", "{not json"),
|
||||
raw(M::POST, "/stimulate", "\"a string\""),
|
||||
bare(M::POST, "/stimulate"),
|
||||
(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
Some("text/plain"),
|
||||
b"{\"by\":\"v\",\"source\":\"chat\"}".to_vec(),
|
||||
),
|
||||
(M::POST, "/stimulate", None, vec![0xff, 0xfe, 0x00]),
|
||||
// The loop dropped the request: the 503 both sides answer.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "drop", "source": "chat"}),
|
||||
),
|
||||
// /reward: 403 unless enabled; its validation once it is.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/reward",
|
||||
json!({"value": 0.5, "by": "op", "source": "operator"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/reward",
|
||||
json!({"value": "x", "by": "op", "source": "operator"}),
|
||||
),
|
||||
bare(M::POST, "/reward"),
|
||||
// /chat: accepted, both refusals, the body rules.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "viewer_two", "text": "go fly go"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "bot", "text": "hello", "bot": true}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "viewer", "text": "see http://x.example"}),
|
||||
),
|
||||
json_case(M::POST, "/chat", json!({"by": "fast", "text": "again"})),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "viewer", "text": "hi", "bot": "yes"}),
|
||||
),
|
||||
json_case(M::POST, "/chat", json!({"by": "viewer"})),
|
||||
json_case(M::POST, "/chat", json!({"text": 5})),
|
||||
raw(M::POST, "/chat", "]"),
|
||||
bare(M::POST, "/chat"),
|
||||
// /checkpoint, /pause, /resume.
|
||||
bare(M::POST, "/checkpoint"),
|
||||
bare(M::POST, "/pause"),
|
||||
bare(M::POST, "/resume"),
|
||||
json_case(M::POST, "/pause", json!({"ignored": true})),
|
||||
// Everything that is not a route is the same 404, the wrong method on a route included.
|
||||
bare(M::GET, "/stimulate"),
|
||||
bare(M::POST, "/status"),
|
||||
bare(M::PUT, "/pause"),
|
||||
bare(M::DELETE, "/checkpoint"),
|
||||
json_case(M::POST, "/button", json!({"button": "a"})),
|
||||
bare(M::GET, "/joypad"),
|
||||
bare(M::POST, "/memory"),
|
||||
bare(M::GET, "/"),
|
||||
bare(M::GET, "/status/"),
|
||||
]
|
||||
}
|
||||
|
||||
async fn compare_all(
|
||||
configure: impl FnOnce(&mut flysim::config::Config),
|
||||
cases: &[Case],
|
||||
) -> Vec<(String, StatusCode)> {
|
||||
let rig = rig(configure).await;
|
||||
let mut seen = Vec::new();
|
||||
for (method, uri, content_type, body) in cases {
|
||||
let direct = exchange(rig.direct(), method, uri, *content_type, body).await;
|
||||
let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await;
|
||||
assert_eq!(
|
||||
direct,
|
||||
edge,
|
||||
"{method} {uri}: direct {} {:?} vs edge {} {:?}",
|
||||
direct.status,
|
||||
String::from_utf8_lossy(&direct.body),
|
||||
edge.status,
|
||||
String::from_utf8_lossy(&edge.body)
|
||||
);
|
||||
seen.push((format!("{method} {uri}"), direct.status));
|
||||
}
|
||||
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
|
||||
seen
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn every_endpoint_through_the_edge_equals_direct() {
|
||||
let seen = compare_all(|_| {}, &cases()).await;
|
||||
// The cases reach every status code control-api.md names, so the comparison is not of
|
||||
// twenty identical 200s.
|
||||
let codes: std::collections::BTreeSet<u16> = seen.iter().map(|(_, s)| s.as_u16()).collect();
|
||||
for code in [200, 202, 400, 403, 404, 422, 429, 503] {
|
||||
assert!(codes.contains(&code), "no case answered {code}: {seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn with_reward_enabled_and_chat_disabled_too() {
|
||||
let seen = compare_all(
|
||||
|config| {
|
||||
config.control.allow_reward = true;
|
||||
config.chat.enabled = false;
|
||||
},
|
||||
&cases(),
|
||||
)
|
||||
.await;
|
||||
let status = |what: &str| seen.iter().find(|(w, _)| w == what).unwrap().1;
|
||||
assert_eq!(status("POST /chat"), StatusCode::FORBIDDEN);
|
||||
assert_eq!(status("POST /reward"), StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_failed_checkpoint_an_unhealthy_loop_and_a_timeout_match_too() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.sim.fail_checkpoint.store(true, Ordering::SeqCst);
|
||||
for (method, uri, body) in [
|
||||
(Method::POST, "/checkpoint", Vec::new()),
|
||||
// The loop takes the command but never answers: both sides wait COMMAND_TIMEOUT and 503.
|
||||
(
|
||||
Method::POST,
|
||||
"/stimulate",
|
||||
serde_json::to_vec(&json!({"by": "hang", "source": "chat"})).unwrap(),
|
||||
),
|
||||
] {
|
||||
let direct = exchange(rig.direct(), &method, uri, Some("application/json"), &body).await;
|
||||
let edge = exchange(
|
||||
rig.via_edge(),
|
||||
&method,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
&body,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(direct, edge, "{method} {uri}");
|
||||
assert!(
|
||||
direct.status.is_server_error(),
|
||||
"{method} {uri}: {}",
|
||||
direct.status
|
||||
);
|
||||
}
|
||||
// A loop that has not advanced for 2 s.
|
||||
tokio::time::sleep(Duration::from_millis(2_100)).await;
|
||||
let direct = exchange(rig.direct(), &Method::GET, "/healthz", None, &[]).await;
|
||||
let edge = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await;
|
||||
assert_eq!(direct, edge);
|
||||
assert_eq!(direct.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_large_events_page_rides_as_an_artifact_and_still_matches() {
|
||||
let rig = rig(|_| {}).await;
|
||||
// Enough events that the page is far over one envelope.
|
||||
let mut log = flysim::eventlog::EventLog::open(
|
||||
&rig.dir.path().join("more-events"),
|
||||
rig.state.shared.events.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
for index in 0..2_000u64 {
|
||||
log.append(
|
||||
2_000 + index,
|
||||
index as f64,
|
||||
flysim::eventlog::NewEvent::new(
|
||||
flysim::snapshot::FeedEventKind::Reward,
|
||||
format!("a reasonably long reward label number {index}"),
|
||||
)
|
||||
.value(0.25),
|
||||
);
|
||||
}
|
||||
let uri = "/events?since=0&limit=4096";
|
||||
let direct = exchange(rig.direct(), &Method::GET, uri, None, &[]).await;
|
||||
let edge = exchange(rig.via_edge(), &Method::GET, uri, None, &[]).await;
|
||||
assert!(
|
||||
direct.body.len() > flysim::controlbus::INLINE_MAX,
|
||||
"{} bytes",
|
||||
direct.body.len()
|
||||
);
|
||||
assert_eq!(direct, edge);
|
||||
// The artifact is released once read.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(rig.bus.router.stats().artifacts, 0);
|
||||
}
|
||||
|
||||
/// A request body over flybus's 65,536-byte envelope (N2): the edge carries it as an artifact and
|
||||
/// the answer is the one direct mode gives, whatever it is, for every body endpoint.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_request_body_over_the_envelope_gets_directs_answer() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let mut cases = Vec::new();
|
||||
for size in [49_000usize, 70_000, 300_000] {
|
||||
let text = "x".repeat(size);
|
||||
for uri in ["/chat", "/stimulate", "/reward"] {
|
||||
cases.push(json_case(
|
||||
Method::POST,
|
||||
uri,
|
||||
json!({"by": "viewer", "source": "points", "text": text, "message": text, "reason": text}),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Over the limit and not JSON at all: direct's 400 either way.
|
||||
cases.push(raw(Method::POST, "/chat", &"{".repeat(100_000)));
|
||||
let mut codes = Vec::new();
|
||||
for (method, uri, content_type, body) in &cases {
|
||||
let direct = exchange(rig.direct(), method, uri, *content_type, body).await;
|
||||
let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await;
|
||||
assert_eq!(
|
||||
direct,
|
||||
edge,
|
||||
"{method} {uri} ({} bytes): direct {} {:?} vs edge {} {:?}",
|
||||
body.len(),
|
||||
direct.status,
|
||||
String::from_utf8_lossy(&direct.body),
|
||||
edge.status,
|
||||
String::from_utf8_lossy(&edge.body)
|
||||
);
|
||||
assert!(
|
||||
!String::from_utf8_lossy(&edge.body).contains("INVALID_ENVELOPE"),
|
||||
"{uri}: {:?}",
|
||||
String::from_utf8_lossy(&edge.body)
|
||||
);
|
||||
codes.push(direct.status.as_u16());
|
||||
}
|
||||
eprintln!("large-body statuses: {codes:?}");
|
||||
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
|
||||
// Every request artifact was released once read.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(rig.bus.router.stats().artifacts, 0);
|
||||
}
|
||||
|
||||
/// Request bodies that ride as artifacts, larger ones first (BUS-02 review N3): each artifact is
|
||||
/// exactly its own body, never a tail of the one before -- a stale byte past a smaller body's end
|
||||
/// would make it a different request (or not JSON), and its answer would differ from direct's.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_smaller_request_body_after_a_larger_one_is_exactly_its_own() {
|
||||
let rig = rig(|_| {}).await;
|
||||
for (size, fill) in [(300_000usize, 'a'), (120_000, 'b'), (70_000, 'c'), (66_000, 'd')] {
|
||||
for uri in ["/chat", "/stimulate"] {
|
||||
let text = fill.to_string().repeat(size);
|
||||
let (method, uri, content_type, body) = json_case(
|
||||
Method::POST,
|
||||
uri,
|
||||
json!({"by": "viewer", "source": "points", "text": text, "message": text}),
|
||||
);
|
||||
let direct = exchange(rig.direct(), &method, uri, content_type, &body).await;
|
||||
let edge = exchange(rig.via_edge(), &method, uri, content_type, &body).await;
|
||||
assert_eq!(direct, edge, "{uri} ({} bytes, {fill:?})", body.len());
|
||||
}
|
||||
}
|
||||
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let stats = rig.bus.router.stats();
|
||||
assert_eq!((stats.artifacts, stats.store_bytes), (0, 0), "every request artifact released");
|
||||
}
|
||||
|
||||
/// The running edge over real sockets: the whole HTTP/1.1 response equals flysim's own listener's,
|
||||
/// `date` aside, for a request of every kind.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn over_tcp_the_edge_answers_the_same_bytes_as_flysim() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.close_edge().await;
|
||||
// flysim's own listener, as direct mode binds it.
|
||||
let direct_addr = common::free_port();
|
||||
let listener = tokio::net::TcpListener::bind(direct_addr).await.unwrap();
|
||||
let router = rig.direct();
|
||||
tokio::spawn(async move { axum::serve(listener, router).await });
|
||||
// The edge process's loop, on another port.
|
||||
let edge_addr = common::free_port();
|
||||
let config = fly_control_edge::EdgeConfig {
|
||||
control_bind: edge_addr,
|
||||
..rig.config.clone()
|
||||
};
|
||||
let metrics = std::sync::Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let edge = tokio::spawn(fly_control_edge::run(
|
||||
config,
|
||||
std::sync::Arc::clone(&metrics),
|
||||
));
|
||||
let mut waited = 0;
|
||||
while metrics.connected.load(Ordering::Relaxed) == 0 {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
waited += 1;
|
||||
assert!(waited < 250, "the edge never bound");
|
||||
}
|
||||
let body = r#"{"by":"viewer","source":"points","durationMs":300}"#;
|
||||
let chat = r#"{"by":"viewer","text":"see http://x.example"}"#;
|
||||
for request in [
|
||||
"GET /status HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /events?since=2&limit=3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
format!(
|
||||
"POST /stimulate HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
),
|
||||
format!(
|
||||
"POST /chat HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{chat}",
|
||||
chat.len()
|
||||
),
|
||||
"POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"POST /reward HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /buttons HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
] {
|
||||
let direct = common::raw_http(direct_addr, &request).await.unwrap();
|
||||
let via_edge = common::raw_http(edge_addr, &request).await.unwrap();
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&direct),
|
||||
String::from_utf8_lossy(&via_edge),
|
||||
"{request}"
|
||||
);
|
||||
assert!(direct.starts_with(b"HTTP/1.1 "), "{}", String::from_utf8_lossy(&direct));
|
||||
}
|
||||
edge.abort();
|
||||
}
|
||||
90
services/flysim/crates/fly-control-edge/tests/serve.rs
Normal file
90
services/flysim/crates/fly-control-edge/tests/serve.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
//! `flysim::serve` with `control.via = bus`: flysim leaves the control port alone, registers the
|
||||
//! control services on its embedded router, and the edge process serves the port from them.
|
||||
//! This is the wiring both runtimes share (`flysim` and `flysim-session` both run `serve`).
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use flysim::config::{Config, ControlVia};
|
||||
use flysim::simloop::Command;
|
||||
use flysim::snapshot::FeedStatus;
|
||||
|
||||
#[test]
|
||||
fn serve_in_control_bus_mode_leaves_the_port_to_the_edge() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut config = Config::default();
|
||||
config.feed.bind = common::free_port();
|
||||
config.control.bind = common::free_port();
|
||||
config.control.via = ControlVia::Bus;
|
||||
config.feed.bus_dir = dir.path().join("bus");
|
||||
let control_bind = config.control.bind;
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let serving = {
|
||||
let config = config.clone();
|
||||
let stop = Arc::clone(&stop);
|
||||
std::thread::spawn(move || {
|
||||
flysim::serve(
|
||||
config,
|
||||
move |shared, _snapshots, mut commands, _notifier| {
|
||||
// A stand-in loop: beats, answers pauses, stops when told.
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
shared.beat();
|
||||
while let Ok(command) = commands.try_recv() {
|
||||
if let Command::Pause { reply } = command {
|
||||
let _ = reply.send(FeedStatus::Paused);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
runtime.block_on(async {
|
||||
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
// The router's sockets appear; flysim never binds the control port.
|
||||
let started = Instant::now();
|
||||
while !dir.path().join("bus/control-edge.sock").exists() {
|
||||
assert!(started.elapsed() < Duration::from_secs(20), "no control socket");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(common::raw_http(control_bind, request).await.is_none(), "flysim bound :7401");
|
||||
for role in ["stage", "bridge", "watchdog", "operator"] {
|
||||
assert!(dir.path().join(format!("bus/control/{role}.sock")).exists(), "{role}");
|
||||
}
|
||||
// The feed is still direct: no feed socket.
|
||||
assert!(!dir.path().join("bus/edge.sock").exists());
|
||||
|
||||
let edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None);
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let edge = tokio::spawn(fly_control_edge::run(edge_config, Arc::clone(&metrics)));
|
||||
let started = Instant::now();
|
||||
while metrics.connected.load(Ordering::Relaxed) == 0 {
|
||||
assert!(started.elapsed() < Duration::from_secs(20), "the edge never bound");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
let health = common::raw_http(control_bind, request).await.unwrap();
|
||||
assert!(health.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&health));
|
||||
let pause = "POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
let paused = String::from_utf8(common::raw_http(control_bind, pause).await.unwrap()).unwrap();
|
||||
assert!(paused.starts_with("HTTP/1.1 200"), "{paused}");
|
||||
assert!(paused.ends_with("{\"status\":\"paused\"}"), "{paused}");
|
||||
|
||||
// flysim stops: the edge lets go of the port.
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
let started = Instant::now();
|
||||
while common::raw_http(control_bind, request).await.is_some() {
|
||||
assert!(started.elapsed() < Duration::from_secs(20), ":7401 stayed bound");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
edge.abort();
|
||||
});
|
||||
serving.join().unwrap().unwrap();
|
||||
}
|
||||
|
|
@ -18,8 +18,9 @@
|
|||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use axum::extract::State;
|
||||
|
|
@ -32,6 +33,19 @@ use flysim::feedbus;
|
|||
use flysim::metrics::{Metrics, metric};
|
||||
use tokio::sync::{oneshot, watch};
|
||||
|
||||
/// A subscription that has delivered nothing for this long is not serving: the loop publishes a
|
||||
/// header at least every `1 / idle_snapshot_hz` even when paused, so silence this long means the
|
||||
/// bus is wedged, not that the fly is idle. `/healthz` turns 503 so the watchdog restarts the edge
|
||||
/// (it restarts nothing while flysim itself is unhealthy: that is flysim's check).
|
||||
pub const STALE_AFTER: Duration = Duration::from_secs(15);
|
||||
|
||||
static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
|
||||
|
||||
/// Milliseconds since the process first asked, plus one so that 0 can mean "never".
|
||||
fn now_ms() -> u64 {
|
||||
EPOCH.elapsed().as_millis() as u64 + 1
|
||||
}
|
||||
|
||||
/// What the edge needs to know. Built from flysim's own configuration, so both processes read
|
||||
/// one environment file and cannot disagree about the port, the bus directory or the cadence.
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
@ -75,9 +89,41 @@ pub struct EdgeMetrics {
|
|||
pub decode_failures: AtomicU64,
|
||||
/// Sessions that reached the bus but could not bind the feed port.
|
||||
pub bind_failures: AtomicU64,
|
||||
/// [`now_ms`] when the last snapshot was taken off the bus; 0 before the first.
|
||||
last_snapshot_ms: AtomicU64,
|
||||
}
|
||||
|
||||
impl EdgeMetrics {
|
||||
/// Note that a snapshot has just been taken off the bus.
|
||||
fn snapshot_arrived(&self) {
|
||||
self.snapshots.fetch_add(1, Ordering::Relaxed);
|
||||
self.last_snapshot_ms.store(now_ms(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Seconds since the last snapshot came off the bus, or `None` before the first.
|
||||
pub fn snapshot_age(&self) -> Option<Duration> {
|
||||
match self.last_snapshot_ms.load(Ordering::Relaxed) {
|
||||
0 => None,
|
||||
at => Some(Duration::from_millis(now_ms().saturating_sub(at))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the edge is serving: subscribed, and hearing from the bus within [`STALE_AFTER`].
|
||||
pub fn health(&self) -> Result<(), String> {
|
||||
self.health_within(STALE_AFTER)
|
||||
}
|
||||
|
||||
fn health_within(&self, stale_after: Duration) -> Result<(), String> {
|
||||
if self.connected.load(Ordering::Relaxed) != 1 {
|
||||
return Err("waiting for the feed bus".to_owned());
|
||||
}
|
||||
match self.snapshot_age() {
|
||||
Some(age) if age <= stale_after => Ok(()),
|
||||
Some(age) => Err(format!("no snapshot for {} s", age.as_secs())),
|
||||
None => Err("no snapshot yet".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::with_capacity(1_024);
|
||||
let feed = &self.feed;
|
||||
|
|
@ -116,6 +162,13 @@ impl EdgeMetrics {
|
|||
"1 while the edge is subscribed to the feed bus and serving.",
|
||||
self.connected.load(Ordering::Relaxed),
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_edge_snapshot_age_seconds",
|
||||
"gauge",
|
||||
"Seconds since the last snapshot came off the feed bus (-1 before the first).",
|
||||
self.snapshot_age().map_or(-1.0, |age| age.as_secs_f64()),
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_edge_bus_lost_total",
|
||||
|
|
@ -218,10 +271,9 @@ async fn prometheus(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoRespons
|
|||
}
|
||||
|
||||
async fn healthz(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
|
||||
if metrics.connected.load(Ordering::Relaxed) == 1 {
|
||||
(StatusCode::OK, "ok")
|
||||
} else {
|
||||
(StatusCode::SERVICE_UNAVAILABLE, "waiting for the feed bus")
|
||||
match metrics.health() {
|
||||
Ok(()) => (StatusCode::OK, "ok".to_owned()),
|
||||
Err(why) => (StatusCode::SERVICE_UNAVAILABLE, why),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -291,7 +343,7 @@ async fn serve(
|
|||
listener: tokio::net::TcpListener,
|
||||
) {
|
||||
let (snapshots, receiver) = watch::channel(Arc::new(first));
|
||||
metrics.snapshots.fetch_add(1, Ordering::Relaxed);
|
||||
metrics.snapshot_arrived();
|
||||
tracing::info!(feed = %config.feed_bind, bus = %config.bus_dir.display(), "serving the feed from the bus");
|
||||
metrics.connected.store(1, Ordering::Relaxed);
|
||||
|
||||
|
|
@ -317,7 +369,7 @@ async fn serve(
|
|||
Ok(snapshot) => {
|
||||
drop(message);
|
||||
snapshots.send_replace(Arc::new(snapshot));
|
||||
metrics.snapshots.fetch_add(1, Ordering::Relaxed);
|
||||
metrics.snapshot_arrived();
|
||||
}
|
||||
Err(error) => {
|
||||
metrics.decode_failures.fetch_add(1, Ordering::Relaxed);
|
||||
|
|
@ -342,3 +394,32 @@ async fn serve(
|
|||
tracing::warn!("the feed listener took more than 5 s to stop");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn health_needs_the_bus_and_recent_snapshots() {
|
||||
let metrics = EdgeMetrics::default();
|
||||
assert_eq!(metrics.snapshot_age(), None);
|
||||
assert!(metrics.health().unwrap_err().contains("waiting"));
|
||||
metrics.connected.store(1, Ordering::Relaxed);
|
||||
assert!(metrics.health().unwrap_err().contains("no snapshot yet"));
|
||||
metrics.snapshot_arrived();
|
||||
assert_eq!(metrics.health(), Ok(()));
|
||||
std::thread::sleep(Duration::from_millis(40));
|
||||
assert!(metrics.snapshot_age().unwrap() >= Duration::from_millis(40));
|
||||
assert!(
|
||||
metrics
|
||||
.health_within(Duration::from_millis(10))
|
||||
.unwrap_err()
|
||||
.contains("no snapshot for")
|
||||
);
|
||||
metrics.snapshot_arrived();
|
||||
assert_eq!(metrics.health_within(Duration::from_millis(30)), Ok(()));
|
||||
metrics.connected.store(0, Ordering::Relaxed);
|
||||
assert!(metrics.health().is_err());
|
||||
assert!(metrics.render().contains("fly_edge_snapshot_age_seconds"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -175,6 +175,68 @@ async fn a_header_too_large_for_an_envelope_travels_as_an_artifact_and_arrives_i
|
|||
assert!(direct == edge);
|
||||
}
|
||||
|
||||
/// Each artifact a snapshot rides on is its own bytes, whatever came before it (BUS-02 review
|
||||
/// N3): smaller attachments after larger ones, and a header that travels as an artifact, then
|
||||
/// inline, then as a smaller artifact, reach the edge's clients exactly as the direct feed
|
||||
/// writes them, with nothing of an earlier snapshot in them.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn smaller_artifacts_after_larger_ones_arrive_exactly() {
|
||||
let base = snapshot_of(&fixture_messages("macros")[10]).unwrap();
|
||||
let with_events = |n: u64, fill: char| {
|
||||
let mut snapshot = base.clone();
|
||||
for id in 0..n {
|
||||
snapshot.header.events.push(flysim::snapshot::FeedEvent {
|
||||
id: 10_000 + id,
|
||||
wall_ms: 1_757_000_000_000 + id,
|
||||
brain_ms: 5.0,
|
||||
kind: flysim::snapshot::FeedEventKind::System,
|
||||
label: fill.to_string().repeat(200),
|
||||
value: None,
|
||||
reward_kind: None,
|
||||
by: None,
|
||||
});
|
||||
}
|
||||
snapshot
|
||||
};
|
||||
// (header events, attachment length, fill): large, then smaller, then large-but-smaller.
|
||||
let plan = [(400, 92_160, 0xA1u8), (0, 1_000, 0xB2), (0, 7, 0xC3), (360, 4_096, 0xD4), (0, 3, 0xE5)];
|
||||
let mut snapshots = Vec::new();
|
||||
for (seq, (events, len, fill)) in plan.into_iter().enumerate() {
|
||||
let mut snapshot = with_events(events, char::from(b'a' + seq as u8));
|
||||
snapshot.header.seq = base.header.seq + seq as u64;
|
||||
snapshot.frame = vec![fill; len].into();
|
||||
snapshot.audio = vec![fill ^ 0xFF; len / 2].into();
|
||||
snapshot.spikes = vec![fill.rotate_left(1); len / 3].into();
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
let paths = start(snapshots[0].clone(), true).await;
|
||||
let wants = ["frame", "audio", "spikes"];
|
||||
let mut direct = connect(paths.direct, &wants).await;
|
||||
let mut edge = connect(paths.edge, &wants).await;
|
||||
for (index, snapshot) in snapshots.iter().enumerate() {
|
||||
if index > 0 {
|
||||
paths.snapshots.send_replace(std::sync::Arc::new(snapshot.clone()));
|
||||
}
|
||||
let d = next_binary(&mut direct, Duration::from_secs(20)).await;
|
||||
let e = next_binary(&mut edge, Duration::from_secs(20)).await;
|
||||
assert_eq!(seq_of(&e), snapshot.header.seq, "#{index}");
|
||||
assert!(d == e, "#{index}: the edge's message differs from the direct feed's");
|
||||
let (_, attachments) = split(&e);
|
||||
let expected: Vec<&[u8]> = snapshot
|
||||
.header
|
||||
.attachments
|
||||
.iter()
|
||||
.map(|kind| match kind {
|
||||
flysim::snapshot::AttachmentKind::Frame => snapshot.frame.as_slice(),
|
||||
flysim::snapshot::AttachmentKind::Audio => snapshot.audio.as_slice(),
|
||||
flysim::snapshot::AttachmentKind::Spikes => snapshot.spikes.as_slice(),
|
||||
})
|
||||
.collect();
|
||||
assert!(!expected.is_empty());
|
||||
assert_eq!(attachments, expected, "#{index}: attachments");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_edge_drops_its_clients_and_unbinds_when_the_bus_goes_away_then_comes_back() {
|
||||
let snapshot = snapshot_of(&fixture_messages("shop")[5]).unwrap();
|
||||
|
|
|
|||
|
|
@ -231,15 +231,29 @@ async fn hoarding_subscriber() -> Outcome {
|
|||
// Every subscription the seat may open, each keeping every delivery at the in-flight cap:
|
||||
// the worst case the store has to hold (`feedbus::limits`, flybus.md "Feed sizing").
|
||||
let seats = feedbus::limits().max_subscriptions_per_client;
|
||||
// The publisher declares the topic on its own task after `start` returns: under load the
|
||||
// first subscribe can get there first (NO_TOPIC), so it waits for the topic (BUS-02 review
|
||||
// N7).
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let mut hoards = Vec::new();
|
||||
for _ in 0..seats {
|
||||
let mut subscription = client
|
||||
.subscribe(
|
||||
feedbus::TOPIC,
|
||||
SubscriptionConfig::latest().in_flight(2).replay(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut subscription = loop {
|
||||
match client
|
||||
.subscribe(
|
||||
feedbus::TOPIC,
|
||||
SubscriptionConfig::latest().in_flight(2).replay(true),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(subscription) => break subscription,
|
||||
Err(error)
|
||||
if error.code == flybus::ErrorCode::NoTopic && Instant::now() < deadline =>
|
||||
{
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
Err(error) => panic!("subscribe: {error:?}"),
|
||||
}
|
||||
};
|
||||
hoards.push(tokio::spawn(async move {
|
||||
let mut kept = Vec::new();
|
||||
while let Some(message) = subscription.next().await {
|
||||
|
|
|
|||
58
services/flysim/crates/fly-legacy-session/Cargo.toml
Normal file
58
services/flysim/crates/fly-legacy-session/Cargo.toml
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
[package]
|
||||
name = "fly-legacy-session"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, the parity harness against the legacy loop's FLY_TRACE, and the flysim-session service."
|
||||
|
||||
[lib]
|
||||
name = "fly_legacy_session"
|
||||
path = "src/lib.rs"
|
||||
|
||||
# SERVE-01: the session runtime as the live service, a drop-in for `flysim`.
|
||||
[[bin]]
|
||||
name = "flysim-session"
|
||||
path = "src/bin/flysim-session.rs"
|
||||
|
||||
# SHADOW-01: the session runtime run beside the live fly (`infra/units/flyshadow.service`).
|
||||
[[bin]]
|
||||
name = "fly-shadow"
|
||||
path = "src/bin/fly-shadow.rs"
|
||||
|
||||
[features]
|
||||
# The LIF tick on the GPU (GPU-02), for `flysim-session` and `fly-shadow`: the same switch as
|
||||
# flysim's, so `FLY_CARGO_FEATURES=cuda infra/build/build-flysim.sh` builds every binary with it.
|
||||
cuda = ["fly-session/cuda", "flysim/cuda"]
|
||||
|
||||
[dependencies]
|
||||
# The session framework and its legacy workers (AGENT-01, ENV-01).
|
||||
fly-session = { path = "../fly-session" }
|
||||
flybus = { path = "../flybus" }
|
||||
# The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's
|
||||
# palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image.
|
||||
# flysim is a library dependency only; nothing here changes the service it builds. SERVE-01's
|
||||
# `flysim-session` runs the session behind flysim's own listeners (`flysim::serve`).
|
||||
flysim = { path = "../flysim" }
|
||||
flybrain-gb = { path = "../flybrain-gb" }
|
||||
flybrain-core = { path = "../flybrain-core" }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
||||
# The service entry point (SERVE-01), with flysim's own versions of each.
|
||||
anyhow = "1.0"
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
toml = "0.9"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# CTRL-01: the service contracts with the control API on the bus (`tests/service_parity.rs`).
|
||||
fly-control-edge = { path = "../fly-control-edge" }
|
||||
tempfile = "3"
|
||||
axum = "0.8"
|
||||
futures-util = "0.3"
|
||||
tokio-tungstenite = "0.29"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
# EDGE-02: the session runtime serves the feed over the bus (tests/feed_bus.rs).
|
||||
fly-edge = { path = "../fly-edge" }
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
//! `reward_bearing IN OUT`: a copy of a FLYSIM01 checkpoint with its adapter ledger thinned so the
|
||||
//! real brain earns rewards where the fly already stands -- the current map unvisited (an `AREA`
|
||||
//! payout on the first sample), its exits unfound (`boundary`), its ground unwalked
|
||||
//! (`exploration`), no wild win a replay (`battle`). TASK-01's brain arm
|
||||
//! (`tests/session_trace.rs`), as a file for SHADOW-01's rehearsal (`tools/shadow-rehearsal.sh`),
|
||||
//! where the real service restores it. A test fixture, never a stream checkpoint.
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let [input, output] = args.as_slice() else {
|
||||
eprintln!("usage: reward_bearing IN OUT");
|
||||
std::process::exit(2);
|
||||
};
|
||||
let bytes = std::fs::read(input).expect("the checkpoint reads");
|
||||
let mut checkpoint = flysim::store::decode(&bytes).expect("FLYSIM01");
|
||||
let reward = &mut checkpoint.runtime.reward;
|
||||
let map = reward["location"]
|
||||
.as_str()
|
||||
.and_then(|l| l.split(':').next())
|
||||
.unwrap_or("0")
|
||||
.to_owned();
|
||||
if let Some(seen) = reward["seen"].as_array_mut() {
|
||||
seen.retain(|key| {
|
||||
let key = key.as_str().unwrap_or("");
|
||||
key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:"))
|
||||
});
|
||||
}
|
||||
if let Some(tiles) = reward["tiles"].as_array_mut() {
|
||||
tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:")));
|
||||
}
|
||||
if let Some(counts) = reward["tileCounts"].as_object_mut() {
|
||||
counts.remove(&map);
|
||||
}
|
||||
reward["wildWins"] = serde_json::json!({});
|
||||
reward["replayBlocked"] = serde_json::json!([]);
|
||||
let out = flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes");
|
||||
std::fs::write(output, out).expect("the copy writes");
|
||||
eprintln!("thinned map {map}: {output}");
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
//! Seed a FLYSIM01 store with one checkpoint file, as its own generation (a soak or rehearsal
|
||||
//! starting from a pulled stream checkpoint; SERVE-01).
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run --release -p fly-legacy-session --example seed_store -- <file.checkpoint> <durable-dir>
|
||||
//! ```
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let [_, file, dir] = args.as_slice() else {
|
||||
eprintln!("usage: seed_store <file.checkpoint> <durable-dir>");
|
||||
std::process::exit(2);
|
||||
};
|
||||
let bytes = std::fs::read(file).expect("reading the checkpoint");
|
||||
let checkpoint = flysim::store::decode(&bytes).expect("a FLYSIM01 checkpoint");
|
||||
let generation = checkpoint.runtime.generation;
|
||||
let store = flysim::store::Store::new(std::path::Path::new(dir), 2);
|
||||
store.create().expect("creating the store");
|
||||
store
|
||||
.commit(generation, &bytes, None)
|
||||
.expect("committing the checkpoint");
|
||||
println!(
|
||||
"seeded {dir} with generation {generation} (frame {}, compatibility {})",
|
||||
checkpoint.runtime.emulator_frame, checkpoint.runtime.compatibility
|
||||
);
|
||||
}
|
||||
126
services/flysim/crates/fly-legacy-session/src/admission.rs
Normal file
126
services/flysim/crates/fly-legacy-session/src/admission.rs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
//! Sugar, admitted by the legacy rules onto the coordinator's admission queue, and the operator
|
||||
//! reward pulse, refused (`legacy-gameboy-v1` section 15 and its amendment of 2026-09-29).
|
||||
//!
|
||||
//! The rules are flysim's own, unchanged: `flysim::ratelimit::RateLimiter` (the per-minute limit
|
||||
//! and "no overlap with an active pulse") and the duration clamp to `[1, sugar_max_ms]`. What
|
||||
//! changed is the pulse they read: the agent's `stimulusRemainingMs` from the **last completed
|
||||
//! commit** ([`AdmissionQueue::stimulus_remaining_ms`]), which the operator accepted as one commit
|
||||
//! stale. Until the first commit of an epoch it is unknown, and a request is refused with a retry.
|
||||
//! A sugar admitted and not yet reported on by a commit counts as active from its admission, as
|
||||
//! the legacy loop's `stimulate` makes it active at once, so two sugars between two commits are
|
||||
//! one admission and one `PulseActive` refusal, exactly as the legacy drain answers them.
|
||||
//!
|
||||
//! The operator's `POST /reward` pulse is refused. The legacy loop refuses it too unless an
|
||||
//! operator turns `control.allow_reward` on (it is off in every shipped configuration); the new
|
||||
//! runtime has no counterpart to turn on, and says so rather than approximating one -- a
|
||||
//! reinforcement outside `Agent.Commit` is not a session-framework operation.
|
||||
|
||||
use flysim::ratelimit::{RateLimiter, Refusal};
|
||||
|
||||
use fly_session::coordinator::{Admission, AdmissionQueue};
|
||||
use fly_session::fly_session_types::gameboy::STIMULUS_REWARD_PULSE;
|
||||
use fly_session::types::*;
|
||||
|
||||
/// Why `POST /reward` is refused (`legacy-gameboy-v1` section 15, amendment of 2026-09-29).
|
||||
pub const OPERATOR_REWARD_REFUSED: &str = "the operator reward pulse is not available on the session runtime (legacy-gameboy-v1 section 15)";
|
||||
|
||||
/// Retry advice while the pulse is unknown: one frame, rounded up.
|
||||
pub const UNKNOWN_PULSE_RETRY_MS: u64 = 17;
|
||||
|
||||
/// The edge-side admission of the legacy composition.
|
||||
pub struct LegacyAdmission {
|
||||
queue: AdmissionQueue,
|
||||
agent_id: Id,
|
||||
limiter: RateLimiter,
|
||||
default_ms: f64,
|
||||
max_ms: f64,
|
||||
serial: u64,
|
||||
}
|
||||
|
||||
impl LegacyAdmission {
|
||||
/// flysim's defaults: 6 per minute, 400 ms by default, at most 1000 ms.
|
||||
pub fn new(queue: AdmissionQueue, agent_id: Id) -> LegacyAdmission {
|
||||
let control = flysim::config::Config::default().control;
|
||||
LegacyAdmission::with_limits(
|
||||
queue,
|
||||
agent_id,
|
||||
control.sugar_per_minute,
|
||||
control.sugar_default_ms,
|
||||
control.sugar_max_ms,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn with_limits(
|
||||
queue: AdmissionQueue,
|
||||
agent_id: Id,
|
||||
per_minute: usize,
|
||||
default_ms: f64,
|
||||
max_ms: f64,
|
||||
) -> LegacyAdmission {
|
||||
LegacyAdmission {
|
||||
queue,
|
||||
agent_id,
|
||||
limiter: RateLimiter::new(per_minute),
|
||||
default_ms,
|
||||
max_ms,
|
||||
serial: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_id(&mut self, kind: &str) -> Id {
|
||||
self.serial += 1;
|
||||
id(&format!("{kind}-{}", self.serial))
|
||||
}
|
||||
|
||||
/// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is
|
||||
/// queued for the next Prepare; the result is its interaction id and the clamped duration.
|
||||
pub fn sugar(&mut self, now_ms: u64, duration_ms: Option<f64>) -> Result<(Id, f64), Refusal> {
|
||||
// Read the pulse, decide and queue under one lock, so a commit cannot land between the
|
||||
// reads and the push (TASK-01 review R2-3). A sugar admitted and not yet reported on by
|
||||
// a commit is an active pulse, as it is in the legacy loop the moment `stimulate` runs:
|
||||
// a second request before the next commit is refused (`PulseActive`), not admitted
|
||||
// into a pulse that would take the max and add nothing (review N1).
|
||||
let agent_id = self.agent_id.clone();
|
||||
let interaction_id = self.next_id("sugar");
|
||||
let (limiter, default_ms, max_ms) = (&mut self.limiter, self.default_ms, self.max_ms);
|
||||
let admission = self.queue.admit_with(&agent_id, |remaining, pending| {
|
||||
let Some(remaining) = remaining else {
|
||||
return Err(Refusal::PulseActive {
|
||||
retry_after_ms: UNKNOWN_PULSE_RETRY_MS,
|
||||
});
|
||||
};
|
||||
limiter.admit(now_ms, remaining.max(pending.unwrap_or(0.0)))?;
|
||||
let duration = duration_ms.unwrap_or(default_ms).clamp(1.0, max_ms).min(max_ms);
|
||||
Ok(Admission::Stimulus {
|
||||
agent_id: agent_id.clone(),
|
||||
interaction_id: interaction_id.clone(),
|
||||
kind_id: id(STIMULUS_REWARD_PULSE),
|
||||
duration_ms: duration,
|
||||
})
|
||||
});
|
||||
if admission.is_err() {
|
||||
// A refusal spends no id.
|
||||
self.serial -= 1;
|
||||
}
|
||||
let Admission::Stimulus { duration_ms: duration, .. } = admission?;
|
||||
Ok((interaction_id, duration))
|
||||
}
|
||||
|
||||
/// `POST /reward`: refused, always (the legacy default, `control.allow_reward = false`).
|
||||
pub fn reward(&mut self, _value: f64) -> Result<Id, &'static str> {
|
||||
Err(OPERATOR_REWARD_REFUSED)
|
||||
}
|
||||
|
||||
/// Admits exactly this sugar, bypassing the rules: a parity run replays the legacy loop's
|
||||
/// admitted inputs, it does not re-decide them.
|
||||
pub fn replay_sugar(&mut self, duration_ms: f64) -> Id {
|
||||
let interaction_id = self.next_id("sugar");
|
||||
self.queue.admit(Admission::Stimulus {
|
||||
agent_id: self.agent_id.clone(),
|
||||
interaction_id: interaction_id.clone(),
|
||||
kind_id: id(STIMULUS_REWARD_PULSE),
|
||||
duration_ms,
|
||||
});
|
||||
interaction_id
|
||||
}
|
||||
}
|
||||
481
services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
Normal file
481
services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
Normal file
|
|
@ -0,0 +1,481 @@
|
|||
//! `fly-shadow`: SHADOW-01, the session runtime run beside the live fly.
|
||||
//!
|
||||
//! ```text
|
||||
//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit)
|
||||
//! fly-shadow check [options] exit 0 only if the verdict allows the cutover (CUT-01's hook)
|
||||
//! fly-shadow relay SHADOW-02, on the release container: stream the trace and the
|
||||
//! saves to a build box's ingest, write its verdict back here
|
||||
//! fly-shadow ingest --root DIR SHADOW-02, on the build box: the relay key's forced command
|
||||
//! ```
|
||||
//!
|
||||
//! `run` reads the live service's own configuration the way flysim does (`/etc/fly/fly.env` through
|
||||
//! the unit's `EnvironmentFile`, `FLY_STATE`, `FLY_STATE_HOT`, ...): the cartridge, the dataset, the
|
||||
//! stores (read only), the macro mode, the speed and the metrics listener. Options:
|
||||
//!
|
||||
//! | Option | Default |
|
||||
//! | --- | --- |
|
||||
//! | `--trace-dir DIR` | `$FLY_TRACE_DIR` |
|
||||
//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` |
|
||||
//! | `--spool DIR` | `<out>/spool` |
|
||||
//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/work`: sockets and artifact stores |
|
||||
//! | `--mode local\|bus/in-process\|bus/thread\|bus/process` | `$FLY_SHADOW_MODE`, else `local` (in-process over the local lane); `in-process`, `thread`, `process` and `bus` are accepted (BUS-01) |
|
||||
//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads |
|
||||
//! | `--required-brain-seconds S` | 10800 |
|
||||
//! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`<out>/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) |
|
||||
//! | `--metrics HOST:PORT` | the live metrics listener |
|
||||
//! | `--spool-max-mib N` | 512 |
|
||||
//! | `--context N` | 30 transition pairs before a divergence |
|
||||
//! | `--all-files` | follow every trace file present, oldest first (a rehearsal) |
|
||||
//! | `--keep-traces` | keep compared trace files |
|
||||
//! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) |
|
||||
//! | `--exit-on-pass` | exit once the verdict is `pass` |
|
||||
//! | `--max-transitions N` | stop after N compared transitions |
|
||||
//! | `--run-id-file FILE` | a remote shadow (SHADOW-02): the run id `fly-shadow ingest` writes; it goes into the verdict, and a change stops the shadow with exit status 4 so its unit starts the new run |
|
||||
//!
|
||||
//! Exit status: 0 passed or stopped, 3 diverged, 4 a new run, 2 the shadow's own error.
|
||||
//!
|
||||
//! `relay` (SHADOW-02) reads the live service's configuration like `run` (`FLY_TRACE_DIR`, the
|
||||
//! stores, `FLY_SHADOW_DIR`) and these: `FLY_SHADOW_RUN_ID` (required, `fly-shadow-run start`
|
||||
//! sets it: the start's Unix ms); `FLY_SHADOW_REMOTE` (the box's ssh destination),
|
||||
//! `FLY_SHADOW_REMOTE_KEY`, `FLY_SHADOW_REMOTE_KNOWN_HOSTS`, `FLY_SHADOW_REMOTE_PORT` (all from the
|
||||
//! operator's private `/etc/fly/shadow-remote.env`); `FLY_SHADOW_REMOTE_COMMAND` replaces the
|
||||
//! whole ssh command (tests); `FLY_SHADOW_RELAY_STALL_SECONDS` (60). Exit status: 0 stopped,
|
||||
//! 3 the remote shadow diverged, 2 an error.
|
||||
//!
|
||||
//! `ingest --root DIR [--keep-mib N]` (SHADOW-02) serves one relay connection on stdin and stdout
|
||||
//! and writes nothing outside DIR; N bounds the mirrored saves (3072).
|
||||
//!
|
||||
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
|
||||
//! [--max-age-seconds N] [--require-arm ARM]`: the cutover rule of
|
||||
//! `fly_legacy_session::shadow::verdict`, and with `--require-arm` (BUS-01: `bus/process`, ...) also
|
||||
//! that the shadow ran that topology. `--current`
|
||||
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
|
||||
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
|
||||
//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`,
|
||||
//! SERVE-01's service). `--compatibility` defaults to this build's legacy compatibility string.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use fly_legacy_session::shadow::{
|
||||
self, LagGuard, ShadowConfig, StopFlag, ingest, relay, release, remote, verdict,
|
||||
};
|
||||
use fly_session::ExecutionMode;
|
||||
|
||||
fn usage() -> ! {
|
||||
eprintln!("usage: fly-shadow run [options] | fly-shadow check --verdict FILE [options]");
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
fn die(message: impl std::fmt::Display) -> ! {
|
||||
eprintln!("fly-shadow: {message}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
struct Args(Vec<String>);
|
||||
|
||||
impl Args {
|
||||
fn flag(&mut self, name: &str) -> bool {
|
||||
match self.0.iter().position(|a| a == name) {
|
||||
Some(i) => {
|
||||
self.0.remove(i);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn value(&mut self, name: &str) -> Option<String> {
|
||||
let i = self.0.iter().position(|a| a == name)?;
|
||||
if i + 1 >= self.0.len() {
|
||||
die(format!("{name} needs a value"));
|
||||
}
|
||||
let value = self.0.remove(i + 1);
|
||||
self.0.remove(i);
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn parsed<T: std::str::FromStr>(&mut self, name: &str) -> Option<T> {
|
||||
self.value(name).map(|v| {
|
||||
v.parse()
|
||||
.unwrap_or_else(|_| die(format!("{name}: cannot parse {v:?}")))
|
||||
})
|
||||
}
|
||||
|
||||
fn done(self) {
|
||||
if !self.0.is_empty() {
|
||||
die(format!("unknown arguments: {:?}", self.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn env_path(name: &str) -> Option<PathBuf> {
|
||||
std::env::var_os(name)
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
}
|
||||
|
||||
fn file_sha256(path: &std::path::Path) -> String {
|
||||
release::file_sha256(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
fn this_binary() -> PathBuf {
|
||||
std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}")))
|
||||
}
|
||||
|
||||
/// SHA-256 of the release binaries in `dir`, by name.
|
||||
fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap<String, String> {
|
||||
release::binaries_in(dir).unwrap_or_else(|e| die(format!("{}: {e}", dir.display())))
|
||||
}
|
||||
|
||||
fn this_release() -> PathBuf {
|
||||
release::this_release()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut argv: Vec<String> = std::env::args().skip(1).collect();
|
||||
if argv.is_empty() {
|
||||
usage();
|
||||
}
|
||||
let command = argv.remove(0);
|
||||
let mut args = Args(argv);
|
||||
match command.as_str() {
|
||||
"run" => run(args),
|
||||
"relay" => {
|
||||
args.done();
|
||||
relay_main()
|
||||
}
|
||||
"ingest" => ingest_main(args),
|
||||
"check" => {
|
||||
let verdict_path: PathBuf = args
|
||||
.value("--verdict")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| usage());
|
||||
// The release CUT-01 switches into (what `/opt/fly/current` resolves to now), and the
|
||||
// binary in it that it switches to: SERVE-01's service.
|
||||
let current = args
|
||||
.value("--current")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/opt/fly/current"));
|
||||
let binary = args
|
||||
.value("--binary")
|
||||
.unwrap_or_else(|| "flysim-session".to_owned());
|
||||
let compatibility = args.value("--compatibility");
|
||||
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
|
||||
// BUS-01: the topology the cutover goes into, which the shadow must have run.
|
||||
let require_arm = args.value("--require-arm");
|
||||
args.done();
|
||||
let compatibility = compatibility.unwrap_or_else(|| {
|
||||
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e));
|
||||
flysim::simloop::compatibility_string(&config).unwrap_or_else(|e| die(e))
|
||||
});
|
||||
let text = std::fs::read_to_string(&verdict_path)
|
||||
.unwrap_or_else(|e| die(format!("{}: {e}", verdict_path.display())));
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(&text).unwrap_or_else(|e| die(format!("verdict: {e}")));
|
||||
let now = verdict::parse_iso(&verdict::now_iso()).expect("now parses");
|
||||
let dir = current
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|e| die(format!("{}: {e}", current.display())));
|
||||
let binaries = binaries_in(&dir);
|
||||
let dir_text = dir.display().to_string();
|
||||
let release = verdict::Release {
|
||||
dir: &dir_text,
|
||||
binaries: &binaries,
|
||||
};
|
||||
let allowed = verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age)
|
||||
.and_then(|()| match &require_arm {
|
||||
Some(arm) => verdict::ran_arm(&value, arm),
|
||||
None => Ok(()),
|
||||
});
|
||||
match allowed {
|
||||
Ok(()) => println!("cutover allowed: {}", value["reason"]),
|
||||
Err(reason) => {
|
||||
println!("cutover refused: {reason}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(mut args: Args) {
|
||||
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(format!("{e:#}")));
|
||||
let out_dir = args
|
||||
.value("--out")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env_path("FLY_SHADOW_DIR"))
|
||||
.unwrap_or_else(|| die("--out or FLY_SHADOW_DIR is required"));
|
||||
let trace_dir = args
|
||||
.value("--trace-dir")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env_path(flysim::trace::DIR_ENV))
|
||||
.unwrap_or_else(|| die("--trace-dir or FLY_TRACE_DIR is required"));
|
||||
let spool_dir = args
|
||||
.value("--spool")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| out_dir.join("spool"));
|
||||
let work_dir = args
|
||||
.value("--work")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env_path("FLY_SHADOW_WORK"))
|
||||
.unwrap_or_else(|| out_dir.join("work"));
|
||||
// BUS-01: `--mode` (else `FLY_SHADOW_MODE`, which the remote relay forwards to the box) names
|
||||
// the topology: `local` (= `in-process`, the default), `bus/in-process`, `bus/thread`,
|
||||
// `bus/process` (= `bus`, = `process`), `thread`.
|
||||
let arm = args
|
||||
.value("--mode")
|
||||
.or_else(|| std::env::var("FLY_SHADOW_MODE").ok().filter(|v| !v.is_empty()))
|
||||
.map(|value| {
|
||||
fly_legacy_session::composition::SessionArm::parse(&value)
|
||||
.unwrap_or_else(|e| die(format!("--mode / FLY_SHADOW_MODE: {e}")))
|
||||
})
|
||||
.unwrap_or(fly_legacy_session::composition::SessionArm::LOCAL);
|
||||
let mode: ExecutionMode = arm.mode;
|
||||
let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| {
|
||||
std::env::var("FLY_SHADOW_THREADS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(2)
|
||||
});
|
||||
let required: f64 = args
|
||||
.parsed("--required-brain-seconds")
|
||||
.unwrap_or(shadow::REQUIRED_BRAIN_SECONDS);
|
||||
let lag_margin: f64 = args.parsed("--lag-guard-margin").unwrap_or(0.05);
|
||||
let metrics = args.value("--metrics").or_else(|| {
|
||||
config.control.metrics_bind.map(|addr| {
|
||||
if addr.ip().is_unspecified() {
|
||||
format!("127.0.0.1:{}", addr.port())
|
||||
} else {
|
||||
addr.to_string()
|
||||
}
|
||||
})
|
||||
});
|
||||
let spool_mib: u64 = args.parsed("--spool-max-mib").unwrap_or(512);
|
||||
let context_lines: usize = args.parsed("--context").unwrap_or(30);
|
||||
let all_files = args.flag("--all-files");
|
||||
let keep_traces = args.flag("--keep-traces");
|
||||
let keep_spool = args.flag("--keep-spool");
|
||||
let exit_on_pass = args.flag("--exit-on-pass");
|
||||
let max_transitions: Option<u64> = args.parsed("--max-transitions");
|
||||
let run_id_file = args.value("--run-id-file").map(PathBuf::from);
|
||||
// Undocumented: the toy connectome, for tests only.
|
||||
let profile = match args.value("--profile") {
|
||||
None => fly_session::legacy_agent::LegacyProfileKind::Production,
|
||||
Some(p) => {
|
||||
fly_session::legacy_agent::LegacyProfileKind::parse(&p).unwrap_or_else(|e| die(e))
|
||||
}
|
||||
};
|
||||
args.done();
|
||||
|
||||
if config.loop_.game != "pokemon-red" {
|
||||
die(format!(
|
||||
"the legacy composition is Pokémon Red, not {:?}",
|
||||
config.loop_.game
|
||||
));
|
||||
}
|
||||
if u64::from(config.feed.audio_hz) != fly_session::legacy_env::DEFAULT_AUDIO_RATE {
|
||||
die(format!(
|
||||
"the live service's audio rate {} is not the legacy environment's {}",
|
||||
config.feed.audio_hz,
|
||||
fly_session::legacy_env::DEFAULT_AUDIO_RATE
|
||||
));
|
||||
}
|
||||
let baseline_file = out_dir.join("baseline.json");
|
||||
let lag_guard = (lag_margin > 0.0)
|
||||
.then_some(())
|
||||
.and(metrics)
|
||||
.map(|metrics_addr| LagGuard {
|
||||
metrics_addr,
|
||||
baseline_file: Some(baseline_file),
|
||||
margin: lag_margin,
|
||||
window: Duration::from_secs(60),
|
||||
back_off: Duration::from_secs(60),
|
||||
suppress: Duration::from_secs(600),
|
||||
});
|
||||
let shadow_config = ShadowConfig {
|
||||
trace_dir,
|
||||
hot_dir: config.paths.hot_dir.clone(),
|
||||
durable_dir: config.paths.save_dir.clone(),
|
||||
out_dir,
|
||||
spool_dir,
|
||||
work_dir,
|
||||
rom_path: config.paths.rom.clone(),
|
||||
dataset_dir: config.paths.dataset.clone(),
|
||||
profile,
|
||||
macro_mode: config.macros.mode,
|
||||
speed: config.loop_.speed,
|
||||
mode,
|
||||
transport: arm.transport,
|
||||
agent_threads,
|
||||
required_brain_seconds: required,
|
||||
all_files,
|
||||
keep_traces,
|
||||
keep_spool,
|
||||
exit_on_pass,
|
||||
max_transitions,
|
||||
spool_max_bytes: spool_mib << 20,
|
||||
context_lines,
|
||||
poll: Duration::from_millis(100),
|
||||
lag_guard,
|
||||
binary_sha256: file_sha256(&this_binary()),
|
||||
binaries: binaries_in(&this_release()),
|
||||
release: this_release().display().to_string(),
|
||||
run_id_file,
|
||||
};
|
||||
eprintln!(
|
||||
"fly-shadow: {} ({} mode), {} threads, following {} (stores {} and {}, read only)",
|
||||
arm.label(),
|
||||
mode.label(),
|
||||
agent_threads,
|
||||
shadow_config.trace_dir.display(),
|
||||
shadow_config.hot_dir.display(),
|
||||
shadow_config.durable_dir.display()
|
||||
);
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap_or_else(|e| die(format!("tokio: {e}")));
|
||||
let stop = StopFlag::default();
|
||||
let ended = runtime.block_on(async {
|
||||
let signals = stop.clone();
|
||||
tokio::spawn(async move {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let mut term = signal(SignalKind::terminate()).expect("SIGTERM");
|
||||
let mut int = signal(SignalKind::interrupt()).expect("SIGINT");
|
||||
tokio::select! {
|
||||
_ = term.recv() => {}
|
||||
_ = int.recv() => {}
|
||||
}
|
||||
eprintln!("fly-shadow: stopping");
|
||||
signals.request();
|
||||
});
|
||||
shadow::run(shadow_config, stop).await
|
||||
});
|
||||
match ended {
|
||||
Ok((shadow::Ended::Diverged, _)) => std::process::exit(3),
|
||||
Ok((shadow::Ended::NewRun, _)) => {
|
||||
eprintln!("fly-shadow: a new run was started; exiting for the unit to start it");
|
||||
std::process::exit(4)
|
||||
}
|
||||
Ok((ended, verdict)) => {
|
||||
eprintln!(
|
||||
"fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}",
|
||||
verdict.agreement.transitions,
|
||||
verdict.brain_seconds(),
|
||||
verdict.status.as_str()
|
||||
);
|
||||
}
|
||||
Err(e) => die(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Signals set the stop flag.
|
||||
fn stop_on_signals(stop: &StopFlag) {
|
||||
let stop = stop.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("fly-shadow-signals".to_owned())
|
||||
.spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("a signal runtime");
|
||||
runtime.block_on(async {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let mut term = signal(SignalKind::terminate()).expect("SIGTERM");
|
||||
let mut int = signal(SignalKind::interrupt()).expect("SIGINT");
|
||||
tokio::select! {
|
||||
_ = term.recv() => {}
|
||||
_ = int.recv() => {}
|
||||
}
|
||||
});
|
||||
stop.request();
|
||||
})
|
||||
.expect("the signal thread starts");
|
||||
}
|
||||
|
||||
/// `fly-shadow relay`: the release container's half of a remote shadow (SHADOW-02).
|
||||
fn relay_main() {
|
||||
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(format!("{e:#}")));
|
||||
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
|
||||
let out_dir = env_path("FLY_SHADOW_DIR").unwrap_or_else(|| die("FLY_SHADOW_DIR is required"));
|
||||
let trace_dir = env_path(flysim::trace::DIR_ENV)
|
||||
.unwrap_or_else(|| die("FLY_TRACE_DIR is required"));
|
||||
let run_id = var("FLY_SHADOW_RUN_ID").unwrap_or_else(|| {
|
||||
die("FLY_SHADOW_RUN_ID is required (fly-shadow-run start sets it)")
|
||||
});
|
||||
let command: Vec<String> = match var("FLY_SHADOW_REMOTE_COMMAND") {
|
||||
Some(command) => command.split_whitespace().map(str::to_owned).collect(),
|
||||
None => {
|
||||
let target = var("FLY_SHADOW_REMOTE")
|
||||
.unwrap_or_else(|| die("FLY_SHADOW_REMOTE (the box's ssh destination) is required"));
|
||||
let key = env_path("FLY_SHADOW_REMOTE_KEY")
|
||||
.unwrap_or_else(|| die("FLY_SHADOW_REMOTE_KEY is required"));
|
||||
let known = env_path("FLY_SHADOW_REMOTE_KNOWN_HOSTS")
|
||||
.unwrap_or_else(|| die("FLY_SHADOW_REMOTE_KNOWN_HOSTS is required"));
|
||||
let port = var("FLY_SHADOW_REMOTE_PORT").map(|p| {
|
||||
p.parse::<u16>()
|
||||
.unwrap_or_else(|_| die(format!("FLY_SHADOW_REMOTE_PORT {p:?}")))
|
||||
});
|
||||
relay::ssh_command(&target, &key, &known, port)
|
||||
}
|
||||
};
|
||||
let mut relay_config = relay::RelayConfig::with_defaults(
|
||||
trace_dir,
|
||||
config.paths.hot_dir.clone(),
|
||||
config.paths.save_dir.clone(),
|
||||
out_dir,
|
||||
command,
|
||||
run_id,
|
||||
);
|
||||
relay_config.release = this_release().display().to_string();
|
||||
relay_config.binaries = binaries_in(&this_release());
|
||||
relay_config.env = remote::FORWARDED_ENV
|
||||
.iter()
|
||||
.filter_map(|name| Some(((*name).to_owned(), var(name)?)))
|
||||
.collect();
|
||||
if let Some(seconds) = var("FLY_SHADOW_RELAY_STALL_SECONDS") {
|
||||
relay_config.stall = Duration::from_secs(
|
||||
seconds
|
||||
.parse()
|
||||
.unwrap_or_else(|_| die(format!("FLY_SHADOW_RELAY_STALL_SECONDS {seconds:?}"))),
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"fly-shadow relay: run {}, release {}, following {} (stores {} and {}, read only)",
|
||||
relay_config.run_id,
|
||||
relay_config.release,
|
||||
relay_config.trace_dir.display(),
|
||||
relay_config.hot_dir.display(),
|
||||
relay_config.durable_dir.display()
|
||||
);
|
||||
let stop = StopFlag::default();
|
||||
stop_on_signals(&stop);
|
||||
match relay::run(relay_config, stop) {
|
||||
Ok(relay::RelayEnd::Stopped) => eprintln!("fly-shadow relay: stopped"),
|
||||
Ok(relay::RelayEnd::Diverged) => std::process::exit(3),
|
||||
Err(e) => die(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fly-shadow ingest --root DIR`: the build box's half (SHADOW-02), one connection on stdio.
|
||||
fn ingest_main(mut args: Args) {
|
||||
let root = args
|
||||
.value("--root")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| die("ingest needs --root DIR"));
|
||||
let keep_mib: u64 = args.parsed("--keep-mib").unwrap_or(3072);
|
||||
args.done();
|
||||
let mut config = ingest::IngestConfig::new(
|
||||
root,
|
||||
this_release().display().to_string(),
|
||||
binaries_in(&this_release()),
|
||||
);
|
||||
config.keep_checkpoint_bytes = keep_mib << 20;
|
||||
let input = std::io::BufReader::with_capacity(1 << 20, std::io::stdin());
|
||||
if let Err(e) = ingest::serve(input, Box::new(std::io::stdout()), config) {
|
||||
die(e);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
//! `flysim-session`: the live fly on the session runtime, as a drop-in for `flysim` (SERVE-01).
|
||||
//!
|
||||
//! ```sh
|
||||
//! flysim-session # what flysim.service runs after `fly-runtime session`
|
||||
//! flysim-session --print-compatibility
|
||||
//! ```
|
||||
//!
|
||||
//! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or
|
||||
//! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat
|
||||
//! sidecar, and serves the same feed, control API and metrics. These variables are its own:
|
||||
//! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`),
|
||||
//! `FLY_SESSION_TRANSPORT` (`local`, the default, or `bus`; `--transport`), `FLY_SESSION_MODE`
|
||||
//! (`in-process`, `thread` or `process`; `process` by default on the bus), `FLY_SESSION_PIN`,
|
||||
//! `FLY_SESSION_AUX_CPUS` and `FLY_SESSION_PROFILE` (`production`, or `toy` for tests).
|
||||
//!
|
||||
//! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's
|
||||
//! own string, which must equal `flysim`'s), `--print-state-compatibility` and
|
||||
//! `--reset-to-milestone` (the store is shared, so these are `flysim`'s own functions).
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use flysim::config::Config;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "flysim-session",
|
||||
about = "The fly brain and its Game Boy on the session runtime: flysim's feed, control API and checkpoints.",
|
||||
version
|
||||
)]
|
||||
struct Args {
|
||||
/// Path to `flysim.toml`. Without it, defaults plus `FLY_*` / `FLYSIM_*` environment
|
||||
/// overrides are used, exactly as for `flysim`.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
config: Option<std::path::PathBuf>,
|
||||
|
||||
/// Print the resolved configuration and exit.
|
||||
#[arg(long)]
|
||||
check_config: bool,
|
||||
|
||||
/// Print the checkpoint compatibility string this build would write, and exit.
|
||||
#[arg(long)]
|
||||
print_compatibility: bool,
|
||||
|
||||
/// Print the compatibility string the checkpoints in this directory carry, and exit.
|
||||
#[arg(long, value_name = "DIR")]
|
||||
print_state_compatibility: Option<std::path::PathBuf>,
|
||||
|
||||
/// Restart the run from the milestone archive for this ladder rung, and exit (with the
|
||||
/// service stopped; `flysim --reset-to-milestone`, the same store).
|
||||
#[arg(long, value_name = "RANK")]
|
||||
reset_to_milestone: Option<u32>,
|
||||
|
||||
/// `local` (in-process over the local lane) or `bus` (every participant a socket client of
|
||||
/// the session's router, one process each unless `FLY_SESSION_MODE` says otherwise).
|
||||
/// Overrides `FLY_SESSION_TRANSPORT`.
|
||||
#[arg(long, value_name = "local|bus")]
|
||||
transport: Option<String>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
init_tracing();
|
||||
|
||||
let config = Config::load(args.config.as_deref())?;
|
||||
let options =
|
||||
fly_legacy_session::service::ServiceOptions::from_env_with(args.transport.as_deref())?;
|
||||
tracing::info!(config = ?config, options = ?options, "resolved configuration");
|
||||
if args.check_config {
|
||||
println!("{}", toml::to_string_pretty(&config)?);
|
||||
return Ok(());
|
||||
}
|
||||
if args.print_compatibility {
|
||||
println!(
|
||||
"{}",
|
||||
fly_legacy_session::service::compatibility_string(&config, &options)?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(dir) = args.print_state_compatibility.as_deref() {
|
||||
if let Some(found) = flysim::store::state_compatibility(dir) {
|
||||
println!("{found}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(rank) = args.reset_to_milestone {
|
||||
let stamp = flysim::reset::utc_stamp(flysim::eventlog::now_wall_ms());
|
||||
let durable = config.paths.save_dir.clone();
|
||||
let hot = config.paths.hot_dir.clone();
|
||||
let archive = flysim::reset::default_archive_dir(&durable, &stamp);
|
||||
for line in flysim::reset::reset_to_milestone(&durable, &hot, rank, &archive)? {
|
||||
println!("{line}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fly_legacy_session::service::run(config, options)
|
||||
}
|
||||
|
||||
/// Logs go to stderr, as `flysim`'s do (binjgb prints the cartridge header to stdout).
|
||||
fn init_tracing() {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_env("FLYSIM_LOG")
|
||||
.or_else(|_| EnvFilter::try_from_default_env())
|
||||
.unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.with_writer(std::io::stderr)
|
||||
.with_target(false)
|
||||
.init();
|
||||
}
|
||||
949
services/flysim/crates/fly-legacy-session/src/composition.rs
Normal file
949
services/flysim/crates/fly-legacy-session/src/composition.rs
Normal file
|
|
@ -0,0 +1,949 @@
|
|||
//! The legacy Game Boy composition on the session framework: one legacy agent (AGENT-01), the
|
||||
//! legacy environment (ENV-01), and the `pokered-macros-v1` task and executor (this crate) in the
|
||||
//! coordinator, over one router, in any of the launcher's execution modes.
|
||||
//!
|
||||
//! This is the whole new runtime of the live fly short of its edge (EDGE-01) and its FLYSIM01
|
||||
//! export (STATE-02): what CUT-01's shadow runs beside the legacy service.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use flybus::{Grants, Pattern, Policy, RouterConfig};
|
||||
|
||||
use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
|
||||
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
|
||||
use fly_session::fly_session_types::gameboy;
|
||||
use fly_session::launcher::{
|
||||
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, ProcessCpus,
|
||||
SUPERVISOR_CLIENT, ThreadBudget, Via,
|
||||
};
|
||||
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
|
||||
use fly_session::legacy_env::BackendConfig;
|
||||
use fly_session::task::ActionExecutor;
|
||||
use fly_session::types::*;
|
||||
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||
use flysim::snapshot::MacroMode;
|
||||
|
||||
use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
|
||||
use fly_session::legacy_checkpoint::{
|
||||
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
|
||||
SaveReport, SaveTicket, TaskHalf, now_wall_ms,
|
||||
};
|
||||
use flysim::store::Checkpoint;
|
||||
use std::time::Instant;
|
||||
|
||||
fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
|
||||
let mut g = Grants::default();
|
||||
f(&mut g);
|
||||
g
|
||||
}
|
||||
|
||||
/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz).
|
||||
const HISTORY: usize = 4096;
|
||||
|
||||
/// A service session's committed-snapshot cadence on the session topic: once a second of frames
|
||||
/// (every 60th boundary), plus every boundary with task events or boundary actions, which the
|
||||
/// coordinator always publishes. The live presentation is the legacy feed (`docs/feed-protocol.md`,
|
||||
/// 30 Hz, built by the service host from the committed boundary), not this topic, which nothing
|
||||
/// in the release subscribes to; each snapshot attaches a sealed copy of the frame and the audio
|
||||
/// chunk, so publishing it every other frame cost about 0.7 ms a frame on the release CPU
|
||||
/// (PERF-01; was 2).
|
||||
const SNAPSHOT_EVERY: u64 = 60;
|
||||
|
||||
const COORDINATOR_CLIENT: &str = "coordinator";
|
||||
const ENV_CLIENT: &str = "legacy-world";
|
||||
const ENV_SERVICE: &str = "env.world";
|
||||
const ENV_WORKER: &str = "world";
|
||||
/// The environment's worker id, which [`LegacyConfig::placements`] names it by.
|
||||
pub const WORLD_WORKER: &str = ENV_WORKER;
|
||||
const AGENT_CLIENT: &str = "legacy-fly";
|
||||
|
||||
/// How the session's participants reach each other (BUS-01).
|
||||
///
|
||||
/// - `Local`: in-process participants are called over the local lane (PERF-01): no bus message
|
||||
/// and no store file per call. Only [`ExecutionMode::InProcess`] has a lane.
|
||||
/// - `Bus`: every participant is a client of the session's router over a Unix-domain socket,
|
||||
/// launcher-bound to its identity, with its artifacts in the router's store: the topology that
|
||||
/// takes more flies and more worlds by configuration. In-process, thread and process modes all
|
||||
/// run it; thread and process modes have no other transport.
|
||||
///
|
||||
/// Neither changes a result, a trace or a checkpoint: the transport carries the same domain calls
|
||||
/// to the same endpoints (`legacy-gameboy-v1` section 12, amendment 2026-10-01 BUS-01).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
#[default]
|
||||
Local,
|
||||
Bus,
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Transport::Local => "local",
|
||||
Transport::Bus => "bus",
|
||||
}
|
||||
}
|
||||
|
||||
/// `local` or `bus`.
|
||||
pub fn parse(value: &str) -> Result<Transport, String> {
|
||||
match value {
|
||||
"local" => Ok(Transport::Local),
|
||||
"bus" => Ok(Transport::Bus),
|
||||
other => Err(format!("transport {other:?}: local or bus")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher transport for a mode: the lane only in process and only when asked for (and
|
||||
/// not turned off by `FLY_SESSION_LOCAL_LANE=0`, which keeps an in-memory bus); Unix sockets
|
||||
/// for the bus, and always for a thread or a process.
|
||||
pub fn via(&self, mode: ExecutionMode) -> Via {
|
||||
match (self, mode) {
|
||||
(Transport::Local, ExecutionMode::InProcess) if local_lane_enabled() => Via::Local,
|
||||
(Transport::Local, ExecutionMode::InProcess) => Via::Memory,
|
||||
_ => Via::Unix,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One way to run the composition: where the participants run and how they are reached.
|
||||
/// `local` (in-process over the lane, the release default until the bus cutover), `bus/in-process`,
|
||||
/// `bus/thread` and `bus/process`. Parity runs and measurements name them this way
|
||||
/// (`FLY_PARITY_ARMS`, `FLY_PERF_ARMS`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct SessionArm {
|
||||
pub mode: ExecutionMode,
|
||||
pub transport: Transport,
|
||||
}
|
||||
|
||||
impl SessionArm {
|
||||
pub const LOCAL: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Transport::Local,
|
||||
};
|
||||
pub const BUS_IN_PROCESS: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Transport::Bus,
|
||||
};
|
||||
pub const BUS_THREAD: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::Thread,
|
||||
transport: Transport::Bus,
|
||||
};
|
||||
pub const BUS_PROCESS: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::Process,
|
||||
transport: Transport::Bus,
|
||||
};
|
||||
|
||||
pub fn label(&self) -> String {
|
||||
match self.transport {
|
||||
Transport::Local => "local".to_owned(),
|
||||
Transport::Bus => format!("bus/{}", self.mode.label()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `local`, `bus` (= `bus/process`), `bus/in-process`, `bus/thread`, `bus/process`; also the
|
||||
/// bare mode names `in-process` (= local), `thread` and `process` (= the bus).
|
||||
pub fn parse(value: &str) -> Result<SessionArm, String> {
|
||||
Ok(match value.trim() {
|
||||
"local" | "in-process" => SessionArm::LOCAL,
|
||||
"bus/in-process" => SessionArm::BUS_IN_PROCESS,
|
||||
"bus/thread" | "thread" => SessionArm::BUS_THREAD,
|
||||
"bus" | "bus/process" | "process" => SessionArm::BUS_PROCESS,
|
||||
other => {
|
||||
return Err(format!(
|
||||
"{other:?}: local, bus/in-process, bus/thread or bus/process"
|
||||
));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The arms a parity run compares with the legacy loop: `FLY_PARITY_ARMS` (a list of
|
||||
/// [`SessionArm::parse`] names), else `local`, `bus/thread` and `bus/process`. Process mode
|
||||
/// needs the workspace's `fly-session` binary; a build without it skips that arm and says so.
|
||||
pub fn parity_arms() -> Vec<SessionArm> {
|
||||
let arms = match std::env::var("FLY_PARITY_ARMS") {
|
||||
Ok(list) if !list.trim().is_empty() => SessionArm::parse_list(&list)
|
||||
.unwrap_or_else(|e| panic!("FLY_PARITY_ARMS: {e}")),
|
||||
_ => vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS],
|
||||
};
|
||||
let program = fly_session::launcher::default_worker_program();
|
||||
arms.into_iter()
|
||||
.filter(|arm| {
|
||||
let runnable = arm.mode != ExecutionMode::Process || program.is_file();
|
||||
if !runnable {
|
||||
eprintln!(
|
||||
"{} skipped: no worker program at {}",
|
||||
arm.label(),
|
||||
program.display()
|
||||
);
|
||||
}
|
||||
runnable
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A comma-separated list of [`SessionArm::parse`] names.
|
||||
pub fn parse_list(value: &str) -> Result<Vec<SessionArm>, String> {
|
||||
value
|
||||
.split(',')
|
||||
.filter(|part| !part.trim().is_empty())
|
||||
.map(SessionArm::parse)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// How one legacy session is composed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LegacyConfig {
|
||||
pub mode: ExecutionMode,
|
||||
/// The transport in-process participants use; thread and process modes always use the bus.
|
||||
pub transport: Transport,
|
||||
/// Process mode: where each participant process's threads run, by worker id (the agent's
|
||||
/// id, [`WORLD_WORKER`]). Empty: they float (BUS-01).
|
||||
pub placements: BTreeMap<Id, ProcessCpus>,
|
||||
pub rom_path: PathBuf,
|
||||
pub dataset_dir: PathBuf,
|
||||
pub profile: LegacyProfileKind,
|
||||
pub macro_mode: MacroMode,
|
||||
pub agent_id: Id,
|
||||
pub agent_threads: usize,
|
||||
/// Record the step details and the task records (a parity run).
|
||||
pub record: bool,
|
||||
}
|
||||
|
||||
/// `FLY_SESSION_LOCAL_LANE=0` keeps in-process participants on the bus: a measurement knob,
|
||||
/// so the local lane can be compared with the bus path in one build. On by default.
|
||||
pub const LOCAL_LANE_ENV: &str = "FLY_SESSION_LOCAL_LANE";
|
||||
|
||||
fn local_lane_enabled() -> bool {
|
||||
std::env::var(LOCAL_LANE_ENV).map_or(true, |v| v != "0")
|
||||
}
|
||||
|
||||
/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds.
|
||||
pub fn channels_and_hold(mode: MacroMode) -> (Vec<String>, f64) {
|
||||
let channels: Vec<&str> = if mode.dealt() {
|
||||
flybrain_gb::macro_channels(crate::task::GAME)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let preset = gameboy_decoder_config_with_macros(&channels);
|
||||
let hold_ms = preset
|
||||
.macros
|
||||
.as_ref()
|
||||
.or(preset.exclusive.as_ref())
|
||||
.map_or(0.0, |group| group.hold_ms);
|
||||
(channels.iter().map(|c| (*c).to_owned()).collect(), hold_ms)
|
||||
}
|
||||
|
||||
/// A running legacy session: its launcher, its coordinator and the task object.
|
||||
pub struct LegacySession {
|
||||
pub coordinator: Coordinator,
|
||||
pub task: PokeredTask,
|
||||
pub launcher: Launcher,
|
||||
pub rom: Vec<u8>,
|
||||
pub config: LegacyConfig,
|
||||
session_id: Id,
|
||||
backend: BackendConfig,
|
||||
/// Which generation of the world is running: 1 is the one the session started.
|
||||
world_generation: u32,
|
||||
/// The legacy store policy, once attached ([`LegacySession::attach_store`]).
|
||||
checkpointer: Option<LegacyCheckpointer>,
|
||||
saves: u64,
|
||||
/// Saves on the writer thread whose outcome has not been collected.
|
||||
pending_saves: Vec<SaveTicket>,
|
||||
/// Captures sent and not yet collected ([`LegacySession::begin_save`]).
|
||||
pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>,
|
||||
/// The feed event log's watermark the saves record: the restored file's, carried over (the
|
||||
/// session runtime has no feed event log of its own before EDGE-01).
|
||||
last_event_id: u64,
|
||||
}
|
||||
|
||||
/// Where the legacy store lives and how often it is written (the service's `[paths]` and
|
||||
/// `[loop]`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StoreConfig {
|
||||
pub hot_dir: PathBuf,
|
||||
pub durable_dir: PathBuf,
|
||||
pub keep_generations: usize,
|
||||
pub hot_seconds: f64,
|
||||
pub checkpoint_seconds: f64,
|
||||
pub speed: f64,
|
||||
}
|
||||
|
||||
/// This build's legacy compatibility string (`flysim --print-compatibility`): the kernel, the
|
||||
/// adapter, the profile's dataset fingerprint, the plasticity rule and the pokered symbols. It is
|
||||
/// the restore gate and what every save records (`legacy-gameboy-v1` section 12).
|
||||
pub fn compatibility_of(config: &LegacyConfig) -> String {
|
||||
let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
|
||||
let profile = config.profile.profile();
|
||||
flybrain_gb::Compatibility {
|
||||
neural_kernel_version: gameboy::KERNEL_VERSION,
|
||||
adapter: flybrain_gb::GameAdapter::id(&adapter),
|
||||
dataset_fingerprint: &profile.dataset_fingerprint,
|
||||
plasticity_version: gameboy::PLASTICITY_VERSION,
|
||||
pokered_commit: &flybrain_gb::GameAdapter::symbol_provenance(&adapter),
|
||||
}
|
||||
.string()
|
||||
}
|
||||
|
||||
/// How a session came up.
|
||||
#[derive(Debug)]
|
||||
pub enum Boot {
|
||||
/// No checkpoint in either store: a fresh fly, warmed up.
|
||||
Fresh,
|
||||
/// A candidate restored, after `skipped` were refused.
|
||||
Restored {
|
||||
candidate: flysim::store::Candidate,
|
||||
skipped: Vec<(flysim::store::Candidate, String)>,
|
||||
migrated_from: Option<String>,
|
||||
imported: crate::import::Imported,
|
||||
},
|
||||
}
|
||||
|
||||
/// `Sim::boot` on the session runtime: restore from the live FLYSIM01 stores in the legacy order
|
||||
/// (hot latest, hot previous, durable latest, durable previous, milestone archives by rank), each
|
||||
/// candidate held to the legacy gate (`RestoreGate`: the cartridge and the compatibility decision
|
||||
/// with `FLY_ACCEPT_ADAPTERS`), falling to the next on *any* refusal -- unreadable, gated, or
|
||||
/// refused by a participant's `State.StageRestore` or the task. A refused install fences its
|
||||
/// session, so each attempt runs on a session of its own (a directory under `root` each). No
|
||||
/// candidate at all is a fresh start; candidates that all fail are an error, as the legacy loop
|
||||
/// refuses to start a fresh fly over them. Either way the store is attached and the startup
|
||||
/// durable save is written, and the intervals run from then.
|
||||
pub async fn boot(
|
||||
root: &Path,
|
||||
config: LegacyConfig,
|
||||
store: &StoreConfig,
|
||||
) -> Result<(LegacySession, Boot), String> {
|
||||
let (mut session, boot) = boot_unsaved(root, config, store).await?;
|
||||
// `Sim::boot`: a durable save of the state the process starts from, then the intervals.
|
||||
session.save(SaveKind::Durable).await?;
|
||||
session
|
||||
.checkpointer_mut()
|
||||
.expect("attached")
|
||||
.start_intervals(Instant::now());
|
||||
Ok((session, boot))
|
||||
}
|
||||
|
||||
/// [`boot`] up to the store: the restore (or the fresh start) with the store attached, but no
|
||||
/// startup save yet and the intervals not started. The service host (SERVE-01) writes its boot
|
||||
/// events first, so the startup save records their watermark as the legacy one does, and then
|
||||
/// takes the save and starts the intervals itself.
|
||||
pub async fn boot_unsaved(
|
||||
root: &Path,
|
||||
config: LegacyConfig,
|
||||
store: &StoreConfig,
|
||||
) -> Result<(LegacySession, Boot), String> {
|
||||
let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations);
|
||||
let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations);
|
||||
let candidates = flysim::store::restore_order(&hot, &durable);
|
||||
let rom = std::fs::read(&config.rom_path)
|
||||
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
|
||||
let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
|
||||
let gate = fly_session::legacy_checkpoint::RestoreGate::from_env(
|
||||
&sha256_hex(&rom),
|
||||
&compatibility_of(&config),
|
||||
flybrain_gb::GameAdapter::migrates_from(&adapter),
|
||||
);
|
||||
let mut skipped: Vec<(flysim::store::Candidate, String)> = Vec::new();
|
||||
let mut outcome = None;
|
||||
for (attempt, candidate) in candidates.iter().enumerate() {
|
||||
let checkpoint = match flysim::store::load(&candidate.path) {
|
||||
Ok(checkpoint) => checkpoint,
|
||||
Err(e) => {
|
||||
skipped.push((candidate.clone(), format!("{e:#}")));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let migrated_from = match gate.check(&checkpoint) {
|
||||
Ok(from) => from,
|
||||
Err(reason) => {
|
||||
skipped.push((candidate.clone(), reason));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut session =
|
||||
LegacySession::start(&root.join(format!("attempt-{attempt}")), config.clone()).await?;
|
||||
let installed = match session.bootstrap().await {
|
||||
Ok(()) => session.import_checkpoint(&checkpoint, &id("e2")).await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match installed {
|
||||
Ok(imported) => {
|
||||
let rank = session.task.rank();
|
||||
session.attach_store(store)?;
|
||||
session
|
||||
.checkpointer_mut()
|
||||
.expect("attached")
|
||||
.restored(rank, imported.rank_since_ms);
|
||||
outcome = Some((
|
||||
session,
|
||||
Boot::Restored {
|
||||
candidate: candidate.clone(),
|
||||
skipped: std::mem::take(&mut skipped),
|
||||
migrated_from,
|
||||
imported,
|
||||
},
|
||||
));
|
||||
break;
|
||||
}
|
||||
Err(reason) => {
|
||||
session.stop().await;
|
||||
skipped.push((candidate.clone(), reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (session, boot) = match outcome {
|
||||
Some(pair) => pair,
|
||||
None if candidates.is_empty() => {
|
||||
let mut session = LegacySession::start(&root.join("fresh"), config).await?;
|
||||
session.bootstrap().await?;
|
||||
session.attach_store(store)?;
|
||||
(session, Boot::Fresh)
|
||||
}
|
||||
None => {
|
||||
let reasons: Vec<String> = skipped
|
||||
.iter()
|
||||
.map(|(candidate, reason)| format!("{}: {reason}", candidate.origin))
|
||||
.collect();
|
||||
return Err(format!(
|
||||
"every one of the {} checkpoint candidates failed to load; refusing to start a \
|
||||
fresh run over them:\n{}",
|
||||
candidates.len(),
|
||||
reasons.join("\n")
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((session, boot))
|
||||
}
|
||||
|
||||
/// A save [`LegacySession::advance`] queued at the boundary it reached.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct SaveQueued {
|
||||
pub generation: u64,
|
||||
pub durable: bool,
|
||||
pub archive_rank: Option<u32>,
|
||||
}
|
||||
|
||||
/// One transition as a parity run sees it.
|
||||
pub struct Step {
|
||||
pub report: StepReport,
|
||||
pub details: Option<StepDetails>,
|
||||
pub records: Vec<TaskRecord>,
|
||||
}
|
||||
|
||||
impl LegacySession {
|
||||
/// Builds the router, launches the world and the fly, and builds the coordinator with the task
|
||||
/// object's two faces. Nothing has been initialized yet.
|
||||
pub async fn start(root: &Path, config: LegacyConfig) -> Result<LegacySession, String> {
|
||||
let rom = std::fs::read(&config.rom_path)
|
||||
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
|
||||
let rom_digest = sha256_hex(&rom);
|
||||
let session_id = id("legacy");
|
||||
let epoch = id("e1");
|
||||
let store_root = root.join("store");
|
||||
let sockets = root.join("sockets");
|
||||
std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?;
|
||||
let agent_service = format!("agent.{}", config.agent_id);
|
||||
let policy = Policy::closed()
|
||||
.client(
|
||||
COORDINATOR_CLIENT,
|
||||
grants(|g| {
|
||||
g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")];
|
||||
g.publish = vec![Pattern::prefix("session.")];
|
||||
g.manage_topics = vec![Pattern::prefix("session.")];
|
||||
g.register = vec![Pattern::prefix("session.")];
|
||||
}),
|
||||
)
|
||||
// The launcher's supervisor: health checks and shutdown, never a registration.
|
||||
.client(
|
||||
SUPERVISOR_CLIENT,
|
||||
grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]),
|
||||
)
|
||||
.client(
|
||||
ENV_CLIENT,
|
||||
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
|
||||
)
|
||||
.client(
|
||||
&format!("{ENV_CLIENT}-r2"),
|
||||
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
|
||||
)
|
||||
.client(
|
||||
AGENT_CLIENT,
|
||||
grants(|g| g.register = vec![Pattern::exact(&agent_service)]),
|
||||
);
|
||||
let mut router_config = RouterConfig::new(&store_root);
|
||||
router_config.policy = policy;
|
||||
let router = flybus::Router::new(router_config).map_err(|e| format!("router: {e}"))?;
|
||||
let budget = ThreadBudget::new(2 + config.agent_threads, 1).map_err(|e| e.message)?;
|
||||
let mut launcher = Launcher::start(
|
||||
router,
|
||||
config.mode,
|
||||
// `Transport::Local`: in-process participants are called over the local lane: the same
|
||||
// worker shell, no bus message and no store file per artifact (PERF-01, `workers-v1`
|
||||
// amendment). `Transport::Bus`: every participant is a socket client of the router,
|
||||
// whatever its mode (BUS-01); a thread or a separate process always is.
|
||||
config.transport.via(config.mode),
|
||||
&store_root,
|
||||
&sockets,
|
||||
budget,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("launcher: {}", e.message))?;
|
||||
|
||||
for (worker, cpus) in &config.placements {
|
||||
launcher.place_process(worker, cpus.clone());
|
||||
}
|
||||
let mut backend = BackendConfig::legacy(&rom_digest);
|
||||
backend.slots = vec![id(crate::task::SLOT)];
|
||||
launcher
|
||||
.launch_legacy_environment(LegacyEnvironmentLaunch {
|
||||
session_id: session_id.clone(),
|
||||
worker_id: id(ENV_WORKER),
|
||||
incarnation_id: id("world-inc-1"),
|
||||
worker_threads: 1,
|
||||
rom_path: config.rom_path.clone(),
|
||||
backend: backend.clone(),
|
||||
client_id: ENV_CLIENT.to_owned(),
|
||||
service: ENV_SERVICE.to_owned(),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("the world: {}", e.message))?;
|
||||
let environment = launcher
|
||||
.worker(&id(ENV_WORKER))
|
||||
.expect("launched")
|
||||
.worker_ref();
|
||||
|
||||
let (macro_channels, hold_ms) = channels_and_hold(config.macro_mode);
|
||||
let identity = launcher
|
||||
.launch_legacy_agent(LegacyAgentLaunch {
|
||||
session_id: session_id.clone(),
|
||||
agent_id: config.agent_id.clone(),
|
||||
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
|
||||
incarnation_id: parse_id(&format!("{}-inc-1", config.agent_id))?,
|
||||
worker_threads: config.agent_threads,
|
||||
dataset_dir: config.dataset_dir.clone(),
|
||||
profile: config.profile,
|
||||
macro_channels: macro_channels.clone(),
|
||||
client_id: AGENT_CLIENT.to_owned(),
|
||||
service: agent_service,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("the fly: {}", e.message))?;
|
||||
let agent_ref = launcher
|
||||
.worker(&config.agent_id)
|
||||
.expect("launched")
|
||||
.worker_ref();
|
||||
let mut slot = AgentSlot::new(
|
||||
agent_ref,
|
||||
config.agent_id.clone(),
|
||||
id(fly_session::legacy_env::DEFAULT_PORT),
|
||||
config.profile.profile().asset,
|
||||
fly_session::legacy_parity::LEGACY_SEED,
|
||||
);
|
||||
slot.worker_threads = identity.worker_threads as u64;
|
||||
slot.model_version = gameboy::KERNEL_VERSION.to_owned();
|
||||
slot.plasticity_version = gameboy::PLASTICITY_VERSION.to_owned();
|
||||
|
||||
let task = PokeredTask::new(
|
||||
PokeredConfig {
|
||||
agent_id: config.agent_id.clone(),
|
||||
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
|
||||
mode: config.macro_mode,
|
||||
macro_channels,
|
||||
hold_ms,
|
||||
record: config.record,
|
||||
},
|
||||
&rom,
|
||||
&rom_digest,
|
||||
&epoch,
|
||||
)?;
|
||||
let client = launcher
|
||||
.connect(COORDINATOR_CLIENT)
|
||||
.await
|
||||
.map_err(|e| format!("connect: {}", e.message))?;
|
||||
let executors: BTreeMap<Id, Box<dyn ActionExecutor>> =
|
||||
BTreeMap::from([(config.agent_id.clone(), task.executor())]);
|
||||
let mut coordinator = Coordinator::new(
|
||||
client,
|
||||
session_id.clone(),
|
||||
epoch,
|
||||
id("ep1"),
|
||||
environment,
|
||||
vec![slot],
|
||||
task.task(),
|
||||
executors,
|
||||
);
|
||||
coordinator.set_environment_config(
|
||||
backend.asset_ref(),
|
||||
fly_session::environment::synthetic_asset("pokered-task", gameboy::EXECUTOR_ID),
|
||||
);
|
||||
coordinator.set_media(
|
||||
&[gameboy::VIEW_ID],
|
||||
&[fly_session::legacy_env::AUDIO_STREAM_ID],
|
||||
);
|
||||
coordinator.set_state_format(fly_session::legacy_env::STATE_FORMAT_ID);
|
||||
coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref());
|
||||
coordinator
|
||||
.declare_rollback_policy(ROLLBACK_POLICY)
|
||||
.map_err(|e| e.message)?;
|
||||
// The legacy loop runs as fast as its brain allows when measured, and the service paces
|
||||
// itself; a parity run is a measurement.
|
||||
if config.record {
|
||||
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
|
||||
} else {
|
||||
// A service session runs indefinitely: its in-memory history stays bounded.
|
||||
coordinator.bound_history(HISTORY);
|
||||
// The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop.
|
||||
coordinator.snapshot_every(SNAPSHOT_EVERY);
|
||||
}
|
||||
Ok(LegacySession {
|
||||
coordinator,
|
||||
task,
|
||||
launcher,
|
||||
rom,
|
||||
config,
|
||||
session_id,
|
||||
backend,
|
||||
world_generation: 1,
|
||||
checkpointer: None,
|
||||
saves: 0,
|
||||
pending_saves: Vec::new(),
|
||||
pending_captures: Vec::new(),
|
||||
last_event_id: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Hello, `Environment.Initialize` (the one-frame scaffold), the task's bootstrap on O[0],
|
||||
/// `Agent.Initialize` (the warm-up): `Ready(0)`.
|
||||
pub async fn bootstrap(&mut self) -> Result<(), String> {
|
||||
self.coordinator
|
||||
.bootstrap()
|
||||
.await
|
||||
.map_err(|e| format!("bootstrap ({}): {}", e.detail, e.error.message))?;
|
||||
if self.config.record {
|
||||
self.coordinator.disable_pacing();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The agent's identity as an import stamps it.
|
||||
pub fn agent_import(&self) -> AgentImport {
|
||||
let (macro_channels, _) = channels_and_hold(self.config.macro_mode);
|
||||
AgentImport {
|
||||
agent_id: self.config.agent_id.clone(),
|
||||
profile: self.config.profile.profile().asset,
|
||||
seed: fly_session::legacy_parity::LEGACY_SEED,
|
||||
macro_channels,
|
||||
}
|
||||
}
|
||||
|
||||
/// This build's legacy compatibility string ([`compatibility_of`]).
|
||||
pub fn compatibility(&self) -> String {
|
||||
compatibility_of(&self.config)
|
||||
}
|
||||
|
||||
/// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`],
|
||||
/// before any transition): the world is replaced by a fresh one (the environment stages a
|
||||
/// restore only on a replacement, as every group restore does), then [`crate::import`] runs
|
||||
/// the group install and the session resumes at the checkpoint's boundary.
|
||||
pub async fn import_checkpoint(
|
||||
&mut self,
|
||||
checkpoint: &Checkpoint,
|
||||
epoch: &Id,
|
||||
) -> Result<crate::import::Imported, String> {
|
||||
if self.world_generation != 1 {
|
||||
return Err("this session has already replaced its world".to_owned());
|
||||
}
|
||||
self.launcher.reap(&id(ENV_WORKER), &id("import")).await;
|
||||
self.world_generation = 2;
|
||||
self.launcher
|
||||
.launch_legacy_environment(LegacyEnvironmentLaunch {
|
||||
session_id: self.session_id.clone(),
|
||||
worker_id: id(ENV_WORKER),
|
||||
incarnation_id: id("world-inc-2"),
|
||||
worker_threads: 1,
|
||||
rom_path: self.config.rom_path.clone(),
|
||||
backend: self.backend.clone(),
|
||||
client_id: format!("{ENV_CLIENT}-r2"),
|
||||
service: ENV_SERVICE.to_owned(),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("the replacement world: {}", e.message))?;
|
||||
let world = self
|
||||
.launcher
|
||||
.worker(&id(ENV_WORKER))
|
||||
.expect("launched")
|
||||
.worker_ref();
|
||||
self.coordinator
|
||||
.replace_participant(&id(ENV_WORKER), world)
|
||||
.map_err(|e| format!("replacing the world: {}", e.error.message))?;
|
||||
let rom = self.rom.clone();
|
||||
let agent = self.agent_import();
|
||||
let imported = crate::import::import_flysim01(
|
||||
&mut self.coordinator,
|
||||
&self.task,
|
||||
checkpoint,
|
||||
&rom,
|
||||
&agent,
|
||||
self.backend.audio_sample_rate,
|
||||
epoch,
|
||||
)
|
||||
.await?;
|
||||
if self.config.record {
|
||||
self.coordinator.disable_pacing();
|
||||
}
|
||||
self.last_event_id = checkpoint.runtime.last_event_id;
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
/// Decodes FLYSIM01 bytes and installs them ([`LegacySession::import_checkpoint`]).
|
||||
pub async fn import_flysim01(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
epoch: &Id,
|
||||
) -> Result<crate::import::Imported, String> {
|
||||
let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e:#}"))?;
|
||||
self.import_checkpoint(&checkpoint, epoch).await
|
||||
}
|
||||
|
||||
// -- the store (STATE-02) ------------------------------------------------------------------
|
||||
|
||||
/// Attaches the legacy store policy (`LegacyCheckpointer`): FLYSIM01 generations in the hot
|
||||
/// and durable stores, milestone archives, the legacy intervals. Rollbacks are deferred from
|
||||
/// here on, so a milestone capture lands between the boundary's slot save and its rollback.
|
||||
pub fn attach_store(&mut self, store: &StoreConfig) -> Result<(), String> {
|
||||
let checkpointer = LegacyCheckpointer::open(CheckpointerConfig {
|
||||
hot_dir: store.hot_dir.clone(),
|
||||
durable_dir: store.durable_dir.clone(),
|
||||
keep_generations: store.keep_generations,
|
||||
hot_seconds: store.hot_seconds,
|
||||
checkpoint_seconds: store.checkpoint_seconds,
|
||||
compatibility: self.compatibility(),
|
||||
speed: store.speed,
|
||||
slot_id: id(crate::task::SLOT),
|
||||
})?;
|
||||
self.checkpointer = Some(checkpointer);
|
||||
self.coordinator.defer_rollbacks(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn checkpointer(&self) -> Option<&LegacyCheckpointer> {
|
||||
self.checkpointer.as_ref()
|
||||
}
|
||||
|
||||
pub fn checkpointer_mut(&mut self) -> Option<&mut LegacyCheckpointer> {
|
||||
self.checkpointer.as_mut()
|
||||
}
|
||||
|
||||
/// The feed event log's watermark the next save records (`lastEventId`): the restored
|
||||
/// file's until a host that keeps a feed event log sets its own.
|
||||
pub fn last_event_id(&self) -> u64 {
|
||||
self.last_event_id
|
||||
}
|
||||
|
||||
/// The service host's event log watermark, recorded by every save from now on as the legacy
|
||||
/// loop records `log.next_id() - 1` (SERVE-01).
|
||||
pub fn set_last_event_id(&mut self, last_event_id: u64) {
|
||||
self.last_event_id = last_event_id;
|
||||
}
|
||||
|
||||
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for
|
||||
/// the commit, so a caller that goes on to read the store finds it. For the startup and
|
||||
/// shutdown saves, which the legacy loop takes blocking too.
|
||||
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> {
|
||||
let ticket = self.queue_save(kind).await?;
|
||||
ticket
|
||||
.reply
|
||||
.await
|
||||
.map_err(|_| "the checkpoint writer stopped".to_owned())?
|
||||
}
|
||||
|
||||
/// One save of the committed boundary, queued: the participants capture now (the boundary's
|
||||
/// state) and the encoding and fsync run on the checkpointer's writer thread while the loop
|
||||
/// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The
|
||||
/// outcome is collected by [`LegacySession::completed_saves`].
|
||||
pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
|
||||
self.begin_save(kind).await?;
|
||||
let mut tickets = self.finish_captures().await?;
|
||||
let last = tickets
|
||||
.pop()
|
||||
.ok_or_else(|| "no save was begun".to_owned())?;
|
||||
self.pending_saves.extend(tickets);
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
/// Begins one save of the committed boundary: every participant's `State.Capture` is sent
|
||||
/// (each takes its state now) and the task's half is taken now; the session may step on
|
||||
/// while the agent encodes and seals its payload off its lock
|
||||
/// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`]
|
||||
/// hands it to the writer.
|
||||
pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> {
|
||||
self.saves += 1;
|
||||
let capture = self
|
||||
.coordinator
|
||||
.begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?)
|
||||
.await
|
||||
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
||||
let (task, _slot_filled) = self.task.task_half();
|
||||
self.pending_captures.push((capture, kind, task));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collects every begun capture, in order, and queues it to the checkpointer's writer.
|
||||
pub async fn finish_captures(&mut self) -> Result<Vec<SaveTicket>, String> {
|
||||
let mut tickets = Vec::new();
|
||||
for (capture, kind, task) in std::mem::take(&mut self.pending_captures) {
|
||||
let (boundary, world, agents) = self
|
||||
.coordinator
|
||||
.finish_capture(capture)
|
||||
.await
|
||||
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
||||
let [(_, agent)] = <[(Id, Vec<u8>); 1]>::try_from(agents)
|
||||
.map_err(|_| "the legacy composition has exactly one agent".to_owned())?;
|
||||
let capture = LegacyCapture {
|
||||
boundary,
|
||||
agent_payload: agent,
|
||||
world_payload: world,
|
||||
task,
|
||||
};
|
||||
let last_event_id = self.last_event_id;
|
||||
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
|
||||
tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?);
|
||||
}
|
||||
Ok(tickets)
|
||||
}
|
||||
|
||||
/// The saves queued so far that have committed (or failed), without waiting; with `wait`,
|
||||
/// every queued save's outcome. Every outcome is reported, a failed save as its own `Err`
|
||||
/// beside the others (TASK-01 review R2-2): the caller decides.
|
||||
pub async fn completed_saves(&mut self, wait: bool) -> Vec<Result<SaveReport, String>> {
|
||||
let mut done = Vec::new();
|
||||
let mut still = Vec::new();
|
||||
for mut ticket in std::mem::take(&mut self.pending_saves) {
|
||||
let stopped = || Err("the checkpoint writer stopped".to_owned());
|
||||
if wait {
|
||||
done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped()));
|
||||
} else {
|
||||
match ticket.reply.try_recv() {
|
||||
Ok(result) => done.push(result),
|
||||
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket),
|
||||
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.pending_saves = still;
|
||||
done
|
||||
}
|
||||
|
||||
/// Hands every begun capture to the writer now and reports what was queued. `advance` does
|
||||
/// this after the next step so the agent's sealing overlaps it; a step that fails does it
|
||||
/// before returning the error, and a caller that pauses (or is about to stop stepping) calls
|
||||
/// this so a save begun at the last boundary reaches the writer as the legacy loop's
|
||||
/// immediate hand-off would have (TASK-01 review R2-1).
|
||||
pub async fn flush_captures(&mut self) -> Result<Vec<SaveQueued>, String> {
|
||||
let mut saves = Vec::new();
|
||||
for ticket in self.finish_captures().await? {
|
||||
saves.push(SaveQueued {
|
||||
generation: ticket.generation,
|
||||
durable: ticket.durable,
|
||||
archive_rank: ticket.archive_rank,
|
||||
});
|
||||
self.pending_saves.push(ticket);
|
||||
}
|
||||
Ok(saves)
|
||||
}
|
||||
|
||||
/// One transition and what the legacy loop does at the boundary it reaches, in the declared
|
||||
/// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the
|
||||
/// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save
|
||||
/// after it, then the interval saves (`checkpoint_if_due`).
|
||||
pub async fn advance(&mut self) -> Result<(Step, Vec<SaveQueued>), String> {
|
||||
let report = match self.coordinator.step().await {
|
||||
Ok(report) => report,
|
||||
Err(e) => {
|
||||
// The legacy writer already has the saves of the earlier boundaries: hand the
|
||||
// begun captures over before reporting the failure (TASK-01 review R2-1).
|
||||
let flushed = self.flush_captures().await.err();
|
||||
let mut message =
|
||||
format!("step ({} at {}): {}", e.detail, e.phase, e.error.message);
|
||||
if let Some(flush) = flushed {
|
||||
message.push_str(&format!("; and the pending saves: {flush}"));
|
||||
}
|
||||
return Err(message);
|
||||
}
|
||||
};
|
||||
// The captures begun at the last boundary: the agent sealed its payload while this
|
||||
// transition's Prepare ticked.
|
||||
let saves = self.flush_captures().await?;
|
||||
if self.checkpointer.is_some() {
|
||||
let rank = self.task.rank();
|
||||
let ms = self.task.brain_ms();
|
||||
let change = self
|
||||
.checkpointer
|
||||
.as_mut()
|
||||
.expect("attached")
|
||||
.observe_rank(rank, ms);
|
||||
if let Some(RankChange::Climbed(rank)) = change {
|
||||
self.begin_save(SaveKind::Milestone(rank)).await?;
|
||||
}
|
||||
}
|
||||
let rolled_back = self
|
||||
.coordinator
|
||||
.apply_pending_rollback()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"rollback ({} at {}): {}",
|
||||
e.detail, e.phase, e.error.message
|
||||
)
|
||||
})?;
|
||||
if self.checkpointer.is_some() {
|
||||
if rolled_back {
|
||||
self.begin_save(SaveKind::Durable).await?;
|
||||
}
|
||||
let due = self
|
||||
.checkpointer
|
||||
.as_mut()
|
||||
.expect("attached")
|
||||
.due(Instant::now());
|
||||
if let Some(kind) = due {
|
||||
self.begin_save(kind).await?;
|
||||
}
|
||||
}
|
||||
Ok((
|
||||
Step {
|
||||
report,
|
||||
details: self.coordinator.take_details(),
|
||||
records: self.task.take_records(),
|
||||
},
|
||||
saves,
|
||||
))
|
||||
}
|
||||
|
||||
/// One transition, with its details when recorded ([`LegacySession::advance`] without the
|
||||
/// saves it reports).
|
||||
pub async fn step(&mut self) -> Result<Step, String> {
|
||||
self.advance().await.map(|(step, _)| step)
|
||||
}
|
||||
|
||||
/// A durable save, as the legacy loop takes on shutdown, then the store's writer is closed.
|
||||
pub async fn shutdown_save(&mut self) -> Result<Option<SaveReport>, String> {
|
||||
if self.checkpointer.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
self.flush_captures().await?;
|
||||
let report = self.save(SaveKind::Durable).await?;
|
||||
let outcomes = self.completed_saves(true).await;
|
||||
if let Some(checkpointer) = self.checkpointer.as_mut() {
|
||||
checkpointer.close();
|
||||
}
|
||||
// Every queued save has been waited for; the first failure is the shutdown's.
|
||||
for outcome in outcomes {
|
||||
outcome?;
|
||||
}
|
||||
Ok(Some(report))
|
||||
}
|
||||
|
||||
pub async fn stop(mut self) {
|
||||
self.launcher.reap_all(&id("done")).await;
|
||||
}
|
||||
}
|
||||
79
services/flysim/crates/fly-legacy-session/src/driver.rs
Normal file
79
services/flysim/crates/fly-legacy-session/src/driver.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
//! A stub readout for parity runs that must earn real rewards: the rotation driver of flysim's ROM
|
||||
//! tests (`tests/rom_catch.rs`, `tests/rom_macros_mode.rs`) -- a decoder of its own, fed rates
|
||||
//! that lean on one macro population at a time, rotating every [`BURST_FRAMES`] frames.
|
||||
//!
|
||||
//! The brain still ticks and decodes exactly as it would; the driver only replaces the decision
|
||||
//! the executor is handed, at the one point the legacy loop lets a harness do that
|
||||
//! (`flysim::frame::FrameObserver::readout`). A session run hands the same driver the same
|
||||
//! `(ms, bound)` in its executor ([`crate::task::PokeredTask::set_driver`]), so both arms press the
|
||||
//! same macros and the rewards those macros earn reach `Agent.Commit`. Not a service path.
|
||||
|
||||
use flybrain_core::decoder::PopulationDecoder;
|
||||
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||
use flybrain_core::ordered::NumberMap;
|
||||
|
||||
/// Frames the stub leans on one channel before the rotation moves on (`rom_catch.rs`).
|
||||
pub const BURST_FRAMES: u32 = 24;
|
||||
/// The hot population's rate, and every other one's (`rom_catch.rs`).
|
||||
const HOT: f64 = 16.0;
|
||||
const REST: f64 = 10.0;
|
||||
|
||||
/// Replaces a decision, given the brain clock and the scene's bound channels.
|
||||
pub trait DecisionDriver: Send {
|
||||
fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec<String>);
|
||||
}
|
||||
|
||||
/// The rotation: one macro population hot at a time, in channel order.
|
||||
pub struct RotationDriver {
|
||||
decoder: PopulationDecoder,
|
||||
channels: Vec<&'static str>,
|
||||
frame: u32,
|
||||
}
|
||||
|
||||
impl Default for RotationDriver {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl RotationDriver {
|
||||
pub fn new() -> RotationDriver {
|
||||
let channels = flybrain_gb::macro_channels(crate::task::GAME);
|
||||
let mut decoder = PopulationDecoder::new(gameboy_decoder_config_with_macros(&channels))
|
||||
.expect("the preset is well formed");
|
||||
decoder.calibrate(&rates(&channels, None));
|
||||
RotationDriver {
|
||||
decoder,
|
||||
channels,
|
||||
frame: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rates(channels: &[&str], hot: Option<&str>) -> NumberMap {
|
||||
let mut rates = NumberMap::new();
|
||||
for channel in channels {
|
||||
rates.set(channel, REST);
|
||||
}
|
||||
for bucket in 0..8 {
|
||||
rates.set(&format!("command_{bucket}"), REST);
|
||||
}
|
||||
if let Some(channel) = hot {
|
||||
rates.set(channel, HOT);
|
||||
}
|
||||
rates
|
||||
}
|
||||
|
||||
impl DecisionDriver for RotationDriver {
|
||||
fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec<String>) {
|
||||
let hot = self.channels[(self.frame / BURST_FRAMES) as usize % self.channels.len()];
|
||||
self.frame += 1;
|
||||
*active = self.decoder.decode_bound(
|
||||
&rates(&self.channels, Some(hot)),
|
||||
ms,
|
||||
false,
|
||||
None,
|
||||
Some(bound),
|
||||
);
|
||||
}
|
||||
}
|
||||
143
services/flysim/crates/fly-legacy-session/src/import.rs
Normal file
143
services/flysim/crates/fly-legacy-session/src/import.rs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
//! A FLYSIM01 checkpoint as a session's start: the legacy fly's own save, installed into the new
|
||||
//! runtime through the ordinary group restore (`Coordinator::import`).
|
||||
//!
|
||||
//! The halves are STATE-02's (`fly_session::legacy_checkpoint`): the world as ENV-01's `FLYENV01`
|
||||
//! payload at `k = emulatorFrame - 1` with the ratchet's snapshot as slot `best`; the agent as its
|
||||
//! `FLYAGT01` payload with the file's reinforcement count and the file's framebuffer as the next
|
||||
//! input, as `LegacyFrame::restore` installs it; the task as `{reward, ratchet, slotFilled}`. The ids
|
||||
//! come from the file (`flysim01-g<generation>`, source scope `(session, legacy, k)`).
|
||||
//!
|
||||
//! The rest is `restore: legacy-transient-reset` (`legacy-gameboy-v1` section 14): the executor
|
||||
//! starts fresh and observes the restored boundary, and the agent's readout transient starts as a
|
||||
//! fresh process has it. The decision context the agent resumes with is computed here, from the
|
||||
//! task's ledger and the checkpoint's own memory image. After the install the coordinator holds the
|
||||
//! task to it: `Task::restored` re-observes the restored world and must derive the same context.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use fly_session::coordinator::{Coordinator, ImportSpec, ImportedAgent};
|
||||
use fly_session::legacy_agent::legacy_remainder_to_rational;
|
||||
use fly_session::legacy_checkpoint::{
|
||||
AgentImport, agent_payload, halves, import_checkpoint_id, legacy_source_scope, world_payload,
|
||||
};
|
||||
use fly_session::types::*;
|
||||
use flybrain_gb::{DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, MemoryImage};
|
||||
use flysim::store::Checkpoint;
|
||||
|
||||
use crate::task::PokeredTask;
|
||||
|
||||
/// What an import installed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Imported {
|
||||
pub boundary: u64,
|
||||
pub epoch: Id,
|
||||
pub brain_ticks: u64,
|
||||
pub checkpoint_id: Id,
|
||||
/// The file's `rankSinceMs` and generation, for the host's rank tracking and store.
|
||||
pub rank_since_ms: f64,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
/// The checkpoint's memory image at its boundary, read as the environment reads it after an
|
||||
/// import: the emulator state imported into a stopped emulator, then MEM-01's one bulk read.
|
||||
pub fn image_of(rom: &[u8], emulator_state: &[u8]) -> Result<MemoryImage, String> {
|
||||
let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
|
||||
.map_err(|e| format!("the cartridge: {e}"))?;
|
||||
emulator
|
||||
.import_state(emulator_state)
|
||||
.map_err(|e| format!("the emulator state: {e}"))?;
|
||||
Ok(emulator.read_memory_image())
|
||||
}
|
||||
|
||||
/// Installs a FLYSIM01 checkpoint as the start of a bootstrapped session that has taken no
|
||||
/// transition, onto a replacement world. `task` is the composition's task object.
|
||||
pub async fn import_flysim01(
|
||||
coordinator: &mut Coordinator,
|
||||
task: &PokeredTask,
|
||||
checkpoint: &Checkpoint,
|
||||
rom: &[u8],
|
||||
agent: &AgentImport,
|
||||
audio_sample_rate: u64,
|
||||
new_epoch: &Id,
|
||||
) -> Result<Imported, String> {
|
||||
let descriptor = coordinator
|
||||
.descriptor()
|
||||
.cloned()
|
||||
.ok_or("the session never bootstrapped")?;
|
||||
let halves = halves(
|
||||
checkpoint,
|
||||
coordinator.episode_id(),
|
||||
&id(crate::task::SLOT),
|
||||
audio_sample_rate,
|
||||
)?;
|
||||
let boundary = halves.world.boundary;
|
||||
let checkpoint_id = import_checkpoint_id(halves.host.generation);
|
||||
let scope = legacy_source_scope(coordinator.session_id(), boundary);
|
||||
let world = world_payload(
|
||||
&halves.world,
|
||||
&coordinator.environment_ref().worker_id,
|
||||
&checkpoint_id,
|
||||
&scope,
|
||||
&descriptor.configuration_digest,
|
||||
);
|
||||
|
||||
// The task's ledger, and from it and the restored image the context the agent resumes with.
|
||||
let (ledger, task_attachments) =
|
||||
PokeredTask::ledger_of(&halves.task, !checkpoint.runtime.ratchet_game.is_empty())
|
||||
.map_err(|e| format!("the task ledger: {}", e.message))?;
|
||||
let brain_ms = halves.agent.network.ms;
|
||||
// `Sim::boot` seeds the palette from the restored brain's RNG state.
|
||||
task.set_palette_seed(halves.agent.network.rng as u32);
|
||||
let image = image_of(rom, &halves.world.emulator)?;
|
||||
let context = task.preview_context(&ledger, &task_attachments, &image, brain_ms)?;
|
||||
let payload = agent_payload(
|
||||
&halves.agent,
|
||||
halves.reinforcements,
|
||||
&checkpoint.runtime.framebuffer,
|
||||
agent,
|
||||
&checkpoint_id,
|
||||
&scope,
|
||||
&context,
|
||||
)?;
|
||||
let remainder = legacy_remainder_to_rational(halves.agent.remainder)
|
||||
.map_err(|e| format!("the remainder: {e}"))?;
|
||||
let audio_positions: BTreeMap<String, u64> = descriptor
|
||||
.audio
|
||||
.iter()
|
||||
.map(|stream| (stream.stream_id.clone(), halves.world.audio_next_sample))
|
||||
.collect();
|
||||
let spec = ImportSpec {
|
||||
checkpoint_id: checkpoint_id.clone(),
|
||||
source_scope: scope,
|
||||
boundary,
|
||||
world_payload: world,
|
||||
agents: vec![ImportedAgent {
|
||||
agent_id: agent.agent_id.clone(),
|
||||
payload,
|
||||
brain_ticks: brain_ms as u64,
|
||||
remainder,
|
||||
context,
|
||||
}],
|
||||
task_ledger: ledger,
|
||||
task_attachments,
|
||||
audio_positions,
|
||||
};
|
||||
coordinator
|
||||
.import(spec, new_epoch)
|
||||
.await
|
||||
.map_err(|e| format!("the import ({}): {}", e.detail, e.error.message))?;
|
||||
coordinator
|
||||
.resume()
|
||||
.map_err(|e| format!("resuming the import: {}", e.error.message))?;
|
||||
// The joypad on the restored boundary, as the legacy `LegacyFrame::restore` installs it: what
|
||||
// a feed header reports until the executor applies its first mask (SERVE-01).
|
||||
task.set_mask(checkpoint.runtime.buttons);
|
||||
Ok(Imported {
|
||||
boundary,
|
||||
epoch: new_epoch.clone(),
|
||||
brain_ticks: brain_ms as u64,
|
||||
checkpoint_id,
|
||||
rank_since_ms: halves.host.rank_since_ms,
|
||||
generation: halves.host.generation,
|
||||
})
|
||||
}
|
||||
25
services/flysim/crates/fly-legacy-session/src/lib.rs
Normal file
25
services/flysim/crates/fly-legacy-session/src/lib.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
//! The live fly on the session framework (TASK-01).
|
||||
//!
|
||||
//! - [`task`]: `pokered-macros-v1`, the Pokémon Red task and its action executor as one object,
|
||||
//! running the legacy macro engine and reward adapter unchanged over the boundary memory image.
|
||||
//! - [`composition`]: the legacy agent, the legacy environment and the task under one coordinator.
|
||||
//! - [`import`]: a FLYSIM01 checkpoint as the session's start.
|
||||
//! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused.
|
||||
//! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison.
|
||||
//! - [`driver`]: a stub readout for parity runs that must earn rewards.
|
||||
//! - [`service`]: the composition as the live service behind flysim's listeners (SERVE-01),
|
||||
//! the `flysim-session` binary.
|
||||
//! - [`shadow`]: SHADOW-01, the session runtime following the live fly's trace, the comparator and
|
||||
//! the verdict CUT-01 reads.
|
||||
//!
|
||||
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
|
||||
//! TASK-01 the record.
|
||||
|
||||
pub mod admission;
|
||||
pub mod composition;
|
||||
pub mod driver;
|
||||
pub mod import;
|
||||
pub mod service;
|
||||
pub mod shadow;
|
||||
pub mod task;
|
||||
pub mod trace;
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue