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 =
<this agent's state dir>/matrix-token*` — the trailing `*` also catches
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
daemon until the next restart. The `.path` unit makes the appearance
of the token re-fire the service so the daemon comes alive in the
would only notice a new token on its next retry. The `.path` unit makes the
appearance of the token re-fire the service so the daemon comes alive in the
same boot cycle as
provisioning. A token in the store changes no file, so a store-backed agent
also gets a timer that restarts the daemon five minutes after it last
exited. A running daemon re-lists its linked accounts in the store
provisioning. A daemon whose primary account has no token, or whose homeserver
is down, doesn't exit: it keeps serving the matrix tools, which answer with
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
75, which the unit's `RestartForceExitStatus` restarts. On the same
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
the built-in `hyperhive` surface (`hive-mcp-http`) — claude reconnects
to the stable URL every turn instead of respawning a stdio child.
Silently exits when the primary account has no token yet; the
`systemd.paths.hive-matrix-daemon` watcher restarts it when a token file
appears, and, on an agent with a store, a timer restarts it while it's
down so it re-reads a token the swarm minted into the store.
When the primary account has no token yet, or the homeserver rejects it
or is down, the daemon stays up and serves the tools anyway: a call that
needs the account fails with `matrix account "<name>" is not up: <why>`,
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,
`org.matrix.simplified_msc3575` in `/versions`) the daemon uses it: one

View file

@ -281,6 +281,8 @@ pub struct AccountStatus {
pub struct Registry {
primary: String,
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
@ -315,11 +317,31 @@ impl Registry {
Self {
primary,
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`.
pub fn insert(&self, name: String, client: Client) {
self.down
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&name);
self.by_name
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
@ -386,10 +408,19 @@ impl Registry {
names.sort_unstable();
let name = pick_name(account, &self.primary, &names)?;
clients.get(name).cloned().ok_or_else(|| {
format!(
"unknown matrix account {name:?}; available accounts: [{}]",
names.join(", ")
)
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: [{}]",
names.join(", ")
),
}
})
}

View file

@ -135,14 +135,15 @@ async fn main() -> Result<ExitCode> {
let registry = Registry::new(primary);
let restore =
|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 {
return Ok(ExitCode::SUCCESS);
};
if registry.is_empty() {
tracing::warn!("no matrix accounts restored; exiting cleanly");
return Ok(ExitCode::SUCCESS);
}
// The daemon stays up whether or not an account came up: a primary with no
// 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.
let Boot {
sync_loops,
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
// 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
/// up, and the secondaries left to [`retry_down`].
/// up, and the accounts left to [`retry_down`].
struct Boot {
sync_loops: Vec<NamedSyncLoop>,
down: DownAccounts<Retry>,
}
/// 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
/// has no token. Each `restore` is bounded by [`within_restore_timeout`].
///
/// # Errors
/// The primary failing to restore, a timeout included.
async fn bring_up_all<F, Fut>(
cfgs: Vec<AccountCfg>,
registry: &Registry,
mut restore: F,
) -> Result<Option<Boot>>
/// and insert each that comes up into `registry`. One that does not (no token,
/// a homeserver that fails, a restore that outlasts [`RESTORE_TIMEOUT`]) is
/// left in the returned [`Boot::down`] and noted in `registry` with its reason.
/// Each `restore` is bounded by [`within_restore_timeout`].
async fn bring_up_all<F, Fut>(cfgs: Vec<AccountCfg>, registry: &Registry, mut restore: F) -> Boot
where
F: FnMut(AccountCfg, bool) -> Fut,
Fut: std::future::Future<Output = Restore>,
@ -351,32 +347,42 @@ where
sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag)));
registry.insert(cfg.name, client);
}
// No token yet: for the primary that means the daemon isn't
// useful — exit 0, and systemd restarts us once a token exists
// (the path-watcher for a file, the re-check timer for the store).
// No token yet. For the primary that is the account the swarm has
// not created yet, or a homeserver that does not answer: the tools
// say so, and the retry loop tries again.
Ok(None) if is_primary => {
tracing::warn!(
account = %cfg.name,
"primary matrix account has no token yet; exiting cleanly \
(systemd restarts us once one exists)"
"primary matrix account has no token yet; the tools say so and the daemon keeps retrying"
);
return Ok(None);
registry.note_down(&cfg.name, NO_TOKEN);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), NO_TOKEN);
}
Ok(None) => {
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);
}
// The primary failing to restore is fatal (propagate so
// systemd retries on a transient blip — matches legacy
// behaviour); a secondary failing is retried with backoff
// The primary failing to restore is retried by `retry_down` like a
// secondary, at once and at a steady pace, and its tools say why
// in the meantime. A secondary failing is retried with backoff
// here, then left to `retry_down`.
Err(e) if is_primary => return Err(e.context("bring up primary matrix account")),
Err(e) => match bring_up_secondary_with_retry(&cfg, e, &mut restore).await {
Some(client) => {
Err(e) if is_primary => {
let reason = format!("{e:#}");
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)));
registry.insert(cfg.name, client);
}
None => {
} else {
registry.note_down(&cfg.name, FAILED_AT_START);
down.failed(
cfg.name.clone(),
(cfg, tag),
@ -384,10 +390,10 @@ where
FAILED_AT_START,
);
}
},
}
}
}
Ok(Some(Boot { sync_loops, down }))
Boot { sync_loops, down }
}
/// `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.
struct DownAccounts<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> {
@ -511,6 +520,7 @@ impl<T> Default for DownAccounts<T> {
fn default() -> Self {
Self {
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
/// worth a warning.
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 {
retry,
failures: 0,
@ -530,7 +541,12 @@ impl<T> DownAccounts<T> {
let news = down.failures == 0 || down.reason != reason;
reason.clone_into(&mut down.reason);
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
}
@ -616,7 +632,7 @@ async fn retry_once<F, Fut>(
let restored = within_restore_timeout(&name, restore(cfg.clone())).await;
match restored {
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);
down.came_up(&name);
registry.insert(name.clone(), client);
@ -627,16 +643,18 @@ async fn retry_once<F, Fut>(
let _ = up.send(named(name, sync_loop));
}
Ok(None) => {
registry.note_down(&name, 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 {
tracing::debug!(account = %name, "secondary matrix account still has no token");
}
}
Err(e) => {
let reason = format!("{e:#}");
registry.note_down(&name, &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 {
tracing::debug!(account = %name, error = %reason, "secondary matrix account still failing");
}
@ -1478,7 +1496,7 @@ mod tests {
}
#[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 boot = tokio::time::timeout(
Duration::from_hours(1),
@ -1487,9 +1505,44 @@ mod tests {
.await
.expect("boot never finished");
let err = boot.err().expect("a hung primary fails the boot");
assert!(format!("{err:#}").contains("hung"), "{err:#}");
// the daemon carries on without it, and the tools say why it's missing
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!(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)]
@ -1504,9 +1557,7 @@ mod tests {
),
)
.await
.expect("boot never finished")
.expect("the primary came up")
.expect("the primary had a token");
.expect("boot never finished");
assert_eq!(names(&reg), ["main", "fine"]);
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
swarm mints `main` into the store; an operator-supplied
secret for an external one). The daemon
leaves an extra account whose token is absent down and tries
it again every few minutes, and
exits cleanly to wait on the path watcher when `main`'s is.
leaves an account whose token is absent down and tries
it again every few minutes, answering its tool calls with
why it is down meanwhile; it stays up when `main`'s is.
'';
};
sessionDir = lib.mkOption {
@ -384,14 +384,10 @@ in
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}";
SyslogIdentifier = "hive-matrix-daemon";
# `on-failure`, not `always`: the daemon deliberately exits 0
# (a clean, non-failure exit) when no token is provisioned yet
# (see the module doc above) — the `systemd.paths` watcher
# below re-fires it the moment a token file appears (the timer
# 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
# `on-failure`, not `always`: a clean exit is deliberate (the
# daemon stays up when no token is provisioned or the homeserver
# is down, and retries the account itself). 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
# non-zero exit, which `on-failure` already restarts.
Restart = "on-failure";
@ -420,8 +416,9 @@ in
# 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
# replaces in the store changes no file: a daemon that exited on a missing
# or replaced token would otherwise stay down until the container restarts.
# replaces in the store changes no file: a daemon that went down
# (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
# runs; five minutes is the swarm's own re-mint cadence.
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
# `tokenFile`, or a `main` from before the swarm minted it). Without this
# the daemon would exit 0 silently on first boot and the MCP
# would have no backend until next restart. See
# `tokenFile`, or a `main` from before the swarm minted it) so the daemon
# picks it up at once instead of on its next two-minute retry. See
# `docs/4-implementation/agent-state/persistence.md` (same section as above).
systemd.paths.hive-matrix-daemon = lib.mkIf matrixEnabled {
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
# 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
# when it has no token of its own (see `Restart = "on-failure"`
# above), so the unit deactivates, the path unit re-arms, the
# 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.
# wildcard is satisfied by a sibling's token, so it would restart a
# daemon that has none of its own. Scoped to this agent, the condition
# is false exactly when the daemon would have nothing to do.
pathConfig.PathExistsGlob = "${stateDir}/matrix-token*";
};
};