Huginn/crates/huginn-daemon/src/daemon.rs
Meta Vens 5eea49f756 Cut 11b: the semantic read, joined back through the mind
Qdrant supplies candidate ids and scores and nothing else. Mind::rank drops
every hit the mind does not hold, then lets CultNet's selection decide
membership over the whole mind with its keys narrowed to the candidates, so
in_force and cited mean what they mean in query. Order is score then ordinal;
the page is cut to the selection's limit and top_k; next is never set. A
cursor with semantic, blank text and an out-of-range top_k are refused by name
before anything is embedded. Mind::query loses its semantic parameter and the
"index is not wired" refusal; the published request schema's description of
SemanticQuery follows.

The serve loop never waits on the embedder: a semantic query becomes a Search
held beside its session, the worker embeds (behind the model's query
instruction) and searches between batches, and the loop answers when the
worker has or when ServeOptions::search_timeout passes. A worker that is
Failing or Refused refuses at once, typed Unavailable naming its own error.
VectorIndex gains search; Qdrant's adapter sends no filter.

Model identity is re-read before every flush and before every search: a model
re-pulled under the same dimensions but a new digest forgets the
reconciliation instead of mixing vectors, and the next step rebuilds. An idle
worker forgets the reconciliation every Backoff::recheck (60 s), so a lost
collection is found without a write. Both go through Projector::reconcile,
still the one judge.

Also fixes a race in the worker loop found by the mutation runs: entries were
taken from the inbox under one lock and published as wanted under another, so
whoami could read a stale Current with nothing queued while the worker held
them. Taking, absorbing and publishing are now one critical section.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-29 13:37:01 +02:00

807 lines
38 KiB
Rust

//! The dispatch: one mind, one request, one response. No socket, no clock, no
//! rule. `now` is the caller's, so a test pins it and the loop is the only
//! thing that reads a wall clock.
use chrono::{DateTime, Utc};
use cultnet_rs::Selection;
use huginn_mind::epiphany_pipeline::{PipelineRef, Slug};
use huginn_mind::wire::{HuginnMindRequest, HuginnMindResponse, IndexStatus};
use huginn_mind::{Mind, MindRefusal, MindStore, PipelineAdmissionOutcome, SemanticQuery};
/// Where the index attaches. Called after a batch commits, with the refs the
/// batch landed, derived writes included; the sink may read each through
/// `mind.view`. Its error is logged and never reaches the caller: the index
/// does not decide whether a batch was admitted, and the call must not wait on
/// the index's transport. `status` is what `whoami` reports of it.
///
/// A semantic query is asked in two steps because the index answers on its own
/// time: `search` starts one and returns a ticket at once, and `searched`
/// hands over the searches that have finished since it was last called. The
/// candidates are the index's word about nearness and nothing else; the daemon
/// judges them through the mind.
pub trait IndexSink<S: MindStore> {
fn committed(&mut self, mind: &Mind<S>, writes: &[PipelineRef]) -> anyhow::Result<()>;
fn status(&self) -> IndexStatus;
/// Starts a search for the documents nearest `text`, at most `top_k` of
/// them wanted. `Err` says why the index cannot be asked now.
fn search(&mut self, text: &str, top_k: u32) -> Result<SearchTicket, String>;
/// Every search that finished since the last call, by ticket: its
/// candidates and scores, or why it failed.
fn searched(&mut self) -> Vec<(SearchTicket, Result<Hits, String>)>;
}
/// Names one search the index was asked, so the loop can match the answer to
/// the client that is waiting for it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SearchTicket(pub u64);
/// What a search returns: candidate documents and how near each scored, best
/// first. Nothing else about them.
pub type Hits = Vec<(PipelineRef, f32)>;
/// A semantic query the index has been asked and has not yet answered. The
/// serve loop holds it beside the session that asked, and hands it back to
/// `Daemon::finish` with the index's answer.
pub struct Search {
pub ticket: SearchTicket,
selection: Selection,
semantic: SemanticQuery,
}
/// What a request came to: an answer, or a search the index has yet to
/// finish.
pub enum Handled {
Answered(HuginnMindResponse),
Searching(Search),
}
impl Handled {
/// The answer, for a request that cannot be a search.
#[cfg(test)]
pub(crate) fn answered(self) -> HuginnMindResponse {
match self {
Self::Answered(response) => response,
Self::Searching(search) => panic!("expected an answer, got the search {:?}", search.ticket),
}
}
}
/// The envelope's `source_runtime_id` on every response a daemon serving this
/// instance sends. Also what the socket is bound under, before a daemon exists.
pub fn runtime_id(instance: &Slug) -> String {
format!("huginn-{}", instance.0)
}
/// One mind and whatever indexes what lands in it.
pub struct Daemon<S: MindStore, I: IndexSink<S>> {
mind: Mind<S>,
index: I,
}
impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
/// A daemon over a mind that is already open. `Mind::open` takes the
/// store's exclusive lock for the daemon's lifetime, and ruling 15 has it
/// refuse before any socket exists: the caller opens the mind first.
pub fn new(mind: Mind<S>, index: I) -> Self {
Self { mind, index }
}
pub fn with_index<J: IndexSink<S>>(self, index: J) -> Daemon<S, J> {
Daemon { mind: self.mind, index }
}
pub fn mind(&self) -> &Mind<S> {
&self.mind
}
pub fn index(&self) -> &I {
&self.index
}
/// The envelope's `source_runtime_id` on every response this daemon sends.
pub fn runtime_id(&self) -> String {
runtime_id(self.mind.instance())
}
/// One request, one answer, or a search to finish. `Admit` goes to the mind whole, because the
/// batch declares its own instance and admission's A1 is the check. Every
/// other request names an instance: `require_instance` now applies the
/// leaf's own grammar before it compares identity, so a name outside the
/// grammar (a fullwidth fold, say) is refused by name rather than read as
/// merely a foreign mind, and the daemon asks nothing twice.
pub fn handle(&mut self, request: HuginnMindRequest, now: DateTime<Utc>) -> Handled {
if let Some(declared) = request.instance()
&& !matches!(request, HuginnMindRequest::Admit(_))
&& let Err(refusal) = self.mind.require_instance(declared)
{
return Handled::Answered(HuginnMindResponse::Refused(refusal));
}
let answer = match request {
HuginnMindRequest::Whoami => HuginnMindResponse::Whoami(self.mind.status(self.index.status())),
HuginnMindRequest::Admit(batch) => {
let outcome = self.mind.admit(batch, now);
if let PipelineAdmissionOutcome::Committed { writes, .. } = &outcome
&& let Err(error) = self.index.committed(&self.mind, writes)
{
let refs = writes.iter().map(|write| write.id.0.clone()).collect::<Vec<_>>().join(", ");
eprintln!("huginn: the index refused the landed writes [{refs}]: {error:#}");
}
HuginnMindResponse::Admit(outcome)
}
HuginnMindRequest::View { id, .. } => match self.mind.view(&id) {
Ok(view) => HuginnMindResponse::View(view),
Err(refusal) => HuginnMindResponse::Refused(refusal),
},
HuginnMindRequest::Query { selection, semantic: None, .. } => match self.mind.query(&selection) {
Ok(page) => HuginnMindResponse::Query(page),
Err(refusal) => HuginnMindResponse::Refused(refusal),
},
HuginnMindRequest::Query { selection, semantic: Some(semantic), .. } => {
return self.begin_search(selection, semantic);
}
};
Handled::Answered(answer)
}
/// A semantic query starts only if the mind would accept it (so nothing is
/// embedded for a query that cannot be ranked) and the index can be asked.
fn begin_search(&mut self, selection: Selection, semantic: SemanticQuery) -> Handled {
let refused = |refusal: MindRefusal| Handled::Answered(HuginnMindResponse::Refused(refusal));
if let Err(refusal) = self.mind.check_semantic(&selection, &semantic) {
return refused(refusal);
}
match self.index.search(&semantic.text.0, semantic.top_k) {
Ok(ticket) => Handled::Searching(Search { ticket, selection, semantic }),
Err(detail) => refused(MindRefusal::Unavailable { detail }),
}
}
/// Searches the index has finished since this was last called.
pub fn searched(&mut self) -> Vec<(SearchTicket, Result<Hits, String>)> {
self.index.searched()
}
/// The ids among `hits` that the mind holds no document for: the index
/// keeps points the mind no longer has (a restored mind, a second store),
/// and a hit is never shown on the index's word alone.
pub(crate) fn unheld<'a>(&self, hits: &'a Hits) -> Vec<&'a str> {
hits.iter().filter(|(id, _)| !matches!(self.mind.view(id), Ok(Some(_)))).map(|(id, _)| id.id.0.as_str()).collect()
}
/// The answer to a search: the index's candidates ranked through the mind
/// (`Mind::rank` drops what the mind does not hold and lets the selection
/// decide the rest), or, when the index could not answer, a typed
/// `Unavailable`. Never an empty page in place of a failure.
pub fn finish(&mut self, search: Search, found: Result<Hits, String>) -> HuginnMindResponse {
let hits = match found {
Ok(hits) => hits,
Err(detail) => return HuginnMindResponse::Refused(MindRefusal::Unavailable { detail }),
};
for id in self.unheld(&hits) {
eprintln!("huginn: the index returned {id}, which this mind does not hold; it is left out");
}
match self.mind.rank(&search.selection, &search.semantic, &hits) {
Ok(page) => HuginnMindResponse::Query(page),
Err(refusal) => HuginnMindResponse::Refused(refusal),
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use chrono::TimeZone;
use huginn_mind::epiphany_pipeline::{
AuthorityMap, CodeLocation, CutDelete, CutVerification, Date, DocRef, FileChange, Line, NegativeCheck,
OrgRepo, PipelineCampaign, PipelineCutSpec, PipelineDocument, PipelineInstance, PipelineKind,
PipelineQuestion, PipelineRuling, PipelineStewardship, QuestionOption, RulingAuthority, Sha, Short,
StructuralDelta, Title, VerificationTest,
};
use huginn_mind::wire::MindStatus;
use huginn_mind::{MindRefusal, OwnedRedbMessagePackBackingStore};
use std::path::Path;
use cultnet_rs::Selection;
use huginn_mind::{Faculty, PipelineAdmissionBatch, PipelineProvenance, PipelinePageItems, PipelineStatus};
use std::sync::{Arc, Mutex};
use tempfile::TempDir;
pub(crate) const INSTANCE: &str = "yggdrasil";
pub(crate) const OTHER: &str = "thought-cage";
/// `INSTANCE`'s own length, differing in its last byte alone.
pub(crate) const NEAR: &str = "yggdrasix";
/// `INSTANCE` whole, with more after it.
pub(crate) const PREFIXED: &str = "yggdrasil-two";
/// `INSTANCE` in another case, which a slug label permits.
pub(crate) const CASED: &str = "Yggdrasil";
pub(crate) const CAMPAIGN: &str = "eureka-state";
pub(crate) fn slug(value: &str) -> Slug {
value.into()
}
pub(crate) fn now() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 9, 16, 12, 0, 0).unwrap()
}
pub(crate) fn provenance() -> PipelineProvenance {
PipelineProvenance {
faculty: Faculty::Hands,
agent: Short("claude".into()),
session: Short("session-1".into()),
tool: Short("admit".into()),
}
}
pub(crate) fn identity(name: &str) -> PipelineDocument {
PipelineDocument::Instance(PipelineInstance {
instance: slug(name),
display_name: Short(format!("{name} mind")),
created_at: Date("2026-09-16".into()),
host: Short(name.into()),
})
}
pub(crate) fn batch(instance: &str, documents: Vec<PipelineDocument>) -> PipelineAdmissionBatch {
PipelineAdmissionBatch { instance: slug(instance), provenance: provenance(), documents }
}
/// A question and the ruling that answers it: admitting the ruling derives
/// the question's resolution, so one batch lands two writes.
pub(crate) fn question_and_ruling() -> (PipelineDocument, PipelineDocument) {
let question = PipelineDocument::Question(PipelineQuestion {
campaign: slug(CAMPAIGN),
label: "Q1".into(),
title: Title("Who owns the state?".into()),
question: "Who owns the state?".into(),
options: vec![
QuestionOption { label: "A".into(), text: "the organ".into() },
QuestionOption { label: "B".into(), text: "the client".into() },
],
recommended: "A".into(),
depends: vec![],
raised_in: None,
asked_on: Date("2026-09-16".into()),
});
let ruling = PipelineDocument::Ruling(PipelineRuling {
campaign: slug(CAMPAIGN),
label: "R1".into(),
title: Title("An instance owns its mind".into()),
answers: Some(Short(format!("{CAMPAIGN}:question:Q1"))),
choice: Some("A".into()),
ruling: "An instance owns its mind.".into(),
operator_quote: None,
ruled_on: Date("2026-09-16".into()),
precedents: vec![],
authority: RulingAuthority::Operator,
});
(question, ruling)
}
pub(crate) const REPO: &str = "GameCult/Epiphany";
/// A `Line` and a `Short` at the leaf's own bound, so a document built out
/// of them is as wide as any writer may make it.
pub(crate) fn line(n: usize) -> Line {
Line(format!("{n:0>1000}"))
}
pub(crate) fn short(n: usize) -> Short {
Short(format!("{n:0>200}"))
}
fn sha() -> Sha {
Sha("5f98228d".into())
}
fn doc_ref() -> DocRef {
DocRef { path: Short("notes/target.md".into()), start_line: 1, end_line: 9, commit: sha() }
}
/// The three documents a cut spec needs before it may be admitted: the
/// mind's identity, its stewardship of the repo, and the campaign that
/// names the repo.
pub(crate) fn campaign_seed() -> Vec<PipelineDocument> {
vec![
identity(INSTANCE),
PipelineDocument::Stewardship(PipelineStewardship {
instance: slug(INSTANCE),
repo: OrgRepo(REPO.into()),
sequence: 1,
assigned_on: Date("2026-09-16".into()),
note: "assigned".into(),
}),
PipelineDocument::Campaign(PipelineCampaign {
slug: slug(CAMPAIGN),
title: Title("Eureka pipeline state".into()),
repos: vec![OrgRepo(REPO.into())],
working_branch: Short("codex/eureka-pipeline-state".into()),
target_doc: doc_ref(),
}),
]
}
/// One cut spec with every list the leaf bounds filled to its maximum and
/// every text at its own: `file_changes` file changes, 64 deletes, keeps,
/// adds, builds, tests, negative checks and operator checks, a full
/// authority map and a full structural delta. At 256 file changes that is
/// roughly a megabyte of field content, which is what a real-sized answer
/// looks like at the leaf's bounds rather than at a fixture's convenience.
/// `depends_on`, `rulings` and `questions` stay empty because each is a
/// reference admission resolves.
pub(crate) fn cut_spec(cut: &str, file_changes: usize) -> PipelineDocument {
let lines = |count: usize| (0..count).map(line).collect::<Vec<_>>();
let shorts = |count: usize| (0..count).map(short).collect::<Vec<_>>();
let location = |n: usize| CodeLocation { path: short(n), line: 1, end_line: Some(9) };
PipelineDocument::CutSpec(PipelineCutSpec {
campaign: slug(CAMPAIGN),
cut: cut.into(),
revision: 1,
title: Title(short(0).0),
repo: OrgRepo(REPO.into()),
branch: short(1),
base: sha(),
depends_on: vec![],
first: lines(16),
deletes: (0..64).map(|n| CutDelete { path: short(n), lines: 9, note: line(n) }).collect(),
keeps_moves: lines(64),
adds: lines(64),
file_changes: (0..file_changes).map(|n| FileChange { location: location(n), change: line(n) }).collect(),
authority_map: Some(AuthorityMap {
owner: line(0),
inputs: lines(16),
outputs: lines(16),
derived_state: lines(16),
forbidden_writers: lines(16),
shared_paths: lines(16),
deletion_line: line(1),
}),
verification: CutVerification {
builds: lines(64),
tests: (0..64).map(|n| VerificationTest { name: short(n), pins: line(n) }).collect(),
negative: (0..64).map(|n| NegativeCheck { pattern: short(n), scope: line(n) }).collect(),
operator: lines(64),
},
estimate: StructuralDelta {
lines_added: 0,
lines_removed: 0,
dependencies_added: shorts(64),
dependencies_removed: shorts(64),
formats_added: shorts(64),
formats_removed: shorts(64),
targets_added: shorts(64),
targets_removed: shorts(64),
},
rulings: vec![],
questions: vec![],
})
}
/// The cut spec at the leaf's own maximum, and one narrow enough that its
/// answer still fits a single send. `WIDE_CHANGES` is the leaf's bound;
/// `FITTING_CHANGES` is chosen so the view of that spec lands inside the
/// window with less than a packet-count's slack, which is what makes the
/// window's own value load-bearing rather than merely generous.
pub(crate) const WIDE_CUT: &str = "wide";
pub(crate) const WIDE_CHANGES: usize = 256;
pub(crate) const FITTING_CUT: &str = "fits";
pub(crate) const FITTING_CHANGES: usize = 180;
/// A daemon whose mind holds the campaign seed, one cut spec as wide as the
/// leaf permits, and one narrow enough to answer, so a read over it is a
/// real-sized answer either way.
pub(crate) fn seeded_wide() -> (TempDir, Daemon<OwnedRedbMessagePackBackingStore, NoIndex>) {
let root = tempfile::tempdir().unwrap();
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
for documents in [
campaign_seed(),
vec![cut_spec(WIDE_CUT, WIDE_CHANGES), cut_spec(FITTING_CUT, FITTING_CHANGES)],
] {
let outcome = daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, documents)), now()).answered();
assert!(
matches!(outcome, HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })),
"{outcome:?}"
);
}
(root, daemon)
}
/// A daemon over a real redb mind in a temporary directory, with its
/// identity admitted. The directory is returned because dropping it
/// removes the store.
pub(crate) fn seeded() -> (TempDir, Daemon<OwnedRedbMessagePackBackingStore, NoIndex>) {
let root = tempfile::tempdir().unwrap();
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
let outcome = daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])), now()).answered();
assert!(
matches!(outcome, HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })),
"{outcome:?}"
);
(root, daemon)
}
/// No index: for the tests whose subject is not the projection.
pub(crate) struct NoIndex;
impl<S: MindStore> IndexSink<S> for NoIndex {
fn committed(&mut self, _mind: &Mind<S>, _writes: &[PipelineRef]) -> anyhow::Result<()> {
Ok(())
}
fn status(&self) -> IndexStatus {
IndexStatus::Current
}
fn search(&mut self, _text: &str, _top_k: u32) -> Result<SearchTicket, String> {
Err("this index cannot search".into())
}
fn searched(&mut self) -> Vec<(SearchTicket, Result<Hits, String>)> {
Vec::new()
}
}
/// A daemon over the instance's mind under `state_root`, with no index.
pub(crate) fn open_unindexed(
state_root: &Path,
instance: &Slug,
) -> Result<Daemon<OwnedRedbMessagePackBackingStore, NoIndex>, MindRefusal> {
Ok(Daemon::new(Mind::open(state_root, instance)?, NoIndex))
}
#[derive(Clone, Default)]
struct RecordingIndex {
seen: Arc<Mutex<Vec<(Vec<String>, Vec<bool>)>>>,
}
impl<S: MindStore> IndexSink<S> for RecordingIndex {
fn committed(&mut self, mind: &Mind<S>, writes: &[PipelineRef]) -> anyhow::Result<()> {
let ids = writes.iter().map(|write| write.id.0.clone()).collect();
let readable = writes.iter().map(|write| mind.view(write).unwrap().is_some()).collect();
self.seen.lock().unwrap().push((ids, readable));
Ok(())
}
fn status(&self) -> IndexStatus {
IndexStatus::Current
}
fn search(&mut self, _text: &str, _top_k: u32) -> Result<SearchTicket, String> {
Err("this index cannot search".into())
}
fn searched(&mut self) -> Vec<(SearchTicket, Result<Hits, String>)> {
Vec::new()
}
}
struct FailingIndex;
impl<S: MindStore> IndexSink<S> for FailingIndex {
fn committed(&mut self, _mind: &Mind<S>, _writes: &[PipelineRef]) -> anyhow::Result<()> {
Err(anyhow::anyhow!("the index is not there"))
}
fn status(&self) -> IndexStatus {
IndexStatus::Current
}
fn search(&mut self, _text: &str, _top_k: u32) -> Result<SearchTicket, String> {
Err("this index cannot search".into())
}
fn searched(&mut self) -> Vec<(SearchTicket, Result<Hits, String>)> {
Vec::new()
}
}
fn status(daemon: &mut Daemon<OwnedRedbMessagePackBackingStore, impl IndexSink<OwnedRedbMessagePackBackingStore>>) -> MindStatus {
match daemon.handle(HuginnMindRequest::Whoami, now()).answered() {
HuginnMindResponse::Whoami(status) => status,
other => panic!("expected a status, got {other:?}"),
}
}
/// Typed hand-off between the organs without a socket: a batch enters and
/// every read answers over what it landed, at a clock the test pins.
#[test]
fn a_batch_round_trips_typed_through_handle_without_a_socket() {
let root = tempfile::tempdir().unwrap();
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
let outcome = daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])), now()).answered();
let HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { writes, .. }) = outcome else {
panic!("expected a commit");
};
assert_eq!(writes.len(), 1);
assert_eq!(writes[0].kind, PipelineKind::Instance);
assert_eq!(
status(&mut daemon),
MindStatus {
instance: slug(INSTANCE),
schema_epoch: "epiphany.pipeline.epoch.v2".into(),
documents: 1,
receipts: 1,
index: IndexStatus::Current,
}
);
assert_eq!(daemon.runtime_id(), "huginn-yggdrasil");
let instances = Selection { schemas: Some(vec![PipelineKind::Instance.type_id().into()]), ..Selection::default() };
let HuginnMindResponse::Query(page) = daemon.handle(
HuginnMindRequest::Query { instance: slug(INSTANCE), selection: instances.clone(), semantic: None },
now(),
).answered() else {
panic!("expected a page");
};
assert_eq!(page.matched, 1);
let PipelinePageItems::Headers(headers) = &page.items else { panic!("the default projection is a header") };
assert_eq!(headers[0].admission.provenance, provenance());
assert_eq!(headers[0].status, huginn_mind::PipelineStatusSummary::InForce);
let id = writes[0].clone();
let whole = Selection { projection: "document".into(), ..instances };
let HuginnMindResponse::Query(page) =
daemon.handle(HuginnMindRequest::Query { instance: slug(INSTANCE), selection: whole, semantic: None }, now()).answered()
else {
panic!("expected a page");
};
let PipelinePageItems::Documents(views) = &page.items else { panic!("the document projection is the view") };
assert_eq!(views[0].status, PipelineStatus::InForce);
let view = daemon.handle(HuginnMindRequest::View { instance: slug(INSTANCE), id: id.clone() }, now()).answered();
assert_eq!(view, HuginnMindResponse::View(Some(views[0].clone())));
}
/// Ruling 14 across the transport, on both sides: the mind refuses a read
/// and a write that name another instance, and nothing lands.
#[test]
fn a_read_or_a_write_naming_another_instance_is_refused_by_the_mind_and_writes_nothing() {
let root = tempfile::tempdir().unwrap();
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
let landed = daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])), now()).answered();
let HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { writes, .. }) = landed else {
panic!("expected a commit");
};
let foreign = MindRefusal::ForeignInstance { declared: OTHER.into(), mind: INSTANCE.into() };
let query = HuginnMindRequest::Query { instance: slug(OTHER), selection: Selection::default(), semantic: None };
assert_eq!(daemon.handle(query, now()).answered(), HuginnMindResponse::Refused(foreign.clone()));
let admit = HuginnMindRequest::Admit(batch(OTHER, vec![identity(OTHER)]));
assert_eq!(
daemon.handle(admit, now()).answered(),
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(foreign.clone()))
);
// The declared instance travels to the mind as the client sent it. A
// batch whose documents name no instance at all is still refused on
// the declaration alone, so nothing between the wire and A1 may
// rewrite it into the mind's own.
let (question, _) = question_and_ruling();
let admit = HuginnMindRequest::Admit(batch(OTHER, vec![question]));
assert_eq!(
daemon.handle(admit, now()).answered(),
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(foreign.clone()))
);
let view = HuginnMindRequest::View { instance: slug(OTHER), id: writes[0].clone() };
assert_eq!(daemon.handle(view, now()).answered(), HuginnMindResponse::Refused(foreign));
// Three names a comparison could mistake for this mind's. `NEAR` is
// `INSTANCE`'s own length and differs in its last byte, so a check
// reading lengths, first bytes, or running only when the declared name
// is longer admits it; `PREFIXED` carries `INSTANCE` whole, so a prefix
// test admits it; `CASED` is `INSTANCE` in another case, which a slug
// label permits, so a check folding case admits it. Each is refused on
// the read side and the write side.
assert_eq!(NEAR.len(), INSTANCE.len());
assert!(PREFIXED.starts_with(INSTANCE));
assert_eq!(CASED.to_ascii_lowercase(), INSTANCE);
for declared in [NEAR, PREFIXED, CASED] {
let refusal = MindRefusal::ForeignInstance { declared: declared.into(), mind: INSTANCE.into() };
let query = HuginnMindRequest::Query { instance: slug(declared), selection: Selection::default(), semantic: None };
assert_eq!(daemon.handle(query, now()).answered(), HuginnMindResponse::Refused(refusal.clone()), "{declared}");
let view = HuginnMindRequest::View { instance: slug(declared), id: writes[0].clone() };
assert_eq!(daemon.handle(view, now()).answered(), HuginnMindResponse::Refused(refusal.clone()), "{declared}");
let admit = HuginnMindRequest::Admit(batch(declared, vec![identity(declared)]));
assert_eq!(
daemon.handle(admit, now()).answered(),
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal)),
"{declared}"
);
}
assert_eq!(status(&mut daemon).documents, 1, "nothing landed");
}
/// A declared instance outside `Slug`'s grammar is refused by its own
/// name, `InvalidFormat`, on the read path, before the identity
/// comparison ever runs: it is not merely a foreign mind, it names no
/// mind a client could compose. A fullwidth Latin small letter y is used
/// because it is the shape Soul named: a check that folds it to plain
/// ASCII `y` before validating would let this probe pass as grammatical
/// and reach `require_instance`, which would then answer `ForeignInstance`
/// instead — the wrong refusal, reached the wrong way.
#[test]
fn a_declared_instance_outside_the_grammar_is_refused_by_name_before_the_identity_check() {
let (_root, mut daemon) = seeded();
let fullwidth = "\u{FF59}ggdrasil";
assert_ne!(fullwidth, INSTANCE, "not the mind's own bytes");
assert!(!fullwidth.is_ascii(), "outside the grammar: a Slug is dot-joined ASCII labels");
let expected = MindRefusal::Document(huginn_mind::epiphany_pipeline::PipelineRefusal::InvalidFormat {
field: "declared".into(),
value: fullwidth.into(),
});
let query = HuginnMindRequest::Query { instance: slug(fullwidth), selection: Selection::default(), semantic: None };
assert_eq!(daemon.handle(query, now()).answered(), HuginnMindResponse::Refused(expected.clone()));
let view = HuginnMindRequest::View {
instance: slug(fullwidth),
id: PipelineRef { kind: PipelineKind::Question, id: Short("not-reached".into()) },
};
assert_eq!(daemon.handle(view, now()).answered(), HuginnMindResponse::Refused(expected));
}
/// `Admit` is excluded from the daemon's own pre-check (its batch is not a
/// read naming an instance the mind is asked about first), but it reaches
/// the identical `require_instance` from inside `admit_steps`'s A1, so a
/// fullwidth *declared batch instance* is `InvalidFormat` there too,
/// named and valued the same as the read path's. One door,
/// `Mind::require_instance`, decides both. The batch's one document names
/// the mind's own real instance, `INSTANCE`, so it clears `admit`'s own
/// per-document `Bounded` check and the only fullwidth text anywhere in
/// the request is the batch's declared instance, the thing this test
/// pins.
#[test]
fn a_fullwidth_instance_is_refused_the_same_way_by_admit_and_by_query() {
let (_root, mut daemon) = seeded();
let fullwidth = "\u{FF59}ggdrasil";
let expected = MindRefusal::Document(huginn_mind::epiphany_pipeline::PipelineRefusal::InvalidFormat {
field: "declared".into(),
value: fullwidth.into(),
});
let admit = HuginnMindRequest::Admit(batch(fullwidth, vec![identity(INSTANCE)]));
assert_eq!(
daemon.handle(admit, now()).answered(),
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(expected.clone()))
);
let query = HuginnMindRequest::Query { instance: slug(fullwidth), selection: Selection::default(), semantic: None };
assert_eq!(daemon.handle(query, now()).answered(), HuginnMindResponse::Refused(expected));
}
/// A refusal a read method raised is the answer the dispatch returns, whole.
/// The instance check refuses before the method runs and is pinned above;
/// these are the refusals the methods themselves raise, so nothing here is
/// the daemon's own. Each must arrive as the mind spelled it: not rewrapped
/// as `Unavailable`, not rewrapped as another read's refusal, and not
/// swallowed into an empty answer, which would read as "no such document"
/// rather than "that is not a reference".
#[test]
fn a_refusal_a_read_raised_is_the_answer_the_dispatch_returns_whole() {
let (_root, mut daemon) = seeded();
// A reference whose kind and id disagree names no document any writer
// could have composed; the leaf's own refusal says so.
let invalid = PipelineRef { kind: PipelineKind::Question, id: "not a reference".into() };
let malformed = MindRefusal::Document(huginn_mind::epiphany_pipeline::PipelineRefusal::InvalidFormat {
field: "ref.id".into(),
value: "not a reference".into(),
});
let view = HuginnMindRequest::View { instance: slug(INSTANCE), id: invalid };
assert_eq!(daemon.handle(view, now()).answered(), HuginnMindResponse::Refused(malformed));
// And the same reads answer rather than refuse when they are asked
// something answerable, so the arms above are refusing on the mind's
// word and not on their own shape.
let absent =
PipelineRef { kind: PipelineKind::Question, id: Short(format!("{CAMPAIGN}:question:Q1")) };
let present = HuginnMindRequest::View { instance: slug(INSTANCE), id: absent };
assert_eq!(daemon.handle(present, now()).answered(), HuginnMindResponse::View(None));
let plain = HuginnMindRequest::Query { instance: slug(INSTANCE), selection: Selection::default(), semantic: None };
let HuginnMindResponse::Query(page) = daemon.handle(plain, now()).answered() else { panic!("expected a page") };
assert_eq!(page.matched, 1);
}
/// A refusal of the selection crosses the dispatch as itself: typed, on
/// the field the client sent, and never swallowed into an empty page or
/// rewrapped as an unavailable store. A stale cursor is the organ's own
/// defect, so a valid walk never meets it.
#[test]
fn a_selection_refusal_crosses_the_dispatch_as_itself() {
let (_root, mut daemon) = seeded();
let ask = |daemon: &mut Daemon<OwnedRedbMessagePackBackingStore, NoIndex>, selection: Selection| {
daemon.handle(HuginnMindRequest::Query { instance: slug(INSTANCE), selection, semantic: None }, now()).answered()
};
let predicate = |index: &str, value: &str| Selection {
fields: Some(vec![cultnet_rs::FieldPredicate {
index: index.into(),
op: "any_of".into(),
values: Some(vec![value.into()]),
number: None,
}]),
..Selection::default()
};
let HuginnMindResponse::Refused(MindRefusal::SelectionInvalid { field, .. }) =
ask(&mut daemon, predicate("nonsense", "x"))
else {
panic!("an undeclared alias is the substrate's refusal");
};
assert_eq!(field, "fields[0].index");
let HuginnMindResponse::Refused(MindRefusal::SelectionInvalid { field, value, .. }) =
ask(&mut daemon, predicate("repo", "a/b/c"))
else {
panic!("a value outside its domain is the organ's refusal");
};
assert_eq!((field.as_str(), value.as_deref()), ("fields[0].values", Some("a/b/c")));
let garbled = Selection { cursor: Some("not a cursor".into()), ..Selection::default() };
assert!(matches!(ask(&mut daemon, garbled), HuginnMindResponse::Refused(MindRefusal::CursorInvalid { .. })));
assert_eq!(ask(&mut daemon, predicate("repo", "a/b/c")).status(), "rejected");
}
/// Cut 11's seam: the index is handed every landed write, derived ones
/// included, and can read each; an index that fails changes nothing.
#[test]
fn the_index_is_handed_every_landed_write_after_commit_and_never_decides_the_outcome() {
let (_root, daemon) = seeded();
let recording = RecordingIndex::default();
let mut daemon = daemon.with_index(recording.clone());
let (question, ruling) = question_and_ruling();
let outcome = daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![question, ruling])), now()).answered();
let HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { writes, .. }) = outcome else {
panic!("expected a commit");
};
let landed: Vec<String> = writes.iter().map(|write| write.id.0.clone()).collect();
assert_eq!(landed.len(), 3, "the ruling answers the question, so a resolution is derived: {landed:?}");
let seen = recording.seen.lock().unwrap().clone();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].0, landed, "the sink sees exactly the landed writes");
assert_eq!(seen[0].1, vec![true, true, true], "and can read each one when it is called");
let (question, ruling) = question_and_ruling();
let mut daemon = daemon.with_index(FailingIndex);
let root = tempfile::tempdir().unwrap();
let mut fresh = open_unindexed(root.path(), &slug(INSTANCE)).unwrap().with_index(FailingIndex);
fresh.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])), now()).answered();
let outcome = fresh.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![question, ruling])), now()).answered();
let HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { writes, .. }) = outcome else {
panic!("a failing index does not refuse the batch");
};
for write in &writes {
let view = fresh.handle(HuginnMindRequest::View { instance: slug(INSTANCE), id: write.clone() }, now()).answered();
assert!(matches!(view, HuginnMindResponse::View(Some(_))), "{write:?} is readable");
}
assert_eq!(status(&mut daemon).documents, 4, "identity, question, ruling and the derived resolution");
}
/// Ruling 15: a mind that will not open is refused, and opening it takes
/// no address, so no socket can precede it. `startup`'s order is
/// pinned in `serve::tests`.
#[test]
fn the_daemon_refuses_loudly_when_it_cannot_open_the_mind_and_binds_nothing() {
let root = tempfile::tempdir().unwrap();
let held = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
let path = Mind::<OwnedRedbMessagePackBackingStore>::store_path_for(root.path(), &slug(INSTANCE)).unwrap();
assert_eq!(
open_unindexed(root.path(), &slug(INSTANCE)).err(),
Some(MindRefusal::MindAlreadyOwned { path: path.display().to_string() })
);
drop(held);
let mut planted = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
planted.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])), now()).answered();
drop(planted);
let moved = Mind::<OwnedRedbMessagePackBackingStore>::store_path_for(root.path(), &slug(OTHER)).unwrap();
std::fs::create_dir_all(moved.parent().unwrap()).unwrap();
std::fs::copy(&path, &moved).unwrap();
assert_eq!(
open_unindexed(root.path(), &slug(OTHER)).err(),
Some(MindRefusal::ForeignInstance { declared: OTHER.into(), mind: INSTANCE.into() })
);
}
}