fly-session: what a service host needs from the session

- Legacy.FeedStatus (capability legacy-feed-status-v1): the legacy agent's
  read-only feed status at a committed boundary -- rates, pulse, the whole
  plasticity statistics and the decoder's baselines/scores -- which no
  session message carries and the legacy header and /status report.
- Coordinator::read_agent_extension (never fences), media_bytes (the
  committed view/audio chunk), digest_views (off for a host that reads the
  details only for commit attachments), trim_records (the trace, phase log,
  audit and injection log grew with every transition: ~120 KB/s on the live
  fly), and timings for the feed status and the per-step publication.
This commit is contained in:
acamilo 2026-09-29 20:31:13 +00:00
parent 95614122a9
commit 4fcd9233c7
3 changed files with 186 additions and 2 deletions

View file

@ -367,6 +367,9 @@ pub struct Coordinator {
commit_attachments: Vec<String>, commit_attachments: Vec<String>,
/// Record [`StepDetails`] for every transition (a parity run). /// Record [`StepDetails`] for every transition (a parity run).
record_details: bool, record_details: bool,
/// Digest every view into the step details (on with them by default; a service that reads
/// the details only for the commit attachments turns it off).
digest_views: bool,
last_details: Option<StepDetails>, last_details: Option<StepDetails>,
/// Audience admissions: queued by the edge, cut into the next Prepare. /// Audience admissions: queued by the edge, cut into the next Prepare.
admissions: AdmissionQueue, admissions: AdmissionQueue,
@ -491,6 +494,7 @@ impl Coordinator {
environment_capabilities: Vec::new(), environment_capabilities: Vec::new(),
commit_attachments: Vec::new(), commit_attachments: Vec::new(),
record_details: false, record_details: false,
digest_views: true,
last_details: None, last_details: None,
admissions: AdmissionQueue::default(), admissions: AdmissionQueue::default(),
in_flight_admissions: Vec::new(), in_flight_admissions: Vec::new(),
@ -588,6 +592,76 @@ impl Coordinator {
.collect() .collect()
} }
/// The bytes of one media attachment this committed boundary holds (a view, e.g.
/// `media::view_attachment("lcd")`, or an audio chunk, `media::audio_attachment(..)`), or
/// `None` when the boundary holds no such attachment. A read: the handle stays held.
///
/// For a host that presents the boundary itself (SERVE-01's service host, which publishes
/// the legacy feed from the committed frame and audio chunk).
pub async fn media_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, String> {
let Some(artifact) = self.views.get(name).or_else(|| self.audio.get(name)) else {
return Ok(None);
};
artifact
.read_all()
.await
.map(Some)
.map_err(|e| format!("reading {name}: {}", e.message))
}
/// One read-only extension call to an agent at the committed boundary, answered by that
/// worker's own method (`method` must be one it lists). Unlike every session operation this
/// never fences the epoch: a read that failed changed nothing, and its caller decides what
/// a missing answer means (SERVE-01: the legacy agent's `Legacy.FeedStatus`).
pub async fn read_agent_extension(
&mut self,
agent_id: &Id,
method: &'static str,
) -> Result<Value, String> {
let Phase::Ready(_) = self.phases.phase() else {
return Err(format!("{method} reads a committed Ready boundary"));
};
let Some(worker) = self.agent_ref(agent_id).cloned() else {
return Err(format!("no agent {agent_id}"));
};
let request_id = self.serials.next(&worker.service);
let started = Instant::now();
let outcome = call_owned(
self.bus.clone(),
worker,
method,
None,
Map::new(),
Vec::new(),
request_id,
Vec::new(),
self.deadlines.probe,
)
.await;
self.metrics.record(method, started.elapsed());
match outcome {
CallOutcome::Answered(reply) => reply
.result()
.cloned()
.map_err(|e| format!("{method}: {}", e.message)),
CallOutcome::Refused(e) => Err(format!("{method}: {}", e.message)),
CallOutcome::Expired => Err(format!("{method}: no reply within the probe deadline")),
}
}
/// Bounds the session's in-memory records for a host that runs for days (SERVE-01's service):
/// the transition trace keeps only its last entry (a deferred rollback amends that one), and
/// the phase trace, the audit and the injection log are emptied. Every one of them otherwise
/// grows with every transition. A parity run or a test that reads them never calls this.
pub fn trim_records(&mut self) {
let last = self.trace.transitions.pop();
self.trace.transitions.clear();
self.trace.transitions.extend(last);
self.trace.phases.clear();
self.audit.clear();
self.injection_log.clear();
}
/// Where each declared audio stream's next chunk may start. /// Where each declared audio stream's next chunk may start.
pub fn audio_positions(&self) -> BTreeMap<String, u64> { pub fn audio_positions(&self) -> BTreeMap<String, u64> {
self.timelines.positions() self.timelines.positions()
@ -741,6 +815,13 @@ impl Coordinator {
self.record_details = on; self.record_details = on;
} }
/// Whether recorded step details carry each view's SHA-256 (`StepDetails::view_digests`):
/// on by default; SERVE-01's service host reads the details for the commit attachments only
/// and turns it off, which saves hashing every frame.
pub fn digest_views(&mut self, on: bool) {
self.digest_views = on;
}
/// The details of the last completed transition, when they are recorded. /// The details of the last completed transition, when they are recorded.
pub fn take_details(&mut self) -> Option<StepDetails> { pub fn take_details(&mut self) -> Option<StepDetails> {
self.last_details.take() self.last_details.take()
@ -2305,7 +2386,7 @@ impl Coordinator {
self.admissions.set_remaining(agent_id, result.telemetry.stimulus_remaining_ms); self.admissions.set_remaining(agent_id, result.telemetry.stimulus_remaining_ms);
} }
let view_digests = if self.record_details { let view_digests = if self.record_details && self.digest_views {
self.view_digests(&step_result.observation).await? self.view_digests(&step_result.observation).await?
} else { } else {
Vec::new() Vec::new()
@ -2372,8 +2453,10 @@ impl Coordinator {
slot.prepared = None; slot.prepared = None;
slot.prepare_request = None; slot.prepare_request = None;
} }
let publishing = Instant::now();
self.publish_events(k + 1, &evaluation.events).await?; self.publish_events(k + 1, &evaluation.events).await?;
self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?;
self.metrics.record("publish", publishing.elapsed());
// A rollback request was applied above and is not an episode end; only a terminal one // A rollback request was applied above and is not an episode end; only a terminal one
// pauses the session for the episode policy. // pauses the session for the episode policy.
@ -3163,7 +3246,7 @@ impl Coordinator {
} }
// Step 5: every reply in hand. The session is at Ready(e', k). // Step 5: every reply in hand. The session is at Ready(e', k).
let view_digests = if self.record_details { let view_digests = if self.record_details && self.digest_views {
let mut out = Vec::new(); let mut out = Vec::new();
for view in &restored.sensory_views { for view in &restored.sensory_views {
let name = media::view_attachment(&view.view_id); let name = media::view_attachment(&view.view_id);

View file

@ -84,6 +84,19 @@ pub const SPIKES_ATTACHMENT: &str = "telemetry.spikes";
/// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes: /// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes:
/// the legacy feed's `spike_bitset` layout. /// the legacy feed's `spike_bitset` layout.
pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset"; pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset";
/// The legacy agent's read-only feed status (SERVE-01), and the capability that advertises it.
///
/// The legacy feed header and `GET /status` carry numbers from inside the network that no
/// session-framework message carries: the plasticity rule's whole statistics (`learning.changed`
/// counts synapses whose gain moved, `learning.synapses` the rule's edges), the decoder's
/// per-channel baseline and last score, and the rates and pulse as they stand at the committed
/// boundary. The session runtime's service host reads them here, once per published snapshot, at a
/// committed `Ready(k)`, which is where the legacy loop reads them for its own publish. It is a
/// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is
/// answered in any phase once initialized, and is not in any trace.
pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus";
pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1";
/// The one stimulus kind the profile supports. /// The one stimulus kind the profile supports.
pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE; pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE;
@ -543,6 +556,66 @@ pub fn telemetry_of(agent: &NeuralAgent, brain_ticks: u64, reinforcements: u64)
} }
} }
/// A finite number for JSON: the legacy header's `finite`, applied before the value is sent.
fn finite_or_zero(value: f64) -> f64 {
if value.is_finite() { value } else { 0.0 }
}
/// The [`METHOD_FEED_STATUS`] result: exactly what the legacy loop's `publish` and
/// `publish_decoder_status` read from the network, in the network's own order.
///
/// ```text
/// { brainMs, rates: [[role, hz], ...], populationRate, rewardRemainingMs,
/// learning: { enabled, updates, changed, synapses, signal },
/// decoder: { calibrated, pending: [...], channels: [{channel, role, baseline, score}] } }
/// ```
///
/// Rates are pairs rather than an object so their order survives any JSON reader. Every
/// number goes through the legacy `finite` first: JSON has no NaN, and the header would have
/// written 0 for one anyway.
pub fn feed_status_of(agent: &NeuralAgent) -> Value {
let network = &agent.network;
let stats = network.plasticity.statistics();
let decoder = &agent.decoder;
let scores = decoder.last_scores();
let baselines = decoder.baselines();
let rates: Vec<Value> = network
.rates
.iter()
.map(|(name, hz)| json!([name, finite_or_zero(hz)]))
.collect();
let channels: Vec<Value> = decoder
.channel_roles()
.into_iter()
.map(|(channel, role)| {
json!({
"channel": channel,
"role": role,
"baseline": finite_or_zero(baselines.get_or_zero(role)),
"score": finite_or_zero(scores.get_or_zero(channel)),
})
})
.collect();
json!({
"brainMs": finite_or_zero(network.ms),
"rates": rates,
"populationRate": finite_or_zero(network.population_rate),
"rewardRemainingMs": finite_or_zero(network.reward_remaining()),
"learning": {
"enabled": stats.enabled,
"updates": finite_or_zero(stats.updates),
"changed": stats.changed,
"synapses": stats.synapses,
"signal": finite_or_zero(stats.signal),
},
"decoder": {
"calibrated": decoder.calibrated(),
"pending": decoder.pending_baseline_roles(),
"channels": channels,
},
})
}
/// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS` /// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS`
/// order, and the first bound channel the decode holds, which is exactly the channel the legacy /// order, and the first bound channel the decode holds, which is exactly the channel the legacy
/// macro layer's `asked` would start. /// macro layer's `asked` would start.
@ -816,6 +889,28 @@ impl LegacyAgentWorker {
telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements) telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements)
} }
// ---------------------------------------------------------------------------------------
// Legacy.FeedStatus (SERVE-01)
/// The network as the legacy loop's `publish` reads it, at the committed boundary.
fn feed_status(&self) -> DomainResult<HandlerReply> {
let Some(agent) = self.agent.as_ref() else {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"Legacy.FeedStatus needs an initialized agent",
));
};
if matches!(self.phase, AgentPhase::Prepared(_) | AgentPhase::Failed) {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"Legacy.FeedStatus reads a committed boundary",
));
}
let mut reply = HandlerReply::new(object(feed_status_of(agent)));
reply.mutated = false;
Ok(reply)
}
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
// Agent.Initialize // Agent.Initialize
@ -1724,6 +1819,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
id("pixel-observation-v1"), id("pixel-observation-v1"),
id(crate::state::CHECKPOINT_CAPABILITY), id(crate::state::CHECKPOINT_CAPABILITY),
id(ROLLBACK_CAPABILITY), id(ROLLBACK_CAPABILITY),
id(FEED_STATUS_CAPABILITY),
] ]
} }
@ -1744,6 +1840,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
"State.Capture", "State.Capture",
"State.StageRestore", "State.StageRestore",
"State.ActivateRestore", "State.ActivateRestore",
METHOD_FEED_STATUS,
] ]
} }
@ -1757,6 +1854,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
"State.Capture" => self.state_capture(&ctx).await, "State.Capture" => self.state_capture(&ctx).await,
"State.StageRestore" => self.state_stage_restore(&ctx).await, "State.StageRestore" => self.state_stage_restore(&ctx).await,
"State.ActivateRestore" => self.state_activate_restore(&ctx).await, "State.ActivateRestore" => self.state_activate_restore(&ctx).await,
METHOD_FEED_STATUS => self.feed_status(),
other => Err(DomainError::before( other => Err(DomainError::before(
ErrorCode::Unsupported, ErrorCode::Unsupported,
format!("{other} is not an agent method"), format!("{other} is not an agent method"),

View file

@ -627,6 +627,9 @@ fn classify_default(method: &str) -> Option<OpClass> {
"Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => { "Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => {
Some(OpClass::ReadOnly) Some(OpClass::ReadOnly)
} }
// The legacy agent's feed status (SERVE-01): a read of the committed boundary that
// changes nothing, so a duplicate simply reads again.
crate::legacy_agent::METHOD_FEED_STATUS => Some(OpClass::ReadOnly),
_ => None, _ => None,
} }
} }