diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index 843ece5..3447aa5 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -88,6 +88,16 @@ pub struct ClaimRequest { /// The capability of a runner that obeys [`RESTART_HEADER`]. pub const CAP_RESTART: &str = "restart"; +/// The capability of a runner that may hand a running job back with [`RequeueRequest`]. +pub const CAP_REQUEUE: &str = "requeue"; + +/// `POST /api/v1/ci/jobs/{id}/requeue`: the runner hands a running job back to the queue, for +/// example to free memory. The job keeps its place in the queue and starts again from a clean log. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RequeueRequest { + pub reason: String, +} + /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops /// claiming, restarts the way a self-update does (exit 75), and the forge clears diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index b28e3f0..e6d0c24 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -1205,6 +1205,37 @@ impl Store { finish(tx, outcome).await } + /// Hands a running job back to the queue. The original `queued_at` is kept, so the job keeps + /// its priority and its anti-starvation clock. The runner, token, timestamps, log size and + /// OOM count of the attempt are cleared. Returns false when the job is not running. + pub async fn requeue_job(&self, job_id: &str) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let Some(job) = load_job(&tx, job_id).await? else { + return Ok(false); + }; + let changed = tx + .execute( + "UPDATE ci_jobs SET state = 'queued', runner_id = NULL, job_token_hash = NULL, \ + started_at = NULL, heartbeat_at = NULL, finished_at = NULL, exit_code = NULL, \ + message = NULL, cancel_requested = 0, log_bytes = 0, oom_kills = NULL \ + WHERE id = ?1 AND state = 'running'", + (job_id.to_string(),), + ) + .await + .map_err(db_err)?; + if changed != 1 { + return Ok(false); + } + recompute_run(&tx, &job.run_id, &now).await?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + /// Cancels the run's queued and blocked jobs now, and sets `cancel_requested` on its running /// jobs. Does nothing to a run that already finished. pub async fn request_cancel(&self, run_id: &str) -> Result<()> { @@ -2605,6 +2636,49 @@ mod tests { assert_eq!(next.0.name, "small"); } + #[tokio::test] + async fn requeue_hands_a_running_job_back_with_its_place() { + let fx = fixture().await; + create( + &fx.store, + &fx.repo.id, + &fx.tahinli.id, + &[job("build", &[], &[])], + false, + ) + .await; + let runner = bare_runner(&[]); + let (claimed, run, _) = fx.store.claim_job(&runner).await.unwrap().unwrap(); + fx.store.add_log_bytes(&claimed.id, 50).await.unwrap(); + fx.store.set_job_oom_kills(&claimed.id, 1).await.unwrap(); + assert!(fx.store.requeue_job(&claimed.id).await.unwrap()); + let back = fx.store.job_by_id(&claimed.id).await.unwrap().unwrap(); + assert_eq!(back.state, JobState::Queued); + assert_eq!(back.queued_at, claimed.queued_at); + assert_eq!(back.started_at, None); + assert_eq!(back.log_bytes, 0); + assert_eq!(back.oom_kills, None); + let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap(); + assert_eq!(run.state, RunState::Running); + // The old token no longer matches, and only a running job can be requeued. + assert!(!fx.store.requeue_job(&claimed.id).await.unwrap()); + assert!(!fx.store.requeue_job("missing").await.unwrap()); + let (again, _, token) = fx + .store + .claim_job_fitting(&runner, None) + .await + .unwrap() + .unwrap(); + assert_eq!(again.id, claimed.id); + assert!( + fx.store + .job_by_token(&again.id, &token) + .await + .unwrap() + .is_some() + ); + } + #[tokio::test] async fn oom_kills_are_stored_on_the_job() { let fx = fixture().await; diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index a35534e..e8adc1d 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -11,8 +11,8 @@ use forge_ci::mask::Masker; use forge_ci::proto::{ BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, - RegisterRequest, RegisterResponse, RestartMode as WireRestart, RunnerConfigOverrides, - RunnerConfigReport, + RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart, + RunnerConfigOverrides, RunnerConfigReport, }; use forge_core::Error as CoreError; use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport}; @@ -930,6 +930,49 @@ async fn finish(cx: &Cx, body: Body) -> topcoat::Result { } } +#[route(POST "/api/v1/ci/jobs/{job_id}/requeue")] +async fn requeue(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let job = match job_from(state, headers(cx), path_param::(cx)).await { + Ok(job) => job, + Err(res) => return Ok(*res), + }; + let request: RequeueRequest = match json_body(body).await { + Ok(request) => request, + Err(res) => return Ok(*res), + }; + match state.store.requeue_job(&job.id).await { + Ok(true) => {} + Ok(false) => { + return Ok(api::error(StatusCode::CONFLICT, "the job is not running")); + } + Err(e) => return Ok(*api::internal(e)), + } + // The next attempt starts from a clean log with one line saying why. + let path = log_path(&state.config.data_dir, &job.id); + let reason = request.reason.replace(['\r', '\n'], " "); + let note = format!("requeued: {reason}. It will start again\n"); + if let Some(parent) = path.parent() + && let Err(e) = tokio::fs::create_dir_all(parent).await + { + tracing::warn!(error = %e, "ci: log directory not created"); + } + if let Err(e) = tokio::fs::write(&path, note).await { + tracing::warn!(error = %e, "ci: requeue log note not written"); + } + state.ci_live.bump_job(&job.id); + state.ci_live.bump_run(&job.run_id); + state.ci_live.bump_runners(); + if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await { + state.ci_live.bump_repo(&run.repo_id); + if let Ok(Some(fresh)) = state.store.job_by_id(&job.id).await { + crate::ci::sync_status(state, &run, &fresh).await; + } + } + state.ci_waker.notify_waiters(); + Ok(api::json(StatusCode::OK, &json!({ "state": "queued" }))) +} + /// Finishes the job, then syncs the statuses of the job and of every job whose state changed /// (skipped or queued by this finish). Wakes the claimers when something was queued, and the /// watchers of every job and run that changed. diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index 00c9c51..7cbf4eb 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -864,6 +864,32 @@ async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) { (id, sent.json()) } +#[tokio::test] +async fn requeue_hands_the_job_back_and_it_can_be_claimed_again() { + let env = bare(|_| {}).await; + let (_runner, secret) = runner(&env, &[]).await; + make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; + let first = claim_job(&env.router, &secret).await; + let id = first["job_id"].as_str().unwrap().to_owned(); + let token = first["job_token"].as_str().unwrap().to_owned(); + let uri = format!("/api/v1/ci/jobs/{id}/requeue"); + let body = json_body(&json!({ "reason": "the runner paused this job for memory" })); + let wrong = send(&env.router, "POST", &uri, &[bearer("nope")], body.clone()).await; + assert_eq!(wrong.status, 401); + let sent = send(&env.router, "POST", &uri, &[bearer(&token)], body.clone()).await; + assert_eq!(sent.status, 200, "{}", sent.json()); + let stored = env.store.job_by_id(&id).await.unwrap().unwrap(); + assert_eq!(stored.state, JobState::Queued); + let log = std::fs::read_to_string(log_path(&env.data_dir, &id)).unwrap(); + assert!(log.starts_with("requeued: "), "{log}"); + // The old token is dead, and the job is handed out again with a new one. + let again = send(&env.router, "POST", &uri, &[bearer(&token)], body).await; + assert_eq!(again.status, 401); + let second = claim_job(&env.router, &secret).await; + assert_eq!(second["job_id"], first["job_id"]); + assert_ne!(second["job_token"], first["job_token"]); +} + #[tokio::test] async fn finish_stores_the_oom_kills_the_runner_saw() { let env = bare(|_| {}).await; diff --git a/docs/ci.md b/docs/ci.md index 27d3e67..e76dc20 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -752,6 +752,7 @@ The runner talks to the forge only over HTTPS. JSON bodies are defined in `forge | `POST /api/v1/ci/jobs/{id}/heartbeat` | `Bearer` job token | Sent every 10 s. The reply says whether the job was cancelled. | | `PUT /api/v1/ci/jobs/{id}/artifacts/{name}` | `Bearer` job token | Upload one artifact as a raw body. | | `POST /api/v1/ci/jobs/{id}/finish` | `Bearer` job token | Report `success`, `failure`, `cancelled` or `error`, with the exit code and an optional message. | +| `POST /api/v1/ci/jobs/{id}/requeue` | `Bearer` job token | Hand a running job back to the queue with a `reason` (runners advertise the `requeue` capability). The job keeps its `queued_at`, its log is cleared and starts with a line saying why, and the job token stops working. 409 when the job is not running. | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull