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
10 changes: 10 additions & 0 deletions crates/fctl-client/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1791,6 +1791,16 @@ impl Api {
.await
}

/// Moves a session off the runner it runs on, to another that would
/// run it (`POST /sessions/{id}/move`).
pub async fn move_off(&self, session: &str) -> Result<Session> {
self.post(
&format!("/sessions/{}/move", enc(session)),
&serde_json::json!({}),
)
.await
}

pub async fn resume(
&self,
session: &str,
Expand Down
2 changes: 1 addition & 1 deletion crates/fctl-control/src/api/autopilots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ async fn view(
handoff_at: row.handoff_at(),
fresh_asked: row.state() == AutopilotState::On
&& row.reasons().contains(&AutopilotWakeReason::Fresh),
session: row.session(),
session: row.session(ctx.now),
wake_at: row.wake_at.filter(|_| row.state() == AutopilotState::On),
wake_reason: row
.wake_reason()
Expand Down
32 changes: 32 additions & 0 deletions crates/fctl-control/src/api/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,38 @@ pub async fn stop(ctx: &mut Ctx, id: &str) -> AppResult<Response> {
get(ctx, id).await
}

/// `POST /sessions/{id}/move`: the session leaves the runner it runs on,
/// which doesn't get it back, and starts on another that would run it, as
/// a resume there does (FleetDO's `move_session`). For a runner that went
/// quiet, or sleeps but for a moment now and then, which a session waits
/// for otherwise.
pub async fn move_off(ctx: &mut Ctx, id: &str) -> AppResult<Response> {
let a = access::session(ctx, id).await?;
a.require_owner()?;
refuse_review(&a.row)?;
if status_now(ctx, &a.row).await.is_terminal() {
return Err(conflict(
"It isn't running: a resume starts it on any runner that would run it.",
));
}
let fleet = internal::fleet_stub(&ctx.env)?;
let moved: internal::Moved = internal::post(
&fleet,
"/move",
&internal::Move {
session_id: id.to_owned(),
},
)
.await?;
ctx.audit_in(
Some(a.workspace_id()),
"session.moved",
Some(id),
Some(serde_json::json!({ "from": moved.from })),
);
get(ctx, id).await
}

pub async fn resume(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Response> {
let body: ResumeSessionRequest = if http::header(req, "Content-Type").is_some() {
http::body(req).await?
Expand Down
136 changes: 100 additions & 36 deletions crates/fctl-control/src/autopilots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,14 @@ pub struct AutopilotRow {
pub session_messaged_at: Option<i64>,
#[serde(deserialize_with = "opt_int", default)]
pub session_updated_at: Option<i64>,
/// The runner its own session runs on, and when D1 last heard from it
/// (each of its heartbeats, while it is enabled).
#[serde(default)]
pub session_runner_id: Option<String>,
#[serde(default)]
pub session_runner_name: Option<String>,
#[serde(deserialize_with = "opt_int", default)]
pub session_runner_seen_at: Option<i64>,
}

pub const AUTOPILOT_SELECT: &str = "SELECT a.project_id, a.workspace_id, a.scope, a.state, a.paused_reason, \
Expand All @@ -140,12 +148,15 @@ pub const AUTOPILOT_SELECT: &str = "SELECT a.project_id, a.workspace_id, a.scope
du.name AS direction_by_name, du.avatar_url AS direction_by_avatar, \
ps.number AS session_number, ps.status AS session_status, ps.created_at AS session_created_at, \
ps.credential_id AS session_credential_id, json_extract(ps.stats, '$.context_tokens') AS session_context, \
ps.messaged_at AS session_messaged_at, ps.updated_at AS session_updated_at \
ps.messaged_at AS session_messaged_at, ps.updated_at AS session_updated_at, \
ps.runner_id AS session_runner_id, psr.name AS session_runner_name, \
CASE WHEN psr.enabled = 1 THEN psr.last_seen_at END AS session_runner_seen_at \
FROM autopilots a \
LEFT JOIN users ou ON ou.id = a.owner_id \
LEFT JOIN users pu ON pu.id = a.paused_by \
LEFT JOIN users du ON du.id = a.direction_by \
LEFT JOIN sessions ps ON ps.id = a.session_id";
LEFT JOIN sessions ps ON ps.id = a.session_id \
LEFT JOIN runners psr ON psr.id = ps.runner_id";

impl AutopilotRow {
pub fn scope(&self) -> AutopilotScope {
Expand Down Expand Up @@ -181,8 +192,8 @@ impl AutopilotRow {
self.session_context.and_then(|t| u64::try_from(t).ok())
}

/// Its own session as people and the API see it.
pub fn session(&self) -> Option<fctl_proto::autopilot::AutopilotSession> {
/// Its own session as people and the API see it, as of `now`.
pub fn session(&self, now: i64) -> Option<fctl_proto::autopilot::AutopilotSession> {
match (
&self.session_id,
self.session_number,
Expand All @@ -196,6 +207,17 @@ impl AutopilotRow {
status,
started_at,
context_tokens: self.session_context(),
runner: match (&self.session_runner_id, &self.session_runner_name) {
(Some(id), Some(name)) => Some(fctl_proto::session::RunnerRef {
id: fctl_proto::ids::RunnerId(id.clone()),
name: name.clone(),
}),
_ => None,
},
// Only while it runs there: a stopped session's runner
// keeps its sandbox, but holds up nothing.
runner_away_since: ap::away_since(self.session_runner_seen_at, now)
.filter(|_| ap::on_runner(status)),
})
}
_ => None,
Expand Down Expand Up @@ -975,13 +997,36 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap
}
// One a person just messaged works already (`ap::own_status`).
let status = row.session_status_now(now);
// Where its own session's sandbox is, as the fleet has it, while it
// has one or may resume into one: should the fleet not say, it
// carries on as before.
let sandbox = match (row.session_id.as_deref(), status) {
(Some(id), Some(st)) if st != SessionStatus::Failed => {
match sandbox_of(env, id).await {
Ok(at) => Some(at),
Err(e) => {
worker::console_error!(
"autopilot {}: where its session's sandbox is: {}",
row.project_id,
e.0.message
);
None
}
}
}
_ => None,
};
let view = sandbox.as_ref().map(sandbox_view).unwrap_or_default();
// Stranded where its runner went away, it works no more, and the
// wake moves it to a fresh session on a runner that can be reached.
let stranded = status.is_some_and(|st| ap::stranded(st, view));
// People asked for a fresh session while its own works: the wake
// waits for that one's turn to end, which wakes it again at once
// (`session_moved`; here, should it have ended since it was read),
// and all it woke for goes to the fresh session. One a message is on
// its way to waits for the turn as long as the message keeps it at
// work, and goes on without it then: its status says idle meanwhile.
if ap::holds(&reasons, status) {
if ap::holds(&reasons, status, view) {
let again = row.message_on_its_way(now).unwrap_or(now);
q(
db,
Expand Down Expand Up @@ -1013,7 +1058,7 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap
);
}
let news = News::gather(db, row, now).await?;
let working = status.is_some_and(ap::at_work);
let working = status.is_some_and(ap::at_work) && !stranded;
// At work already: a check-in can wait; news reaches it at its next
// step.
let only_time = reasons
Expand Down Expand Up @@ -1043,29 +1088,13 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap
}
_ => Some(ap::Fresh::Failed),
};
// Between its turns, where its sandbox is counts too: off a runner
// that drains, and rather than resume without its conversation on
// another runner, it moves to a fresh session (`ap::moves`). Should
// the fleet not say, it carries on as before.
let mut sandbox = None;
let fresh = match (fresh, row.session_id.as_deref(), status) {
(None, Some(id), Some(st)) if ap::between_turns(st) => match sandbox_of(env, id).await
{
Ok(at) => {
let moved = ap::moves(st, sandbox_view(&at));
sandbox = Some(at);
moved
}
Err(e) => {
worker::console_error!(
"autopilot {}: where its session's sandbox is: {}",
row.project_id,
e.0.message
);
None
}
},
(f, ..) => f,
// Where its sandbox is counts too: off a runner that went away, or
// between its turns off one that drains, and rather than resume
// without its conversation on another runner, it moves to a fresh
// session (`ap::moves`).
let fresh = match (fresh, status) {
(None, Some(st)) if sandbox.is_some() => ap::moves(st, view),
(f, _) => f,
};
let carries_on = fresh.is_none();
// Near where it hands off, it hears so, to write down what its next
Expand Down Expand Up @@ -1159,12 +1188,14 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap
.await?;
let mut line = woke_line(&reasons, &wake);
if let Some(why) = fresh.filter(|_| row.session_id.is_some())
&& let Some(said) = ap::fresh_why(
why,
sandbox.as_ref().map(sandbox_view).unwrap_or_default(),
)
&& let Some(said) = ap::fresh_why(why, view)
{
line.push_str(&format!(", in a fresh session: {said}"));
// Its runner went away, alone: the fresh session says it all.
if reasons == [AutopilotWakeReason::Away] {
line = format!("Woke in a fresh session: {said}");
} else {
line.push_str(&format!(", in a fresh session: {said}"));
}
}
log(
db,
Expand Down Expand Up @@ -1396,6 +1427,8 @@ fn retrying(db: &D1Database, project_id: &str, at: i64) -> AppResult<Query> {

/// What [`woke_line`] says of [`AutopilotWakeReason::Fresh`], alone.
const FRESH_ASKED: &str = "someone asked for a fresh session";
/// What [`woke_line`] says of [`AutopilotWakeReason::Away`].
const AWAY: &str = "its session's runner went away";

/// What a wake says in the log: "Woke for its check-in", "Woke: Ada's
/// note, shop#41".
Expand Down Expand Up @@ -1439,13 +1472,19 @@ fn woke_line(reasons: &[AutopilotWakeReason], wake: &AutopilotWake) -> String {
[] => "people's sessions".into(),
many => format!("{} of people's sessions", many.len()),
},
AutopilotWakeReason::Away => AWAY.into(),
AutopilotWakeReason::Other => continue,
});
}
match parts.as_slice() {
[] => "Woke".into(),
// "Woke as it was put on", alone; "being put on" among others.
[one] if one.starts_with("it was ") || one == "someone woke it" || one == FRESH_ASKED => {
[one]
if one.starts_with("it was ")
|| one == "someone woke it"
|| one == FRESH_ASKED
|| one == AWAY =>
{
format!("Woke as {one}")
}
[one] => format!("Woke for {one}"),
Expand All @@ -1457,6 +1496,7 @@ fn woke_line(reasons: &[AutopilotWakeReason], wake: &AutopilotWake) -> String {
Some(was) => format!("being {was}"),
None if p == "someone woke it" => "someone waking it".to_owned(),
None if p == FRESH_ASKED => "someone asking for a fresh session".to_owned(),
None if p == AWAY => "its session's runner going away".to_owned(),
None => p.clone(),
})
.collect::<Vec<_>>()
Expand Down Expand Up @@ -1648,6 +1688,7 @@ fn sandbox_view(at: &crate::internal::SandboxAt) -> ap::Sandbox<'_> {
online: at.runner.as_ref().is_some_and(|r| r.online),
draining: at.runner.as_ref().is_some_and(|r| r.draining),
elsewhere: at.elsewhere,
away: at.runner.as_ref().is_some_and(|r| r.away),
}
}

Expand Down Expand Up @@ -2589,6 +2630,28 @@ pub async fn session_moved(
Ok(())
}

/// Its own session `session_id` was cut off: fctl stopped it as its runner
/// stayed away (`do_fleet`'s `expire_offline_runners`), in the middle of
/// its turn or before it took up a message. Nothing else may wake it
/// before its check-in, so it wakes now, and carries on in a fresh
/// session on a runner that can be reached (`ap::moves`).
pub async fn own_cut_off(env: &Env, autopilot: &str, session_id: &str, now: i64) -> AppResult<()> {
let db = env.d1("DB")?;
let woke = nudging(
&db,
autopilot,
AutopilotWakeReason::Away,
now,
Some(("session_id = ?4", vec![s(session_id)])),
)?
.run()
.await?;
if woke > 0 {
ring(env).await;
}
Ok(())
}

/// What a session people started that moved means to the autopilot that
/// manages it, if one does ([`manager`]; from SessionObject, which tells
/// it only of what would wake the autopilot for one of its own,
Expand Down Expand Up @@ -4422,7 +4485,8 @@ mod tests {
);
assert!(ap::holds(
&[AutopilotWakeReason::Fresh],
r.session_status_now(NOW)
r.session_status_now(NOW),
ap::Sandbox::default()
));
Ok(())
}
Expand Down
Loading
Loading