Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,6 @@ jobs:
workspaces: runtime/noded
- name: Run the canonical repository check
run: bash scripts/check.sh
- name: Qualify relay-only packet filtering in isolated Linux namespaces
run: |
sudo apt-get install --yes nftables iptables iproute2
sudo env UCLOUD_RUN_NETNS_TESTS=1 PYTHONPATH="$PWD" \
"$(command -v python)" tests/test_relay_network_linux.py
- name: Run the Docker Distribution contract
run: |
docker run --detach --name ucloud-test-registry \
Expand Down
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

- `sandboxes/`: the Python package. CLI (`cli.py`); gateway
(`control_plane.py`, `gateway/`); shared state on PostgreSQL (`shared_control/`,
`routing.py`); node agent (`node_agent.py`, `direct_*.py`); images and chunk store
`routing.py`); builder agent (`builder_agent.py`) and VM bootstrap (`vm_init.py`,
`standalone_noded_config.py`); images and chunk store
(`environment_*.py`, `chunk_*.py`); model relay (`model_relay.py`); providers.
- `runtime/noded/`: `ucloud-noded`, the Rust node daemon.
- `runtime/noded/`: `ucloud-noded`, the standalone Rust sandbox node daemon.
- `runtime/managed_process/`, `runtime/chunk_serve/`: Go components.
- `runtime/gvisor/`, `runtime/storage_native/`, `runtime/nydusd/`: pinned upstream
builds and patches. `runtime/toolkits/`: agent toolkits.
Expand Down
54 changes: 18 additions & 36 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,9 @@ flowchart LR
**Sandbox nodes**, set up at boot by
[vm_init.py](../sandboxes/vm_init.py):

- `ucloud-sandbox-noded`, the Rust daemon `ucloud-noded`
([runtime/noded](../runtime/noded)), which owns the port, creates, execs
and the pause tier, and behind `sandbox.direct_node_standalone_rust`
runs standalone (`--standalone-config`) for every worker route without
`ucloud-sandbox-node` (see [below](#the-python-agent-and-ucloud-noded)).
- `ucloud-sandbox-node`, the legacy Python node agent (omitted when
`sandbox.direct_node_standalone_rust` is enabled). When running alongside
`ucloud-noded`, its Warden handles the remaining lifecycle routes and
heartbeats.
- `ucloud-sandbox-noded`, the standalone Rust daemon `ucloud-noded`
([runtime/noded](../runtime/noded)), launched with `--standalone-config`
as the sole sandbox worker daemon (see [below](#ucloud-noded)).
- `ucloud-storage-native`: writable volumes, memory backing, checkpoint
publication.
- `ucloud-environment-io`: serves immutable image roots from the chunk store.
Expand Down Expand Up @@ -296,36 +290,24 @@ of space mid-capture could lose it). RAM rather than disk then limits density.
Under disk pressure the node publishes parked sandboxes and the gateway
cold-offloads old published parks; after that, work is refused.

### The Python agent and ucloud-noded
### ucloud-noded

The node side began as one Python process, and under create bursts the
interpreter lock was the bound (doubling create slots changed nothing).
`ucloud-noded` took over the node in slices, each behind the same HTTP
contract and on-disk files. It owns the node's TCP port and proxies the rest
to the agent's Unix socket; the node registry and the create pipeline
(unsupported creates, such as relay egress, DNS-named egress and migration
imports, go to the agent unchanged); execs on running sandboxes and
managed-job reads, start and signal; and the pause tier: thaw-on-exec, idle
pauses, paused reclaim, escalation decisions and node-local model waits. Two
flags remain off by default: `sandbox.direct_node_rust_admission` moves the
transition ledger, slots, growth forecasts and resident sampling into
`ucloud-noded`, and `sandbox.direct_node_standalone_rust` launches
`ucloud-noded --standalone-config` as the sole sandbox worker daemon — owning
file I/O, archive upload, image pulls (with pure-Rust Ed25519 manifest
verification), RAM-backed park/wake, snapshot publication, migration,
commit-export, `/healthz`, `/v1/heartbeat` (including `storage-native` metrics),
`/v1/drain`, heartbeat pushing, and boot-time/TTL reconciliation with no Python
node agent process. The flags of the earlier slices are retired; deployment
files may still name them, as true only.

When `sandbox.direct_node_standalone_rust` is off, the Python agent still owns
heartbeats, park/wake/migration/delete with their lifecycle locks, the drain
row, and workspace growth. In that split mode the processes coordinate through
the kernel and files, not a lock manager: per-sandbox flocks fence execs
against parks, and admission claims are tokens bound to the agent's session, so
a restart of either side cannot leak or double a grant. Managed-job state sits
in a host-visible bind mount, so noded serves job status and logs without
entering, thawing or locking the guest.
`ucloud-noded` took over the node in slices behind the same HTTP contract and
on-disk files, and now runs standalone (`ucloud-noded --standalone-config`) as
the sole sandbox worker daemon — owning the TCP port, the node registry, create
and delete pipelines, execs, managed-job status/logs/start/signal, file I/O and
archive upload, image pulls (with pure-Rust Ed25519 manifest verification),
pause tier (thaw-on-exec, idle pauses, paused reclaim, escalation decisions,
node-local model waits), RAM-backed park/wake, snapshot publication, migration,
commit-export, admission and workspace growth, `/healthz`, `/v1/heartbeat`
(including `storage-native` metrics), `/v1/drain`, heartbeat pushing, and
boot-time/TTL reconciliation with no Python node agent process. Managed-job
state sits in a host-visible bind mount, so `ucloud-noded` serves job status
and logs without entering, thawing or locking the guest. The flags of the
migration slices (including `sandbox.direct_node_standalone_rust`) are retired;
deployment files may still name them, as true only.

## Managed agents and the model relay

Expand Down
2 changes: 1 addition & 1 deletion docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ automation; Hetzner Cloud is a supported alternative.
| --- | --- | --- | --- |
| Gateway VM | Operator (`submit-vm --role gateway`) | Gateway API, placement worker, model relay, private registry and its timers, autoscaler, build service, PostgreSQL 18, observability stack | `data_root`, PostgreSQL, `/etc/ucloud-sandboxes` |
| Store node | Operator, then `init-vm --role store` | Chunk store (read cache or replica over S3), optionally chunk index and `ucloud-chunk-serve` | Chunk-index database and replica cache; S3 holds the permanent copy |
| Sandbox workers | Autoscaler | gVisor Warden (`serve-direct-node-agent`), storage-native service, optional `noded` | None |
| Sandbox workers | Autoscaler | Standalone Rust `ucloud-noded`, storage-native service, environment-io service | None |
| Builders | Autoscaler | `serve-builder-agent`, Docker, Buildx | None |

Registry blobs, backups and release kits live on the project drive
Expand Down
25 changes: 6 additions & 19 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,30 @@ under [Open decisions](#open-decisions).

## Node daemon (`ucloud-noded`)

- **Flip `sandbox.direct_node_standalone_rust` to default on**, then delete the legacy
Python sandbox node daemon (`node_agent.py` direct path, `direct_service.py`,
`direct_warden.py`, `hibernation.py`, `heartbeat_sender.py`, `transition_admission.py`).
Standalone Rust `ucloud-noded --standalone-config` now implements all sandbox worker routes
(create, exec, jobs, files/archive/environment, list/delete, images/pull with pure-Rust
Ed25519 verification, RAM-only park/wake, snapshot publication, migration, commit-export,
`/healthz`, `/v1/heartbeat`, `/v1/drain`, heartbeat pusher, and boot-time/TTL reconciler),
and the builder-only HTTP server is split into `sandboxes/builder_agent.py`.
- **Create-path tails.** `runsc_create`, storage prepare (`mkfs.xfs` per create) and
registry commit set node-side create p95 (`runtime/noded/src/`: `create.rs`, `storage.rs`, `registry/`).
- **CPU QoS for background work** (`cpu.idle`/`cpu.weight` for prefetch, publication, offload, cache fill).
- **IPv6 off on the agent's relay-egress veths** (`direct_network.py`).
- **IPv6 off on relay-egress veths** (`runtime/noded/src/network.rs`).
- **Drop the retired noded flag keys** (`direct_node_front_door`, `direct_node_rust_create/exec/pause`,
`direct_pause_tier`, `direct_local_model_waits`, `direct_split_memory_backing`) from
deployment files and their true-only check in `config.py`, once no rollback to 0.10.0 is possible.
`direct_pause_tier`, `direct_local_model_waits`, `direct_split_memory_backing`,
`direct_node_standalone_rust`) from deployment files and their true-only check in `config.py`,
once no rollback to 0.10.0 is possible.

## Admission

- **Last two gates for Rust admission:** a mid-burst drain must not report ready early, and
growth admission at ~180 sandboxes/node must stay under 1 s (`scripts/bench/bench_rl_scale.py`,
`scripts/bench/live_relay_load_benchmark.py`, flag `sandbox.direct_node_rust_admission`).
- **Delete the Python admission ledger** one release after the flag is on
(`transition_admission.py`, ledger/pool/growth code in `direct_service.py`, `DemandPublisher`,
`agent-demand.json`). `admission.py` stays for the gateway.
- **Drop gateway wake admission** (`wake_admission.py`, `resource_admission.py`); the node admits.

## Writable state and memory

- **Hibernate cost independent of bytes written** (gVisor patch 0008, external filestore);
today a park after large writes takes tens of seconds (`runtime/gvisor/`, `direct_warden.py`).
today a park after large writes takes tens of seconds (`runtime/gvisor/`, `runtime/noded/src/`).
- **One writable backing:** node-local XFS project quotas and reflink instead of per-sandbox
ublk, `mkfs.xfs` and the growth poller (`storage_native_*.py`, `runtime/storage_native/`).

## RL state primitives

- **Commit, gateway half:** route, `image_commits` table, reconciler and SDK call on top of the
existing worker export (`node_commit.py`, `commit_steps.py`, builder `publish_commit`).
existing worker export (`runtime/noded/src/node_lifecycle.rs`, `commit_steps.py`, builder `publish_commit`).
- **Fork and templates:** not started; open questions are partial forks and cross-deployment commits.
- **Node-side hydration:** warm a worker's cache for a planned group before its creates land
(`environment_backend.py`, new node route).
Expand Down
10 changes: 10 additions & 0 deletions runtime/noded/src/control_front.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ impl ControlNode for NodeControl {
}
let mut record = sandbox_record_json(reg, &state);
if state == "parked" {
if let Some(mp) = crate::node_lifecycle::load_parked_managed_process(std::path::Path::new(&reg.bundle)) {
if let Some(obj) = record.as_object_mut() {
obj.insert("managed_process".into(), mp);
}
}
if let Some(st) = &standalone {
if let Some(pub_snap) = st.lifecycle.published_snapshot(reg.sandbox_id(), reg.sandbox_generation) {
if let Some(obj) = record.as_object_mut() {
Expand Down Expand Up @@ -176,6 +181,11 @@ impl ControlNode for NodeControl {
let state = registration_state(&node, &reg);
let mut record = sandbox_record_json(&reg, &state);
if state == "parked" {
if let Some(mp) = crate::node_lifecycle::load_parked_managed_process(std::path::Path::new(&reg.bundle)) {
if let Some(obj) = record.as_object_mut() {
obj.insert("managed_process".into(), mp);
}
}
if let Some(pub_snap) = st.lifecycle.published_snapshot(reg.sandbox_id(), reg.sandbox_generation) {
if let Some(obj) = record.as_object_mut() {
obj.insert("published_snapshot".into(), pub_snap);
Expand Down
98 changes: 88 additions & 10 deletions runtime/noded/src/exec_front.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub struct ExecFront {
node: Arc<OnceLock<Arc<NodePipeline>>>,
manager: Arc<ExecManager>,
token: Bytes,
standalone: bool,
}

fn full(bytes: impl Into<Bytes>) -> Body {
Expand Down Expand Up @@ -66,8 +67,13 @@ fn session_route(path: &str) -> Option<(&str, &str)> {
(!sid.is_empty()).then_some((sid, sub))
}

/// `MemAvailable` in MiB.
fn available_mib() -> Option<u64> {
/// `MemAvailable` in MiB (or `memory_available_mb` from `metrics_override_file` in test harnesses).
fn available_mib(override_file: Option<&std::path::Path>) -> Option<u64> {
if let Some(path) = override_file {
let bytes = std::fs::read(path).ok()?;
let parsed: Value = serde_json::from_slice(&bytes).ok()?;
return parsed.get("memory_available_mb").and_then(Value::as_u64);
}
let text = std::fs::read_to_string("/proc/meminfo").ok()?;
let line = text.lines().find(|line| line.starts_with("MemAvailable:"))?;
let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
Expand Down Expand Up @@ -106,6 +112,14 @@ impl ExecFront {
}

pub fn with_limits(node: Arc<OnceLock<Arc<NodePipeline>>>, token: &str, limits: ExecLimits) -> Arc<Self> {
Self::build(node, token, limits, false)
}

pub fn standalone(node: Arc<OnceLock<Arc<NodePipeline>>>, token: &str, limits: ExecLimits) -> Arc<Self> {
Self::build(node, token, limits, true)
}

fn build(node: Arc<OnceLock<Arc<NodePipeline>>>, token: &str, limits: ExecLimits, standalone: bool) -> Arc<Self> {
let hook: crate::exec::ActivityHook = Arc::new(|_, guard| {
if let Some(lease) = guard.downcast_ref::<ActivityLease>() {
lease.touch();
Expand All @@ -115,6 +129,7 @@ impl ExecFront {
node,
manager: ExecManager::new(limits, Some(hook)),
token: Bytes::copy_from_slice(token.as_bytes()),
standalone,
})
}

Expand All @@ -137,7 +152,7 @@ impl ExecFront {
pub fn intercepts<B>(&self, request: &Request<B>) -> bool {
let path = request.uri().path();
let start = request.method() == Method::POST && path.starts_with("/v1/sandboxes/") && path.ends_with("/exec");
let session = session_route(path).is_some_and(|(sid, _)| self.manager.owns(sid));
let session = session_route(path).is_some_and(|(sid, _)| self.standalone || self.manager.owns(sid));
if !(start || session) {
return false;
}
Expand All @@ -162,6 +177,12 @@ impl ExecFront {
let method = request.method().clone();
if let Some((sid, sub)) = session_route(&path) {
let sid = sid.to_string();
if !self.manager.owns(&sid) {
if self.standalone {
return Outcome::Response(respond(Reply::new(404, serde_json::json!({"error": "exec session not found"}))));
}
return Outcome::Forward(request);
}
let reply = match (method, sub) {
(Method::GET, "") => self.manager.get(&sid),
(Method::GET, "events") => self.manager.events(&sid, &query).await,
Expand Down Expand Up @@ -240,13 +261,32 @@ impl ExecFront {
.await
.map_err(|_| Decline::Forward("registry worker"))?;
mark(&mut timings, "registry");
let registration = registration
.ok()
.flatten()
.filter(|r| r.phase == Phase::Owned)
.ok_or(Decline::Forward("not an owned registration"))?;
let registration = match registration.ok().flatten() {
Some(r) if r.phase == Phase::Owned => r,
Some(r) if self.standalone => {
return Err(Decline::Reply(Reply::new(
503,
serde_json::json!({"error": format!("direct sandbox is in phase {}", r.phase.as_str())}),
)));
}
None if self.standalone => {
return Err(Decline::Reply(Reply::new(404, serde_json::json!({"error": "sandbox not found"}))));
}
_ => return Err(Decline::Forward("not an owned registration")),
};
// A drain committed before its answer closes admission for execs too.
if !drain.map(|drain| drain.admission_open).unwrap_or(false) {
if self.standalone {
return Err(Decline::Reply(Reply {
status: 503,
body: serde_json::json!({
"error": "node is draining and not accepting new work",
"error_code": "node_admission_closed",
"retryable": true,
}),
headers: vec![("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")],
}));
}
return Err(Decline::Forward("admission closed or unreadable"));
}
let fence = ExecFence::new(&config.warden_locks_dir);
Expand All @@ -267,10 +307,48 @@ impl ExecFront {
};
let marker = config.warden_paused_dir.join(format!("{}.sandbox-{}", sandbox.sandbox_id, sandbox.generation));
if !running(node, &sandbox) {
if self.standalone {
let warden = node.warden().clone();
let sb = sandbox.clone();
let quarantined = tokio::task::spawn_blocking(move || {
let journal = warden.journal();
if let Ok(Some(rec)) = journal.load(&sb.sandbox_id, sb.generation) {
let st = rec.get("state").and_then(Value::as_str).unwrap_or("");
let auth = rec.get("authority").and_then(Value::as_str).unwrap_or("");
let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(0);
if st == "running" && auth == "live" {
let _ = journal.quarantine(&sb.sandbox_id, sb.generation, "sandbox sentry exited unexpectedly", rev);
return "recovery-required".to_string();
}
return st.to_string();
}
"unavailable".to_string()
})
.await
.unwrap_or_else(|_| "unavailable".to_string());
let status = if quarantined == "parked" { 409 } else { 503 };
return Err(Decline::Reply(Reply::new(
status,
serde_json::json!({"error": format!("direct sandbox is in state {quarantined}")}),
)));
}
return Err(Decline::Forward("not running"));
}
mark(&mut timings, "running");
if config.active_capacity_configured && available_mib().is_none_or(|mib| mib < config.memory_floor_mib) {
if config.active_capacity_configured
&& available_mib(node.config().metrics_override_file.as_deref()).is_none_or(|mib| mib < config.memory_floor_mib)
{
if self.standalone {
return Err(Decline::Reply(Reply {
status: 503,
body: serde_json::json!({
"error": "node memory headroom is below active admission floor",
"error_code": "node_active_exec_deferred",
"retryable": true,
}),
headers: vec![("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")],
}));
}
return Err(Decline::Forward("memory floor"));
}
// Python's start fence: the warden flock across the spawn only.
Expand Down Expand Up @@ -317,7 +395,7 @@ pub(crate) fn running(node: &NodePipeline, sandbox: &Sandbox) -> bool {
) else {
return false;
};
crate::runsc::start_time_ticks(std::path::Path::new("/proc"), pid as u32).is_ok_and(|now| now == ticks)
crate::runsc::start_time_ticks(&node.warden().config().proc_root, pid as u32).is_ok_and(|now| now == ticks)
}

fn millis(elapsed: Duration) -> f64 {
Expand Down
Loading
Loading