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
4 changes: 4 additions & 0 deletions arc/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ which path recovers orphaned supervised runs.

Engine runs keep their first payload start in `started_at` and finish in
`ended_at`, using source timestamps when available and observation time otherwise.
Box runs stay starting until remote inspection confirms a live payload PID.

The snapshot contract below applies in both modes. The engine lifecycle and
`orx-host` sections describe engine-owned runs; supervised runs keep their
Expand Down Expand Up @@ -197,6 +198,9 @@ identity; a changed identity resets the reader rather than splicing different
bytes. API backends offer no random access, so their logs stream into a local
spool.

Kubernetes cancellation keeps the deleting Job visible until its Pods are gone.
Once both are gone, the log already spooled on this computer becomes the kept log.

When a run ends, keeping its log becomes an obligation recorded in the same
transaction as the terminal phase:

Expand Down
6 changes: 6 additions & 0 deletions src/commands/supervise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ use crate::jobs::{is_terminal_stage, stage_to_run_status, BackendDescriptor};
use crate::store::{log_path, now_ms, RunStatus, Store};

pub(crate) trait RunSink {
fn finish_log_collection(&self, _run: &str) -> Result<()> {
Ok(())
}
fn transport_error(&self, _run: &str, _target: &ssh::SshTarget, _cause: &str) -> Result<()> {
Ok(())
}
Expand Down Expand Up @@ -1143,6 +1146,9 @@ pub(crate) async fn watch_ssh_job(
format!("{prefix}: {message}")
});
store.finish(run_id, status, exit_code, reason.as_deref())?;
if collected {
store.finish_log_collection(run_id)?;
}
if descriptor.rental_lease.is_some()
&& stage != "LOST"
&& collected
Expand Down
239 changes: 227 additions & 12 deletions src/engine/adapters/api_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ else:
std::fs::write(root.join("resources.json"), partial.to_string()).unwrap();
assert!(matches!(adapter.recover(&intent).await, Recovery::Absent));
let calls = std::fs::read_to_string(root.join("kubectl.log")).unwrap();
assert!(calls.contains("delete job/primary -n default --wait=false"));
assert!(calls.contains("delete job/primary -n default --cascade=foreground --wait=false"));
}

#[tokio::test]
Expand Down Expand Up @@ -934,14 +934,15 @@ async fn openresearch_rejected_key_auto_cancel_checks_rental_and_survives_restar
}
}

async fn legacy_rejected_key(root: PathBuf, watching: bool) {
async fn legacy_box(root: PathBuf, initial_stage: &str) {
use super::openresearch::{LegacyTransport, OpenResearch};
use super::ssh::Ssh;
use crate::engine::transport::{Config, HostConn, Status};
use crate::store::StoredRun;
use orx_test_support::host_binaries as binaries;
// Paces the timers the checks below outlast.
std::env::set_var("ORX_TEST_SPEEDUP", "10");
let watching = initial_stage != "starting";
let server = orx_test_support::Sshd::start().unwrap();
crate::config::save_credentials(&crate::config::Credentials {
api_url: std::env::var("HF_ENDPOINT").unwrap(),
Expand Down Expand Up @@ -1018,6 +1019,9 @@ async fn legacy_rejected_key(root: PathBuf, watching: bool) {
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("pid"), server.pid().to_string()).unwrap();
std::fs::write(dir.join("log"), vec![b'x'; 5000]).unwrap();
if initial_stage == "done" {
std::fs::write(dir.join("exit_code"), "0\n").unwrap();
}
}
let engine = Arc::new(engine(&root));
let stored = StoredRun {
Expand Down Expand Up @@ -1049,7 +1053,59 @@ async fn legacy_rejected_key(root: PathBuf, watching: bool) {
descriptor: Box::new(descriptor),
},
}];
let mut events = engine.bus.subscribe();
adapter.observe(&watched, Duration::from_secs(1)).await;
if initial_stage == "done" {
let dir = server.home().join(format!(".orx/runs/{id}"));
tokio::time::timeout(Duration::from_secs(20), async {
while !dir.join("final_collected").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert_eq!(engine.load(&id).unwrap().0.status, "done");
assert!(!engine.store().log_collection_pending(&id).unwrap());
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| {
matches!(event, crate::engine::bus::RunEvent::LogCollection { run_id } if run_id == id)
}));
std::fs::remove_dir_all(dir).unwrap();
let runtime = crate::engine::runtime::Runtime::new(
engine.clone(),
Arc::new(TestClock::new()),
root.join("store"),
None,
);
let api = crate::commands::up::api_v2::Api::new(
"test".into(),
"token".into(),
engine,
runtime,
Box::new(|_| Ok(Box::new(()))),
root.join("store"),
)
.unwrap();
crate::commands::up::api_v2::install(Arc::new(api)).unwrap();
use tower::ServiceExt;
let response = crate::commands::up::api_v2::router()
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/runs/{id}/log?start=0&end=1048576"))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), axum::http::StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let page: LogPage = serde_json::from_slice(&bytes).unwrap();
assert!(
matches!(page, LogPage::Data { bytes, eof: true, .. } if bytes == vec![b'x'; 5000])
);
return;
}
if watching {
tokio::time::timeout(Duration::from_secs(20), async {
loop {
Expand Down Expand Up @@ -1170,6 +1226,7 @@ async fn legacy_rejected_key(root: PathBuf, watching: bool) {
if watching {
assert!(engine.cancel(&adapter, &id, "user").await.unwrap());
assert_eq!(engine.load(&id).unwrap().0.status, "cancelled");
assert!(!engine.store().log_collection_pending(&id).unwrap());
} else {
assert!(engine.abandon(&id).unwrap());
engine
Expand All @@ -1196,15 +1253,23 @@ async fn openresearch_staging_rejected_key_needs_auth_after_one_attempt() {
let Some(root) = isolated().await else {
return;
};
legacy_rejected_key(root, false).await;
legacy_box(root, "starting").await;
}

#[tokio::test]
async fn openresearch_watching_rejected_key_needs_auth_after_one_attempt() {
let Some(root) = isolated().await else {
return;
};
legacy_rejected_key(root, true).await;
legacy_box(root, "running").await;
}

#[tokio::test]
async fn openresearch_completed_log_is_readable_after_release() {
let Some(root) = isolated().await else {
return;
};
legacy_box(root, "done").await;
}

#[tokio::test]
Expand Down Expand Up @@ -1543,10 +1608,144 @@ async fn finished_modal_logs_drain_through_pauses_before_they_are_kept() {
assert_eq!(bytes, b"first\nlast\n");
}

/// A pod lookup that fails, or finds no pod yet, is never a closed stream: draining errs, and
/// the log stays owed.
#[tokio::test]
async fn kubernetes_lookup_failures_never_complete_a_drain() {
async fn kubernetes_cancel_keeps_the_spool_without_an_attention_notice() {
use super::api::Api;
use crate::commands::up::api_v2::Commands;

let Some(root) = isolated().await else {
return;
};
script(
&root.join("bin/kubectl"),
r#"#!/usr/bin/env python3
import json, os, sys
from pathlib import Path
root = Path(os.environ['ORX_API_ROOT'])
a = sys.argv[1:]
if a[0] == 'delete':
assert '--cascade=foreground' in a and '--wait=false' in a
(root/'deleting').touch()
elif a[:2] == ['get', 'job']:
if (root/'gone').exists() or (root/'unexpected-deletion').exists():
print('Error from server (NotFound): jobs.batch "job" not found', file=sys.stderr)
sys.exit(1)
metadata = {'deletionTimestamp': '2026-11-05T01:43:00Z'} if (root/'deleting').exists() else {}
print(json.dumps({'metadata': metadata, 'status': {'active': 1}}))
elif a[:2] == ['get', 'pods']:
metadata = {'name': 'pod'}
if (root/'deleting').exists():
metadata['deletionTimestamp'] = '2026-11-05T01:43:00Z'
pods = [] if (root/'gone').exists() else [{'metadata': metadata, 'status': {'phase': 'Running'}}]
print(json.dumps({'items': pods}))
elif a[0] == 'logs':
assert not (root/'gone').exists()
print('2026-11-05T01:42:00Z SMOKE_CANCEL_READY')
else:
raise Exception(a)
"#,
);
let engine = Arc::new(engine(&root));
let clock = Arc::new(TestClock::new());
let runtime = crate::engine::runtime::Runtime::new(
engine.clone(),
clock.clone(),
root.join("store"),
None,
);
let handle = super::api::test_handle("k8s_job", Some("default"), None, vec!["job/job".into()]);
let row = crate::store::StoredRun {
id: "run".into(),
experiment_id: "exp".into(),
project_id: "proj".into(),
status: "running".into(),
backend_json: crate::engine::handle::backend_json(
"run",
Some(&handle),
&BackendDescriptor::parse(r#"{"kind":"k8s_job","namespace":"default"}"#).unwrap(),
)
.unwrap(),
command: "sleep 180".into(),
created_at: 1,
updated_at: 1,
ended_at: None,
exit_code: None,
commit_sha: None,
result_markdown: None,
cancel_requested: false,
cancel_reason: None,
chat_session_id: Some("chat".into()),
};
engine.store().upsert_run(&row).unwrap();
engine.store().subscribe_run("run", "chat", 1).unwrap();
let backend = runtime.backend(&row).unwrap();
let run = WatchedRun {
id: "run".into(),
handle,
};
let account = K8sAccount {
context: None,
namespace: "default".into(),
};
for terminating in [false, true] {
std::fs::write(root.join("unexpected-deletion"), "").unwrap();
if terminating {
std::fs::write(root.join("deleting"), "").unwrap();
}
assert!(matches!(
account.inspect(&run).await.unwrap(),
Observation::Unreconciled { .. }
));
}
std::fs::remove_file(root.join("unexpected-deletion")).unwrap();
std::fs::remove_file(root.join("deleting")).unwrap();

backend.drain_log(&run).await.unwrap();
assert!(engine
.cancel(backend.as_ref(), "run", "Dashboard stop")
.await
.unwrap());
engine
.observe_runs(
backend.as_ref(),
std::slice::from_ref(&run),
Duration::from_secs(5),
)
.await
.unwrap();
assert_eq!(engine.load("run").unwrap().0.status, "running");
assert!(engine.store().run_notice_batch("chat").unwrap().is_empty());

backend.drain_log(&run).await.unwrap();
std::fs::write(root.join("gone"), "").unwrap();
clock.advance(Duration::from_secs(10));
engine
.observe_runs(backend.as_ref(), &[run], Duration::from_secs(5))
.await
.unwrap();
assert_eq!(engine.load("run").unwrap().0.status, "cancelled");
let notices = engine.store().run_notice_batch("chat").unwrap();
assert_eq!(notices.len(), 1);
assert_eq!(notices[0].kind, crate::store::TERMINAL);

runtime.start();
tokio::time::timeout(Duration::from_secs(30), async {
while engine.store().log_collection_pending("run").unwrap() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("cancelled log was not kept");
assert_eq!(
std::fs::read(root.join("store/run-logs/run.log")).unwrap(),
b"SMOKE_CANCEL_READY\n"
);
let ranges = crate::commands::up::api_v2::kept_ranges(&root.join("store"), "run").unwrap();
assert!(ranges.iter().any(|range| range.eof));
}

#[tokio::test]
async fn kubernetes_missing_pods_close_logs_only_after_job_deletion() {
use super::api::Api;
let Some(root) = isolated().await else {
return;
Expand All @@ -1560,9 +1759,17 @@ async fn kubernetes_lookup_failures_never_complete_a_drain() {
vec!["job/job".into()],
),
};
for get in [
"echo 'Unable to connect to the server' >&2; exit 1",
"printf '{\"items\":[]}'",
for (get, expected_closed) in [
("echo 'Unable to connect to the server' >&2; exit 1", false),
("printf '{\"items\":[]}'", false),
(
r#"if test "$2" = job; then echo 'Error from server (Unauthorized)' >&2; exit 1; fi; printf '{"items":[]}'"#,
false,
),
(
r#"if test "$2" = job; then echo 'Error from server (NotFound)' >&2; exit 1; fi; printf '{"items":[]}'"#,
true,
),
] {
script(
&root.join("bin/kubectl"),
Expand All @@ -1576,10 +1783,18 @@ async fn kubernetes_lookup_failures_never_complete_a_drain() {
let closed = account
.logs(&run, &mut cursor, Duration::from_secs(5), &mut |_| {})
.await;
assert!(!matches!(closed, Ok(true)), "{get}: {closed:?}");
assert_eq!(
matches!(closed, Ok(true)),
expected_closed,
"{get}: {closed:?}"
);
let backend =
super::api::Adapter::new(account, Arc::new(TestClock::new()), root.join("spools"));
assert!(backend.drain_log(&run).await.is_err(), "{get}");
assert_eq!(
backend.drain_log(&run).await.is_ok(),
expected_closed,
"{get}"
);
}
}

Expand Down
Loading
Loading