swactor/apps/myelin/src/observability/provisioning_logs.rs

181 lines
5.5 KiB
Rust
Raw Normal View History

use std::io::{BufRead, BufReader, Read};
use std::thread::{self, JoinHandle};
use datastream::{ChannelContent, DatastreamProducer, Lifetime, NodeId, StreamId};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::observability::telemetry::{
MYELIN_PROVISIONING_LOGS, MyelinProvisionLogRecord, myelin_provision_log_channel,
};
refactor: prune public api Collapse mvp-system's public surface to three binary entrypoints and make every domain module private, deleting dead provider/worker/membership implementations and inlining provider config. - lib.rs: expose only run_chat_from_args/run_orchestrator_from_args/run_worker_node_from_env (plus a crate-private in-process helper) and the cached-model consts, and demote chat/node/observability/orchestration/prompt/staging/transport to private mods - orchestration/mod.rs: make app private, gate engine_builder behind cfg(test), drop docker_cluster from provider_adapters, tighten vastai to pub(super), and replace pub re-exports with pub(super) run_from_args/run_in_process_from_args - orchestration/config.rs: inline VastAiConfig/ResolvedVastAiConfig/looks_remote_image (removing provider_adapters/vastai/config.rs) and drop the DEFAULT_PIPELINE_CACHED_MODEL_* consts (hoisted to lib.rs) - orchestration/provider_adapters/vastai: delete the ProviderPlugin impl VastAiProviderPlugin and all client/bootstrap/config accessors; repoint call sites to crate-level #[path] mods for provisioning/node_provisioning/node_actor/gguf_shard/run_fsm/run_plan - delete orchestration/{membership_readiness,token_endpoint,resource_inventory}, node/{boot_lifecycle,data_plane_bridge(-74)}, and the worker crate-internal modules (control/device_bridge/process_adapter) along with their guarantees tests - chat/node: narrow node_image and worker_node_runtime to private and expose only pub(super) run_from_args / run_worker_node_from_env Signed-off-by: Zachery Aaron Shores-Chmielewski <zacheryasc@gmail.com>
2026-07-29 10:02:50 +00:00
use crate::provisioning::{
NodeProvisionSpec, PluginObservation, PluginSink, ProvisionLogLine, ProvisionLogStream,
};
pub(crate) fn node_stream_id(run_id: u64, node_id: u64) -> StreamId {
StreamId::new(NodeId::new(&node_id.to_string()), Lifetime(run_id))
}
#[derive(Clone)]
pub(crate) struct BootstrapDatastreamBridge {
spec: NodeProvisionSpec,
sink: PluginSink,
producer: Option<DatastreamProducer>,
}
impl BootstrapDatastreamBridge {
pub(crate) fn new(
spec: NodeProvisionSpec,
sink: PluginSink,
producer: Option<DatastreamProducer>,
) -> Self {
Self {
spec,
sink,
producer,
}
}
pub(crate) fn spec(&self) -> &NodeProvisionSpec {
&self.spec
}
pub(crate) fn observe_stdout_line(&self, line: impl Into<String>) {
let line = line.into();
if let Some(frame) = parse_stdio_datastream_frame(&self.spec, &line) {
self.sink.observe(frame);
return;
}
self.submit_log(ProvisionLogStream::Stdout, &line);
self.sink.observe(PluginObservation::StdoutLine {
run_id: self.spec.run_id,
node_id: self.spec.node_id,
line: line.clone(),
});
}
pub(crate) fn observe_stderr_line(&self, line: impl Into<String>) {
let line = line.into();
self.submit_log(ProvisionLogStream::Stderr, &line);
self.sink.observe(PluginObservation::StderrLine {
run_id: self.spec.run_id,
node_id: self.spec.node_id,
line,
});
}
pub(crate) fn observe_provider_line(&self, line: impl Into<String>) {
let line = line.into();
self.submit_log(ProvisionLogStream::Provider, &line);
self.sink.observe(PluginObservation::ProviderLine {
run_id: self.spec.run_id,
node_id: self.spec.node_id,
line,
});
}
feat(engine): substrate-neutral execution engine abstraction Introduce the swactor engine: a swactor-owned composite that retains a selected execution substrate, drives the core runtime, and hosts the async/blocking/timer work that backs actors. Integrations receive one cloneable EngineHandle and never construct or borrow a raw Tokio runtime/handle. Engine crate (crates/engine): - The contract: spawn / spawn_blocking / timer / interval / now, a per-implementation capability model with construction-time binding (require()), and engine-owned time. The engine owns all progression; actor handlers stay synchronous and never .await. - TokioBackend owns the Tokio runtime and schedules core ticks and supporting futures on it; SteppingBackend is a single-threaded deterministic scheduler with virtual time (the non-Tokio portability proof). Core is driven through its existing tick() surface; a self-rescheduling CoreDriver is installed at construction and is the sole place permitted to call try_tick. iroh-driver: - Receives an EngineHandle instead of a raw Tokio Handle. Accepts, reads, dials, writes, endpoint construction, and teardown schedule through it; required capabilities (tasks/timers/io) are validated before the endpoint binds. Engine-hosted interval pumps drive actor-bridge, datastream, and edge ingress. myelin: - One node/orchestrator engine owns core, protocol tick injection, and transport progression; the application loop only drains integration-owned queues. Stage-shard process readers, delayed actor messages, helper stdout/stderr, prompt RPC, and CPU sampling all schedule through the engine (spawn_blocking / engine tasks / timers). - Removed the split-engine APIs: install_actor_bridge_pump(period) and spawn_protocol_ticker(period) use each component's stored engine; deleted the no-op pump_network callback and its plumbing; deleted the dashboard raw-Tokio/standalone-runtime conveniences. Enforcement: - A clippy disallowed-methods boundary forbids direct runtime/scheduling/ time/core-driving bypasses, denied in swactor-engine, iroh-driver, and myelin. Retained excluded uses (VastAI provider, provider process supervision/log capture, OS-signal/stdin/process-control sequencing) carry narrow allowances with reasons. Verification: - Engine contract + unit tests (incl. the SteppingBackend portability proof), iroh integration tests (capability rejection before binding, multi-node actor behavior), and a production execution-composition smoke test that observes engine-driven actor progress with no ambient Tokio runtime and no manual tick/pump. Workspace all-target/all-feature clippy and tests are green. Specs co-located with their crates: ENGINE_SPEC.md in crates/engine, IROH_DRIVER_SPEC.md in crates/iroh-driver. VastAI remains explicitly out of scope pending its separate redesign.
2026-08-10 20:23:03 +00:00
// provider log capture is out of scope (ENGINE_SPEC.md §2)
#[allow(clippy::disallowed_methods)]
pub(crate) fn spawn_stdout_reader<R>(&self, stdout: R) -> JoinHandle<()>
where
R: Read + Send + 'static,
{
let bridge = self.clone();
thread::spawn(move || bridge.read_stdout(stdout))
}
feat(engine): substrate-neutral execution engine abstraction Introduce the swactor engine: a swactor-owned composite that retains a selected execution substrate, drives the core runtime, and hosts the async/blocking/timer work that backs actors. Integrations receive one cloneable EngineHandle and never construct or borrow a raw Tokio runtime/handle. Engine crate (crates/engine): - The contract: spawn / spawn_blocking / timer / interval / now, a per-implementation capability model with construction-time binding (require()), and engine-owned time. The engine owns all progression; actor handlers stay synchronous and never .await. - TokioBackend owns the Tokio runtime and schedules core ticks and supporting futures on it; SteppingBackend is a single-threaded deterministic scheduler with virtual time (the non-Tokio portability proof). Core is driven through its existing tick() surface; a self-rescheduling CoreDriver is installed at construction and is the sole place permitted to call try_tick. iroh-driver: - Receives an EngineHandle instead of a raw Tokio Handle. Accepts, reads, dials, writes, endpoint construction, and teardown schedule through it; required capabilities (tasks/timers/io) are validated before the endpoint binds. Engine-hosted interval pumps drive actor-bridge, datastream, and edge ingress. myelin: - One node/orchestrator engine owns core, protocol tick injection, and transport progression; the application loop only drains integration-owned queues. Stage-shard process readers, delayed actor messages, helper stdout/stderr, prompt RPC, and CPU sampling all schedule through the engine (spawn_blocking / engine tasks / timers). - Removed the split-engine APIs: install_actor_bridge_pump(period) and spawn_protocol_ticker(period) use each component's stored engine; deleted the no-op pump_network callback and its plumbing; deleted the dashboard raw-Tokio/standalone-runtime conveniences. Enforcement: - A clippy disallowed-methods boundary forbids direct runtime/scheduling/ time/core-driving bypasses, denied in swactor-engine, iroh-driver, and myelin. Retained excluded uses (VastAI provider, provider process supervision/log capture, OS-signal/stdin/process-control sequencing) carry narrow allowances with reasons. Verification: - Engine contract + unit tests (incl. the SteppingBackend portability proof), iroh integration tests (capability rejection before binding, multi-node actor behavior), and a production execution-composition smoke test that observes engine-driven actor progress with no ambient Tokio runtime and no manual tick/pump. Workspace all-target/all-feature clippy and tests are green. Specs co-located with their crates: ENGINE_SPEC.md in crates/engine, IROH_DRIVER_SPEC.md in crates/iroh-driver. VastAI remains explicitly out of scope pending its separate redesign.
2026-08-10 20:23:03 +00:00
// provider log capture is out of scope (ENGINE_SPEC.md §2)
#[allow(clippy::disallowed_methods)]
pub(crate) fn spawn_stderr_reader<R>(&self, stderr: R) -> JoinHandle<()>
where
R: Read + Send + 'static,
{
let bridge = self.clone();
thread::spawn(move || bridge.read_stderr(stderr))
}
fn read_stdout<R>(&self, stdout: R)
where
R: Read,
{
let reader = BufReader::new(stdout);
for next in reader.lines() {
match next {
Ok(line) => self.observe_stdout_line(line),
Err(error) => {
self.sink.observe(PluginObservation::Failed {
run_id: self.spec.run_id,
node_id: self.spec.node_id,
reason: format!("read stdout: {error}"),
});
break;
}
}
}
}
fn read_stderr<R>(&self, stderr: R)
where
R: Read,
{
let reader = BufReader::new(stderr);
for next in reader.lines() {
match next {
Ok(line) => self.observe_stderr_line(line),
Err(error) => {
self.sink.observe(PluginObservation::Failed {
run_id: self.spec.run_id,
node_id: self.spec.node_id,
reason: format!("read stderr: {error}"),
});
break;
}
}
}
}
fn submit_log(&self, stream: ProvisionLogStream, line: &str) {
let Some(producer) = &self.producer else {
return;
};
let record = MyelinProvisionLogRecord::new(ProvisionLogLine {
run_id: self.spec.run_id,
node_id: self.spec.node_id,
stream,
line: line.to_owned(),
});
let channel = producer.register_channel(
myelin_provision_log_channel(self.spec.node_id, stream),
ChannelContent::JsonRecord {
schema: Some(MYELIN_PROVISIONING_LOGS.to_owned()),
},
);
let payload = serde_json::to_vec(&record).expect("serialize bootstrap log record");
producer.submit_bytes(channel, payload);
}
}
#[derive(Deserialize, Serialize)]
struct StdioDatastreamFrame {
myelin_stdio_event: u32,
kind: String,
channel: String,
payload: Value,
}
pub(crate) fn parse_stdio_datastream_frame(
spec: &NodeProvisionSpec,
line: &str,
) -> Option<PluginObservation> {
let frame = serde_json::from_str::<StdioDatastreamFrame>(line).ok()?;
if frame.myelin_stdio_event != 1 || frame.kind != "datastream_frame" {
return None;
}
Some(PluginObservation::DatastreamFrame {
run_id: spec.run_id,
node_id: spec.node_id,
channel: frame.channel,
payload: frame.payload.to_string(),
})
}