Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(engine): keep box logs before releasing their rental
Publish mirrored bytes as kept ranges and settle completed collection before acknowledging the remote supervisor. Verified release also seals a cancelled run’s available copy, including an empty log: the aborted copy task can never publish another EOF.

Assisted-by: gpt-6.1-sol
Assisted-by: claude-opus-5.5
  • Loading branch information
small-angel committed Nov 5, 2026
commit 03179d9e6f2b246882371e59be48eab6a2a60cc9
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
71 changes: 68 additions & 3 deletions src/engine/adapters/api_tests.rs
Original file line number Diff line number Diff line change
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
45 changes: 44 additions & 1 deletion src/engine/adapters/openresearch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,21 @@ impl LegacyTransport {
&serde_json::to_vec(&cursor)?,
Some(0o600),
)?;
if let Some(ident) = cursor.ident {
crate::commands::up::api_v2::keep_ranges(
self.log_dir
.parent()
.ok_or_else(|| anyhow!("Missing log parent"))?,
run,
vec![crate::commands::up::api_v2::KeptRange {
offset: 0,
len: cursor.offset,
file: path,
ident,
eof,
}],
)?;
}
#[cfg(unix)]
std::fs::File::open(&self.log_dir)?.sync_all()?;
Ok(serde_json::json!({ "eof": eof }))
Expand Down Expand Up @@ -294,6 +309,13 @@ impl RunSink for EngineSink {
fn queue_finished_remote_cleanup(&self, run: &str) -> Result<()> {
self.engine.store().queue_finished_remote_cleanup(run)
}
fn finish_log_collection(&self, run: &str) -> Result<()> {
self.engine.store().finish_log_collection(run)?;
self.engine
.bus
.publish(crate::engine::bus::RunEvent::LogCollection { run_id: run.into() });
Ok(())
}
fn transport_error(&self, run: &str, target: &ssh::SshTarget, cause: &str) -> Result<()> {
let transport = target
.transport
Expand Down Expand Up @@ -601,7 +623,28 @@ impl Backend for OpenResearch {
.await;

match released {
Ok(()) => CancelOutcome::Verified,
Ok(()) => {
if let Some(target) = descriptor.openresearch_ssh_target() {
let kept = (|| {
let transport = (self.transport)(&target)?;
let data_dir = transport
.log_dir
.parent()
.ok_or_else(|| anyhow!("Missing log parent"))?;
if crate::commands::up::api_v2::kept_ranges(data_dir, &run.id)?
.iter()
.any(|range| range.eof)
{
self.engine.store().finish_log_collection(&run.id)?;
}
Ok::<_, crate::error::Error>(())
})();
if let Err(error) = kept {
eprintln!("Could not settle cancelled run {}'s log: {error}", run.id);
}
}
CancelOutcome::Verified
}
Err(error) => CancelOutcome::Undelivered {
detail: error.to_string(),
},
Expand Down
138 changes: 128 additions & 10 deletions src/engine/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,17 +692,44 @@ impl Runtime {
budget: Duration,
) -> Result<bool> {
let mirrored = matches!(&run.handle, Handle::Legacy { descriptor } if descriptor.kind == "openresearch_job");
if !mirrored {
let mut progressed = false;
let collected = async {
backend.drain_log(run).await?;
self.collect_log(backend, run, &mut progressed).await
};
match tokio::time::timeout(budget, collected).await {
Ok(result) => result?,
Err(_) if progressed => return Ok(false),
Err(_) => bail!("timed out without keeping more log bytes"),
if mirrored {
let mut ranges = crate::commands::up::api_v2::kept_ranges(&self.data_dir, &run.id)?;
let (stored, state) = self.engine.load(&run.id)?;
if Phase::parse(&stored.status).is_some_and(Phase::is_terminal)
&& state.cancel_accepted_at.is_some()
&& state.contact == crate::store::Contact::Live
{
if let Some(last) = ranges.last_mut() {
last.eof = true;
} else {
let path = self
.data_dir
.join("run-logs")
.join(format!("{}.log", run.id));
std::fs::create_dir_all(path.parent().unwrap())?;
crate::local::git::atomic_write_with_mode(&path, &[], Some(0o600))?;
ranges.push(KeptRange {
offset: 0,
len: 0,
file: path,
ident: FileIdent { dev: 0, ino: 0 },
eof: true,
});
}
crate::commands::up::api_v2::keep_ranges(&self.data_dir, &run.id, ranges)?;
return Ok(true);
}
return Ok(ranges.iter().any(|range| range.eof));
}
let mut progressed = false;
let collected = async {
backend.drain_log(run).await?;
self.collect_log(backend, run, &mut progressed).await
};
match tokio::time::timeout(budget, collected).await {
Ok(result) => result?,
Err(_) if progressed => return Ok(false),
Err(_) => bail!("timed out without keeping more log bytes"),
}
Ok(true)
}
Expand Down Expand Up @@ -1653,6 +1680,97 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}

#[tokio::test]
async fn released_boxes_settle_partial_and_empty_logs_only_after_stop_proof() {
for partial in [false, true] {
let dir = std::env::temp_dir().join(format!("orx-released-{}", uuid::Uuid::new_v4()));
let runtime = collector(&dir);
let descriptor = crate::jobs::BackendDescriptor::parse(
r#"{"kind":"openresearch_job","jobId":"box","namespace":"org"}"#,
)
.unwrap();
runtime
.engine
.insert(SubmittingRun {
id: "run",
experiment_id: "exp",
project_id: "project",
metadata: &descriptor,
command: "true",
created_at: 1,
commit_sha: None,
chat_session_id: None,
spec_digest: "digest",
launch: &LaunchSpec {
kind: "openresearch_job".into(),
target: Some("org".into()),
options: json!({}),
},
})
.unwrap();
let run = WatchedRun {
id: "run".into(),
handle: Handle::Legacy {
descriptor: Box::new(descriptor),
},
};
runtime
.store()
.unwrap()
.record_run_handle("run", 1, &run.handle)
.unwrap();
runtime
.store()
.unwrap()
.accept_run_cancel("run", Some("user"))
.unwrap();
if partial {
let path = dir.join("run-logs/run.log");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"available copy").unwrap();
crate::commands::up::api_v2::keep_ranges(
&dir,
"run",
vec![KeptRange {
offset: 0,
len: 14,
file: path,
ident: FileIdent { dev: 1, ino: 2 },
eof: false,
}],
)
.unwrap();
}
let backend = Host::default();
assert!(!runtime
.collect(&backend, &run, COLLECTION_BUDGET)
.await
.unwrap());
let stored = runtime.engine.load("run").unwrap().0;
runtime
.engine
.apply_cancel(&stored, super::super::CancelOutcome::Verified)
.unwrap();
assert!(runtime
.collect(&backend, &run, COLLECTION_BUDGET)
.await
.unwrap());
let ranges = kept_ranges(&dir);
assert_eq!(ranges.len(), 1);
assert!(ranges[0].eof);
assert_eq!(
std::fs::read(&ranges[0].file).unwrap(),
if partial {
b"available copy".as_slice()
} else {
b""
}
);
drop(runtime);
std::fs::remove_dir_all(dir).unwrap();
}
}

#[tokio::test]
async fn finalization_retries_after_restart_without_reopening_destroyed_logs() {
use std::sync::atomic::Ordering;
Expand Down