Watch
0
0
Fork
You've already forked hyperhive
0

matrix daemon: stay up when the primary account is down and say why in the tools

This commit is contained in:
damocles 2026-11-28 02:37:21 +01:00 • committed by mara
commit 73ef63a5e5
5 changed files with 159 additions and 81 deletions

View file

@ -683,13 +683,14 @@ Without the path-trigger sibling
(`systemd.paths.hive-matrix-daemon`, `PathExistsGlob = (`systemd.paths.hive-matrix-daemon`, `PathExistsGlob =
<this agent's state dir>/matrix-token*` — the trailing `*` also catches <this agent's state dir>/matrix-token*` — the trailing `*` also catches
a declared secondary token file like `matrix-token-ccc`), the daemon a declared secondary token file like `matrix-token-ccc`), the daemon
would exit 0 quietly the first time it ran and the MCP would have no would only notice a new token on its next retry. The `.path` unit makes the
daemon until the next restart. The `.path` unit makes the appearance appearance of the token re-fire the service so the daemon comes alive in the
of the token re-fire the service so the daemon comes alive in the
same boot cycle as same boot cycle as
provisioning. A token in the store changes no file, so a store-backed agent provisioning. A daemon whose primary account has no token, or whose homeserver
also gets a timer that restarts the daemon five minutes after it last is down, doesn't exit: it keeps serving the matrix tools, which answer with
exited. A running daemon re-lists its linked accounts in the store why the account is down, and it tries the primary again every two minutes. A token in the store changes no
file, so that retry (and a restart) is how the daemon picks up one the swarm
minted. A running daemon re-lists its linked accounts in the store
every two minutes and, when the set changed, exits with status every two minutes and, when the set changed, exits with status
75, which the unit's `RestartForceExitStatus` restarts. On the same 75, which the unit's `RestartForceExitStatus` restarts. On the same
two-minute tick it tries again each secondary account that didn't come two-minute tick it tries again each secondary account that didn't come

View file

@ -112,10 +112,12 @@ directly over streamable-http on `services.hyperhive.agent.mcp.matrixHttpPort`
`{ type = "http"; url = ...; }`). Same shape as `hive-bash-daemon` and `{ type = "http"; url = ...; }`). Same shape as `hive-bash-daemon` and
the built-in `hyperhive` surface (`hive-mcp-http`) — claude reconnects the built-in `hyperhive` surface (`hive-mcp-http`) — claude reconnects
to the stable URL every turn instead of respawning a stdio child. to the stable URL every turn instead of respawning a stdio child.
Silently exits when the primary account has no token yet; the When the primary account has no token yet, or the homeserver rejects it
`systemd.paths.hive-matrix-daemon` watcher restarts it when a token file or is down, the daemon stays up and serves the tools anyway: a call that
appears, and, on an agent with a store, a timer restarts it while it's needs the account fails with `matrix account "<name>" is not up: <why>`,
down so it re-reads a token the swarm minted into the store. and the daemon retries the account every two minutes until it joins. The
`systemd.paths.hive-matrix-daemon` watcher also restarts the daemon when a
token file appears, so a fresh token doesn't wait for the next retry.
**Sync protocol**: when the homeserver advertises sliding sync (MSC4186, **Sync protocol**: when the homeserver advertises sliding sync (MSC4186,
`org.matrix.simplified_msc3575` in `/versions`) the daemon uses it: one `org.matrix.simplified_msc3575` in `/versions`) the daemon uses it: one

View file

@ -281,6 +281,8 @@ pub struct AccountStatus {
pub struct Registry { pub struct Registry {
primary: String, primary: String,
by_name: RwLock<HashMap<String, Arc<Client>>>, by_name: RwLock<HashMap<String, Arc<Client>>>,
/// Why each account that is not up is not: what a tool call for it says.
down: RwLock<HashMap<String, String>>,
} }
/// Pick which account name a request resolves to, or an error. Pure (no /// Pick which account name a request resolves to, or an error. Pure (no
@ -315,11 +317,31 @@ impl Registry {
Self { Self {
primary, primary,
by_name: RwLock::default(), by_name: RwLock::default(),
down: RwLock::default(),
} }
} }
/// The primary account's name.
#[must_use]
pub fn primary(&self) -> &str {
&self.primary
}
/// Note that `name` is not up, for `reason`, so a tool call for it can say
/// so instead of finding no such account.
pub fn note_down(&self, name: &str, reason: &str) {
self.down
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(name.to_owned(), reason.to_owned());
}
/// Register a restored client under `name`. /// Register a restored client under `name`.
pub fn insert(&self, name: String, client: Client) { pub fn insert(&self, name: String, client: Client) {
self.down
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&name);
self.by_name self.by_name
.write() .write()
.unwrap_or_else(std::sync::PoisonError::into_inner) .unwrap_or_else(std::sync::PoisonError::into_inner)
@ -386,10 +408,19 @@ impl Registry {
names.sort_unstable(); names.sort_unstable();
let name = pick_name(account, &self.primary, &names)?; let name = pick_name(account, &self.primary, &names)?;
clients.get(name).cloned().ok_or_else(|| { clients.get(name).cloned().ok_or_else(|| {
format!( let down = self
.down
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match down.get(name) {
Some(reason) => format!(
"matrix account {name:?} is not up: {reason}; the daemon keeps trying, so try the call again later"
),
None => format!(
"unknown matrix account {name:?}; available accounts: [{}]", "unknown matrix account {name:?}; available accounts: [{}]",
names.join(", ") names.join(", ")
) ),
}
}) })
} }

View file

@ -135,14 +135,15 @@ async fn main() -> Result<ExitCode> {
let registry = Registry::new(primary); let registry = Registry::new(primary);
let restore = let restore =
|cfg: AccountCfg, is_primary| async move { restore_account(&cfg, is_primary).await }; |cfg: AccountCfg, is_primary| async move { restore_account(&cfg, is_primary).await };
let Some(Boot { sync_loops, down }) = bring_up_all(cfgs, &registry, restore).await? else { // The daemon stays up whether or not an account came up: a primary with no
return Ok(ExitCode::SUCCESS); // token yet, or a homeserver that does not answer, leaves it down and
}; // retried, while the tools answer with why (see `Registry::resolve`) instead
// of the agent finding the MCP server refusing connections.
if registry.is_empty() { let Boot {
tracing::warn!("no matrix accounts restored; exiting cleanly"); sync_loops,
return Ok(ExitCode::SUCCESS); mut down,
} } = bring_up_all(cfgs, &registry, restore).await;
down.steady = Some(registry.primary().to_owned());
// Startup cancel-and-recreate (loose-ends v2): wipe this agent's // Startup cancel-and-recreate (loose-ends v2): wipe this agent's
// matrix todos so stale ones (rooms read / invites resolved while the // matrix todos so stale ones (rooms read / invites resolved while the
@ -316,23 +317,18 @@ async fn wait_for_linked_change(
} }
/// What [`bring_up_all`] brought up: the sync loops of the accounts that came /// What [`bring_up_all`] brought up: the sync loops of the accounts that came
/// up, and the secondaries left to [`retry_down`]. /// up, and the accounts left to [`retry_down`].
struct Boot { struct Boot {
sync_loops: Vec<NamedSyncLoop>, sync_loops: Vec<NamedSyncLoop>,
down: DownAccounts<Retry>, down: DownAccounts<Retry>,
} }
/// Try each account of `cfgs` once with `restore`, the first as the primary, /// Try each account of `cfgs` once with `restore`, the first as the primary,
/// and insert each that comes up into `registry`. `Ok(None)` when the primary /// and insert each that comes up into `registry`. One that does not (no token,
/// has no token. Each `restore` is bounded by [`within_restore_timeout`]. /// a homeserver that fails, a restore that outlasts [`RESTORE_TIMEOUT`]) is
/// /// left in the returned [`Boot::down`] and noted in `registry` with its reason.
/// # Errors /// Each `restore` is bounded by [`within_restore_timeout`].
/// The primary failing to restore, a timeout included. async fn bring_up_all<F, Fut>(cfgs: Vec<AccountCfg>, registry: &Registry, mut restore: F) -> Boot
async fn bring_up_all<F, Fut>(
cfgs: Vec<AccountCfg>,
registry: &Registry,
mut restore: F,
) -> Result<Option<Boot>>
where where
F: FnMut(AccountCfg, bool) -> Fut, F: FnMut(AccountCfg, bool) -> Fut,
Fut: std::future::Future<Output = Restore>, Fut: std::future::Future<Output = Restore>,
@ -351,32 +347,42 @@ where
sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag))); sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag)));
registry.insert(cfg.name, client); registry.insert(cfg.name, client);
} }
// No token yet: for the primary that means the daemon isn't // No token yet. For the primary that is the account the swarm has
// useful — exit 0, and systemd restarts us once a token exists // not created yet, or a homeserver that does not answer: the tools
// (the path-watcher for a file, the re-check timer for the store). // say so, and the retry loop tries again.
Ok(None) if is_primary => { Ok(None) if is_primary => {
tracing::warn!( tracing::warn!(
account = %cfg.name, account = %cfg.name,
"primary matrix account has no token yet; exiting cleanly \ "primary matrix account has no token yet; the tools say so and the daemon keeps retrying"
(systemd restarts us once one exists)"
); );
return Ok(None); registry.note_down(&cfg.name, NO_TOKEN);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), NO_TOKEN);
} }
Ok(None) => { Ok(None) => {
tracing::warn!(account = %cfg.name, "secondary matrix account has no token; will retry"); tracing::warn!(account = %cfg.name, "secondary matrix account has no token; will retry");
registry.note_down(&cfg.name, NO_TOKEN);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), NO_TOKEN); down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), NO_TOKEN);
} }
// The primary failing to restore is fatal (propagate so // The primary failing to restore is retried by `retry_down` like a
// systemd retries on a transient blip — matches legacy // secondary, at once and at a steady pace, and its tools say why
// behaviour); a secondary failing is retried with backoff // in the meantime. A secondary failing is retried with backoff
// here, then left to `retry_down`. // here, then left to `retry_down`.
Err(e) if is_primary => return Err(e.context("bring up primary matrix account")), Err(e) if is_primary => {
Err(e) => match bring_up_secondary_with_retry(&cfg, e, &mut restore).await { let reason = format!("{e:#}");
Some(client) => { tracing::warn!(
account = %cfg.name,
error = %reason,
"primary matrix account failed to come up; the tools say so and the daemon keeps retrying"
);
registry.note_down(&cfg.name, &reason);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), &reason);
}
Err(e) => {
if let Some(client) = bring_up_secondary_with_retry(&cfg, e, &mut restore).await {
sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag))); sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag)));
registry.insert(cfg.name, client); registry.insert(cfg.name, client);
} } else {
None => { registry.note_down(&cfg.name, FAILED_AT_START);
down.failed( down.failed(
cfg.name.clone(), cfg.name.clone(),
(cfg, tag), (cfg, tag),
@ -384,10 +390,10 @@ where
FAILED_AT_START, FAILED_AT_START,
); );
} }
},
} }
} }
Ok(Some(Boot { sync_loops, down })) }
Boot { sync_loops, down }
} }
/// `restore` of `account`, failing once it has run for [`RESTORE_TIMEOUT`]. /// `restore` of `account`, failing once it has run for [`RESTORE_TIMEOUT`].
@ -497,6 +503,9 @@ fn retry_delay(failures: u32) -> std::time::Duration {
/// again (`T`) and the earliest time to. /// again (`T`) and the earliest time to.
struct DownAccounts<T> { struct DownAccounts<T> {
by_name: BTreeMap<String, Down<T>>, by_name: BTreeMap<String, Down<T>>,
/// The account that is retried at the base pace however often it fails,
/// not at a doubling one: the primary, whose tools are all down with it.
steady: Option<String>,
} }
struct Down<T> { struct Down<T> {
@ -511,6 +520,7 @@ impl<T> Default for DownAccounts<T> {
fn default() -> Self { fn default() -> Self {
Self { Self {
by_name: BTreeMap::new(), by_name: BTreeMap::new(),
steady: None,
} }
} }
} }
@ -521,6 +531,7 @@ impl<T> DownAccounts<T> {
/// account's first, or for a different reason than the last — and so /// account's first, or for a different reason than the last — and so
/// worth a warning. /// worth a warning.
fn failed(&mut self, name: String, retry: T, at: Instant, reason: &str) -> bool { fn failed(&mut self, name: String, retry: T, at: Instant, reason: &str) -> bool {
let steady = self.steady.as_deref() == Some(name.as_str());
let down = self.by_name.entry(name).or_insert(Down { let down = self.by_name.entry(name).or_insert(Down {
retry, retry,
failures: 0, failures: 0,
@ -530,7 +541,12 @@ impl<T> DownAccounts<T> {
let news = down.failures == 0 || down.reason != reason; let news = down.failures == 0 || down.reason != reason;
reason.clone_into(&mut down.reason); reason.clone_into(&mut down.reason);
down.failures += 1; down.failures += 1;
down.not_before = at + retry_delay(down.failures); down.not_before = at
+ if steady {
LINKED_REFRESH
} else {
retry_delay(down.failures)
};
news news
} }
@ -616,7 +632,7 @@ async fn retry_once<F, Fut>(
let restored = within_restore_timeout(&name, restore(cfg.clone())).await; let restored = within_restore_timeout(&name, restore(cfg.clone())).await;
match restored { match restored {
Ok(Some(client)) => { Ok(Some(client)) => {
tracing::info!(account = %name, "secondary matrix account came up"); tracing::info!(account = %name, "matrix account came up");
let sync_loop = account_sync_loop(&client, tag); let sync_loop = account_sync_loop(&client, tag);
down.came_up(&name); down.came_up(&name);
registry.insert(name.clone(), client); registry.insert(name.clone(), client);
@ -627,16 +643,18 @@ async fn retry_once<F, Fut>(
let _ = up.send(named(name, sync_loop)); let _ = up.send(named(name, sync_loop));
} }
Ok(None) => { Ok(None) => {
registry.note_down(&name, NO_TOKEN);
if down.failed(name.clone(), (cfg, tag), now, NO_TOKEN) { if down.failed(name.clone(), (cfg, tag), now, NO_TOKEN) {
tracing::warn!(account = %name, "secondary matrix account has no token; will keep retrying"); tracing::warn!(account = %name, "matrix account has no token; will keep retrying");
} else { } else {
tracing::debug!(account = %name, "secondary matrix account still has no token"); tracing::debug!(account = %name, "secondary matrix account still has no token");
} }
} }
Err(e) => { Err(e) => {
let reason = format!("{e:#}"); let reason = format!("{e:#}");
registry.note_down(&name, &reason);
if down.failed(name.clone(), (cfg, tag), now, &reason) { if down.failed(name.clone(), (cfg, tag), now, &reason) {
tracing::warn!(account = %name, error = %reason, "secondary matrix account failing; will keep retrying"); tracing::warn!(account = %name, error = %reason, "matrix account failing; will keep retrying");
} else { } else {
tracing::debug!(account = %name, error = %reason, "secondary matrix account still failing"); tracing::debug!(account = %name, error = %reason, "secondary matrix account still failing");
} }
@ -1478,7 +1496,7 @@ mod tests {
} }
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn a_primary_whose_restore_hangs_at_boot_fails_the_boot() { async fn a_primary_whose_restore_hangs_at_boot_goes_down_and_says_why() {
let reg = Registry::new("hung".to_owned()); let reg = Registry::new("hung".to_owned());
let boot = tokio::time::timeout( let boot = tokio::time::timeout(
Duration::from_hours(1), Duration::from_hours(1),
@ -1487,9 +1505,44 @@ mod tests {
.await .await
.expect("boot never finished"); .expect("boot never finished");
let err = boot.err().expect("a hung primary fails the boot"); // the daemon carries on without it, and the tools say why it's missing
assert!(format!("{err:#}").contains("hung"), "{err:#}"); assert_eq!(names(&reg), ["fine"]);
assert_eq!(boot.sync_loops.len(), 1);
let err = reg.resolve(Some("hung")).expect_err("the primary is down");
assert!(err.contains("not up"), "{err}");
assert!(err.contains("try the call again later"), "{err}");
}
#[tokio::test(start_paused = true)]
async fn a_primary_without_a_token_goes_down_instead_of_ending_the_boot() {
let reg = Registry::new("main".to_owned());
let boot = bring_up_all(vec![cfg("main")], &reg, |_, _| async {
Ok(None) as Restore
})
.await;
assert!(reg.is_empty()); assert!(reg.is_empty());
assert!(boot.sync_loops.is_empty());
let err = reg.resolve(None).expect_err("the primary is down");
assert!(err.contains("not up"), "{err}");
}
#[test]
fn the_primary_is_retried_at_a_steady_pace_and_a_secondary_backs_off() {
let t0 = Instant::now();
let mut down = DownAccounts::<()> {
steady: Some("main".to_owned()),
..DownAccounts::default()
};
// three failures each: the secondary's wait doubles, the primary's doesn't
for _ in 0..3 {
down.failed("main".to_owned(), (), t0, "again");
down.failed("other".to_owned(), (), t0, "again");
}
let due = down.due(t0 + LINKED_REFRESH).map(|(name, ())| name);
assert_eq!(due, Some("main"));
down.came_up("main");
assert!(down.due(t0 + LINKED_REFRESH).is_none());
} }
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
@ -1504,9 +1557,7 @@ mod tests {
), ),
) )
.await .await
.expect("boot never finished") .expect("boot never finished");
.expect("the primary came up")
.expect("the primary had a token");
assert_eq!(names(&reg), ["main", "fine"]); assert_eq!(names(&reg), ["main", "fine"]);
assert_eq!(boot.sync_loops.len(), 2); assert_eq!(boot.sync_loops.len(), 2);

View file

@ -97,9 +97,9 @@ in
(for `main`, a file only when the store has no token: the (for `main`, a file only when the store has no token: the
swarm mints `main` into the store; an operator-supplied swarm mints `main` into the store; an operator-supplied
secret for an external one). The daemon secret for an external one). The daemon
leaves an extra account whose token is absent down and tries leaves an account whose token is absent down and tries
it again every few minutes, and it again every few minutes, answering its tool calls with
exits cleanly to wait on the path watcher when `main`'s is. why it is down meanwhile; it stays up when `main`'s is.
''; '';
}; };
sessionDir = lib.mkOption { sessionDir = lib.mkOption {
@ -384,14 +384,10 @@ in
serviceConfig = { serviceConfig = {
ExecStart = "${config.services.hyperhive.agent.packages.hive-matrix-daemon}/bin/hive-matrix-daemon --http 127.0.0.1:${toString config.services.hyperhive.agent.mcp.matrixHttpPort}"; ExecStart = "${config.services.hyperhive.agent.packages.hive-matrix-daemon}/bin/hive-matrix-daemon --http 127.0.0.1:${toString config.services.hyperhive.agent.mcp.matrixHttpPort}";
SyslogIdentifier = "hive-matrix-daemon"; SyslogIdentifier = "hive-matrix-daemon";
# `on-failure`, not `always`: the daemon deliberately exits 0 # `on-failure`, not `always`: a clean exit is deliberate (the
# (a clean, non-failure exit) when no token is provisioned yet # daemon stays up when no token is provisioned or the homeserver
# (see the module doc above) — the `systemd.paths` watcher # is down, and retries the account itself). This is no different
# below re-fires it the moment a token file appears (the timer # from `hive-bash-daemon`'s reasoning (a down window loses the MCP
# above, for a token in the store),
# instead of `always` busy-looping every `RestartSec` until
# then. Once a token exists this is no different from
# `hive-bash-daemon`'s reasoning (a down window loses the MCP
# tools with no stdio fallback) — a genuine crash is a # tools with no stdio fallback) — a genuine crash is a
# non-zero exit, which `on-failure` already restarts. # non-zero exit, which `on-failure` already restarts.
Restart = "on-failure"; Restart = "on-failure";
@ -420,8 +416,9 @@ in
# Re-start the daemon while it is down, when its token lives in the store. # Re-start the daemon while it is down, when its token lives in the store.
# The path unit below only sees files, and a token the swarm mints or # The path unit below only sees files, and a token the swarm mints or
# replaces in the store changes no file: a daemon that exited on a missing # replaces in the store changes no file: a daemon that went down
# or replaced token would otherwise stay down until the container restarts. # (crash, or the exit 75 below) would otherwise stay down until the
# container restarts.
# Relative to the daemon's last exit, so it never fires while the daemon # Relative to the daemon's last exit, so it never fires while the daemon
# runs; five minutes is the swarm's own re-mint cadence. # runs; five minutes is the swarm's own re-mint cadence.
systemd.timers.hive-matrix-daemon = lib.mkIf (matrixEnabled && storeConfigured) { systemd.timers.hive-matrix-daemon = lib.mkIf (matrixEnabled && storeConfigured) {
@ -431,9 +428,8 @@ in
}; };
# Re-fire the daemon when a matrix token file appears (a declared # Re-fire the daemon when a matrix token file appears (a declared
# `tokenFile`, or a `main` from before the swarm minted it). Without this # `tokenFile`, or a `main` from before the swarm minted it) so the daemon
# the daemon would exit 0 silently on first boot and the MCP # picks it up at once instead of on its next two-minute retry. See
# would have no backend until next restart. See
# `docs/4-implementation/agent-state/persistence.md` (same section as above). # `docs/4-implementation/agent-state/persistence.md` (same section as above).
systemd.paths.hive-matrix-daemon = lib.mkIf matrixEnabled { systemd.paths.hive-matrix-daemon = lib.mkIf matrixEnabled {
description = "trigger hive-matrix-daemon when a matrix token appears"; description = "trigger hive-matrix-daemon when a matrix token appears";
@ -443,12 +439,9 @@ in
# #
# ⚠️ This agent's own state dir, not a glob over `/agents/*/`. Every # ⚠️ This agent's own state dir, not a glob over `/agents/*/`. Every
# agent's state dir is visible from inside every container, so a # agent's state dir is visible from inside every container, so a
# wildcard is satisfied by a sibling's token — and this daemon exits 0 # wildcard is satisfied by a sibling's token, so it would restart a
# when it has no token of its own (see `Restart = "on-failure"` # daemon that has none of its own. Scoped to this agent, the condition
# above), so the unit deactivates, the path unit re-arms, the # is false exactly when the daemon would have nothing to do.
# sibling's token still matches, and it fires again until the start
# limit stops it. Scoped to this agent, the condition is false exactly
# when the daemon would have nothing to do.
pathConfig.PathExistsGlob = "${stateDir}/matrix-token*"; pathConfig.PathExistsGlob = "${stateDir}/matrix-token*";
}; };
}; };