Runners can hand a running job back to the queue
Browse files at this commit8d8258bbbb648c355e161cc20b51099a2e82706fParent: 7e7f295- feat
- runners can hand a running job back to the queue
5 changed files +156 -2
- crates/forge-ci/src/proto.rs +10 -0
- crates/forge-core/src/store/ci.rs +74 -0
- crates/forge-web/src/ci/api.rs +45 -2
- crates/forge-web/src/ci/api_tests.rs +26 -0
- docs/ci.md +1 -0
crates/forge-ci/src/proto.rsmodified+10 -0
| @@ -88,6 +88,16 @@ pub struct ClaimRequest { | |||
| 88 | /// The capability of a runner that obeys [`RESTART_HEADER`]. | 88 | /// The capability of a runner that obeys [`RESTART_HEADER`]. |
| 89 | pub const CAP_RESTART: &str = "restart"; | 89 | pub const CAP_RESTART: &str = "restart"; |
| 90 | 90 | ||
| 91 | +/// The capability of a runner that may hand a running job back with [`RequeueRequest`]. | ||
| 92 | +pub const CAP_REQUEUE: &str = "requeue"; | ||
| 93 | + | ||
| 94 | +/// `POST /api/v1/ci/jobs/{id}/requeue`: the runner hands a running job back to the queue, for | ||
| 95 | +/// example to free memory. The job keeps its place in the queue and starts again from a clean log. | ||
| 96 | +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | ||
| 97 | +pub struct RequeueRequest { | ||
| 98 | + pub reason: String, | ||
| 99 | +} | ||
| 100 | + | ||
| 91 | /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish | 101 | /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish |
| 92 | /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops | 102 | /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops |
| 93 | /// claiming, restarts the way a self-update does (exit 75), and the forge clears | 103 | /// claiming, restarts the way a self-update does (exit 75), and the forge clears |
crates/forge-core/src/store/ci.rsmodified+74 -0
| @@ -1205,6 +1205,37 @@ impl Store { | |||
| 1205 | finish(tx, outcome).await | 1205 | finish(tx, outcome).await |
| 1206 | } | 1206 | } |
| 1207 | 1207 | ||
| 1208 | + /// Hands a running job back to the queue. The original `queued_at` is kept, so the job keeps | ||
| 1209 | + /// its priority and its anti-starvation clock. The runner, token, timestamps, log size and | ||
| 1210 | + /// OOM count of the attempt are cleared. Returns false when the job is not running. | ||
| 1211 | + pub async fn requeue_job(&self, job_id: &str) -> Result<bool> { | ||
| 1212 | + let now = now_stamp(); | ||
| 1213 | + let conn = self.inner.conn.lock().await; | ||
| 1214 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 1215 | + let outcome: Result<bool> = async { | ||
| 1216 | + let Some(job) = load_job(&tx, job_id).await? else { | ||
| 1217 | + return Ok(false); | ||
| 1218 | + }; | ||
| 1219 | + let changed = tx | ||
| 1220 | + .execute( | ||
| 1221 | + "UPDATE ci_jobs SET state = 'queued', runner_id = NULL, job_token_hash = NULL, \ | ||
| 1222 | + started_at = NULL, heartbeat_at = NULL, finished_at = NULL, exit_code = NULL, \ | ||
| 1223 | + message = NULL, cancel_requested = 0, log_bytes = 0, oom_kills = NULL \ | ||
| 1224 | + WHERE id = ?1 AND state = 'running'", | ||
| 1225 | + (job_id.to_string(),), | ||
| 1226 | + ) | ||
| 1227 | + .await | ||
| 1228 | + .map_err(db_err)?; | ||
| 1229 | + if changed != 1 { | ||
| 1230 | + return Ok(false); | ||
| 1231 | + } | ||
| 1232 | + recompute_run(&tx, &job.run_id, &now).await?; | ||
| 1233 | + Ok(true) | ||
| 1234 | + } | ||
| 1235 | + .await; | ||
| 1236 | + finish(tx, outcome).await | ||
| 1237 | + } | ||
| 1238 | + | ||
| 1208 | /// Cancels the run's queued and blocked jobs now, and sets `cancel_requested` on its running | 1239 | /// Cancels the run's queued and blocked jobs now, and sets `cancel_requested` on its running |
| 1209 | /// jobs. Does nothing to a run that already finished. | 1240 | /// jobs. Does nothing to a run that already finished. |
| 1210 | pub async fn request_cancel(&self, run_id: &str) -> Result<()> { | 1241 | pub async fn request_cancel(&self, run_id: &str) -> Result<()> { |
| @@ -2605,6 +2636,49 @@ mod tests { | |||
| 2605 | assert_eq!(next.0.name, "small"); | 2636 | assert_eq!(next.0.name, "small"); |
| 2606 | } | 2637 | } |
| 2607 | 2638 | ||
| 2639 | + #[tokio::test] | ||
| 2640 | + async fn requeue_hands_a_running_job_back_with_its_place() { | ||
| 2641 | + let fx = fixture().await; | ||
| 2642 | + create( | ||
| 2643 | + &fx.store, | ||
| 2644 | + &fx.repo.id, | ||
| 2645 | + &fx.tahinli.id, | ||
| 2646 | + &[job("build", &[], &[])], | ||
| 2647 | + false, | ||
| 2648 | + ) | ||
| 2649 | + .await; | ||
| 2650 | + let runner = bare_runner(&[]); | ||
| 2651 | + let (claimed, run, _) = fx.store.claim_job(&runner).await.unwrap().unwrap(); | ||
| 2652 | + fx.store.add_log_bytes(&claimed.id, 50).await.unwrap(); | ||
| 2653 | + fx.store.set_job_oom_kills(&claimed.id, 1).await.unwrap(); | ||
| 2654 | + assert!(fx.store.requeue_job(&claimed.id).await.unwrap()); | ||
| 2655 | + let back = fx.store.job_by_id(&claimed.id).await.unwrap().unwrap(); | ||
| 2656 | + assert_eq!(back.state, JobState::Queued); | ||
| 2657 | + assert_eq!(back.queued_at, claimed.queued_at); | ||
| 2658 | + assert_eq!(back.started_at, None); | ||
| 2659 | + assert_eq!(back.log_bytes, 0); | ||
| 2660 | + assert_eq!(back.oom_kills, None); | ||
| 2661 | + let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap(); | ||
| 2662 | + assert_eq!(run.state, RunState::Running); | ||
| 2663 | + // The old token no longer matches, and only a running job can be requeued. | ||
| 2664 | + assert!(!fx.store.requeue_job(&claimed.id).await.unwrap()); | ||
| 2665 | + assert!(!fx.store.requeue_job("missing").await.unwrap()); | ||
| 2666 | + let (again, _, token) = fx | ||
| 2667 | + .store | ||
| 2668 | + .claim_job_fitting(&runner, None) | ||
| 2669 | + .await | ||
| 2670 | + .unwrap() | ||
| 2671 | + .unwrap(); | ||
| 2672 | + assert_eq!(again.id, claimed.id); | ||
| 2673 | + assert!( | ||
| 2674 | + fx.store | ||
| 2675 | + .job_by_token(&again.id, &token) | ||
| 2676 | + .await | ||
| 2677 | + .unwrap() | ||
| 2678 | + .is_some() | ||
| 2679 | + ); | ||
| 2680 | + } | ||
| 2681 | + | ||
| 2608 | #[tokio::test] | 2682 | #[tokio::test] |
| 2609 | async fn oom_kills_are_stored_on_the_job() { | 2683 | async fn oom_kills_are_stored_on_the_job() { |
| 2610 | let fx = fixture().await; | 2684 | let fx = fixture().await; |
crates/forge-web/src/ci/api.rsmodified+45 -2
| @@ -11,8 +11,8 @@ use forge_ci::mask::Masker; | |||
| 11 | use forge_ci::proto::{ | 11 | use forge_ci::proto::{ |
| 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, | 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 13 | JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, | 13 | JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, |
| 14 | - RegisterRequest, RegisterResponse, RestartMode as WireRestart, RunnerConfigOverrides, | 14 | + RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart, |
| 15 | - RunnerConfigReport, | 15 | + RunnerConfigOverrides, RunnerConfigReport, |
| 16 | }; | 16 | }; |
| 17 | use forge_core::Error as CoreError; | 17 | use forge_core::Error as CoreError; |
| 18 | use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport}; | 18 | use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport}; |
| @@ -930,6 +930,49 @@ async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 930 | } | 930 | } |
| 931 | } | 931 | } |
| 932 | 932 | ||
| 933 | +#[route(POST "/api/v1/ci/jobs/{job_id}/requeue")] | ||
| 934 | +async fn requeue(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 935 | + let state = app_context::<AppState>(cx); | ||
| 936 | + let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await { | ||
| 937 | + Ok(job) => job, | ||
| 938 | + Err(res) => return Ok(*res), | ||
| 939 | + }; | ||
| 940 | + let request: RequeueRequest = match json_body(body).await { | ||
| 941 | + Ok(request) => request, | ||
| 942 | + Err(res) => return Ok(*res), | ||
| 943 | + }; | ||
| 944 | + match state.store.requeue_job(&job.id).await { | ||
| 945 | + Ok(true) => {} | ||
| 946 | + Ok(false) => { | ||
| 947 | + return Ok(api::error(StatusCode::CONFLICT, "the job is not running")); | ||
| 948 | + } | ||
| 949 | + Err(e) => return Ok(*api::internal(e)), | ||
| 950 | + } | ||
| 951 | + // The next attempt starts from a clean log with one line saying why. | ||
| 952 | + let path = log_path(&state.config.data_dir, &job.id); | ||
| 953 | + let reason = request.reason.replace(['\r', '\n'], " "); | ||
| 954 | + let note = format!("requeued: {reason}. It will start again\n"); | ||
| 955 | + if let Some(parent) = path.parent() | ||
| 956 | + && let Err(e) = tokio::fs::create_dir_all(parent).await | ||
| 957 | + { | ||
| 958 | + tracing::warn!(error = %e, "ci: log directory not created"); | ||
| 959 | + } | ||
| 960 | + if let Err(e) = tokio::fs::write(&path, note).await { | ||
| 961 | + tracing::warn!(error = %e, "ci: requeue log note not written"); | ||
| 962 | + } | ||
| 963 | + state.ci_live.bump_job(&job.id); | ||
| 964 | + state.ci_live.bump_run(&job.run_id); | ||
| 965 | + state.ci_live.bump_runners(); | ||
| 966 | + if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await { | ||
| 967 | + state.ci_live.bump_repo(&run.repo_id); | ||
| 968 | + if let Ok(Some(fresh)) = state.store.job_by_id(&job.id).await { | ||
| 969 | + crate::ci::sync_status(state, &run, &fresh).await; | ||
| 970 | + } | ||
| 971 | + } | ||
| 972 | + state.ci_waker.notify_waiters(); | ||
| 973 | + Ok(api::json(StatusCode::OK, &json!({ "state": "queued" }))) | ||
| 974 | +} | ||
| 975 | + | ||
| 933 | /// Finishes the job, then syncs the statuses of the job and of every job whose state changed | 976 | /// Finishes the job, then syncs the statuses of the job and of every job whose state changed |
| 934 | /// (skipped or queued by this finish). Wakes the claimers when something was queued, and the | 977 | /// (skipped or queued by this finish). Wakes the claimers when something was queued, and the |
| 935 | /// watchers of every job and run that changed. | 978 | /// watchers of every job and run that changed. |
crates/forge-web/src/ci/api_tests.rsmodified+26 -0
| @@ -864,6 +864,32 @@ async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) { | |||
| 864 | (id, sent.json()) | 864 | (id, sent.json()) |
| 865 | } | 865 | } |
| 866 | 866 | ||
| 867 | +#[tokio::test] | ||
| 868 | +async fn requeue_hands_the_job_back_and_it_can_be_claimed_again() { | ||
| 869 | + let env = bare(|_| {}).await; | ||
| 870 | + let (_runner, secret) = runner(&env, &[]).await; | ||
| 871 | + make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; | ||
| 872 | + let first = claim_job(&env.router, &secret).await; | ||
| 873 | + let id = first["job_id"].as_str().unwrap().to_owned(); | ||
| 874 | + let token = first["job_token"].as_str().unwrap().to_owned(); | ||
| 875 | + let uri = format!("/api/v1/ci/jobs/{id}/requeue"); | ||
| 876 | + let body = json_body(&json!({ "reason": "the runner paused this job for memory" })); | ||
| 877 | + let wrong = send(&env.router, "POST", &uri, &[bearer("nope")], body.clone()).await; | ||
| 878 | + assert_eq!(wrong.status, 401); | ||
| 879 | + let sent = send(&env.router, "POST", &uri, &[bearer(&token)], body.clone()).await; | ||
| 880 | + assert_eq!(sent.status, 200, "{}", sent.json()); | ||
| 881 | + let stored = env.store.job_by_id(&id).await.unwrap().unwrap(); | ||
| 882 | + assert_eq!(stored.state, JobState::Queued); | ||
| 883 | + let log = std::fs::read_to_string(log_path(&env.data_dir, &id)).unwrap(); | ||
| 884 | + assert!(log.starts_with("requeued: "), "{log}"); | ||
| 885 | + // The old token is dead, and the job is handed out again with a new one. | ||
| 886 | + let again = send(&env.router, "POST", &uri, &[bearer(&token)], body).await; | ||
| 887 | + assert_eq!(again.status, 401); | ||
| 888 | + let second = claim_job(&env.router, &secret).await; | ||
| 889 | + assert_eq!(second["job_id"], first["job_id"]); | ||
| 890 | + assert_ne!(second["job_token"], first["job_token"]); | ||
| 891 | +} | ||
| 892 | + | ||
| 867 | #[tokio::test] | 893 | #[tokio::test] |
| 868 | async fn finish_stores_the_oom_kills_the_runner_saw() { | 894 | async fn finish_stores_the_oom_kills_the_runner_saw() { |
| 869 | let env = bare(|_| {}).await; | 895 | let env = bare(|_| {}).await; |
docs/ci.mdmodified+1 -0
| @@ -752,6 +752,7 @@ The runner talks to the forge only over HTTPS. JSON bodies are defined in `forge | |||
| 752 | | `POST /api/v1/ci/jobs/{id}/heartbeat` | `Bearer` job token | Sent every 10 s. The reply says whether the job was cancelled. | | 752 | | `POST /api/v1/ci/jobs/{id}/heartbeat` | `Bearer` job token | Sent every 10 s. The reply says whether the job was cancelled. | |
| 753 | | `PUT /api/v1/ci/jobs/{id}/artifacts/{name}` | `Bearer` job token | Upload one artifact as a raw body. | | 753 | | `PUT /api/v1/ci/jobs/{id}/artifacts/{name}` | `Bearer` job token | Upload one artifact as a raw body. | |
| 754 | | `POST /api/v1/ci/jobs/{id}/finish` | `Bearer` job token | Report `success`, `failure`, `cancelled` or `error`, with the exit code and an optional message. | | 754 | | `POST /api/v1/ci/jobs/{id}/finish` | `Bearer` job token | Report `success`, `failure`, `cancelled` or `error`, with the exit code and an optional message. | |
| 755 | +| `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. | | ||
| 755 | 756 | ||
| 756 | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, | 757 | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, |
| 757 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull | 758 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull |