1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//! A started session's turn in the daemon-wide agent budget (#1714).
//!
//! The turns of a session another session started share
//! `behavior.agent_concurrency` with subagent runs: each waits `queued` for
//! a slot before it runs. Unlike a subagent run, such a turn can wait on
//! others: on a person's answer, or on the sessions and subagents it
//! started, which may need a slot from the same budget. So it holds its slot
//! only while it runs alone (`JobRegistry::runs_alone`): `running`, with
//! nothing it started under way. Otherwise it lends the slot back to the
//! budget, and once it runs alone again it takes a slot again, in line, and
//! works on meanwhile. A slot is therefore only ever held by a turn that
//! waits on no other job's slot, and the budget cannot deadlock on itself.
//!
//! A turn that lent its slot is not paused: nothing gates its next model
//! request on a slot. So the budget bounds turns that run alone, not every
//! running agent: each started session with work of its own under way can
//! run one agent beyond it, as many as session control's depth and session
//! caps let agents start.
use std::{convert::Infallible, future::Future, pin::Pin};
use futures_util::FutureExt;
use rho_sdk::CancellationToken;
use super::{
super::{jobs::JobRegistry, subagents::TurnBudget},
turn::DaemonView,
};
use crate::app::{
agent_binding::CapacityClass,
agent_concurrency::{AgentConcurrency, RuntimePermits},
};
/// A turn cancelled, or stopped by the daemon's stop, while it waited for
/// its first slot.
pub(super) struct Withdrawn;
/// What a turn runs with in the budget.
pub(super) enum Slot {
/// Nothing: a person's session's turn.
Unbudgeted,
/// The slot it was admitted with, and the budget to take one again.
Budgeted {
permits: RuntimePermits,
concurrency: AgentConcurrency,
},
}
/// Waits for the turn's first slot, its job `queued` until it has one and
/// then `running`; at once without a `budget`. The request that sent the
/// prompt learns the turn began as soon as it must wait, so it does not wait
/// for capacity; a slot free at once, or a cancel already sent, leaves that
/// to the turn, as for a person's session.
pub(super) async fn admit(
view: &mut DaemonView,
budget: Option<TurnBudget>,
cancel: &CancellationToken,
stopping: &CancellationToken,
) -> Result<Slot, Withdrawn> {
let Some(TurnBudget {
queued,
concurrency,
listing: _listing,
}) = budget
else {
return Ok(Slot::Unbudgeted);
};
let acquire = queued.acquire(cancel);
tokio::pin!(acquire);
let permits = match acquire.as_mut().now_or_never() {
Some(permits) => permits,
None => {
// Answered as begun, but not recorded so: nothing ran yet, so
// a later daemon runs the prompt when it is sent again.
view.accepted();
tokio::select! {
biased;
() = stopping.cancelled() => None,
permits = &mut acquire => permits,
}
}
}
.ok_or(Withdrawn)?;
view.session.admitted();
Ok(Slot::Budgeted {
permits,
concurrency,
})
}
impl Slot {
/// Runs `turn`, the turn of `job`, lending the slot whenever the turn
/// does not run alone and taking one again when it does.
pub(super) async fn lend_while_waiting<T>(
self,
jobs: &JobRegistry,
job: &super::super::jobs::JobId,
turn: impl Future<Output = T>,
) -> T {
match self {
Self::Unbudgeted => turn.await,
Self::Budgeted {
permits,
concurrency,
} => {
tokio::select! {
biased;
ended = turn => ended,
never = keep(permits, &concurrency, jobs, job) => match never {},
}
}
}
}
}
/// A wait for a slot taken again, which leaves the line when dropped.
type Retaking = Pin<Box<dyn Future<Output = Option<RuntimePermits>> + Send>>;
/// Holds `permits` while `job` runs alone, lends them while it does not,
/// and takes a slot again once it does. Runs until the turn drops it.
async fn keep(
permits: RuntimePermits,
concurrency: &AgentConcurrency,
jobs: &JobRegistry,
job: &super::super::jobs::JobId,
) -> Infallible {
let mut held = Some(permits);
let mut retaking: Option<Retaking> = None;
loop {
let changed = jobs.changed();
tokio::pin!(changed);
changed.as_mut().enable();
if !jobs.runs_alone(job) {
if held.take().is_some() {
tracing::debug!(%job, "lent a started session's slot while it waits");
}
retaking = None;
} else if held.is_none() && retaking.is_none() {
let queued = concurrency.join(CapacityClass::Rho);
retaking = Some(Box::pin(async move {
// Only dropping this wait ends it.
queued.acquire(&CancellationToken::new()).await
}));
}
match &mut retaking {
Some(acquire) => tokio::select! {
permits = acquire => {
held = permits;
retaking = None;
}
() = &mut changed => {}
},
None => changed.await,
}
}
}