Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eee0b1439b | ||
|
|
de8b027ebc | ||
|
|
8e288867ad | ||
|
|
ae3279cdf0 | ||
|
|
dcd8f2116b | ||
|
|
4909108be3 | ||
|
|
436b9e6971 | ||
|
|
6dac5e36c2 | ||
|
|
9c1e99264b | ||
|
|
6920b3535f | ||
|
|
cc1abe5831 | ||
|
|
befb2174aa | ||
|
|
323522a3d6 | ||
|
|
26d82443f3 | ||
|
|
4114090846 | ||
|
|
53aeb168dc |
42 changed files with 512 additions and 4672 deletions
|
|
@ -509,7 +509,6 @@ fn unexpected(answer: &HuginnMindResponse) -> Trouble {
|
|||
HuginnMindResponse::PersonaPut(_) => "a persona put",
|
||||
HuginnMindResponse::Sources(_) => "source hits",
|
||||
HuginnMindResponse::Activity(_) => "repo activity",
|
||||
HuginnMindResponse::RootsTouched(_) => "roots touched",
|
||||
HuginnMindResponse::Refused(_) => "a refusal",
|
||||
HuginnMindResponse::Deferred(_) => "a deferral",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@
|
|||
//! reads through `eureka_state::hold`, the decider the heartbeat's gate reads.
|
||||
|
||||
use clap::{Args, Subcommand};
|
||||
use eureka_state::hold::BLOCKING;
|
||||
use huginn_mind::SemanticQuery;
|
||||
use huginn_mind::eureka_pipeline::{Line, PipelineKind};
|
||||
use serde_json::{Value, json};
|
||||
|
|
@ -17,6 +16,8 @@ use crate::trouble::Trouble;
|
|||
const GAP_HOME: &str = "eureka-substrate";
|
||||
/// How many neighbours `precedent` asks the index for.
|
||||
const PRECEDENT_TOP_K: u32 = 10;
|
||||
/// Severities that block a cut.
|
||||
const BLOCKING: [&str; 2] = ["Blocker", "High"];
|
||||
|
||||
#[derive(Args, Clone, Debug, Default)]
|
||||
pub struct Paging {
|
||||
|
|
|
|||
|
|
@ -44,10 +44,6 @@ pub fn citing(target: &PipelineRef, role: Option<&str>) -> Citation {
|
|||
}
|
||||
}
|
||||
|
||||
/// Severities that block a cut: the one answer to what counts as blocking, read by `huginn findings --blocking` and by a Mind's
|
||||
/// first line.
|
||||
pub const BLOCKING: [&str; 2] = ["Blocker", "High"];
|
||||
|
||||
pub fn of_kind(kind: PipelineKind) -> Selection {
|
||||
Selection {
|
||||
schemas: Some(vec![kind.type_id().to_string()]),
|
||||
|
|
|
|||
|
|
@ -200,10 +200,6 @@ impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
|
|||
HuginnMindRequest::Query { selection, semantic: Some(semantic), .. } => {
|
||||
return self.begin_search(selection, semantic);
|
||||
}
|
||||
HuginnMindRequest::RootsTouched { .. } => match self.mind.roots_touched() {
|
||||
Ok(roots) => HuginnMindResponse::RootsTouched(roots),
|
||||
Err(refusal) => HuginnMindResponse::Refused(refusal),
|
||||
},
|
||||
HuginnMindRequest::StewardedActivity { instance, repos, after } => {
|
||||
let refused = |message: &str| MindRefusal::SelectionInvalid { field: "repos".into(), value: None, message: message.into() };
|
||||
if repos.len() > ACTIVITY_REPOS_MAX {
|
||||
|
|
@ -1077,32 +1073,6 @@ pub(crate) mod tests {
|
|||
}
|
||||
|
||||
|
||||
/// A roots read through the daemon's handle answers from the mind it serves: the campaign with its repos in force and the
|
||||
/// instance's own root with none; a request naming another instance is refused at the door, as every read is, before the mind
|
||||
/// is asked.
|
||||
#[test]
|
||||
fn roots_touched_answers_on_the_wire() {
|
||||
let (_root, mut daemon) = seeded_wide();
|
||||
let HuginnMindResponse::RootsTouched(roots) = daemon.handle(HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) }, now()).answered() else {
|
||||
panic!("a roots read answers the roots");
|
||||
};
|
||||
let by_root = |name: &str| roots.iter().find(|root| root.root.0 == name).unwrap_or_else(|| panic!("{name} in {roots:?}"));
|
||||
assert_eq!(by_root(CAMPAIGN).repos, [OrgRepo(REPO.into())]);
|
||||
assert!(by_root(INSTANCE).repos.is_empty());
|
||||
assert_eq!(roots.len(), 2, "{roots:?}");
|
||||
|
||||
let bytes = rmp_serde::to_vec_named(&HuginnMindResponse::RootsTouched(roots.clone())).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindResponse>(&bytes).unwrap(), HuginnMindResponse::RootsTouched(roots));
|
||||
|
||||
for declared in [OTHER, NEAR, PREFIXED, CASED] {
|
||||
assert_eq!(
|
||||
daemon.handle(HuginnMindRequest::RootsTouched { instance: slug(declared) }, now()).answered(),
|
||||
HuginnMindResponse::Refused(MindRefusal::ForeignInstance { declared: declared.into(), mind: INSTANCE.into() }),
|
||||
"{declared}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn activity_request(repos: &[&str]) -> HuginnMindRequest {
|
||||
HuginnMindRequest::StewardedActivity { instance: slug(INSTANCE), repos: repos.iter().map(|repo| OrgRepo::from(*repo)).collect(), after: Some(1) }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -792,173 +792,6 @@ mod tests {
|
|||
assert_eq!(documents(&mut daemon), 1, "the admission that crossed the wire landed");
|
||||
}
|
||||
|
||||
fn question_doc(n: usize) -> huginn_mind::eureka_pipeline::PipelineDocument {
|
||||
use huginn_mind::eureka_pipeline::{Date, PipelineDocument, PipelineQuestion, QuestionOption, Title};
|
||||
PipelineDocument::Question(PipelineQuestion {
|
||||
campaign: slug(crate::daemon::tests::CAMPAIGN),
|
||||
label: format!("Q{n}").as_str().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()),
|
||||
})
|
||||
}
|
||||
|
||||
fn resolution_of(subject: PipelineRef, outcome: huginn_mind::eureka_pipeline::ResolutionOutcome) -> huginn_mind::eureka_pipeline::PipelineDocument {
|
||||
huginn_mind::eureka_pipeline::PipelineDocument::Resolution(huginn_mind::eureka_pipeline::PipelineResolution {
|
||||
subject,
|
||||
sequence: 1,
|
||||
outcome,
|
||||
rationale: "Resolved.".into(),
|
||||
resolved_on: huginn_mind::eureka_pipeline::Date("2026-09-16".into()),
|
||||
})
|
||||
}
|
||||
|
||||
/// One client session asks `request` and decodes the answer.
|
||||
fn ask(client: &mut Client, message_id: &str, request: &HuginnMindRequest) -> HuginnMindResponse {
|
||||
let reply = exchange(client, &encode_request(message_id, request, None).unwrap()).unwrap();
|
||||
decode_response(&reply).unwrap().1.unwrap_or_else(|failure| panic!("{message_id}: {failure:?}"))
|
||||
}
|
||||
|
||||
fn connect(endpoint: &str, name: &str) -> Client {
|
||||
let mut client = CultMesh::create_rudp_client_for_endpoint(
|
||||
format!("eureka-state-{name}"),
|
||||
CULTNET_OPERATION_CONNECTION_ID,
|
||||
endpoint,
|
||||
CultMeshRudpSocketOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
client.connect(Vec::new()).unwrap();
|
||||
for _ in 0..1000 {
|
||||
let _ = client.receive_once();
|
||||
if client.connected() {
|
||||
return client;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
panic!("{name} never connected");
|
||||
}
|
||||
|
||||
/// One client admits batches that close, withdraw and re-open records while three others read
|
||||
/// the same mind: fresh queries, cursor walks across commits, a hop and whoami. The loop is
|
||||
/// serial, so every answer is one snapshot's; at quiesce each answer must equal what a fresh
|
||||
/// derivation from the store gives at the snapshot it names, and no client sees the head go
|
||||
/// backwards. The test pins the behaviour, not the mechanism.
|
||||
#[test]
|
||||
fn reads_racing_admissions_on_the_wire_answer_their_snapshot() {
|
||||
use huginn_mind::eureka_pipeline::{PipelineKind as K, ResolutionOutcome};
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
|
||||
let seeded = daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, crate::daemon::tests::campaign_seed())), now()).answered();
|
||||
assert!(matches!(seeded, HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })), "{seeded:?}");
|
||||
let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let endpoint = format!("rudp://{}", hub.local_addr().unwrap());
|
||||
let registry = schema_registry().unwrap();
|
||||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
let result = run(&mut daemon, &mut hub, ®istry, &loop_stopping, &ServeOptions::default());
|
||||
(result, daemon)
|
||||
});
|
||||
|
||||
let done = Arc::new(AtomicBool::new(false));
|
||||
let writer = {
|
||||
let (endpoint, done) = (endpoint.clone(), Arc::clone(&done));
|
||||
std::thread::spawn(move || {
|
||||
let mut client = connect(&endpoint, "writer");
|
||||
let admit = |client: &mut Client, n: usize, documents| {
|
||||
let answer = ask(client, &format!("w-{n}"), &HuginnMindRequest::Admit(batch(INSTANCE, documents)));
|
||||
assert!(matches!(answer, HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })), "{answer:?}");
|
||||
};
|
||||
let withdrawn = || ResolutionOutcome::Withdrawn { reason: "race".into() };
|
||||
let mut n = 0;
|
||||
for cut in 0..14 {
|
||||
let spec = PipelineRef { kind: K::Question, id: format!("{}:question:Q{cut}", crate::daemon::tests::CAMPAIGN).as_str().into() };
|
||||
admit(&mut client, n, vec![question_doc(cut)]);
|
||||
admit(&mut client, n + 1, vec![resolution_of(spec, withdrawn())]);
|
||||
if cut % 2 == 0 {
|
||||
let closing = PipelineRef { kind: K::Resolution, id: format!("{}:resolution:question.Q{cut}.n1", crate::daemon::tests::CAMPAIGN).as_str().into() };
|
||||
admit(&mut client, n + 2, vec![resolution_of(closing, withdrawn())]);
|
||||
}
|
||||
n += 3;
|
||||
}
|
||||
done.store(true, Ordering::Relaxed);
|
||||
})
|
||||
};
|
||||
let readers: Vec<_> = (0..3)
|
||||
.map(|index| {
|
||||
let (endpoint, done) = (endpoint.clone(), Arc::clone(&done));
|
||||
std::thread::spawn(move || {
|
||||
let mut client = connect(&endpoint, &format!("reader-{index}"));
|
||||
let of_specs = |extra: Selection| Selection { schemas: Some(vec![K::Question.type_id().into()]), ..extra };
|
||||
let in_force = FieldPredicate { index: "in_force".into(), op: "any_of".into(), values: Some(vec!["true".into()]), number: None };
|
||||
let mut recorded: Vec<(Selection, huginn_mind::PipelineSelectionPage)> = Vec::new();
|
||||
let mut status_walk = of_specs(Selection { fields: Some(vec![in_force.clone()]), limit: Some(1), projection: "document".into(), ..Selection::default() });
|
||||
let mut head = 0;
|
||||
let mut round = 0;
|
||||
while !done.load(Ordering::Relaxed) || round < 3 {
|
||||
round += 1;
|
||||
let query = |client: &mut Client, selection: &Selection| {
|
||||
match ask(client, &format!("r-{index}-{round}"), &HuginnMindRequest::Query { instance: slug(INSTANCE), selection: selection.clone(), semantic: None }) {
|
||||
HuginnMindResponse::Query(page) => page,
|
||||
other => panic!("expected a page, got {other:?}"),
|
||||
}
|
||||
};
|
||||
let fresh = of_specs(Selection { fields: Some(vec![in_force.clone()]), limit: Some(5), ..Selection::default() });
|
||||
let page = query(&mut client, &fresh);
|
||||
assert!(page.as_of >= head, "a client's head never goes backwards");
|
||||
head = page.as_of;
|
||||
recorded.push((fresh, page));
|
||||
let mut walking = of_specs(Selection { limit: Some(1), ..Selection::default() });
|
||||
for _ in 0..3 {
|
||||
let page = query(&mut client, &walking);
|
||||
let next = page.next.clone();
|
||||
recorded.push((walking.clone(), page));
|
||||
match next {
|
||||
Some(cursor) => walking.cursor = Some(cursor),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
// A status walk: its cursor pins the snapshot it began at while the writer
|
||||
// closes and reopens the questions, so a page is read at an old snapshot
|
||||
// through the status filter and the document, which only the row's
|
||||
// status_changed can answer.
|
||||
let page = query(&mut client, &status_walk);
|
||||
let next = page.next.clone();
|
||||
recorded.push((status_walk.clone(), page));
|
||||
status_walk.cursor = next;
|
||||
let hop = Selection { cited: Some(cultnet_rs::Incoming { role: "subject".into(), exists: true }), ..Selection::default() };
|
||||
let page = query(&mut client, &hop);
|
||||
recorded.push((hop, page));
|
||||
assert!(matches!(ask(&mut client, "whoami", &HuginnMindRequest::Whoami), HuginnMindResponse::Whoami(_)));
|
||||
}
|
||||
recorded
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
writer.join().unwrap();
|
||||
let recorded: Vec<_> = readers.into_iter().flat_map(|reader| reader.join().unwrap()).collect();
|
||||
stopping.store(true, Ordering::Relaxed);
|
||||
let (result, daemon) = serving.join().unwrap();
|
||||
result.unwrap();
|
||||
let mind = daemon.mind();
|
||||
let final_head = mind.query(&Selection::default()).unwrap().as_of;
|
||||
let mut snapshots = std::collections::BTreeSet::new();
|
||||
for (selection, page) in &recorded {
|
||||
snapshots.insert(page.as_of);
|
||||
assert_eq!(huginn_mind::oracle::oracle_page(mind, selection, page.as_of).as_ref(), Ok(page), "{selection:?} at {}", page.as_of);
|
||||
}
|
||||
assert!(snapshots.len() > 1, "the readers saw more than one snapshot: {snapshots:?}");
|
||||
assert!(snapshots.iter().all(|as_of| *as_of <= final_head));
|
||||
}
|
||||
|
||||
fn encoded_len(message: &CultNetMessage) -> u64 {
|
||||
encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap().len() as u64
|
||||
}
|
||||
|
|
|
|||
|
|
@ -124,8 +124,7 @@ impl<S: MindStore> Mind<S> {
|
|||
return Err(MindRefusal::BatchSize { actual: envelopes.len() as u32 });
|
||||
}
|
||||
let mind = self.instance().clone();
|
||||
let image = self.image()?;
|
||||
let mut docs = Docs::at(image, image.head);
|
||||
let mut docs = Docs::from_image(self.envelopes())?;
|
||||
// A3, A5, then A4 on push.
|
||||
for envelope in envelopes {
|
||||
docs.push(stage(envelope, &mind)?)?;
|
||||
|
|
@ -367,7 +366,7 @@ fn references(staged: &Staged, mind: &Slug) -> Result<Vec<Reference>, MindRefusa
|
|||
|
||||
/// A7: every referent is in the batch or the image; the image ones are the
|
||||
/// receipt's strong reads.
|
||||
fn resolve(docs: &Docs<'_>, staged: &Staged, mind: &Slug, strong: &mut BTreeSet<(String, String)>) -> Result<(), MindRefusal> {
|
||||
fn resolve(docs: &Docs, staged: &Staged, mind: &Slug, strong: &mut BTreeSet<(String, String)>) -> Result<(), MindRefusal> {
|
||||
for reference in references(staged, mind)? {
|
||||
if docs.in_batch(reference.kind, &reference.id).is_some() {
|
||||
continue;
|
||||
|
|
@ -390,7 +389,7 @@ fn resolve(docs: &Docs<'_>, staged: &Staged, mind: &Slug, strong: &mut BTreeSet<
|
|||
/// the stewardship withdrawal on its source side and the stewardship
|
||||
/// assignment on its receiving side. One the batch already carries is not
|
||||
/// derived again.
|
||||
fn derive(docs: &Docs<'_>, mind: &Slug) -> Vec<PipelineDocument> {
|
||||
fn derive(docs: &Docs, mind: &Slug) -> Vec<PipelineDocument> {
|
||||
use PipelineDocument as D;
|
||||
use PipelineKind as K;
|
||||
let mut derived = Vec::new();
|
||||
|
|
@ -445,7 +444,7 @@ fn derive(docs: &Docs<'_>, mind: &Slug) -> Vec<PipelineDocument> {
|
|||
}
|
||||
|
||||
/// A8: the per-kind rules.
|
||||
fn check(docs: &Docs<'_>, staged: &Staged, mind: &Slug) -> Result<(), MindRefusal> {
|
||||
fn check(docs: &Docs, staged: &Staged, mind: &Slug) -> Result<(), MindRefusal> {
|
||||
use PipelineDocument as D;
|
||||
use PipelineKind as K;
|
||||
let key = staged.key.as_str();
|
||||
|
|
@ -630,7 +629,7 @@ fn check(docs: &Docs<'_>, staged: &Staged, mind: &Slug) -> Result<(), MindRefusa
|
|||
/// The one rule for a run opening or reinstated by withdrawing its close: every
|
||||
/// claim in force (a replay of an admitted run owes none) and held by no other
|
||||
/// live run, then at most one live run of hers per instance and turn.
|
||||
fn run_rule(docs: &Docs<'_>, run_key: &str, run: &PipelineRun, replay: bool) -> Result<(), MindRefusal> {
|
||||
fn run_rule(docs: &Docs, run_key: &str, run: &PipelineRun, replay: bool) -> Result<(), MindRefusal> {
|
||||
for claim in &run.claims {
|
||||
if !replay && !docs.in_force(claim.kind, &claim.id.0) {
|
||||
return Err(MindRefusal::CitesResolvedDocument { kind: claim.kind, id: claim.id.0.clone() });
|
||||
|
|
@ -648,7 +647,7 @@ fn run_rule(docs: &Docs<'_>, run_key: &str, run: &PipelineRun, replay: bool) ->
|
|||
/// Revision 1 stands alone; revision N needs a resolution in the batch that
|
||||
/// supersedes revision N-1 by this document. The predecessor's key is the
|
||||
/// leaf's, from the same document one revision back.
|
||||
fn revision_rule(docs: &Docs<'_>, kind: PipelineKind, key: &str, revision: u32, predecessor: &PipelineDocument) -> Result<(), MindRefusal> {
|
||||
fn revision_rule(docs: &Docs, kind: PipelineKind, key: &str, revision: u32, predecessor: &PipelineDocument) -> Result<(), MindRefusal> {
|
||||
if revision == 1 {
|
||||
return Ok(());
|
||||
}
|
||||
|
|
@ -732,7 +731,7 @@ fn matrix(subject: PipelineKind, outcome: &ResolutionOutcome) -> bool {
|
|||
/// every referent in force, and the two
|
||||
/// coherence rules (an `Answered` ruling answers this question; a cut spec is
|
||||
/// superseded within its cut).
|
||||
fn resolution_rule(docs: &Docs<'_>, resolution: &PipelineResolution) -> Result<(), MindRefusal> {
|
||||
fn resolution_rule(docs: &Docs, resolution: &PipelineResolution) -> Result<(), MindRefusal> {
|
||||
use PipelineDocument as D;
|
||||
use PipelineKind as K;
|
||||
let subject_kind = resolution.subject.kind;
|
||||
|
|
@ -831,7 +830,7 @@ fn resolution_rule(docs: &Docs<'_>, resolution: &PipelineResolution) -> Result<(
|
|||
/// A10: a write whose identity the image already holds. Every kind answers
|
||||
/// the same way now that a resolution key carries a sequence: the identity is
|
||||
/// taken. Whether a subject is closed is A8's question, not this one's.
|
||||
fn refuse_collisions(docs: &Docs<'_>) -> Result<(), MindRefusal> {
|
||||
fn refuse_collisions(docs: &Docs) -> Result<(), MindRefusal> {
|
||||
for staged in &docs.batch {
|
||||
if docs.in_image(staged.kind, &staged.key).is_some() {
|
||||
return Err(MindRefusal::IdentityCollision { kind: staged.kind, id: staged.key.clone() });
|
||||
|
|
@ -1071,8 +1070,8 @@ mod tests {
|
|||
let key = format!("{INSTANCE}:stewardship:gamecult_-epiphany.n1");
|
||||
assert!(yggdrasil.envelope(K::Stewardship, &key).is_some());
|
||||
assert!(thought_cage.envelope(K::Stewardship, &key).is_none());
|
||||
assert_eq!(yggdrasil.envelopes().count(), 4);
|
||||
assert_eq!(thought_cage.envelopes().count(), 3);
|
||||
assert_eq!(yggdrasil.envelopes().len(), 4);
|
||||
assert_eq!(thought_cage.envelopes().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1578,7 +1577,7 @@ mod tests {
|
|||
refusal(admit(&mut mind, vec![resolution(r(K::Resolution, &withdrawal), withdrawn())])),
|
||||
MindRefusal::AlreadyStewarded { repo: REPO.into() }
|
||||
);
|
||||
let docs = docs_of(&mind);
|
||||
let docs = Docs::from_image(mind.envelopes()).unwrap();
|
||||
let in_force = docs.stewardships_of(&slug(INSTANCE), &repo(REPO), None).iter().map(|(key, _)| *key).collect::<Vec<_>>();
|
||||
assert_eq!(in_force, vec![again.as_str()], "one assignment stands, and it is the later one");
|
||||
}
|
||||
|
|
@ -1600,9 +1599,8 @@ mod tests {
|
|||
assert!(!docs_of(&mind).in_force(K::Target, &id("target", "r1")));
|
||||
}
|
||||
|
||||
fn docs_of<S: MindStore>(mind: &Mind<S>) -> Docs<'_> {
|
||||
let image = mind.image().unwrap();
|
||||
Docs::at(image, image.head)
|
||||
fn docs_of<S: MindStore>(mind: &Mind<S>) -> Docs {
|
||||
Docs::from_image(mind.envelopes()).unwrap()
|
||||
}
|
||||
|
||||
/// The withdrawal a hand-off derives is a record of its subject like any
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ use eureka_pipeline::{
|
|||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::image::Image;
|
||||
use crate::refusal::MindRefusal;
|
||||
|
||||
/// A batch document after A3 and A5: decoded, keyed, and its envelope.
|
||||
|
|
@ -24,12 +23,16 @@ pub(crate) struct Staged {
|
|||
pub(crate) envelope: CultCacheEnvelope,
|
||||
}
|
||||
|
||||
/// The held image at one snapshot and the batch, the two places a rule or a view
|
||||
/// may look. The one door of visibility: a document is there when its writing
|
||||
/// receipt's ordinal is at or before `as_of`. Admission runs at the head.
|
||||
pub(crate) struct Docs<'i> {
|
||||
image: &'i Image,
|
||||
as_of: u64,
|
||||
/// An image document, decoded.
|
||||
pub(crate) struct Held {
|
||||
pub(crate) kind: PipelineKind,
|
||||
pub(crate) key: String,
|
||||
pub(crate) document: PipelineDocument,
|
||||
}
|
||||
|
||||
/// The image and the batch, the two places a rule may look.
|
||||
pub(crate) struct Docs {
|
||||
pub(crate) image: Vec<Held>,
|
||||
pub(crate) batch: Vec<Staged>,
|
||||
}
|
||||
|
||||
|
|
@ -37,13 +40,17 @@ pub(crate) fn kind_of_type(type_id: &str) -> Option<PipelineKind> {
|
|||
PipelineKind::ALL.iter().copied().find(|kind| kind.type_id() == type_id)
|
||||
}
|
||||
|
||||
impl<'i> Docs<'i> {
|
||||
pub(crate) fn at(image: &'i Image, as_of: u64) -> Self {
|
||||
Self { image, as_of, batch: Vec::new() }
|
||||
}
|
||||
|
||||
fn visible(&self, id: u32) -> bool {
|
||||
self.image.row(id).ordinal <= self.as_of
|
||||
impl Docs {
|
||||
pub(crate) fn from_image(envelopes: &[CultCacheEnvelope]) -> Result<Self, MindRefusal> {
|
||||
let mut image = Vec::new();
|
||||
for envelope in envelopes {
|
||||
let Some(kind) = kind_of_type(&envelope.r#type) else { continue };
|
||||
let document = PipelineDocument::decode(envelope).map_err(|refusal| MindRefusal::Unavailable {
|
||||
detail: format!("stored document {} does not decode: {refusal}", envelope.key),
|
||||
})?;
|
||||
image.push(Held { kind, key: envelope.key.clone(), document });
|
||||
}
|
||||
Ok(Self { image, batch: Vec::new() })
|
||||
}
|
||||
|
||||
/// A4: one identity, once.
|
||||
|
|
@ -60,7 +67,7 @@ impl<'i> Docs<'i> {
|
|||
}
|
||||
|
||||
pub(crate) fn in_image(&self, kind: PipelineKind, id: &str) -> Option<&PipelineDocument> {
|
||||
self.image.id_of(kind, id).filter(|row| self.visible(*row)).map(|row| &self.image.row(row).view.document)
|
||||
self.image.iter().find(|held| held.kind == kind && held.key == id).map(|held| &held.document)
|
||||
}
|
||||
|
||||
pub(crate) fn find(&self, kind: PipelineKind, id: &str) -> Option<&PipelineDocument> {
|
||||
|
|
@ -69,14 +76,17 @@ impl<'i> Docs<'i> {
|
|||
|
||||
pub(crate) fn of_kind(&self, kind: PipelineKind) -> impl Iterator<Item = (&str, &PipelineDocument)> {
|
||||
let batch = self.batch.iter().filter(move |staged| staged.kind == kind).map(|staged| (staged.key.as_str(), &staged.document));
|
||||
let image = self
|
||||
.image
|
||||
.of_kind(kind)
|
||||
.filter(move |(_, row)| self.visible(*row))
|
||||
.map(move |(key, row)| (key, &self.image.row(row).view.document));
|
||||
let image = self.image.iter().filter(move |held| held.kind == kind).map(|held| (held.key.as_str(), &held.document));
|
||||
batch.chain(image)
|
||||
}
|
||||
|
||||
pub(crate) fn resolutions(&self) -> impl Iterator<Item = (&str, &PipelineResolution)> {
|
||||
self.of_kind(PipelineKind::Resolution).filter_map(|(key, document)| match document {
|
||||
PipelineDocument::Resolution(resolution) => Some((key, resolution)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn stewardships(&self) -> impl Iterator<Item = (&str, &PipelineStewardship)> {
|
||||
self.of_kind(PipelineKind::Stewardship).filter_map(|(key, document)| match document {
|
||||
PipelineDocument::Stewardship(stewardship) => Some((key, stewardship)),
|
||||
|
|
@ -87,25 +97,7 @@ impl<'i> Docs<'i> {
|
|||
/// Every resolution of one subject, in image and batch: the scope a
|
||||
/// subject's sequence counts in.
|
||||
pub(crate) fn resolutions_of(&self, subject: &PipelineRef) -> impl Iterator<Item = (&str, &PipelineResolution)> {
|
||||
self.resolutions_naming(subject.kind, &subject.id.0)
|
||||
}
|
||||
|
||||
/// The resolutions naming one document: the batch's first, then the held ones visible at
|
||||
/// `as_of` in resolution-key order, the order a closing resolution is found in.
|
||||
fn resolutions_naming(&self, kind: PipelineKind, id: &str) -> impl Iterator<Item = (&str, &PipelineResolution)> {
|
||||
let batch = self.batch.iter().filter_map(move |staged| match &staged.document {
|
||||
PipelineDocument::Resolution(resolution) if resolution.subject.kind == kind && resolution.subject.id.0 == id => {
|
||||
Some((staged.key.as_str(), resolution))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let held = self.image.closers_of(kind, id).filter(move |(_, row)| self.visible(*row)).filter_map(move |(key, row)| {
|
||||
match &self.image.row(row).view.document {
|
||||
PipelineDocument::Resolution(resolution) => Some((key, resolution)),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
batch.chain(held)
|
||||
self.resolutions().filter(move |(_, resolution)| resolution.subject == *subject)
|
||||
}
|
||||
|
||||
/// Every assignment of one repo to one mind, in image and batch, in force
|
||||
|
|
@ -136,8 +128,8 @@ impl<'i> Docs<'i> {
|
|||
subject: &PipelineRef,
|
||||
derived: impl Fn(&ResolutionOutcome) -> bool,
|
||||
) -> u32 {
|
||||
self.resolutions_of(subject)
|
||||
.find(|(_, resolution)| derived(&resolution.outcome))
|
||||
self.resolutions()
|
||||
.find(|(_, resolution)| resolution.subject == *subject && derived(&resolution.outcome))
|
||||
.map_or_else(|| self.latest_resolution(subject, None) + 1, |(_, resolution)| resolution.sequence)
|
||||
}
|
||||
|
||||
|
|
@ -182,7 +174,12 @@ impl<'i> Docs<'i> {
|
|||
id: &str,
|
||||
own: impl Fn(&PipelineResolution) -> bool,
|
||||
) -> Option<(&str, &PipelineResolution)> {
|
||||
self.resolutions_naming(kind, id).find(|&(key, resolution)| !own(resolution) && self.in_force(PipelineKind::Resolution, key))
|
||||
self.resolutions().find(|&(key, resolution)| {
|
||||
resolution.subject.kind == kind
|
||||
&& resolution.subject.id.0 == id
|
||||
&& !own(resolution)
|
||||
&& self.in_force(PipelineKind::Resolution, key)
|
||||
})
|
||||
}
|
||||
|
||||
/// The repos a campaign's cuts may name: the repo set of the highest-revision
|
||||
|
|
@ -295,8 +292,10 @@ impl<'i> Docs<'i> {
|
|||
hand_off_key
|
||||
.and_then(|hand_off| {
|
||||
candidates.iter().find(|(key, _)| {
|
||||
self.resolutions_naming(PipelineKind::Stewardship, key).any(|(_, resolution)| {
|
||||
matches!(&resolution.outcome, ResolutionOutcome::Withdrawn { reason } if reason.0 == hand_off)
|
||||
self.resolutions().any(|(_, resolution)| {
|
||||
resolution.subject.kind == PipelineKind::Stewardship
|
||||
&& resolution.subject.id.0 == *key
|
||||
&& matches!(&resolution.outcome, ResolutionOutcome::Withdrawn { reason } if reason.0 == hand_off)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -561,6 +560,10 @@ mod tests {
|
|||
use PipelineDocument as D;
|
||||
use PipelineKind as K;
|
||||
|
||||
fn held(kind: K, key: String, document: D) -> Held {
|
||||
Held { kind, key, document }
|
||||
}
|
||||
|
||||
fn named(campaign: &str, revision: u32, repos: &[&str]) -> (String, D) {
|
||||
let D::Target(mut target) = target(revision, &[INVARIANT]) else { panic!("a target") };
|
||||
target.campaign = campaign.into();
|
||||
|
|
@ -585,13 +588,15 @@ mod tests {
|
|||
let (closed_key, closed) = named(CAMPAIGN, 2, &["GameCult/Closed"]);
|
||||
let (foreign_key, foreign) = named("other-campaign", 3, &["GameCult/Foreign"]);
|
||||
let closing = resolution(r(K::Target, &closed_key), superseded(&[r(K::Target, &in_force_key)]));
|
||||
let image = Image::of_documents(vec![
|
||||
(K::Target, in_force_key, in_force),
|
||||
(K::Target, closed_key, closed),
|
||||
(K::Target, foreign_key, foreign),
|
||||
(K::Resolution, id("resolution", "target.r2.n1"), closing),
|
||||
]);
|
||||
let docs = Docs::at(&image, image.head);
|
||||
let docs = Docs {
|
||||
image: vec![
|
||||
held(K::Target, in_force_key, in_force),
|
||||
held(K::Target, closed_key, closed),
|
||||
held(K::Target, foreign_key, foreign),
|
||||
held(K::Resolution, id("resolution", "target.r2.n1"), closing),
|
||||
],
|
||||
batch: Vec::new(),
|
||||
};
|
||||
assert_eq!(docs.repos_in_force(&this), [repo(REPO), repo(OTHER_REPO)], "neither the closed higher revision nor another campaign's higher target decides");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,378 +0,0 @@
|
|||
//! The mind's one decoded, indexed image: a pure fold of the commit receipts
|
||||
//! in ordinal order. It is built only by replaying the receipts and advanced
|
||||
//! only by the function the replay calls, so a held image and a fresh fold of
|
||||
//! the same store are equal by construction. Nothing here is stored: a restart
|
||||
//! re-folds the store, which is the truth.
|
||||
//!
|
||||
//! A row is the only decoded copy of its document. Status is derived through
|
||||
//! the closing resolutions at an `as_of` and is never stored in a document;
|
||||
//! a row holds the head's answer and `status_changed` says from which
|
||||
//! snapshot that answer holds. The postings, closers, citers and kind maps
|
||||
//! only narrow which rows a read hands the substrate: `universe` is a superset
|
||||
//! of what `select` can match, and `select` still decides membership, order,
|
||||
//! cursors and edges.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultnet_rs::Selection;
|
||||
use eureka_pipeline::{PipelineDocument, PipelineKind, PipelineRef, PipelineResolution, Short};
|
||||
|
||||
use crate::docs::{Docs, citations, kind_of_id, kind_of_type};
|
||||
use crate::mind::Envelopes;
|
||||
use crate::persona::HuginnPersonaEntry;
|
||||
use crate::query::{AdmissionFacts, AdmissionIndex, PipelineDocumentView, PipelineStatus};
|
||||
use crate::receipt::HuginnCommitReceipt;
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::rows::{Alias, STATUS_ALIASES, SelectionRow, root_and_local};
|
||||
|
||||
type Postings = BTreeMap<PipelineKind, BTreeMap<&'static str, HashMap<String, BTreeSet<u32>>>>;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Image {
|
||||
/// The newest receipt's ordinal: `N` of a dense `1..=N`.
|
||||
pub(crate) head: u64,
|
||||
/// Append-only; a row's index is its id. Receipts' order, then identity order within one.
|
||||
pub(crate) rows: Vec<SelectionRow>,
|
||||
/// Per row, the newest ordinal at which its status changed.
|
||||
pub(crate) status_changed: Vec<u64>,
|
||||
/// Kind, then key, to row id, in key order: the image's identity lookup and its per-kind order.
|
||||
by_kind: BTreeMap<PipelineKind, BTreeMap<String, u32>>,
|
||||
/// (kind, alias, value) to the rows answering it.
|
||||
postings: Postings,
|
||||
/// Subject kind and id to the resolutions naming it, by resolution key.
|
||||
closers: BTreeMap<PipelineKind, HashMap<String, BTreeMap<String, u32>>>,
|
||||
/// Target id to the (role, citer) edges that name it.
|
||||
citers: HashMap<String, BTreeSet<(&'static str, u32)>>,
|
||||
/// Root to the newest row written under it.
|
||||
roots: BTreeMap<String, u32>,
|
||||
/// Whether every citation edge names a target of its role's kinds. When one does not, a hop
|
||||
/// selection reads every row, so the substrate refuses it exactly as it would over the whole mind.
|
||||
pub(crate) edges_in_target: bool,
|
||||
}
|
||||
|
||||
fn integrity(type_id: &str, key: &str, fault: &str) -> MindRefusal {
|
||||
MindRefusal::Unavailable { detail: format!("document {type_id}/{key} {fault}") }
|
||||
}
|
||||
|
||||
pub(crate) fn status_of(closing: Option<(&str, &PipelineResolution)>) -> PipelineStatus {
|
||||
match closing {
|
||||
Some((key, record)) => PipelineStatus::Resolved {
|
||||
resolution: PipelineRef { kind: PipelineKind::Resolution, id: Short(key.to_string()) },
|
||||
record: record.clone(),
|
||||
},
|
||||
None => PipelineStatus::InForce,
|
||||
}
|
||||
}
|
||||
|
||||
impl Image {
|
||||
pub(crate) fn empty() -> Self {
|
||||
Self {
|
||||
head: 0,
|
||||
rows: Vec::new(),
|
||||
status_changed: Vec::new(),
|
||||
by_kind: BTreeMap::new(),
|
||||
postings: BTreeMap::new(),
|
||||
closers: BTreeMap::new(),
|
||||
citers: HashMap::new(),
|
||||
roots: BTreeMap::new(),
|
||||
edges_in_target: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fold of a store's envelopes. Faults, in order: a pipeline document that does not decode,
|
||||
/// the receipts (undecodable, not dense, a document written twice), a document no receipt wrote.
|
||||
/// There is no other way to make an image: this replays the receipts through `advance`.
|
||||
pub(crate) fn build(
|
||||
envelopes: &Envelopes,
|
||||
receipts: &Result<Vec<HuginnCommitReceipt>, MindRefusal>,
|
||||
) -> Result<Self, MindRefusal> {
|
||||
let mut decoded: HashMap<(&str, &str), PipelineDocument> = HashMap::new();
|
||||
for (type_id, keyed) in envelopes {
|
||||
if kind_of_type(type_id).is_none() {
|
||||
continue;
|
||||
}
|
||||
for (key, envelope) in keyed {
|
||||
let document = PipelineDocument::decode(envelope).map_err(|refusal| MindRefusal::Unavailable {
|
||||
detail: format!("stored document {key} does not decode: {refusal}"),
|
||||
})?;
|
||||
decoded.insert((type_id.as_str(), key.as_str()), document);
|
||||
}
|
||||
}
|
||||
let receipts = receipts.clone()?;
|
||||
let index = AdmissionIndex::build(&receipts)?;
|
||||
for (type_id, keyed) in envelopes {
|
||||
if kind_of_type(type_id).is_some()
|
||||
&& let Some(key) = keyed.keys().find(|key| !index.contains(type_id, key))
|
||||
{
|
||||
return Err(integrity(type_id, key, "has no commit receipt"));
|
||||
}
|
||||
}
|
||||
let mut ordered: Vec<&HuginnCommitReceipt> = receipts.iter().collect();
|
||||
ordered.sort_by_key(|receipt| receipt.ordinal);
|
||||
let mut image = Self::empty();
|
||||
for receipt in ordered {
|
||||
let mut documents = Vec::new();
|
||||
for write in receipt.writes.iter().filter(|write| write.document_type != HuginnPersonaEntry::TYPE) {
|
||||
let Some(kind) = kind_of_type(&write.document_type) else { continue };
|
||||
// A receipted document the store no longer holds gets no row; read_back names it.
|
||||
if let Some(document) = decoded.remove(&(write.document_type.as_str(), write.document_key.as_str())) {
|
||||
documents.push((kind, write.document_key.clone(), document));
|
||||
}
|
||||
}
|
||||
image.advance(&AdmissionFacts::of(receipt), documents)?;
|
||||
}
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
pub(crate) fn id_of(&self, kind: PipelineKind, key: &str) -> Option<u32> {
|
||||
self.by_kind.get(&kind)?.get(key).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn row(&self, id: u32) -> &SelectionRow {
|
||||
&self.rows[id as usize]
|
||||
}
|
||||
|
||||
/// The ids of one kind in key order.
|
||||
pub(crate) fn of_kind(&self, kind: PipelineKind) -> impl Iterator<Item = (&str, u32)> {
|
||||
self.by_kind.get(&kind).into_iter().flat_map(|keyed| keyed.iter().map(|(key, id)| (key.as_str(), *id)))
|
||||
}
|
||||
|
||||
/// The resolutions naming one subject, in resolution-key order.
|
||||
pub(crate) fn closers_of(&self, kind: PipelineKind, id: &str) -> impl Iterator<Item = (&str, u32)> {
|
||||
self.closers.get(&kind).and_then(|named| named.get(id)).into_iter().flat_map(|keyed| keyed.iter().map(|(key, id)| (key.as_str(), *id)))
|
||||
}
|
||||
|
||||
/// Every root with the newest row under it.
|
||||
pub(crate) fn roots(&self) -> impl Iterator<Item = (&str, &SelectionRow)> {
|
||||
self.roots.iter().map(|(root, id)| (root.as_str(), self.row(*id)))
|
||||
}
|
||||
|
||||
/// Folds one receipt's documents, given in the receipt's write order, into the image. The same
|
||||
/// function replays the log and follows each commit.
|
||||
pub(crate) fn advance(
|
||||
&mut self,
|
||||
facts: &AdmissionFacts,
|
||||
documents: Vec<(PipelineKind, String, PipelineDocument)>,
|
||||
) -> Result<(), MindRefusal> {
|
||||
let first = self.rows.len() as u32;
|
||||
// Phase 1: every document of the receipt gets a row, so a subject that sorts after its
|
||||
// resolution in one batch is found by phase 2.
|
||||
for (kind, key, document) in documents {
|
||||
if self.id_of(kind, &key).is_some() {
|
||||
return Err(integrity(kind.type_id(), &key, "is written by two receipts"));
|
||||
}
|
||||
let id = self.rows.len() as u32;
|
||||
let edges = citations(&document);
|
||||
for (role, target) in &edges {
|
||||
let in_target = kind_of_id(&target.id.0).is_some_and(|named| role.target_kinds().contains(&named));
|
||||
self.edges_in_target &= in_target;
|
||||
self.citers.entry(target.id.0.clone()).or_default().insert((role.name(), id));
|
||||
}
|
||||
if let PipelineDocument::Resolution(resolution) = &document {
|
||||
self.closers
|
||||
.entry(resolution.subject.kind)
|
||||
.or_default()
|
||||
.entry(resolution.subject.id.0.clone())
|
||||
.or_default()
|
||||
.insert(key.clone(), id);
|
||||
}
|
||||
self.roots.insert(root_and_local(&key).0.to_string(), id);
|
||||
self.by_kind.entry(kind).or_default().insert(key.clone(), id);
|
||||
let view = PipelineDocumentView {
|
||||
id: PipelineRef { kind, id: Short(key.clone()) },
|
||||
document,
|
||||
admission: facts.clone(),
|
||||
status: PipelineStatus::InForce,
|
||||
};
|
||||
self.rows.push(SelectionRow::new(kind, &key, None, view, edges));
|
||||
self.status_changed.push(facts.ordinal);
|
||||
}
|
||||
self.head = facts.ordinal;
|
||||
// Phase 2: a new resolution changes its subject's status, and a subject that is itself a
|
||||
// resolution reopens or closes its own subject in turn, so the chain is walked to the first
|
||||
// document that is not a resolution.
|
||||
let mut touched: BTreeSet<u32> = (first..self.rows.len() as u32).collect();
|
||||
for id in first..self.rows.len() as u32 {
|
||||
let mut current = id;
|
||||
while let PipelineDocument::Resolution(resolution) = &self.row(current).view.document {
|
||||
let Some(subject) = self.id_of(resolution.subject.kind, &resolution.subject.id.0) else { break };
|
||||
touched.insert(subject);
|
||||
current = subject;
|
||||
}
|
||||
}
|
||||
for id in touched {
|
||||
self.rebuild(id, id >= first, facts.ordinal);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The row with `status`, its base walked through the subjects held.
|
||||
pub(crate) fn make_row(&self, id: u32, status: PipelineStatus) -> SelectionRow {
|
||||
let old = self.row(id);
|
||||
let mut view = old.view.clone();
|
||||
view.status = status;
|
||||
let mut current = id;
|
||||
while let PipelineDocument::Resolution(resolution) = &self.row(current).view.document {
|
||||
let Some(subject) = self.id_of(resolution.subject.kind, &resolution.subject.id.0) else { break };
|
||||
current = subject;
|
||||
}
|
||||
let base = self.row(current);
|
||||
SelectionRow::new(old.kind, &old.key, Some((&base.key, &base.view.document)), view, citations(&old.view.document))
|
||||
}
|
||||
|
||||
fn rebuild(&mut self, id: u32, fresh: bool, ordinal: u64) {
|
||||
let (kind, key) = {
|
||||
let row = self.row(id);
|
||||
(row.kind, row.key.clone())
|
||||
};
|
||||
let status = status_of(Docs::at(self, u64::MAX).closing_resolution(kind, &key));
|
||||
let row = self.make_row(id, status);
|
||||
if !fresh {
|
||||
self.unindex(id);
|
||||
}
|
||||
if row.view.status != self.row(id).view.status {
|
||||
self.status_changed[id as usize] = ordinal;
|
||||
}
|
||||
self.rows[id as usize] = row;
|
||||
self.index(id);
|
||||
}
|
||||
|
||||
fn index(&mut self, id: u32) {
|
||||
let row = &self.rows[id as usize];
|
||||
for (alias, values) in row.alias_values() {
|
||||
for value in values {
|
||||
self.postings
|
||||
.entry(row.kind)
|
||||
.or_default()
|
||||
.entry(alias)
|
||||
.or_default()
|
||||
.entry(value.clone())
|
||||
.or_default()
|
||||
.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unindex(&mut self, id: u32) {
|
||||
let row = &self.rows[id as usize];
|
||||
for (alias, values) in row.alias_values() {
|
||||
for value in values {
|
||||
if let Some(posting) = self.postings.get_mut(&row.kind).and_then(|aliases| aliases.get_mut(alias)).and_then(|values| values.get_mut(value)) {
|
||||
posting.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn posting(&self, kind: PipelineKind, alias: &str, value: &str) -> Option<&BTreeSet<u32>> {
|
||||
self.postings.get(&kind)?.get(alias)?.get(value)
|
||||
}
|
||||
|
||||
/// The row ids a selection can match at `as_of`, ascending, with those written after `as_of`
|
||||
/// among them for the caller to drop: a superset of what `select` matches, never a verdict.
|
||||
pub(crate) fn universe(&self, selection: &Selection, as_of: u64) -> Vec<u32> {
|
||||
let hop = selection.has_hop();
|
||||
if hop && !self.edges_in_target {
|
||||
return (0..self.rows.len() as u32).collect();
|
||||
}
|
||||
let hop_only_cites = selection.cites.is_some() && selection.cited.is_none();
|
||||
let base = if hop_only_cites { BTreeSet::new() } else { self.base_candidates(selection, as_of) };
|
||||
let mut ids: BTreeSet<u32> = BTreeSet::new();
|
||||
let citers_of = |key: &str, role: Option<&str>| -> Vec<u32> {
|
||||
self.citers
|
||||
.get(key)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(named, _)| role.is_none_or(|role| role == *named))
|
||||
.map(|(_, citer)| *citer)
|
||||
.collect()
|
||||
};
|
||||
match (&selection.cites, &selection.cited) {
|
||||
(None, None) => ids = base,
|
||||
(Some(cites), None) => {
|
||||
let key = cites.target.record_key.as_str();
|
||||
// A row that passes the hop cites the target, so the citers are the superset; the kinds,
|
||||
// keys and fields only the substrate decides.
|
||||
ids.extend(citers_of(key, cites.role.as_deref()));
|
||||
ids.extend(self.any_kind(key));
|
||||
}
|
||||
(cites, Some(cited)) => {
|
||||
for id in &base {
|
||||
ids.extend(citers_of(&self.row(*id).key, Some(&cited.role)));
|
||||
}
|
||||
if let Some(cites) = cites {
|
||||
ids.extend(self.any_kind(&cites.target.record_key));
|
||||
}
|
||||
ids.extend(base);
|
||||
}
|
||||
}
|
||||
ids.into_iter().collect()
|
||||
}
|
||||
|
||||
fn any_kind(&self, key: &str) -> Vec<u32> {
|
||||
match kind_of_id(key) {
|
||||
Some(kind) => self.id_of(kind, key).into_iter().collect(),
|
||||
None => PipelineKind::ALL.iter().filter_map(|kind| self.id_of(*kind, key)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest set the kinds, keys and any_of fields of a selection allow.
|
||||
fn base_candidates(&self, selection: &Selection, as_of: u64) -> BTreeSet<u32> {
|
||||
if let Some(keys) = &selection.keys {
|
||||
return keys.iter().flat_map(|key| self.any_kind(key)).collect();
|
||||
}
|
||||
let kinds: Vec<PipelineKind> = match &selection.schemas {
|
||||
Some(schemas) => schemas.iter().filter_map(|schema| kind_of_type(schema)).collect(),
|
||||
None => PipelineKind::ALL.to_vec(),
|
||||
};
|
||||
let mut out = BTreeSet::new();
|
||||
for kind in kinds {
|
||||
let mut best: Option<(usize, Vec<&BTreeSet<u32>>)> = None;
|
||||
for field in selection.fields.iter().flatten() {
|
||||
if field.op != "any_of" {
|
||||
continue;
|
||||
}
|
||||
let Some(alias) = Alias::from_name(&field.index) else { continue };
|
||||
if STATUS_ALIASES.contains(&alias) && as_of != self.head {
|
||||
continue;
|
||||
}
|
||||
let sets: Vec<&BTreeSet<u32>> =
|
||||
field.values.iter().flatten().filter_map(|value| self.posting(kind, alias.name(), value)).collect();
|
||||
let size = sets.iter().map(|set| set.len()).sum();
|
||||
if best.as_ref().is_none_or(|(smallest, _)| size < *smallest) {
|
||||
best = Some((size, sets));
|
||||
}
|
||||
}
|
||||
let whole = self.by_kind.get(&kind).map_or(0, BTreeMap::len);
|
||||
match best {
|
||||
Some((size, sets)) if size < whole => out.extend(sets.into_iter().flatten().copied()),
|
||||
_ => out.extend(self.by_kind.get(&kind).into_iter().flat_map(|keyed| keyed.values().copied())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Image {
|
||||
/// An image of hand-made documents, one receipt each in the order given.
|
||||
pub(crate) fn of_documents(documents: Vec<(PipelineKind, String, PipelineDocument)>) -> Self {
|
||||
let mut image = Self::empty();
|
||||
for (n, document) in documents.into_iter().enumerate() {
|
||||
let facts = AdmissionFacts {
|
||||
receipt_id: format!("receipt-{}", n + 1),
|
||||
admitted_at: "2026-09-16T12:00:00Z".into(),
|
||||
provenance: crate::receipt::PipelineProvenance {
|
||||
faculty: crate::receipt::Faculty::Hands,
|
||||
agent: Short("claude".into()),
|
||||
session: Short("session-1".into()),
|
||||
tool: Short("admit".into()),
|
||||
},
|
||||
ordinal: n as u64 + 1,
|
||||
};
|
||||
image.advance(&facts, vec![document]).unwrap();
|
||||
}
|
||||
image
|
||||
}
|
||||
}
|
||||
|
|
@ -10,7 +10,9 @@
|
|||
use eureka_pipeline::{PipelineDocument, PipelineKind, PipelineRef};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::docs::Docs;
|
||||
use crate::mind::Mind;
|
||||
use crate::query::AdmissionIndex;
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::rows::root_and_local;
|
||||
use crate::store::MindStore;
|
||||
|
|
@ -112,31 +114,32 @@ impl<S: MindStore> Mind<S> {
|
|||
/// document the mind does not hold is a refusal, not a silent omission: a
|
||||
/// caller names what a commit just landed.
|
||||
pub fn index_entries(&self, only: Option<&[PipelineRef]>) -> Result<Vec<IndexEntry>, MindRefusal> {
|
||||
let image = self.image()?;
|
||||
let held: Vec<(PipelineKind, &str, &PipelineDocument, u64)> = match only {
|
||||
let documents: Vec<(PipelineKind, String, PipelineDocument)> = match only {
|
||||
Some(refs) => {
|
||||
let mut held = Vec::with_capacity(refs.len());
|
||||
for reference in refs {
|
||||
reference.validate_ref()?;
|
||||
let row = image.id_of(reference.kind, &reference.id.0).map(|id| image.row(id)).ok_or_else(|| {
|
||||
let document = self.get(reference.kind, &reference.id.0)?.ok_or_else(|| {
|
||||
MindRefusal::Unavailable { detail: format!("index: {} is not held", reference.id.0) }
|
||||
})?;
|
||||
held.push((reference.kind, row.key.as_str(), &row.view.document, row.ordinal));
|
||||
held.push((reference.kind, reference.id.0.clone(), document));
|
||||
}
|
||||
held
|
||||
}
|
||||
None => {
|
||||
let mut held: Vec<_> = image.rows.iter().map(|row| (row.kind, row.key.as_str(), &row.view.document, row.ordinal)).collect();
|
||||
held.sort_by(|left, right| (left.0.type_id(), left.1).cmp(&(right.0.type_id(), right.1)));
|
||||
held
|
||||
}
|
||||
None => Docs::from_image(self.envelopes())?
|
||||
.image
|
||||
.into_iter()
|
||||
.map(|held| (held.kind, held.key, held.document))
|
||||
.collect(),
|
||||
};
|
||||
let facts = AdmissionIndex::build(self)?;
|
||||
let mut entries = Vec::new();
|
||||
for (kind, key, document, ordinal) in held {
|
||||
let Some(text) = index_text(document) else { continue };
|
||||
for (kind, key, document) in documents {
|
||||
let Some(text) = index_text(&document) else { continue };
|
||||
let ordinal = facts.ordinal_of(kind, &key)?;
|
||||
entries.push(IndexEntry {
|
||||
root: root_and_local(key).0.to_string(),
|
||||
id: PipelineRef { kind, id: key.into() },
|
||||
root: root_and_local(&key).0.to_string(),
|
||||
id: PipelineRef { kind, id: key.as_str().into() },
|
||||
text_sha256: sha256_hex(&text),
|
||||
text,
|
||||
ordinal,
|
||||
|
|
|
|||
|
|
@ -10,10 +10,9 @@
|
|||
//! cross-document rule, every derived write, and the replay check, in one
|
||||
//! ordered path that `admit`, the daemon's sink and the hand-off all share.
|
||||
//!
|
||||
//! The read side answers one typed selection (CultNet's, over rows this crate
|
||||
//! supplies) from the mind's held image: a fold of the receipts, held by `Mind`,
|
||||
//! advanced per commit, rebuilt on restart and on a lost swap. Status is derived
|
||||
//! through the same `docs` the rules use; nothing is stored for it.
|
||||
//! The read side derives status, joins the receipts and answers one typed
|
||||
//! selection (CultNet's, over rows this crate supplies) through the same
|
||||
//! `docs` the rules use; nothing is stored for it.
|
||||
//!
|
||||
//! The wire vocabulary and its operation envelope (`envelope`) are here too,
|
||||
//! so the daemon and the client share one set
|
||||
|
|
@ -28,14 +27,11 @@
|
|||
|
||||
pub mod admission;
|
||||
mod docs;
|
||||
mod image;
|
||||
pub mod envelope;
|
||||
pub mod index;
|
||||
pub mod mind;
|
||||
pub mod persona;
|
||||
mod rows;
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub mod oracle;
|
||||
pub mod query;
|
||||
pub mod receipt;
|
||||
pub mod refusal;
|
||||
|
|
@ -45,9 +41,6 @@ pub mod wire;
|
|||
#[cfg(test)]
|
||||
pub(crate) mod fixtures;
|
||||
|
||||
#[cfg(test)]
|
||||
mod read_tests;
|
||||
|
||||
pub use docs::CitationRole;
|
||||
pub use index::{INDEX_TEXT_MAX_BYTES, INDEX_TEXT_VERSION, IndexEntry, index_text};
|
||||
pub use admission::{BATCH_MAX, PipelineAdmissionBatch, PipelineAdmissionOutcome};
|
||||
|
|
@ -55,7 +48,7 @@ pub use mind::{HuginnMindEpoch, Mind};
|
|||
pub use persona::{PersonaPutOutcome, PersonaStateView};
|
||||
pub use query::{
|
||||
AdmissionFacts, PipelineDocumentSummary, PipelineDocumentView, PipelineEdge, PipelineFacts, PipelinePageItems,
|
||||
Members, PipelineSelectionPage, PipelineStatus, PipelineStatusSummary, Ranked, RootTouched, SUMMARY_MAX_BYTES, SemanticQuery,
|
||||
Members, PipelineSelectionPage, PipelineStatus, PipelineStatusSummary, Ranked, SUMMARY_MAX_BYTES, SemanticQuery,
|
||||
};
|
||||
pub use receipt::{DocumentVersion, Faculty, HuginnCommitReceipt, PipelineProvenance, RECEIPT_SCHEMA_VERSION};
|
||||
pub use refusal::{MindRefusal, RunId};
|
||||
|
|
|
|||
|
|
@ -9,16 +9,13 @@
|
|||
//! every gate before it attaches, so a refused store is never read into an
|
||||
//! image.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry, OwnedRedbMessagePackBackingStore};
|
||||
use cultnet_rs::CursorKey;
|
||||
use eureka_pipeline::{PIPELINE_SCHEMA_EPOCH, PipelineDocument, PipelineKind, Slug, register_pipeline_document_types};
|
||||
|
||||
use crate::image::Image;
|
||||
use crate::persona::{HuginnPersonaEntry, persona_receipt_of};
|
||||
use crate::query::AdmissionFacts;
|
||||
use crate::persona::HuginnPersonaEntry;
|
||||
use crate::receipt::HuginnCommitReceipt;
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::store::MindStore;
|
||||
|
|
@ -94,53 +91,15 @@ fn is_known_type(type_id: &str) -> bool {
|
|||
|| PipelineKind::ALL.iter().any(|kind| kind.type_id() == type_id)
|
||||
}
|
||||
|
||||
/// The store's envelopes by type and key: the bytes as stored, in identity order.
|
||||
pub(crate) type Envelopes = BTreeMap<String, BTreeMap<String, CultCacheEnvelope>>;
|
||||
|
||||
fn envelopes_of(raw: Vec<CultCacheEnvelope>) -> Envelopes {
|
||||
let mut envelopes = Envelopes::new();
|
||||
for envelope in raw {
|
||||
envelopes.entry(envelope.r#type.clone()).or_default().insert(envelope.key.clone(), envelope);
|
||||
}
|
||||
envelopes
|
||||
}
|
||||
|
||||
/// Every commit receipt in the envelopes, in receipt-id order.
|
||||
pub(crate) fn decode_receipts(envelopes: &Envelopes) -> Result<Vec<HuginnCommitReceipt>, MindRefusal> {
|
||||
envelopes
|
||||
.get(HuginnCommitReceipt::TYPE)
|
||||
.into_iter()
|
||||
.flat_map(|keyed| keyed.values())
|
||||
.map(|envelope| {
|
||||
rmp_serde::from_slice::<HuginnCommitReceipt>(&envelope.payload).map_err(|error| MindRefusal::Unavailable {
|
||||
detail: format!("receipt {} does not decode: {error}", envelope.key),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one fold: the image and the persona's receipt, both read out of the receipts. A fault is
|
||||
/// held, not raised, so a faulted store still opens and every read answers the fault.
|
||||
fn fold(envelopes: &Envelopes, instance: &Slug) -> (Result<Image, MindRefusal>, Result<Option<String>, MindRefusal>) {
|
||||
let receipts = decode_receipts(envelopes);
|
||||
let persona = receipts.as_ref().map(|receipts| persona_receipt_of(receipts, instance)).map_err(Clone::clone);
|
||||
(Image::build(envelopes, &receipts), persona)
|
||||
}
|
||||
|
||||
/// One instance's mind: the declared instance, the store, the registry of
|
||||
/// the nineteen schemas, the store's envelopes as last pulled, and the image
|
||||
/// folded from them. The envelopes are the store's bytes and the image is a
|
||||
/// pure fold of the receipts among them: both advance with each commit and
|
||||
/// are rebuilt from the store on a lost swap, a store error and a restart.
|
||||
/// A cache of the store, never its authority; only `Mind::advance` and
|
||||
/// `refresh` write them.
|
||||
/// One instance's mind: the declared instance, the store, the registered
|
||||
/// cache attached to it, and the image (the store's envelopes as last pulled,
|
||||
/// in identity order). The image is a cache of the store and is re-pulled
|
||||
/// after every commit; nothing writes it directly.
|
||||
pub struct Mind<S: MindStore> {
|
||||
instance: Slug,
|
||||
store: S,
|
||||
cache: CultCache,
|
||||
pub(crate) envelopes: Envelopes,
|
||||
image: Result<Image, MindRefusal>,
|
||||
pub(crate) persona_receipt: Result<Option<String>, MindRefusal>,
|
||||
image: Vec<CultCacheEnvelope>,
|
||||
/// Mints and verifies this process's selection cursors. Never stored: a
|
||||
/// cursor does not survive a reopen, which the substrate accepts.
|
||||
cursor_key: CursorKey,
|
||||
|
|
@ -227,10 +186,8 @@ impl<S: MindStore> Mind<S> {
|
|||
refuse_foreign_epoch(&raw)?;
|
||||
refuse_foreign_types(&raw)?;
|
||||
refuse_foreign_identity(&raw, instance)?;
|
||||
let cache = schema_cache()?;
|
||||
let envelopes = envelopes_of(raw);
|
||||
let (image, persona_receipt) = fold(&envelopes, instance);
|
||||
Ok(Self { instance: instance.clone(), store, cache, envelopes, image, persona_receipt, cursor_key: CursorKey::random() })
|
||||
let (cache, image) = attach(store.clone())?;
|
||||
Ok(Self { instance: instance.clone(), store, cache, image, cursor_key: CursorKey::random() })
|
||||
}
|
||||
|
||||
pub fn instance(&self) -> &Slug {
|
||||
|
|
@ -252,20 +209,10 @@ impl<S: MindStore> Mind<S> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Every envelope the store held at the last pull, in identity order.
|
||||
pub fn envelopes(&self) -> impl Iterator<Item = &CultCacheEnvelope> {
|
||||
self.envelopes.values().flat_map(|keyed| keyed.values())
|
||||
}
|
||||
|
||||
/// The held image, or the fault the store holds: the same answer at any snapshot.
|
||||
pub(crate) fn image(&self) -> Result<&Image, MindRefusal> {
|
||||
self.image.as_ref().map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// The image folded from a fresh pull of the store: what a restart would hold.
|
||||
pub(crate) fn fresh_image(&self) -> Result<Image, MindRefusal> {
|
||||
let envelopes = envelopes_of(self.store.pull_all().map_err(unavailable)?);
|
||||
fold(&envelopes, &self.instance).0
|
||||
/// The image: every envelope the store held at the last pull, in
|
||||
/// identity order. Cut 10's snapshot source reads this.
|
||||
pub fn envelopes(&self) -> &[CultCacheEnvelope] {
|
||||
&self.image
|
||||
}
|
||||
|
||||
pub(crate) fn cursor_key(&self) -> &CursorKey {
|
||||
|
|
@ -273,7 +220,7 @@ impl<S: MindStore> Mind<S> {
|
|||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.envelopes.values().all(BTreeMap::is_empty)
|
||||
self.image.is_empty()
|
||||
}
|
||||
|
||||
/// The stored bytes of one document, by kind and id.
|
||||
|
|
@ -290,7 +237,15 @@ impl<S: MindStore> Mind<S> {
|
|||
|
||||
/// Every commit receipt in the image, in receipt-id order.
|
||||
pub(crate) fn receipts(&self) -> Result<Vec<HuginnCommitReceipt>, MindRefusal> {
|
||||
decode_receipts(&self.envelopes)
|
||||
self.image
|
||||
.iter()
|
||||
.filter(|envelope| envelope.r#type == HuginnCommitReceipt::TYPE)
|
||||
.map(|envelope| {
|
||||
rmp_serde::from_slice::<HuginnCommitReceipt>(&envelope.payload).map_err(|error| {
|
||||
MindRefusal::Unavailable { detail: format!("receipt {} does not decode: {error}", envelope.key) }
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The mind's own identity: the receipt id of its first admission
|
||||
|
|
@ -304,7 +259,7 @@ impl<S: MindStore> Mind<S> {
|
|||
}
|
||||
|
||||
pub(crate) fn raw_envelope(&self, type_id: &str, key: &str) -> Option<&CultCacheEnvelope> {
|
||||
self.envelopes.get(type_id)?.get(key)
|
||||
self.image.iter().find(|envelope| envelope.r#type == type_id && envelope.key == key)
|
||||
}
|
||||
|
||||
pub(crate) fn cache(&self) -> &CultCache {
|
||||
|
|
@ -315,55 +270,11 @@ impl<S: MindStore> Mind<S> {
|
|||
&self.store
|
||||
}
|
||||
|
||||
/// Rebuilds the envelopes and the image from the store: the one rebuild, run only when a swap
|
||||
/// was lost or the store errored, the two signals that the store moved beneath the holder.
|
||||
/// One rule for a look that fails: the holder no longer knows the store, so it holds the fault
|
||||
/// (reads and admission refuse with it) until a restart, exactly as a fold fault is held.
|
||||
/// Re-pulls the image from the store through the attached cache.
|
||||
pub(crate) fn refresh(&mut self) -> Result<(), MindRefusal> {
|
||||
match self.store.pull_all().map_err(unavailable) {
|
||||
Ok(raw) => {
|
||||
self.envelopes = envelopes_of(raw);
|
||||
(self.image, self.persona_receipt) = fold(&self.envelopes, &self.instance);
|
||||
Ok(())
|
||||
}
|
||||
Err(fault) => {
|
||||
self.image = Err(fault.clone());
|
||||
self.persona_receipt = Err(fault.clone());
|
||||
Err(fault)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds a commit the compare-and-swap said landed into the held state. If the fold itself
|
||||
/// faults on bytes that already landed, the state is rebuilt from the store, so the fault held
|
||||
/// is exactly what a reopen would hold, and the commit stays committed.
|
||||
pub(crate) fn advance(&mut self, receipt: &HuginnCommitReceipt, receipt_envelope: CultCacheEnvelope, writes: &[CultCacheEnvelope]) {
|
||||
for envelope in writes.iter().chain(std::iter::once(&receipt_envelope)) {
|
||||
self.envelopes.entry(envelope.r#type.clone()).or_default().insert(envelope.key.clone(), envelope.clone());
|
||||
}
|
||||
if receipt.writes.iter().any(|write| write.document_type == HuginnPersonaEntry::TYPE && write.document_key == self.instance.0)
|
||||
&& let Ok(held) = &mut self.persona_receipt
|
||||
{
|
||||
*held = Some(receipt.receipt_id.clone());
|
||||
}
|
||||
let Ok(image) = &mut self.image else { return };
|
||||
let mut documents = Vec::new();
|
||||
let mut faulted = false;
|
||||
for write in &receipt.writes {
|
||||
let Some(kind) = PipelineKind::ALL.iter().copied().find(|kind| kind.type_id() == write.document_type) else { continue };
|
||||
let Some(envelope) = writes.iter().find(|envelope| envelope.r#type == write.document_type && envelope.key == write.document_key) else {
|
||||
faulted = true;
|
||||
break;
|
||||
};
|
||||
match PipelineDocument::decode(envelope) {
|
||||
Ok(document) => documents.push((kind, write.document_key.clone(), document)),
|
||||
Err(_) => faulted = true,
|
||||
}
|
||||
}
|
||||
if faulted || image.advance(&AdmissionFacts::of(receipt), documents).is_err() {
|
||||
// A failed look holds its own fault.
|
||||
let _ = self.refresh();
|
||||
}
|
||||
self.cache.pull_all_backing_stores().map_err(unavailable)?;
|
||||
self.image = snapshot(&self.cache);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -432,6 +343,22 @@ fn refuse_foreign_identity(raw: &[CultCacheEnvelope], instance: &Slug) -> Result
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Step 5: the registered cache, the store as its one generic home, and the
|
||||
/// image pulled through it.
|
||||
fn attach<S: MindStore>(store: S) -> Result<(CultCache, Vec<CultCacheEnvelope>), MindRefusal> {
|
||||
let mut cache = schema_cache()?;
|
||||
cache.add_generic_backing_store(store).map_err(unavailable)?;
|
||||
cache.pull_all_backing_stores().map_err(unavailable)?;
|
||||
let image = snapshot(&cache);
|
||||
Ok((cache, image))
|
||||
}
|
||||
|
||||
fn snapshot(cache: &CultCache) -> Vec<CultCacheEnvelope> {
|
||||
let mut image = cache.snapshot_envelopes();
|
||||
image.sort_by(|left, right| (&left.r#type, &left.key).cmp(&(&right.r#type, &right.key)));
|
||||
image
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -537,11 +464,11 @@ mod tests {
|
|||
Some(MindRefusal::ForeignEpoch { found: "2 records".into(), expected: PIPELINE_SCHEMA_EPOCH.into() })
|
||||
);
|
||||
}
|
||||
// A store that passes every gate is read once: the pull the gates ran on is the one the image folds.
|
||||
// A store that passes every gate attaches, which is the second pull.
|
||||
let store = planted(vec![epoch(), prepare(&instance(INSTANCE))]);
|
||||
let mind = Mind::open_with(store.clone(), &yggdrasil).unwrap();
|
||||
assert_eq!(store.pull_count(), 1);
|
||||
assert_eq!(mind.envelopes().count(), 2);
|
||||
assert_eq!(store.pull_count(), 2);
|
||||
assert_eq!(mind.envelopes().len(), 2);
|
||||
assert!(!mind.is_empty());
|
||||
let empty = MemoryStore::new();
|
||||
assert!(Mind::open_with(empty, &yggdrasil).unwrap().is_empty());
|
||||
|
|
@ -632,7 +559,7 @@ mod tests {
|
|||
let store = OwnedRedbMessagePackBackingStore::new(&moved).unwrap();
|
||||
let mind = Mind::open_with(store, &slug(INSTANCE)).unwrap();
|
||||
assert_eq!(mind.instance(), &slug(INSTANCE));
|
||||
assert_eq!(mind.envelopes().count(), 2);
|
||||
assert_eq!(mind.envelopes().len(), 2);
|
||||
}
|
||||
|
||||
/// One check, one owner: the value admission refuses a foreign instance
|
||||
|
|
|
|||
|
|
@ -1,336 +0,0 @@
|
|||
//! The read side's definition, frozen: decode every stored document and every
|
||||
//! receipt on each call, derive status by a linear recursive scan, build every
|
||||
//! row, and let the substrate select over all of them. It shares nothing with
|
||||
//! the held `Image` or with `Docs`, so a test that sets the two side by side
|
||||
//! compares two derivations, not one with itself. No production consumer.
|
||||
//!
|
||||
//! Also the synthetic history the floor test scales a store with.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use chrono::{TimeZone, Utc};
|
||||
use cultcache_rs::{CultCacheEnvelope, DatabaseEntry};
|
||||
use cultnet_rs::{Selection, select, validate};
|
||||
use eureka_pipeline::{
|
||||
CodeLocation, CommitRange, Date, Evidence, EvidenceKind, FindingConfidence, FindingOrigin, FindingSeverity, Label, MutationRecord,
|
||||
PipelineCutReport, PipelineDocument, PipelineFinding, PipelineKind, PipelineRef, PipelineResolution, ReportCommit, ResolutionOutcome, Sha,
|
||||
Line, Para, Short, Slug, StructuralDelta, pipeline_key,
|
||||
};
|
||||
|
||||
use crate::docs::{citations, kind_of_type};
|
||||
use crate::mind::{Mind, schema_cache};
|
||||
use crate::persona::HuginnPersonaEntry;
|
||||
use crate::query::{AdmissionFacts, PipelineDocumentView, PipelineSelectionPage, PipelineStatus};
|
||||
use crate::receipt::{self, Faculty, HuginnCommitReceipt, PipelineProvenance};
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::rows::{SelectionRow, Vocabulary, refuse_values};
|
||||
use crate::store::MindStore;
|
||||
|
||||
struct Doc {
|
||||
kind: PipelineKind,
|
||||
key: String,
|
||||
document: PipelineDocument,
|
||||
facts: AdmissionFacts,
|
||||
}
|
||||
|
||||
/// The mind as the store holds it, derived from nothing but the store.
|
||||
struct Fresh {
|
||||
docs: Vec<Doc>,
|
||||
}
|
||||
|
||||
fn fault(detail: String) -> MindRefusal {
|
||||
MindRefusal::Unavailable { detail }
|
||||
}
|
||||
|
||||
impl Fresh {
|
||||
fn pull<S: MindStore>(mind: &Mind<S>) -> Result<Self, MindRefusal> {
|
||||
let mut raw = mind.store().pull_all().map_err(|error| fault(format!("{error:#}")))?;
|
||||
raw.sort_by(|left, right| (&left.r#type, &left.key).cmp(&(&right.r#type, &right.key)));
|
||||
let mut held = Vec::new();
|
||||
for envelope in &raw {
|
||||
let Some(kind) = kind_of_type(&envelope.r#type) else { continue };
|
||||
let document = PipelineDocument::decode(envelope)
|
||||
.map_err(|refusal| fault(format!("stored document {} does not decode: {refusal}", envelope.key)))?;
|
||||
held.push((kind, envelope.key.clone(), document));
|
||||
}
|
||||
let mut receipts = Vec::new();
|
||||
for envelope in raw.iter().filter(|envelope| envelope.r#type == HuginnCommitReceipt::TYPE) {
|
||||
receipts.push(rmp_serde::from_slice::<HuginnCommitReceipt>(&envelope.payload).map_err(|error| {
|
||||
fault(format!("receipt {} does not decode: {error}", envelope.key))
|
||||
})?);
|
||||
}
|
||||
let mut ordinals: Vec<u64> = receipts.iter().map(|receipt| receipt.ordinal).collect();
|
||||
ordinals.sort_unstable();
|
||||
if !ordinals.iter().copied().eq(1..=ordinals.len() as u64) {
|
||||
return Err(fault("receipt ordinals are not 1..=N: found a duplicate or a gap".into()));
|
||||
}
|
||||
let mut facts: BTreeMap<(String, String), AdmissionFacts> = BTreeMap::new();
|
||||
for receipt in &receipts {
|
||||
for write in receipt.writes.iter().filter(|write| write.document_type != HuginnPersonaEntry::TYPE) {
|
||||
let landed = AdmissionFacts {
|
||||
receipt_id: receipt.receipt_id.clone(),
|
||||
admitted_at: receipt.committed_at.clone(),
|
||||
provenance: receipt.provenance.clone(),
|
||||
ordinal: receipt.ordinal,
|
||||
};
|
||||
if facts.insert((write.document_type.clone(), write.document_key.clone()), landed).is_some() {
|
||||
return Err(fault(format!("document {}/{} is written by two receipts", write.document_type, write.document_key)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut docs = Vec::new();
|
||||
for (kind, key, document) in held {
|
||||
let type_id = kind.type_id();
|
||||
let landed = facts
|
||||
.get(&(type_id.to_string(), key.clone()))
|
||||
.cloned()
|
||||
.ok_or_else(|| fault(format!("document {type_id}/{key} has no commit receipt")))?;
|
||||
docs.push(Doc { kind, key, document, facts: landed });
|
||||
}
|
||||
Ok(Self { docs })
|
||||
}
|
||||
|
||||
fn visible(&self, as_of: u64) -> Vec<&Doc> {
|
||||
self.docs.iter().filter(|doc| doc.facts.ordinal <= as_of).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The recursive derivation, by linear scan over the visible documents.
|
||||
fn closing<'a>(visible: &[&'a Doc], kind: PipelineKind, key: &str) -> Option<(&'a str, &'a PipelineResolution)> {
|
||||
visible.iter().find_map(|doc| match &doc.document {
|
||||
PipelineDocument::Resolution(resolution)
|
||||
if resolution.subject.kind == kind
|
||||
&& resolution.subject.id.0 == key
|
||||
&& closing(visible, PipelineKind::Resolution, &doc.key).is_none() =>
|
||||
{
|
||||
Some((doc.key.as_str(), resolution))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn view_of(visible: &[&Doc], doc: &Doc) -> PipelineDocumentView {
|
||||
let status = match closing(visible, doc.kind, &doc.key) {
|
||||
Some((key, record)) => PipelineStatus::Resolved {
|
||||
resolution: PipelineRef { kind: PipelineKind::Resolution, id: Short(key.to_string()) },
|
||||
record: record.clone(),
|
||||
},
|
||||
None => PipelineStatus::InForce,
|
||||
};
|
||||
PipelineDocumentView {
|
||||
id: PipelineRef { kind: doc.kind, id: Short(doc.key.clone()) },
|
||||
document: doc.document.clone(),
|
||||
admission: doc.facts.clone(),
|
||||
status,
|
||||
}
|
||||
}
|
||||
|
||||
fn base<'a>(visible: &[&'a Doc], doc: &'a Doc) -> &'a Doc {
|
||||
let mut current = doc;
|
||||
while let PipelineDocument::Resolution(resolution) = ¤t.document {
|
||||
let Some(subject) = visible.iter().find(|other| other.kind == resolution.subject.kind && other.key == resolution.subject.id.0) else {
|
||||
return current;
|
||||
};
|
||||
current = subject;
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
fn row_of(visible: &[&Doc], doc: &Doc) -> SelectionRow {
|
||||
let base = base(visible, doc);
|
||||
SelectionRow::new(doc.kind, &doc.key, Some((&base.key, &base.document)), view_of(visible, doc), citations(&doc.document))
|
||||
}
|
||||
|
||||
/// The page a selection earns at `as_of`, derived from the store alone.
|
||||
pub fn oracle_page<S: MindStore>(mind: &Mind<S>, selection: &Selection, as_of: u64) -> Result<PipelineSelectionPage, MindRefusal> {
|
||||
validate(selection, &Vocabulary).map_err(cultnet_rs::SelectionRefusal::Invalid)?;
|
||||
let selection = refuse_values(selection)?;
|
||||
let fresh = Fresh::pull(mind)?;
|
||||
let visible = fresh.visible(as_of);
|
||||
let rows: Vec<SelectionRow> = visible.iter().map(|doc| row_of(&visible, doc)).collect();
|
||||
let rows: Vec<&SelectionRow> = rows.iter().collect();
|
||||
let evaluation = select(&Vocabulary, &rows, &selection, as_of, mind.cursor_key())?;
|
||||
Mind::<S>::page(&selection, evaluation, as_of, None)
|
||||
}
|
||||
|
||||
/// The view of one document at `as_of`, derived from the store alone.
|
||||
pub fn oracle_view<S: MindStore>(
|
||||
mind: &Mind<S>,
|
||||
id: &PipelineRef,
|
||||
as_of: u64,
|
||||
) -> Result<Option<PipelineDocumentView>, MindRefusal> {
|
||||
let fresh = Fresh::pull(mind)?;
|
||||
let visible = fresh.visible(as_of);
|
||||
Ok(visible.iter().find(|doc| doc.kind == id.kind && doc.key == id.id.0).map(|doc| view_of(&visible, doc)))
|
||||
}
|
||||
|
||||
/// Every pipeline identity the store holds, in the snapshot's order.
|
||||
pub fn oracle_ids<S: MindStore>(mind: &Mind<S>, as_of: u64) -> Result<Vec<PipelineRef>, MindRefusal> {
|
||||
let fresh = Fresh::pull(mind)?;
|
||||
Ok(fresh.visible(as_of).iter().map(|doc| PipelineRef { kind: doc.kind, id: Short(doc.key.clone()) }).collect())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The synthetic history
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const BATCH_RECEIPTS: usize = 700;
|
||||
|
||||
fn pad(text: &str, bytes: usize) -> String {
|
||||
let mut out = text.to_string();
|
||||
while out.len() < bytes {
|
||||
out.push_str(" padding for payload size");
|
||||
}
|
||||
out.truncate(bytes.max(text.len()));
|
||||
out
|
||||
}
|
||||
|
||||
fn range() -> CommitRange {
|
||||
CommitRange { base: Sha("5f98228d".into()), head: Sha("a1b2c3d4".into()) }
|
||||
}
|
||||
|
||||
fn finding(root: &str, unit: usize, n: usize) -> PipelineDocument {
|
||||
PipelineDocument::Finding(PipelineFinding {
|
||||
campaign: Slug(root.into()),
|
||||
verdict: Short(format!("{root}:verdict:cut-u{unit}.s1")),
|
||||
label: Label(format!("f{unit}-{n}")),
|
||||
range: range(),
|
||||
confidence: FindingConfidence::Confirmed,
|
||||
severity: FindingSeverity::Medium,
|
||||
claim: Line(pad("A synthetic claim.", 500)),
|
||||
invariants: vec![Label("synthetic".into())],
|
||||
locations: vec![CodeLocation { path: Short("crates/huginn-mind/src/query.rs".into()), line: 1, end_line: None, symbol: None }],
|
||||
failure_scenario: Para(pad("A synthetic failure scenario.", 700)),
|
||||
evidence: vec![Evidence { kind: EvidenceKind::Test, locator: "cargo test".into(), result: "ok".into() }],
|
||||
precedents: vec![],
|
||||
origin: FindingOrigin::Introduced,
|
||||
})
|
||||
}
|
||||
|
||||
fn cut_report(root: &str, unit: usize) -> PipelineDocument {
|
||||
let delta = StructuralDelta {
|
||||
lines_added: 0,
|
||||
lines_removed: 0,
|
||||
dependencies_added: vec![],
|
||||
dependencies_removed: vec![],
|
||||
formats_added: vec![],
|
||||
formats_removed: vec![],
|
||||
targets_added: vec![],
|
||||
targets_removed: vec![],
|
||||
};
|
||||
PipelineDocument::CutReport(PipelineCutReport {
|
||||
campaign: Slug(root.into()),
|
||||
cut_spec: Short(format!("{root}:cut_spec:cut-u{unit}.r1")),
|
||||
attempt: 1,
|
||||
repo: eureka_pipeline::OrgRepo("GameCult/Huginn".into()),
|
||||
branch: Short("hands/synthetic".into()),
|
||||
commits: vec![ReportCommit { sha: Sha("5f98228d".into()), subject: "Land the cut".into(), builds: true }],
|
||||
range: range(),
|
||||
verification: (0..8)
|
||||
.map(|n| Evidence { kind: EvidenceKind::Command, locator: Line(format!("command {n}")), result: Line(pad("passed", 1000)) })
|
||||
.collect(),
|
||||
mutations: vec![MutationRecord {
|
||||
label: Label("M1".into()),
|
||||
rule: "the rule".into(),
|
||||
location: CodeLocation { path: Short("crates/huginn-mind/src/query.rs".into()), line: 1, end_line: None, symbol: None },
|
||||
before: "before".into(),
|
||||
after: "after".into(),
|
||||
commit: Sha("5f98228d".into()),
|
||||
failed_as_expected: true,
|
||||
}],
|
||||
deviations: vec![],
|
||||
forks: vec![],
|
||||
structural_delta: delta,
|
||||
landed_names: vec![],
|
||||
undone: vec![],
|
||||
promises: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
fn resolution(subject: PipelineRef) -> PipelineDocument {
|
||||
PipelineDocument::Resolution(PipelineResolution {
|
||||
subject,
|
||||
sequence: 1,
|
||||
outcome: ResolutionOutcome::Recorded { reason: "Synthetic.".into() },
|
||||
rationale: Para(pad("Resolved.", 100)),
|
||||
resolved_on: Date("2026-10-01".into()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Grows a store to `factor` times its pipeline documents with synthetic
|
||||
/// history: findings, cut reports and the resolutions that close four records
|
||||
/// in five, about three writes a receipt, through the store's own
|
||||
/// compare-and-swap in dense receipts. `spread` puts each hundred units under
|
||||
/// its own `synth-<n>` root; otherwise everything goes under
|
||||
/// `eureka-substrate`, one root growing. Returns the documents written.
|
||||
pub fn synth_history<S: MindStore>(store: &S, instance: &Slug, factor: u32, spread: bool) -> Result<usize, MindRefusal> {
|
||||
let pulled = store.pull_all().map_err(|error| fault(format!("{error:#}")))?;
|
||||
let existing = pulled.iter().filter(|envelope| kind_of_type(&envelope.r#type).is_some()).count();
|
||||
let mut ordinal = pulled.iter().filter(|envelope| envelope.r#type == HuginnCommitReceipt::TYPE).count() as u64;
|
||||
let want = existing * factor.saturating_sub(1) as usize;
|
||||
// A unit is five records (four findings, one cut report) and the four
|
||||
// resolutions that close four of them.
|
||||
let units = want / 9;
|
||||
let cache = schema_cache()?;
|
||||
let provenance = PipelineProvenance {
|
||||
faculty: Faculty::Hands,
|
||||
agent: Short("synth".into()),
|
||||
session: Short("synth".into()),
|
||||
tool: Short("synth".into()),
|
||||
};
|
||||
let now = Utc.with_ymd_and_hms(2026, 10, 1, 12, 0, 0).unwrap();
|
||||
let mut pending: Vec<Vec<CultCacheEnvelope>> = Vec::new();
|
||||
let mut written = 0;
|
||||
let flush = |groups: &mut Vec<Vec<CultCacheEnvelope>>, ordinal: &mut u64| -> Result<(), MindRefusal> {
|
||||
if groups.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut replacements = Vec::new();
|
||||
for writes in groups.drain(..) {
|
||||
*ordinal += 1;
|
||||
let receipt = receipt::candidate(instance, provenance.clone(), &[], &writes, *ordinal, now)?;
|
||||
let (envelope, _) = cache.prepare_entry_named(&receipt.receipt_id, &receipt).map_err(|error| fault(format!("{error:#}")))?;
|
||||
replacements.extend(writes);
|
||||
replacements.push(envelope);
|
||||
}
|
||||
if !store.compare_and_swap_batch(&[], replacements).map_err(|error| fault(format!("{error:#}")))? {
|
||||
return Err(fault("the synthetic batch lost its swap".into()));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let prepare = |document: &PipelineDocument| -> Result<(PipelineRef, CultCacheEnvelope), MindRefusal> {
|
||||
let key = pipeline_key(document)?;
|
||||
let envelope = document.prepare(&cache).map_err(|error| fault(format!("{error:#}")))?;
|
||||
Ok((PipelineRef { kind: document.kind(), id: Short(key) }, envelope))
|
||||
};
|
||||
for unit in 0..units {
|
||||
let root = if spread { format!("synth-{}", unit / 100) } else { "eureka-substrate".to_string() };
|
||||
let mut records = Vec::new();
|
||||
for n in 0..4 {
|
||||
records.push(prepare(&finding(&root, unit, n))?);
|
||||
}
|
||||
records.push(prepare(&cut_report(&root, unit))?);
|
||||
let mut closers = Vec::new();
|
||||
for (subject, _) in records.iter().take(4) {
|
||||
closers.push(prepare(&resolution(subject.clone()))?);
|
||||
}
|
||||
let mut all = records.into_iter().chain(closers).map(|(_, envelope)| envelope).collect::<Vec<_>>();
|
||||
written += all.len();
|
||||
let tail = all.split_off(6);
|
||||
let middle = all.split_off(3);
|
||||
pending.extend([all, middle, tail]);
|
||||
if pending.len() >= BATCH_RECEIPTS {
|
||||
flush(&mut pending, &mut ordinal)?;
|
||||
}
|
||||
}
|
||||
flush(&mut pending, &mut ordinal)?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// Opens the store at `path` under its exclusive lock, grows it, and lets go
|
||||
/// of the lock, so a `Mind::open` can follow.
|
||||
pub fn synth_history_at(path: &Path, instance: &Slug, factor: u32, spread: bool) -> Result<usize, MindRefusal> {
|
||||
let store = crate::store::OwnedRedbMessagePackBackingStore::new(path).map_err(|error| fault(format!("{error:#}")))?;
|
||||
synth_history(&store, instance, factor, spread)
|
||||
}
|
||||
|
|
@ -19,10 +19,7 @@ use schemars::JsonSchema;
|
|||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use eureka_pipeline::Slug;
|
||||
|
||||
use crate::mind::Mind;
|
||||
use crate::receipt::HuginnCommitReceipt;
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::store::MindStore;
|
||||
|
||||
|
|
@ -127,15 +124,6 @@ pub(crate) fn updated_at(value: &Value) -> Option<&str> {
|
|||
value.get("updatedAt").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// The receipt that wrote the persona's stored bytes: the newest receipt whose writes name it.
|
||||
pub(crate) fn persona_receipt_of(receipts: &[HuginnCommitReceipt], instance: &Slug) -> Option<String> {
|
||||
receipts
|
||||
.iter()
|
||||
.filter(|receipt| receipt.writes.iter().any(|write| write.document_type == HuginnPersonaEntry::TYPE && write.document_key == instance.0))
|
||||
.max_by_key(|receipt| receipt.ordinal)
|
||||
.map(|receipt| receipt.receipt_id.clone())
|
||||
}
|
||||
|
||||
impl<S: MindStore> Mind<S> {
|
||||
/// This mind's persona envelope, if one is stored.
|
||||
pub(crate) fn persona_envelope(&self) -> Option<&CultCacheEnvelope> {
|
||||
|
|
@ -158,7 +146,14 @@ impl<S: MindStore> Mind<S> {
|
|||
let value = decode(envelope)?;
|
||||
let integrity = |detail: &str| MindRefusal::Unavailable { detail: detail.into() };
|
||||
let updated_at = updated_at(&value).ok_or_else(|| integrity("the stored persona has no updatedAt"))?.to_string();
|
||||
let receipt_id = self.persona_receipt.clone()?.ok_or_else(|| integrity("the stored persona has no receipt"))?;
|
||||
let identity = (envelope.r#type.as_str(), envelope.key.as_str());
|
||||
let receipt_id = self
|
||||
.receipts()?
|
||||
.into_iter()
|
||||
.filter(|receipt| receipt.writes.iter().any(|write| write.identity() == identity))
|
||||
.max_by_key(|receipt| receipt.ordinal)
|
||||
.ok_or_else(|| integrity("the stored persona has no receipt"))?
|
||||
.receipt_id;
|
||||
Ok(Some(PersonaStateView { value, updated_at, receipt_id }))
|
||||
}
|
||||
}
|
||||
|
|
@ -590,7 +585,7 @@ mod tests {
|
|||
let mut with_one = base();
|
||||
with_one.push(entry(INSTANCE, persona(INSTANCE, T1)));
|
||||
let mind = Mind::open_with(planted(with_one.clone()), &yggdrasil).unwrap();
|
||||
assert_eq!(mind.envelopes().count(), 3);
|
||||
assert_eq!(mind.envelopes().len(), 3);
|
||||
assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Unreadable);
|
||||
assert!(mind.persona().is_err());
|
||||
|
||||
|
|
@ -611,31 +606,6 @@ mod tests {
|
|||
/// Status answers in the door's own terms: a stored persona the door
|
||||
/// cannot read is `Unreadable`, not the `Absent` of a mind with none, while
|
||||
/// `PersonaGet` answers `Unavailable` for the same bytes.
|
||||
/// The persona's receipt is the newest put that wrote it, advanced with each put and the same
|
||||
/// after a restart.
|
||||
#[test]
|
||||
fn the_persona_receipt_is_the_newest_put_held_and_after_a_restart() {
|
||||
let store = MemoryStore::new();
|
||||
let mut mind = seeded_over(&store);
|
||||
committed(put(&mut mind, persona(INSTANCE, T1), None));
|
||||
let first = mind.persona().unwrap().unwrap().receipt_id;
|
||||
committed(put(&mut mind, persona(INSTANCE, T2), Some(T1)));
|
||||
let second = mind.persona().unwrap().unwrap().receipt_id;
|
||||
assert_ne!(first, second);
|
||||
let newest = mind
|
||||
.receipts()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|receipt| receipt.writes.iter().any(|write| write.document_type == HuginnPersonaEntry::TYPE))
|
||||
.max_by_key(|receipt| receipt.ordinal)
|
||||
.unwrap()
|
||||
.receipt_id;
|
||||
assert_eq!(second, newest);
|
||||
let reopened = Mind::open_with(store, &slug(INSTANCE)).unwrap();
|
||||
assert_eq!(reopened.persona().unwrap().unwrap().receipt_id, second);
|
||||
assert_eq!(reopened.persona_receipt, mind.persona_receipt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_says_unreadable_where_the_door_says_unavailable() {
|
||||
let yggdrasil = slug(INSTANCE);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,9 @@
|
|||
//! The read side of a mind: a document with the facts of its admission and
|
||||
//! its status, and one typed selection over them.
|
||||
//!
|
||||
//! Nothing derived here is stored in a document. The rows come from the mind's
|
||||
//! held `image::Image`, a fold of the receipts; status is derived through the
|
||||
//! same `docs::Docs` the admission rules use, at the head when the image was
|
||||
//! advanced and at an old snapshot when a reader asks, so a withdrawn
|
||||
//! resolution reopens its subject for a reader exactly when it reopens it for
|
||||
//! a rule. The facts come
|
||||
//! Nothing here is stored. Status is derived per call through the same
|
||||
//! `docs::Docs` the admission rules use, so a withdrawn resolution reopens its
|
||||
//! subject for a reader exactly when it reopens it for a rule. The facts come
|
||||
//! from the commit receipts, from their `writes` and from nothing else: a
|
||||
//! document's `admitted_at` is the `now` its batch was admitted at
|
||||
//! (`committed_at`), never the store's `stored_at` stamp. A pipeline document
|
||||
|
|
@ -16,33 +13,31 @@
|
|||
//! `query` is CultNet's selection over rows this crate supplies (`rows.rs`).
|
||||
//! The substrate owns the filter, the order, the hop, the cursor and the
|
||||
//! paging; this module owns the snapshot (`Reader::at`: every derivation runs
|
||||
//! over the documents admitted at or before the page's `asOf`, and the image
|
||||
//! only narrows which of its rows the substrate is handed), the
|
||||
//! over the documents admitted at or before the page's `asOf`), the
|
||||
//! projection to a header or a whole view, and the typing of the edges.
|
||||
//!
|
||||
//! `rank` is the semantic read: the daemon's index supplies candidate ids and
|
||||
//! scores, and this module joins them back through the mind and lets the
|
||||
//! selection decide. No clock, no store handle, no network.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultnet_rs::{
|
||||
Cursor, EdgeAnchor, EdgeMatch, Evaluation, LIMIT_MAX, LIMIT_MIN, PROJECTION_DOCUMENT, Selection, select, validate,
|
||||
Cursor, EdgeAnchor, EdgeMatch, Evaluation, LIMIT_MAX, LIMIT_MIN, PROJECTION_DOCUMENT, Row, Selection, select, validate,
|
||||
};
|
||||
use eureka_pipeline::{
|
||||
ClaimOutcome, CommitRange, Date, FindingConfidence, FindingOrigin, FindingSeverity, Label, Line, MemoryOrigin, MemorySort, OrgRepo,
|
||||
PipelineCampaign, PipelineDocument, PipelineKind, PipelineRef, PipelineResolution, ResolutionOutcome, RulingAuthority, RunOperator, RunTurn, Sha,
|
||||
PipelineDocument, PipelineKind, PipelineRef, PipelineResolution, ResolutionOutcome, RulingAuthority, RunOperator, RunTurn, Sha,
|
||||
Short, Slug, Title, pipeline_key,
|
||||
};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::docs::{CitationRole, Docs, kind_of_type};
|
||||
use crate::image::{Image, status_of};
|
||||
use crate::docs::{CitationRole, Docs, Held, citations, kind_of_type};
|
||||
use crate::mind::{Mind, schema_cache};
|
||||
use crate::persona::HuginnPersonaEntry;
|
||||
use crate::receipt::{HuginnCommitReceipt, PipelineProvenance};
|
||||
use crate::receipt::{self, PipelineProvenance};
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::rows::{SelectionRow, Vocabulary, refuse_values};
|
||||
use crate::store::MindStore;
|
||||
|
|
@ -330,51 +325,57 @@ pub struct Ranked {
|
|||
pub dropped: Vec<PipelineRef>,
|
||||
}
|
||||
|
||||
impl AdmissionFacts {
|
||||
/// What a receipt records about every document it wrote.
|
||||
pub(crate) fn of(receipt: &HuginnCommitReceipt) -> Self {
|
||||
Self {
|
||||
receipt_id: receipt.receipt_id.clone(),
|
||||
admitted_at: receipt.committed_at.clone(),
|
||||
provenance: receipt.provenance.clone(),
|
||||
ordinal: receipt.ordinal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The identities the receipts wrote, checked once per build. A chain that is not exactly
|
||||
/// `{1..=N}` refuses before a single ordinal is trusted. `writes` only: a document a later batch
|
||||
/// cited as a strong read keeps the receipt that wrote it. A10 admits one write per pipeline
|
||||
/// identity, so two receipts naming one pipeline document is an integrity fault, not a choice to
|
||||
/// make. The persona document is the one identity replaced by design (`put_persona` is a
|
||||
/// compare-and-swap on `updatedAt`) and is not a pipeline document: it has no admission facts
|
||||
/// here, and the mind holds its receipt apart.
|
||||
pub(crate) struct AdmissionIndex(HashSet<(String, String)>);
|
||||
/// The admission facts of every stored document, built once per read call from
|
||||
/// the receipts. `writes` only: a document a later batch cited as a strong read
|
||||
/// keeps the receipt that wrote it. A10 admits one write per pipeline identity,
|
||||
/// so two receipts naming one pipeline document is an integrity fault, not a
|
||||
/// choice to make. The persona document is the one identity replaced by design
|
||||
/// (`put_persona` is a compare-and-swap on `updatedAt`) and is not a pipeline
|
||||
/// document: it has no admission facts here, and `Mind::persona` reads its own
|
||||
/// receipt.
|
||||
pub(crate) struct AdmissionIndex(BTreeMap<(String, String), AdmissionFacts>);
|
||||
|
||||
impl AdmissionIndex {
|
||||
pub(crate) fn build(receipts: &[HuginnCommitReceipt]) -> Result<Self, MindRefusal> {
|
||||
let mut ordinals = receipts.iter().map(|receipt| receipt.ordinal).collect::<Vec<_>>();
|
||||
ordinals.sort_unstable();
|
||||
if !ordinals.iter().copied().eq(1..=ordinals.len() as u64) {
|
||||
return Err(MindRefusal::Unavailable { detail: "receipt ordinals are not 1..=N: found a duplicate or a gap".into() });
|
||||
}
|
||||
let mut identities = HashSet::new();
|
||||
for receipt in receipts {
|
||||
pub(crate) fn build<S: MindStore>(mind: &Mind<S>) -> Result<Self, MindRefusal> {
|
||||
// Every reader of the ordinal asks the same density check admission
|
||||
// does, through `head`: a chain that is not exactly `{1..=N}` refuses
|
||||
// here before a single ordinal is copied out, not only when admission
|
||||
// happens to be the caller.
|
||||
receipt::head(mind)?;
|
||||
let mut facts = BTreeMap::new();
|
||||
for receipt in mind.receipts()? {
|
||||
for write in receipt.writes.iter().filter(|write| write.document_type != HuginnPersonaEntry::TYPE) {
|
||||
if !identities.insert((write.document_type.clone(), write.document_key.clone())) {
|
||||
let identity = (write.document_type.clone(), write.document_key.clone());
|
||||
let landed = AdmissionFacts {
|
||||
receipt_id: receipt.receipt_id.clone(),
|
||||
admitted_at: receipt.committed_at.clone(),
|
||||
provenance: receipt.provenance.clone(),
|
||||
ordinal: receipt.ordinal,
|
||||
};
|
||||
if facts.insert(identity, landed).is_some() {
|
||||
return Err(integrity(&write.document_type, &write.document_key, "is written by two receipts"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self(identities))
|
||||
Ok(Self(facts))
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, type_id: &str, key: &str) -> bool {
|
||||
self.0.contains(&(type_id.to_string(), key.to_string()))
|
||||
fn of(&self, held: &Held) -> Result<AdmissionFacts, MindRefusal> {
|
||||
self.facts_of(held.kind, &held.key)
|
||||
}
|
||||
|
||||
pub(crate) fn identities(&self) -> impl Iterator<Item = &(String, String)> {
|
||||
self.0.iter()
|
||||
fn facts_of(&self, kind: PipelineKind, key: &str) -> Result<AdmissionFacts, MindRefusal> {
|
||||
let type_id = kind.type_id();
|
||||
self.0
|
||||
.get(&(type_id.to_string(), key.to_string()))
|
||||
.cloned()
|
||||
.ok_or_else(|| integrity(type_id, key, "has no commit receipt"))
|
||||
}
|
||||
|
||||
/// The ordinal of the receipt that wrote a document: the projection's
|
||||
/// position for it.
|
||||
pub(crate) fn ordinal_of(&self, kind: PipelineKind, key: &str) -> Result<u64, MindRefusal> {
|
||||
self.facts_of(kind, key).map(|facts| facts.ordinal)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -382,103 +383,85 @@ fn integrity(type_id: &str, key: &str, fault: &str) -> MindRefusal {
|
|||
MindRefusal::Unavailable { detail: format!("document {type_id}/{key} {fault}") }
|
||||
}
|
||||
|
||||
/// A root of the mind and the newest admission under it. `repos` is the repo set in force of a root that is an in-force campaign,
|
||||
/// and empty for any other root.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct RootTouched {
|
||||
pub root: Slug,
|
||||
pub admitted_at: String,
|
||||
#[schemars(range(min = 1))]
|
||||
pub ordinal: u64,
|
||||
pub repos: Vec<OrgRepo>,
|
||||
/// One read call's working set: the image as of one snapshot and the facts it
|
||||
/// was built from. Built once per call and thrown away with it; nothing here
|
||||
/// outlives the answer.
|
||||
struct Reader {
|
||||
docs: Docs,
|
||||
facts: AdmissionIndex,
|
||||
}
|
||||
|
||||
impl RootTouched {
|
||||
fn of(root: &str, facts: &AdmissionFacts, repos: &[OrgRepo]) -> Self {
|
||||
Self { root: Slug(root.to_string()), admitted_at: facts.admitted_at.clone(), ordinal: facts.ordinal, repos: repos.to_vec() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One read call's view of the held image at one snapshot. Nothing is decoded or built here: a row
|
||||
/// is the image's own, unless its status changed after `as_of`, in which case it is rebuilt once
|
||||
/// with the status the closing resolutions give at `as_of`.
|
||||
pub(crate) struct Reader<'i> {
|
||||
docs: Docs<'i>,
|
||||
image: &'i Image,
|
||||
as_of: u64,
|
||||
patched: HashMap<u32, SelectionRow>,
|
||||
}
|
||||
|
||||
impl<'i> Reader<'i> {
|
||||
/// The mind as it stood when receipt `as_of` landed. The held fault, if the store has one, is
|
||||
/// answered at any snapshot.
|
||||
pub(crate) fn at<S: MindStore>(mind: &'i Mind<S>, as_of: u64) -> Result<Self, MindRefusal> {
|
||||
let image = mind.image()?;
|
||||
Ok(Self { docs: Docs::at(image, as_of), image, as_of, patched: HashMap::new() })
|
||||
}
|
||||
|
||||
fn status_at(&self, id: u32) -> PipelineStatus {
|
||||
let row = self.image.row(id);
|
||||
status_of(self.docs.closing_resolution(row.kind, &row.key))
|
||||
}
|
||||
|
||||
/// Whether the row exists at `as_of`; when it does, its snapshot row is ready for `row`.
|
||||
pub(crate) fn prepare(&mut self, id: u32) -> bool {
|
||||
if self.image.row(id).ordinal > self.as_of {
|
||||
return false;
|
||||
impl Reader {
|
||||
/// The mind as it stood when receipt `as_of` landed: the documents whose
|
||||
/// writing receipt has `ordinal <= as_of`, and every derivation (in
|
||||
/// force, the closing resolution, `base`, citations) over that image
|
||||
/// alone. The facts are built over all receipts, and every held document
|
||||
/// must have its receipt whatever `as_of` is, so an orphan or a double
|
||||
/// write refuses at any snapshot.
|
||||
fn at<S: MindStore>(mind: &Mind<S>, as_of: u64) -> Result<Self, MindRefusal> {
|
||||
let mut docs = Docs::from_image(mind.envelopes())?;
|
||||
let facts = AdmissionIndex::build(mind)?;
|
||||
let mut visible = Vec::with_capacity(docs.image.len());
|
||||
for held in docs.image {
|
||||
if facts.of(&held)?.ordinal <= as_of {
|
||||
visible.push(held);
|
||||
}
|
||||
}
|
||||
if self.image.status_changed[id as usize] > self.as_of && !self.patched.contains_key(&id) {
|
||||
let row = self.image.make_row(id, self.status_at(id));
|
||||
self.patched.insert(id, row);
|
||||
}
|
||||
true
|
||||
docs.image = visible;
|
||||
Ok(Self { docs, facts })
|
||||
}
|
||||
|
||||
/// A prepared row.
|
||||
pub(crate) fn row(&self, id: u32) -> &SelectionRow {
|
||||
if self.image.status_changed[id as usize] > self.as_of { &self.patched[&id] } else { self.image.row(id) }
|
||||
}
|
||||
|
||||
/// The rows a selection can match at this snapshot: a superset the substrate then decides over.
|
||||
pub(crate) fn universe(&mut self, selection: &Selection) -> Vec<u32> {
|
||||
let ids = self.image.universe(selection, self.as_of);
|
||||
ids.into_iter().filter(|id| self.prepare(*id)).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn rows(&self, ids: &[u32]) -> Vec<&SelectionRow> {
|
||||
ids.iter().map(|id| self.row(*id)).collect()
|
||||
fn held(&self, kind: PipelineKind, key: &str) -> Option<&Held> {
|
||||
self.docs.image.iter().find(|held| held.kind == kind && held.key == key)
|
||||
}
|
||||
|
||||
/// The lookup `Mind::view` answers through, so a caller holding one `Reader`
|
||||
/// views many documents from one snapshot.
|
||||
pub(crate) fn id_of(&self, kind: PipelineKind, key: &str) -> Option<u32> {
|
||||
self.image.id_of(kind, key)
|
||||
fn view(&self, id: &PipelineRef) -> Result<Option<PipelineDocumentView>, MindRefusal> {
|
||||
self.held(id.kind, &id.id.0).map(|held| self.view_of(held)).transpose()
|
||||
}
|
||||
|
||||
pub(crate) fn view(&self, id: &PipelineRef) -> Result<Option<PipelineDocumentView>, MindRefusal> {
|
||||
let Some(row) = self.image.id_of(id.kind, &id.id.0) else { return Ok(None) };
|
||||
let held = self.image.row(row);
|
||||
if held.ordinal > self.as_of {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.image.status_changed[row as usize] <= self.as_of {
|
||||
return Ok(Some(held.view.clone()));
|
||||
}
|
||||
Ok(Some(self.image.make_row(row, self.status_at(row)).view))
|
||||
fn view_of(&self, held: &Held) -> Result<PipelineDocumentView, MindRefusal> {
|
||||
let admission = self.facts.of(held)?;
|
||||
let status = match self.docs.closing_resolution(held.kind, &held.key) {
|
||||
Some((key, record)) => PipelineStatus::Resolved {
|
||||
resolution: PipelineRef { kind: PipelineKind::Resolution, id: Short(key.to_string()) },
|
||||
record: record.clone(),
|
||||
},
|
||||
None => PipelineStatus::InForce,
|
||||
};
|
||||
Ok(PipelineDocumentView {
|
||||
id: PipelineRef { kind: held.kind, id: Short(held.key.clone()) },
|
||||
document: held.document.clone(),
|
||||
admission,
|
||||
status,
|
||||
})
|
||||
}
|
||||
|
||||
fn roots_touched(&self) -> Vec<RootTouched> {
|
||||
let docs = &self.docs;
|
||||
let campaigns: BTreeMap<&str, &PipelineCampaign> = docs
|
||||
.of_kind(PipelineKind::Campaign)
|
||||
.filter_map(|(key, document)| match document {
|
||||
PipelineDocument::Campaign(campaign) if docs.in_force(PipelineKind::Campaign, key) => Some((campaign.slug.0.as_str(), campaign)),
|
||||
_ => None,
|
||||
/// The document `repo` and `cut` are read through: a resolution's
|
||||
/// subject, and its subject's subject when that is a resolution too (the
|
||||
/// Q19 cap stops the chain at two). A7 puts every subject in the image,
|
||||
/// and a resolution key is strictly longer than the id it resolves, so
|
||||
/// this walks down and stops. Anything that is not a resolution is its
|
||||
/// own base.
|
||||
fn base<'b>(&'b self, held: &'b Held) -> &'b Held {
|
||||
let mut current = held;
|
||||
while let PipelineDocument::Resolution(resolution) = ¤t.document {
|
||||
let Some(subject) = self.held(resolution.subject.kind, &resolution.subject.id.0) else {
|
||||
return current;
|
||||
};
|
||||
current = subject;
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
fn rows(&self) -> Result<Vec<SelectionRow>, MindRefusal> {
|
||||
self.docs
|
||||
.image
|
||||
.iter()
|
||||
.map(|held| {
|
||||
Ok(SelectionRow::new(held, self.base(held), self.view_of(held)?, citations(&held.document)))
|
||||
})
|
||||
.collect();
|
||||
self.image
|
||||
.roots()
|
||||
.map(|(root, newest)| RootTouched::of(root, &newest.view.admission, campaigns.get(root).map_or(&[][..], |campaign| docs.repos_in_force(campaign))))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
|
@ -499,7 +482,7 @@ impl<S: MindStore> Mind<S> {
|
|||
/// vocabulary for one rule.
|
||||
pub fn view(&self, id: &PipelineRef) -> Result<Option<PipelineDocumentView>, MindRefusal> {
|
||||
id.validate_ref()?;
|
||||
Reader::at(self, self.image()?.head)?.view(id)
|
||||
Reader::at(self, receipt::head(self)?)?.view(id)
|
||||
}
|
||||
|
||||
/// The upgrade gate (ruling readback-gate-and-materialized-image): every
|
||||
|
|
@ -507,29 +490,21 @@ impl<S: MindStore> Mind<S> {
|
|||
/// stored key, type and payload bytes, and views back unchanged through the
|
||||
/// read path `view` uses; every pipeline write a receipt names is stored,
|
||||
/// and every stored document has its receipt. Returns how many documents
|
||||
/// it read back; an empty store is a fault. The held image is first set beside a
|
||||
/// fresh fold of the store and must equal it. That clause proves the holder's advance
|
||||
/// only for a mind that has committed since it opened; on the just-opened mind the
|
||||
/// upgrade reads, both sides are one fold of the same bytes, so a wrong fold passes
|
||||
/// it. What the gate proves today is the per-document read-back below. One pass over
|
||||
/// the mind, O(N). Admits nothing. A fault names the document's key and what failed,
|
||||
/// never its content.
|
||||
/// it read back; an empty store is a fault. One `Reader` serves every view,
|
||||
/// because `Reader::at` is the expensive build. Admits nothing. A fault
|
||||
/// names the document's key and what failed, never its content.
|
||||
pub fn read_back(&self) -> Result<usize, MindRefusal> {
|
||||
self.read_back_through(|reader, id| reader.view(id))
|
||||
self.read_back_through(Reader::view)
|
||||
}
|
||||
|
||||
/// The gate's one body; `lookup` is the read path under test, which tests
|
||||
/// replace with a lying one to prove the view comparison refuses.
|
||||
fn read_back_through(
|
||||
&self,
|
||||
lookup: impl Fn(&Reader<'_>, &PipelineRef) -> Result<Option<PipelineDocumentView>, MindRefusal>,
|
||||
lookup: impl Fn(&Reader, &PipelineRef) -> Result<Option<PipelineDocumentView>, MindRefusal>,
|
||||
) -> Result<usize, MindRefusal> {
|
||||
let cache = schema_cache()?;
|
||||
let image = self.image()?;
|
||||
if *image != self.fresh_image()? {
|
||||
return Err(MindRefusal::Unavailable { detail: "the held image differs from a fresh fold".into() });
|
||||
}
|
||||
let reader = Reader::at(self, image.head)?;
|
||||
let reader = Reader::at(self, receipt::head(self)?)?;
|
||||
let mut count = 0;
|
||||
for envelope in self.envelopes() {
|
||||
let Some(kind) = kind_of_type(&envelope.r#type) else { continue };
|
||||
|
|
@ -549,14 +524,10 @@ impl<S: MindStore> Mind<S> {
|
|||
}
|
||||
count += 1;
|
||||
}
|
||||
let receipted = AdmissionIndex::build(&self.receipts()?)?;
|
||||
let mut missing: Vec<&(String, String)> = receipted
|
||||
.identities()
|
||||
.filter(|(type_id, key)| kind_of_type(type_id).is_some() && self.raw_envelope(type_id, key).is_none())
|
||||
.collect();
|
||||
missing.sort();
|
||||
if let Some((type_id, key)) = missing.first() {
|
||||
return Err(integrity(type_id, key, "is named by a receipt but not stored"));
|
||||
for (type_id, key) in reader.facts.0.keys() {
|
||||
if kind_of_type(type_id).is_some() && self.raw_envelope(type_id, key).is_none() {
|
||||
return Err(integrity(type_id, key, "is named by a receipt but not stored"));
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return Err(MindRefusal::Unavailable { detail: "the store holds no pipeline document".into() });
|
||||
|
|
@ -574,7 +545,7 @@ impl<S: MindStore> Mind<S> {
|
|||
pub fn query(&self, selection: &Selection) -> Result<PipelineSelectionPage, MindRefusal> {
|
||||
validate(selection, &Vocabulary).map_err(cultnet_rs::SelectionRefusal::Invalid)?;
|
||||
let selection = refuse_values(selection)?;
|
||||
let head = self.image()?.head;
|
||||
let head = receipt::head(self)?;
|
||||
let as_of = match selection.cursor.as_deref().filter(|cursor| !cursor.is_empty()) {
|
||||
Some(cursor) => {
|
||||
let as_of = Cursor::parse(cursor)?.as_of;
|
||||
|
|
@ -587,31 +558,9 @@ impl<S: MindStore> Mind<S> {
|
|||
}
|
||||
None => head,
|
||||
};
|
||||
self.select_at(&selection, as_of)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// The doors `query` passes, then the one body at a snapshot the caller names: the entry the
|
||||
/// oracle tests set against the oracle at every `as_of`.
|
||||
pub(crate) fn query_at(&self, selection: &Selection, as_of: u64) -> Result<PipelineSelectionPage, MindRefusal> {
|
||||
validate(selection, &Vocabulary).map_err(cultnet_rs::SelectionRefusal::Invalid)?;
|
||||
let selection = refuse_values(selection)?;
|
||||
self.select_at(&selection, as_of)
|
||||
}
|
||||
|
||||
fn select_at(&self, selection: &Selection, as_of: u64) -> Result<PipelineSelectionPage, MindRefusal> {
|
||||
let mut reader = Reader::at(self, as_of)?;
|
||||
let ids = reader.universe(selection);
|
||||
let rows = reader.rows(&ids);
|
||||
let evaluation = select(&Vocabulary, &rows, selection, as_of, self.cursor_key())?;
|
||||
Self::page(selection, evaluation, as_of, None)
|
||||
}
|
||||
|
||||
/// Every root this mind holds a document under, with its newest admission and, for a root that is an in-force
|
||||
/// campaign, the repos in force (`Docs::repos_in_force`, never the campaign row's opening set). A resolution's
|
||||
/// key carries its subject's root, so a later resolution is a touch of that root. One pass at the head, no rows.
|
||||
pub fn roots_touched(&self) -> Result<Vec<RootTouched>, MindRefusal> {
|
||||
Ok(Reader::at(self, self.image()?.head)?.roots_touched())
|
||||
let rows = Reader::at(self, as_of)?.rows()?;
|
||||
let evaluation = select(&Vocabulary, &rows, &selection, as_of, self.cursor_key())?;
|
||||
Self::page(&selection, evaluation, as_of, None)
|
||||
}
|
||||
|
||||
/// What a semantic query must satisfy before anything is embedded: the
|
||||
|
|
@ -656,8 +605,8 @@ impl<S: MindStore> Mind<S> {
|
|||
/// ids this returns.
|
||||
pub fn members(&self, selection: &Selection, semantic: &SemanticQuery) -> Result<Members, MindRefusal> {
|
||||
let selection = Self::semantic_selection(selection, semantic)?;
|
||||
let head = self.image()?.head;
|
||||
let mut reader = Reader::at(self, head)?;
|
||||
let head = receipt::head(self)?;
|
||||
let rows = Reader::at(self, head)?.rows()?;
|
||||
// The walk is built here, field by field, from the caller's filters
|
||||
// alone and never spread from the caller's selection: the page size
|
||||
// is ours (the caller's `limit` shapes an answer, not the walk's cost:
|
||||
|
|
@ -676,11 +625,9 @@ impl<S: MindStore> Mind<S> {
|
|||
let mut ids = Vec::new();
|
||||
let mut pages = 0;
|
||||
loop {
|
||||
let universe = reader.universe(&walk);
|
||||
let rows = reader.rows(&universe);
|
||||
let evaluation = select(&Vocabulary, &rows, &walk, head, self.cursor_key())?;
|
||||
pages += 1;
|
||||
ids.extend(evaluation.rows.iter().map(|row| ref_of(row)));
|
||||
ids.extend(evaluation.rows.iter().map(ref_of));
|
||||
match evaluation.next_cursor {
|
||||
Some(next) => walk.cursor = Some(next),
|
||||
None => return Ok(Members { as_of: head, ids, pages }),
|
||||
|
|
@ -716,19 +663,18 @@ impl<S: MindStore> Mind<S> {
|
|||
) -> Result<Ranked, MindRefusal> {
|
||||
let selection = Self::semantic_selection(selection, semantic)?;
|
||||
let as_of = members.as_of;
|
||||
let mut reader = Reader::at(self, as_of)?;
|
||||
let rows = Reader::at(self, as_of)?.rows()?;
|
||||
|
||||
let held: BTreeMap<(PipelineKind, &str), i64> =
|
||||
rows.iter().map(|row| ((row.kind, row.key.as_str()), row.ordinal())).collect();
|
||||
let member: BTreeSet<(PipelineKind, &str)> =
|
||||
members.ids.iter().map(|id| (id.kind, id.id.0.as_str())).collect();
|
||||
let mut candidates: Vec<(&str, f32, i64)> = Vec::new();
|
||||
let mut dropped = Vec::new();
|
||||
for (hit, score) in hits {
|
||||
let id = (hit.kind, hit.id.0.as_str());
|
||||
let ordinal = match reader.id_of(hit.kind, id.1) {
|
||||
Some(row) if reader.prepare(row) => Some(reader.row(row).ordinal as i64),
|
||||
_ => None,
|
||||
};
|
||||
match ordinal {
|
||||
Some(ordinal) if member.contains(&id) => candidates.push((id.1, *score, ordinal)),
|
||||
match held.get(&id) {
|
||||
Some(&ordinal) if member.contains(&id) => candidates.push((id.1, *score, ordinal)),
|
||||
_ => dropped.push(hit.clone()),
|
||||
}
|
||||
}
|
||||
|
|
@ -748,18 +694,16 @@ impl<S: MindStore> Mind<S> {
|
|||
Evaluation { rows: Vec::new(), matched: 0, edges: Vec::new(), next_cursor: None }
|
||||
} else {
|
||||
let narrowed = Selection { keys: Some(keys), limit: Some(LIMIT_MAX), ..selection.clone() };
|
||||
let ids = reader.universe(&narrowed);
|
||||
let rows = reader.rows(&ids);
|
||||
select(&Vocabulary, &rows, &narrowed, as_of, self.cursor_key())?
|
||||
};
|
||||
let score = |row: &SelectionRow| scores.get(row.key.as_str()).copied().unwrap_or(f32::NEG_INFINITY);
|
||||
evaluation.rows.sort_by(|a, b| score(b).total_cmp(&score(a)).then(a.ordinal.cmp(&b.ordinal)));
|
||||
evaluation.rows.sort_by(|a, b| score(b).total_cmp(&score(a)).then(a.ordinal().cmp(&b.ordinal())));
|
||||
evaluation.rows.truncate(limit);
|
||||
evaluation.next_cursor = None;
|
||||
let row_scores: Vec<f32> = evaluation.rows.iter().map(|row| score(row)).collect();
|
||||
let row_scores: Vec<f32> = evaluation.rows.iter().map(score).collect();
|
||||
let position =
|
||||
|kind: PipelineKind, key: &str| evaluation.rows.iter().position(|row| row.kind == kind && row.key == key);
|
||||
let mut kept: Vec<(usize, EdgeMatch<&SelectionRow>)> = std::mem::take(&mut evaluation.edges)
|
||||
let mut kept: Vec<(usize, EdgeMatch<SelectionRow>)> = std::mem::take(&mut evaluation.edges)
|
||||
.into_iter()
|
||||
.filter_map(|edge| {
|
||||
let owner = match edge.anchor {
|
||||
|
|
@ -777,9 +721,9 @@ impl<S: MindStore> Mind<S> {
|
|||
|
||||
/// The projection of an evaluation: a header or a whole view per row, and
|
||||
/// the typed edges a hop traversed.
|
||||
pub(crate) fn page(
|
||||
fn page(
|
||||
selection: &Selection,
|
||||
evaluation: Evaluation<&SelectionRow>,
|
||||
evaluation: Evaluation<SelectionRow>,
|
||||
as_of: u64,
|
||||
scores: Option<Vec<f32>>,
|
||||
) -> Result<PipelineSelectionPage, MindRefusal> {
|
||||
|
|
@ -794,7 +738,7 @@ impl<S: MindStore> Mind<S> {
|
|||
let role = CitationRole::from_name(&edge.role).ok_or_else(|| MindRefusal::Unavailable {
|
||||
detail: format!("the evaluator returned an edge in role {:?}, which is not a citation role", edge.role),
|
||||
})?;
|
||||
typed.push(PipelineEdge { from: ref_of(edge.from), role, to: ref_of(edge.to) });
|
||||
typed.push(PipelineEdge { from: ref_of(&edge.from), role, to: ref_of(&edge.to) });
|
||||
}
|
||||
Some(typed)
|
||||
} else {
|
||||
|
|
@ -808,15 +752,8 @@ impl<S: MindStore> Mind<S> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
use crate::fixtures::*;
|
||||
use crate::receipt::{self, Faculty};
|
||||
use crate::receipt::Faculty;
|
||||
use cultnet_rs::{Citation, FieldPredicate, Incoming, RecordRef};
|
||||
|
||||
/// Every row the mind holds at `as_of`, as the substrate is handed them.
|
||||
fn all_rows(mind: &Mind<MemoryStore>, as_of: u64) -> Vec<SelectionRow> {
|
||||
let mut reader = Reader::at(mind, as_of).unwrap();
|
||||
let ids = reader.universe(&Selection::default());
|
||||
reader.rows(&ids).into_iter().cloned().collect()
|
||||
}
|
||||
use crate::store::test_stores::MemoryStore;
|
||||
use chrono::{TimeZone, Utc};
|
||||
use eureka_pipeline::{
|
||||
|
|
@ -1352,7 +1289,7 @@ mod tests {
|
|||
committed(admit(&mut mind, vec![question_n(1), question_n(2)]));
|
||||
let selection = of_kinds(&[K::Question]);
|
||||
let head = 2;
|
||||
let rows = all_rows(&mind, head);
|
||||
let rows = Reader::at(&mind, head).unwrap().rows().unwrap();
|
||||
let at = |as_of: u64| Selection {
|
||||
cursor: Some(Cursor::mint(as_of, &rows[0], &selection, mind.cursor_key())),
|
||||
..selection.clone()
|
||||
|
|
@ -1406,7 +1343,7 @@ mod tests {
|
|||
#[test]
|
||||
fn every_emitted_closed_value_passes_the_door() {
|
||||
let mind = worked();
|
||||
let rows = all_rows(&mind, 100);
|
||||
let rows = Reader::at(&mind, 100).unwrap().rows().unwrap();
|
||||
for row in &rows {
|
||||
for alias in ["root", "in_force", "faculty", "repo", "cut", "severity", "confidence", "origin", "authority", "claim_outcome", "outcome"] {
|
||||
for value in cultnet_rs::Row::values(row, alias) {
|
||||
|
|
@ -2035,44 +1972,6 @@ mod tests {
|
|||
assert_eq!((ids(&page), page.matched), (vec![shelf.r4.clone()], plain_matched(&shelf.mind, &standing(Selection::default()))), "top_k bounds the page too");
|
||||
}
|
||||
|
||||
/// Three equal scores in every arrival order rank by ordinal alone, so a lookup that gives
|
||||
/// every hit the same row (or the wrong one) is seen.
|
||||
#[test]
|
||||
fn equal_scores_rank_by_each_documents_own_ordinal_in_any_arrival_order() {
|
||||
let shelf = shelf();
|
||||
let image = shelf.mind.image().unwrap();
|
||||
let named = [(K::Question, shelf.q2.clone()), (K::Ruling, shelf.r4.clone()), (K::Resolution, shelf.withdrawn_resolution.clone())];
|
||||
let ordinal = |(kind, key): &(K, String)| image.row(image.id_of(*kind, key).unwrap()).ordinal;
|
||||
let mut expected: Vec<(K, String)> = named.to_vec();
|
||||
expected.sort_by_key(ordinal);
|
||||
assert!(ordinal(&expected[0]) < ordinal(&expected[1]) && ordinal(&expected[1]) < ordinal(&expected[2]), "the fixture's ordinals are distinct");
|
||||
for order in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] {
|
||||
let hits: Vec<_> = order.iter().map(|at| hit(named[*at].0, &named[*at].1, 0.5)).collect();
|
||||
let page = rank_all(&shelf.mind, &Selection::default(), &asking(10), &hits).page;
|
||||
assert_eq!(ids(&page), expected.iter().map(|(_, key)| key.clone()).collect::<Vec<_>>(), "arrival order {order:?}");
|
||||
// The cut is where the tie-break decides: the page keeps the earliest ordinals.
|
||||
let keys: Vec<String> = expected.iter().map(|(_, key)| key.clone()).collect();
|
||||
let limited = Selection { limit: Some(1), ..Selection::default() };
|
||||
assert_eq!(ids(&rank_all(&shelf.mind, &limited, &asking(10), &hits).page), keys[..1].to_vec(), "limit 1, arrival order {order:?}");
|
||||
assert_eq!(ids(&rank_all(&shelf.mind, &Selection::default(), &asking(2), &hits).page), keys[..2].to_vec(), "top_k 2, arrival order {order:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the candidate cut the tie-break decides who is kept: equal scores arriving in reverse
|
||||
/// keep the earliest ordinals, which a lookup that gives every hit one row does not.
|
||||
#[test]
|
||||
fn equal_scores_past_the_cut_keep_the_earliest_ordinals() {
|
||||
let mut mind = seeded();
|
||||
let total = LIMIT_MAX + 3;
|
||||
for n in 1..=total {
|
||||
committed(admit(&mut mind, vec![question_n(n)]));
|
||||
}
|
||||
let key = |n: u32| id("question", &format!("Q{n}"));
|
||||
let hits: Vec<_> = (1..=total).rev().map(|n| hit(K::Question, &key(n), 0.5)).collect();
|
||||
let page = rank_all(&mind, &Selection::default(), &asking(LIMIT_MAX), &hits).page;
|
||||
assert_eq!(ids(&page), (1..=LIMIT_MAX).map(key).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// Membership is the selection's alone: a kind, a key allowlist and a
|
||||
/// citation predicate each cut the candidates exactly as they cut a plain
|
||||
/// query, and the citation predicate sees the whole mind, not only the
|
||||
|
|
@ -2584,8 +2483,8 @@ mod tests {
|
|||
let absent = mind(gate_rows()).read_back_through(|_, _| Ok(None));
|
||||
assert!(matches!(&absent, Err(MindRefusal::Unavailable { detail }) if detail.contains("does not view back")), "{absent:?}");
|
||||
let other = mind(gate_rows()).read_back_through(|reader, id| {
|
||||
let (first, _) = reader.image.of_kind(id.kind).next().unwrap();
|
||||
reader.view(&PipelineRef { kind: id.kind, id: Short(first.to_string()) })
|
||||
let first = reader.docs.image.iter().find(|held| held.kind == id.kind).unwrap();
|
||||
reader.view_of(first).map(Some)
|
||||
});
|
||||
assert!(matches!(&other, Err(MindRefusal::Unavailable { detail }) if detail.contains("does not view back")), "{other:?}");
|
||||
}
|
||||
|
|
@ -2622,98 +2521,4 @@ mod tests {
|
|||
let count = mind.read_back().unwrap();
|
||||
println!("read back {count} stored documents in {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
fn at_hour(hour: u32) -> chrono::DateTime<Utc> {
|
||||
Utc.with_ymd_and_hms(2026, 9, 16, 12 + hour, 0, 0).unwrap()
|
||||
}
|
||||
|
||||
fn touched(mind: &Mind<MemoryStore>) -> BTreeMap<String, RootTouched> {
|
||||
mind.roots_touched().unwrap().into_iter().map(|root| (root.root.0.clone(), root)).collect()
|
||||
}
|
||||
|
||||
/// A target revision naming `repos`, and the supersession of its predecessor.
|
||||
fn repo_revision(campaign: &str, revision: u32, repos: &[&str]) -> Vec<D> {
|
||||
let D::Target(mut named) = target(revision, &[INVARIANT]) else { panic!("a target") };
|
||||
named.campaign = campaign.into();
|
||||
named.repos = repos.iter().map(|name| repo(name)).collect();
|
||||
let key = |n: u32| format!("{campaign}:target:r{n}");
|
||||
let mut batch = vec![D::Target(named)];
|
||||
if revision > 1 {
|
||||
batch.push(resolution(r(K::Target, &key(revision - 1)), superseded(&[r(K::Target, &key(revision))])));
|
||||
}
|
||||
batch
|
||||
}
|
||||
|
||||
/// Each root answers its newest admission: a later document counts, and so does a later resolution of an older one; an
|
||||
/// instance's root is listed with no repos; a root is listed once, in the order of its name.
|
||||
#[test]
|
||||
fn roots_touched_is_the_newest_admission_per_root() {
|
||||
let mut mind = seeded();
|
||||
let first = touched(&mind);
|
||||
assert_eq!(first.keys().map(String::as_str).collect::<Vec<_>>(), [CAMPAIGN, INSTANCE]);
|
||||
assert_eq!((first[CAMPAIGN].admitted_at.as_str(), first[INSTANCE].admitted_at.as_str()), ("2026-09-16T12:00:00Z", "2026-09-16T12:00:00Z"));
|
||||
assert!(first[INSTANCE].repos.is_empty(), "an instance root is no campaign");
|
||||
|
||||
let D::Campaign(mut other) = campaign(&["GameCult/Third"]) else { panic!("a campaign") };
|
||||
other.slug = "other-campaign".into();
|
||||
committed(admit_at(&mut mind, vec![D::Campaign(other)], at_hour(1)));
|
||||
committed(admit_at(&mut mind, vec![question_n(1)], at_hour(2)));
|
||||
let second = touched(&mind);
|
||||
assert_eq!(second.keys().map(String::as_str).collect::<Vec<_>>(), [CAMPAIGN, "other-campaign", INSTANCE]);
|
||||
assert_eq!(second["other-campaign"].admitted_at, "2026-09-16T13:00:00Z");
|
||||
assert_eq!(second[CAMPAIGN].admitted_at, "2026-09-16T14:00:00Z", "a later document touches its root");
|
||||
assert_eq!(second[INSTANCE].admitted_at, "2026-09-16T12:00:00Z", "and no other root");
|
||||
assert!(second[INSTANCE].ordinal < second["other-campaign"].ordinal && second["other-campaign"].ordinal < second[CAMPAIGN].ordinal, "{second:?}");
|
||||
|
||||
committed(admit_at(&mut mind, vec![resolution(r(K::Question, &id("question", "Q1")), withdrawn())], at_hour(5)));
|
||||
let third = touched(&mind);
|
||||
assert_eq!(third[CAMPAIGN].admitted_at, "2026-09-16T17:00:00Z", "a later resolution is a touch of its subject's root");
|
||||
assert!(third[CAMPAIGN].ordinal > second[CAMPAIGN].ordinal);
|
||||
assert_eq!(third["other-campaign"], second["other-campaign"]);
|
||||
}
|
||||
|
||||
/// A campaign answers the repos in force, not the opening set: the target that changes the set decides, a closed target does
|
||||
/// not, another campaign's target does not; a campaign closed answers none.
|
||||
#[test]
|
||||
fn roots_touched_repos_are_the_ones_in_force() {
|
||||
let mut mind = seeded();
|
||||
assert_eq!(touched(&mind)[CAMPAIGN].repos, [repo(REPO)], "no target names repos: the opening set");
|
||||
|
||||
committed(admit(&mut mind, repo_revision(CAMPAIGN, 2, &[REPO, OTHER_REPO])));
|
||||
assert_eq!(touched(&mind)[CAMPAIGN].repos, [repo(REPO), repo(OTHER_REPO)], "a target that changes the set decides");
|
||||
|
||||
let D::Campaign(mut other) = campaign(&[REPO]) else { panic!("a campaign") };
|
||||
other.slug = "other-campaign".into();
|
||||
let mut batch = vec![D::Campaign(other)];
|
||||
batch.extend(repo_revision("other-campaign", 1, &["GameCult/Third"]));
|
||||
committed(admit(&mut mind, batch));
|
||||
let both = touched(&mind);
|
||||
assert_eq!(both["other-campaign"].repos, [repo("GameCult/Third")]);
|
||||
assert_eq!(both[CAMPAIGN].repos, [repo(REPO), repo(OTHER_REPO)], "another campaign's higher target decides nothing here");
|
||||
|
||||
committed(admit(&mut mind, repo_revision(CAMPAIGN, 3, &[OTHER_REPO])));
|
||||
assert_eq!(touched(&mind)[CAMPAIGN].repos, [repo(OTHER_REPO)], "neither the opening set nor the closed revision decides");
|
||||
}
|
||||
|
||||
/// A campaign with a resolution in force answers no repos, and one beside it that is open keeps its own. Admission has no row to
|
||||
/// close a campaign, so the image is built by hand.
|
||||
#[test]
|
||||
fn a_closed_campaign_answers_no_repos() {
|
||||
let (open_key, closed_key, closing_key) = ("open:campaign:open".to_string(), "closed:campaign:closed".to_string(), "closed:resolution:campaign.n1".to_string());
|
||||
let named = |slug: &str, repo_name: &str| {
|
||||
let D::Campaign(mut c) = campaign(&[repo_name]) else { panic!("a campaign") };
|
||||
c.slug = slug.into();
|
||||
D::Campaign(c)
|
||||
};
|
||||
let image = Image::of_documents(vec![
|
||||
(K::Campaign, open_key.clone(), named("open", REPO)),
|
||||
(K::Campaign, closed_key.clone(), named("closed", OTHER_REPO)),
|
||||
(K::Resolution, closing_key.clone(), resolution(r(K::Campaign, &closed_key), withdrawn())),
|
||||
]);
|
||||
let roots = Reader { docs: Docs::at(&image, image.head), image: &image, as_of: image.head, patched: HashMap::new() }.roots_touched();
|
||||
let by_root: BTreeMap<&str, &RootTouched> = roots.iter().map(|root| (root.root.0.as_str(), root)).collect();
|
||||
assert_eq!(by_root["open"].repos, [repo(REPO)]);
|
||||
assert!(by_root["closed"].repos.is_empty(), "{roots:?}");
|
||||
assert_eq!(by_root["closed"].ordinal, 3, "the closure is a touch of the campaign it closes");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,768 +0,0 @@
|
|||
//! The held image against the oracle. The oracle derives every answer from the store alone, per
|
||||
//! call, by the linear derivation the read side had before it held an image; these tests set the
|
||||
//! two side by side over a history with withdrawal chains, a re-resolution, hand-offs, a run and
|
||||
//! its closure, at every snapshot, across a restart, and across the commit paths that do not
|
||||
//! land. They fail when a held answer differs from a fresh one, not when a particular structure
|
||||
//! changes.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, DatabaseEntry, PushAllOptions};
|
||||
use cultnet_rs::{Citation, FieldPredicate, Incoming, RecordRef, Row, Selection};
|
||||
use eureka_pipeline::{ClaimOutcome, FindingConfidence, PipelineDocument as D, PipelineKind as K, RunTurn, pipeline_key};
|
||||
|
||||
use crate::docs::{CitationRole, kind_of_id};
|
||||
use crate::fixtures::*;
|
||||
use crate::image::Image;
|
||||
use crate::mind::{Mind, schema_cache};
|
||||
use crate::oracle::{oracle_ids, oracle_page, oracle_view};
|
||||
use crate::query::{AdmissionIndex, PipelineSelectionPage, Reader};
|
||||
use crate::receipt::{self, Faculty, HuginnCommitReceipt};
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::rows::{Alias, STATUS_ALIASES, SelectionRow};
|
||||
use crate::store::MindStore;
|
||||
use crate::store::test_stores::{MemoryStore, RefusingStore, SwapCommand};
|
||||
|
||||
fn answering(label: &str, question: &str) -> D {
|
||||
let mut ruling = ruling(label);
|
||||
ruling.answers = Some(s(question));
|
||||
ruling.choice = Some(l("A"));
|
||||
D::Ruling(ruling)
|
||||
}
|
||||
|
||||
fn key_of(document: &D) -> String {
|
||||
pipeline_key(document).unwrap()
|
||||
}
|
||||
|
||||
/// The batches of a history, each with the faculty that admits it.
|
||||
fn history() -> Vec<(Faculty, Vec<D>)> {
|
||||
let spec = |cut: &str, revision: u32| id("cut_spec", &format!("cut-{cut}.r{revision}"));
|
||||
let run_a = mind_run("a", RunTurn::SelfRun, &[r(K::CutSpec, &spec("1", 1))]);
|
||||
let run_key = key_of(&run_a);
|
||||
let mut back = match hand_off(OTHER_INSTANCE, INSTANCE, REPO, &[]) {
|
||||
D::HandOff(back) => back,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
back.handed_on = eureka_pipeline::Date("2026-09-17".into());
|
||||
vec![
|
||||
(Faculty::Hands, vec![
|
||||
question("Q1", &["A", "B"], "A"),
|
||||
D::Ruling(ruling("R1")),
|
||||
D::CutSpec(cut_spec("1", 1)),
|
||||
D::CutSpec(cut_spec("9", 1)),
|
||||
D::CutSpec(cut_spec("10", 1)),
|
||||
follow_up("FU-1", r(K::Question, &id("question", "Q1"))),
|
||||
]),
|
||||
(Faculty::Hands, vec![D::CutReport(cut_report("9", 1)), D::CutReport(cut_report("10", 1))]),
|
||||
(Faculty::Hands, vec![
|
||||
verdict("9", 1, vec![claim(ClaimOutcome::Falsified, &[&id("finding", "cut-9.s1.F1")], Some("P1"), &["M1"])]),
|
||||
D::Finding(finding("9", 1, "F1", FindingConfidence::Confirmed)),
|
||||
]),
|
||||
// A resolution that sorts before its subject's superseder in the batch it arrives in.
|
||||
(Faculty::Hands, vec![
|
||||
D::CutSpec(cut_spec("9", 2)),
|
||||
resolution(r(K::CutSpec, &spec("9", 1)), superseded(&[r(K::CutSpec, &spec("9", 2))])),
|
||||
]),
|
||||
// The withdrawal of a resolution, and its withdrawal: the spec closes and reopens.
|
||||
(Faculty::Hands, vec![resolution(r(K::CutSpec, &spec("10", 1)), withdrawn())]),
|
||||
(Faculty::Hands, vec![resolution(r(K::Resolution, &id("resolution", "cut_spec.cut-10.r1.n1")), withdrawn())]),
|
||||
(Faculty::Soul, vec![D::Ruling(ruling("R2"))]),
|
||||
(Faculty::Hands, vec![answering("R3", &id("question", "Q1"))]),
|
||||
// A hand-off away and back: a stewardship closes, its closure is withdrawn, a new one opens.
|
||||
(Faculty::Hands, vec![hand_off(INSTANCE, OTHER_INSTANCE, REPO, &[])]),
|
||||
(Faculty::Hands, vec![D::HandOff(back)]),
|
||||
// A run that claims a spec, then is withdrawn unrun.
|
||||
(Faculty::Hands, vec![run_a]),
|
||||
(Faculty::Hands, vec![resolution(r(K::Run, &run_key), withdrawn())]),
|
||||
(Faculty::Life, vec![question_n(2)]),
|
||||
]
|
||||
}
|
||||
|
||||
fn apply<S: MindStore>(mind: &mut Mind<S>, faculty: Faculty, documents: Vec<D>) {
|
||||
committed(admit_as(mind, faculty, documents));
|
||||
}
|
||||
|
||||
fn history_mind() -> Mind<MemoryStore> {
|
||||
let mut mind = seeded();
|
||||
for (faculty, documents) in history() {
|
||||
apply(&mut mind, faculty, documents);
|
||||
}
|
||||
mind
|
||||
}
|
||||
|
||||
fn held_equals_fresh<S: MindStore>(mind: &Mind<S>) {
|
||||
let held = mind.image().unwrap();
|
||||
let fresh = mind.fresh_image().unwrap();
|
||||
assert!(*held == fresh, "the held image differs from a fresh fold at head {}", held.head);
|
||||
}
|
||||
|
||||
fn of_kinds(kinds: &[K]) -> Selection {
|
||||
Selection { schemas: Some(kinds.iter().map(|kind| kind.type_id().to_string()).collect()), ..Selection::default() }
|
||||
}
|
||||
|
||||
fn any_of(index: &str, values: &[&str]) -> FieldPredicate {
|
||||
FieldPredicate { index: index.into(), op: "any_of".into(), values: Some(values.iter().map(|v| v.to_string()).collect()), number: None }
|
||||
}
|
||||
|
||||
fn with(mut selection: Selection, predicate: FieldPredicate) -> Selection {
|
||||
selection.fields.get_or_insert_with(Vec::new).push(predicate);
|
||||
selection
|
||||
}
|
||||
|
||||
fn all_rows<S: MindStore>(mind: &Mind<S>, as_of: u64) -> Vec<SelectionRow> {
|
||||
let mut reader = Reader::at(mind, as_of).unwrap();
|
||||
let ids = reader.universe(&Selection::default());
|
||||
reader.rows(&ids).into_iter().cloned().collect()
|
||||
}
|
||||
|
||||
/// Selections that between them touch every kind, every alias value the history emits, keys, both
|
||||
/// hops on every role with both `exists`, combinations, the other order and the smallest page.
|
||||
fn corpus<S: MindStore>(mind: &Mind<S>) -> Vec<Selection> {
|
||||
let head = mind.image().unwrap().head;
|
||||
let rows = all_rows(mind, head);
|
||||
let mut out = vec![Selection::default()];
|
||||
for kind in K::ALL.iter().copied() {
|
||||
out.push(of_kinds(&[kind]));
|
||||
out.push(Selection { descending: true, limit: Some(1), ..of_kinds(&[kind]) });
|
||||
for alias in ["in_force", "root", "faculty"] {
|
||||
for value in ["true", "false", CAMPAIGN, "Hands"] {
|
||||
out.push(with(of_kinds(&[kind]), any_of(alias, &[value])));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mut pairs, mut edges) = (BTreeSet::new(), BTreeSet::new());
|
||||
for row in &rows {
|
||||
for alias in Alias::ALL {
|
||||
for value in Row::values(row, alias.name()) {
|
||||
pairs.insert((alias.name(), value));
|
||||
}
|
||||
}
|
||||
for (role, target, _) in Row::references(row) {
|
||||
edges.insert((role, target));
|
||||
}
|
||||
out.push(Selection { keys: Some(vec![row.key.clone()]), projection: "document".into(), ..Selection::default() });
|
||||
}
|
||||
out.push(Selection { keys: Some(vec!["nobody:question:nothing".into()]), ..Selection::default() });
|
||||
for (alias, value) in &pairs {
|
||||
out.push(with(Selection::default(), any_of(alias, &[value])));
|
||||
}
|
||||
for (role, target) in &edges {
|
||||
let schema = kind_of_id(target).map_or("epiphany.pipeline.question.v1".to_string(), |kind| kind.type_id().to_string());
|
||||
for role_filter in [Some(role.clone()), None] {
|
||||
let citation = Citation { target: RecordRef::new(schema.clone(), target.clone()), role: role_filter };
|
||||
out.push(Selection { cites: Some(citation.clone()), ..Selection::default() });
|
||||
out.push(with(Selection { cites: Some(citation), ..Selection::default() }, any_of("in_force", &["true"])));
|
||||
}
|
||||
}
|
||||
for role in CitationRole::ALL {
|
||||
for exists in [true, false] {
|
||||
let incoming = Incoming { role: role.name().into(), exists };
|
||||
out.push(Selection { cited: Some(incoming.clone()), ..Selection::default() });
|
||||
out.push(with(Selection { cited: Some(incoming.clone()), ..Selection::default() }, any_of("in_force", &["true"])));
|
||||
out.push(Selection { cited: Some(incoming), descending: true, limit: Some(1), ..of_kinds(&[K::CutSpec, K::Question]) });
|
||||
}
|
||||
}
|
||||
if let Some((role, target)) = edges.iter().next() {
|
||||
let citation = Citation { target: RecordRef::new(K::Question.type_id(), target.clone()), role: Some(role.clone()) };
|
||||
out.push(Selection { cites: Some(citation), cited: Some(Incoming { role: "subject".into(), exists: false }), ..Selection::default() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One page, both ways, whole page or whole refusal.
|
||||
fn agree<S: MindStore>(mind: &Mind<S>, selection: &Selection, as_of: u64) -> Result<PipelineSelectionPage, MindRefusal> {
|
||||
let held = mind.query_at(selection, as_of);
|
||||
let fresh = oracle_page(mind, selection, as_of);
|
||||
assert_eq!(held, fresh, "as_of {as_of}: {selection:?}");
|
||||
held
|
||||
}
|
||||
|
||||
fn walk<S: MindStore>(mind: &Mind<S>, selection: &Selection, as_of: u64) {
|
||||
let mut selection = Selection { limit: Some(1), ..selection.clone() };
|
||||
let mut at = as_of;
|
||||
for _ in 0..80 {
|
||||
let Ok(page) = agree(mind, &selection, at) else { return };
|
||||
let Some(next) = page.next else { return };
|
||||
at = page.as_of;
|
||||
selection.cursor = Some(next);
|
||||
}
|
||||
panic!("a limit-1 walk did not end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_image_equals_a_fresh_fold_after_every_commit() {
|
||||
let mut mind = seeded();
|
||||
held_equals_fresh(&mind);
|
||||
for (faculty, documents) in history() {
|
||||
apply(&mut mind, faculty, documents);
|
||||
held_equals_fresh(&mind);
|
||||
}
|
||||
let image = mind.image().unwrap();
|
||||
assert!(image.status_changed.iter().any(|at| *at > 1), "the history changes a status after the row was written");
|
||||
assert_eq!(image.head, history().len() as u64 + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_read_agrees_with_the_oracle_at_every_snapshot() {
|
||||
let mind = history_mind();
|
||||
let head = mind.image().unwrap().head;
|
||||
let corpus = corpus(&mind);
|
||||
assert!(corpus.len() > 300, "the corpus is {}", corpus.len());
|
||||
let mut differs_from_head = 0;
|
||||
for as_of in 1..=head {
|
||||
for selection in &corpus {
|
||||
let _ = agree(&mind, selection, as_of);
|
||||
}
|
||||
let open = Selection { fields: Some(vec![any_of("in_force", &["true"])]), ..Selection::default() };
|
||||
if mind.query_at(&open, as_of).unwrap().matched != mind.query_at(&open, head).unwrap().matched {
|
||||
differs_from_head += 1;
|
||||
}
|
||||
}
|
||||
assert!(differs_from_head > 0, "a status reversed by a later withdrawal shows at an old snapshot");
|
||||
for kind in K::ALL.iter().copied() {
|
||||
walk(&mind, &of_kinds(&[kind]), head);
|
||||
walk(&mind, &of_kinds(&[kind]), head - 3);
|
||||
}
|
||||
walk(&mind, &Selection::default(), head);
|
||||
walk(&mind, &Selection { descending: true, ..Selection::default() }, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_and_status_agree_with_the_oracle_at_every_snapshot() {
|
||||
let mind = history_mind();
|
||||
let head = mind.image().unwrap().head;
|
||||
let every = oracle_ids(&mind, head).unwrap();
|
||||
assert_eq!(every.len(), mind.image().unwrap().rows.len(), "the oracle names every document, or the loop below proves nothing");
|
||||
for as_of in 1..=head {
|
||||
let reader = Reader::at(&mind, as_of).unwrap();
|
||||
for id in &every {
|
||||
assert_eq!(reader.view(id).unwrap(), oracle_view(&mind, id, as_of).unwrap(), "{} at {as_of}", id.id.0);
|
||||
}
|
||||
}
|
||||
let spec = r(K::CutSpec, &id("cut_spec", "cut-10.r1"));
|
||||
assert_eq!(mind.view(&spec).unwrap().unwrap().status, crate::query::PipelineStatus::InForce, "the reopened spec stands at the head");
|
||||
let closed = Reader::at(&mind, 6).unwrap().view(&spec).unwrap().unwrap();
|
||||
assert!(matches!(closed.status, crate::query::PipelineStatus::Resolved { .. }), "and is closed while its withdrawal is the head");
|
||||
let reopened = Mind::open_with(mind.store().clone(), &slug(INSTANCE)).unwrap();
|
||||
assert_eq!(reopened.status(crate::wire::IndexStatus::Current), mind.status(crate::wire::IndexStatus::Current));
|
||||
assert_eq!(reopened.persona().unwrap(), mind.persona().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_answers_what_the_held_image_answered() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance = slug(INSTANCE);
|
||||
let mut mind = Mind::open(dir.path(), &instance).unwrap();
|
||||
seed(&mut mind);
|
||||
for (faculty, documents) in history() {
|
||||
apply(&mut mind, faculty, documents);
|
||||
}
|
||||
let head = mind.image().unwrap().head;
|
||||
let corpus = corpus(&mind);
|
||||
// A cursor is minted under the process's own key, so the answers are compared without it.
|
||||
let plain = |page: Result<PipelineSelectionPage, MindRefusal>| page.map(|page| PipelineSelectionPage { next: None, ..page });
|
||||
let answers: Vec<_> = corpus.iter().map(|selection| plain(mind.query_at(selection, head))).collect();
|
||||
let cursor = mind.query(&Selection { limit: Some(1), ..of_kinds(&[K::Question]) }).unwrap().next.unwrap();
|
||||
let held = mind.image().unwrap().clone();
|
||||
drop(mind);
|
||||
let reopened = Mind::open(dir.path(), &instance).unwrap();
|
||||
assert!(*reopened.image().unwrap() == held, "the image a restart folds is the image the holder held");
|
||||
for (selection, before) in corpus.iter().zip(&answers) {
|
||||
assert_eq!(&plain(reopened.query_at(selection, head)), before, "{selection:?}");
|
||||
}
|
||||
let stale = Selection { limit: Some(1), cursor: Some(cursor), ..of_kinds(&[K::Question]) };
|
||||
assert!(matches!(reopened.query(&stale), Err(MindRefusal::CursorInvalid { .. })), "a cursor does not survive a restart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lost_swap_rebuilds_from_what_the_store_holds() {
|
||||
let store = MemoryStore::new();
|
||||
let mut holder = opened(store.clone(), INSTANCE);
|
||||
seed(&mut holder);
|
||||
let mut other = Mind::open_with(store.clone(), &slug(INSTANCE)).unwrap();
|
||||
committed(admit(&mut other, vec![question_n(7)]));
|
||||
let planted = r(K::Question, &id("question", "Q7"));
|
||||
assert!(holder.view(&planted).unwrap().is_none(), "without a lost swap the plant stays unseen until restart: the stated contract");
|
||||
assert_eq!(Mind::open_with(store.clone(), &slug(INSTANCE)).unwrap().view(&planted).unwrap().map(|v| v.id), Some(planted.clone()));
|
||||
let outcome = admit(&mut holder, vec![question_n(7)]);
|
||||
assert!(matches!(outcome, crate::admission::PipelineAdmissionOutcome::Conflict { .. }), "{outcome:?}");
|
||||
held_equals_fresh(&holder);
|
||||
assert!(holder.view(&planted).unwrap().is_some(), "the lost swap looked at the store");
|
||||
committed(admit(&mut holder, vec![question_n(8)]));
|
||||
held_equals_fresh(&holder);
|
||||
}
|
||||
|
||||
/// A store that lands the swap and then reports an error, so the holder cannot know.
|
||||
#[derive(Clone)]
|
||||
struct LandsThenFails {
|
||||
inner: MemoryStore,
|
||||
armed: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl CacheBackingStore for LandsThenFails {
|
||||
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
self.inner.pull_all()
|
||||
}
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.push(entry)
|
||||
}
|
||||
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.delete(entry)
|
||||
}
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
|
||||
self.inner.push_all(entries, options)
|
||||
}
|
||||
}
|
||||
|
||||
impl MindStore for LandsThenFails {
|
||||
fn compare_and_swap_batch(&self, expected: &[CultCacheEnvelope], replacements: Vec<CultCacheEnvelope>) -> Result<bool> {
|
||||
let landed = self.inner.compare_and_swap_batch(expected, replacements)?;
|
||||
if self.armed.swap(false, Ordering::SeqCst) {
|
||||
return Err(anyhow!("the store failed after landing"));
|
||||
}
|
||||
Ok(landed)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_error_during_commit_rebuilds() {
|
||||
let inner = MemoryStore::new();
|
||||
let armed = Arc::new(AtomicBool::new(false));
|
||||
let mut mind = opened(LandsThenFails { inner: inner.clone(), armed: armed.clone() }, INSTANCE);
|
||||
seed(&mut mind);
|
||||
armed.store(true, Ordering::SeqCst);
|
||||
let outcome = admit(&mut mind, vec![question_n(1)]);
|
||||
assert!(matches!(outcome, crate::admission::PipelineAdmissionOutcome::Refused(MindRefusal::Unavailable { .. })), "{outcome:?}");
|
||||
held_equals_fresh(&mind);
|
||||
assert!(mind.view(&r(K::Question, &id("question", "Q1"))).unwrap().is_some(), "the batch that landed is held");
|
||||
committed(admit(&mut mind, vec![question_n(2)]));
|
||||
held_equals_fresh(&mind);
|
||||
|
||||
let refusing = RefusingStore::new();
|
||||
let mut mind = opened(refusing.clone(), INSTANCE);
|
||||
seed(&mut mind);
|
||||
refusing.command(SwapCommand::Fail);
|
||||
let before = mind.image().unwrap().clone();
|
||||
assert!(matches!(admit(&mut mind, vec![question_n(1)]), crate::admission::PipelineAdmissionOutcome::Refused(_)));
|
||||
held_equals_fresh(&mind);
|
||||
assert!(*mind.image().unwrap() == before, "a store that did not land leaves the image as it was");
|
||||
refusing.command(SwapCommand::Delegate);
|
||||
committed(admit(&mut mind, vec![question_n(1)]));
|
||||
held_equals_fresh(&mind);
|
||||
}
|
||||
|
||||
/// The rows of a healthy two-step mind, to be broken one way at a time.
|
||||
fn healthy_rows() -> Vec<CultCacheEnvelope> {
|
||||
let mut mind = seeded();
|
||||
committed(admit(&mut mind, vec![question_n(1)]));
|
||||
mind.store().rows()
|
||||
}
|
||||
|
||||
fn receipt_of(rows: &[CultCacheEnvelope], ordinal: u64) -> HuginnCommitReceipt {
|
||||
rows.iter()
|
||||
.filter(|row| row.r#type == HuginnCommitReceipt::TYPE)
|
||||
.map(|row| rmp_serde::from_slice::<HuginnCommitReceipt>(&row.payload).unwrap())
|
||||
.find(|receipt| receipt.ordinal == ordinal)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn faulted_mind(rows: Vec<CultCacheEnvelope>) -> (Mind<MemoryStore>, MemoryStore) {
|
||||
let store = MemoryStore::new();
|
||||
rows.into_iter().for_each(|row| store.plant(row));
|
||||
(Mind::open_with(store.clone(), &slug(INSTANCE)).unwrap(), store)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_faulted_store_refuses_alike_at_every_snapshot() {
|
||||
let cache = schema_cache().unwrap();
|
||||
let mut cases: Vec<(&str, Vec<CultCacheEnvelope>)> = Vec::new();
|
||||
|
||||
let mut rows = healthy_rows();
|
||||
let at = rows.iter().position(|row| row.key == id("question", "Q1")).unwrap();
|
||||
rows[at].payload = vec![0xc1];
|
||||
cases.push(("an undecodable document", rows));
|
||||
|
||||
let mut rows = healthy_rows();
|
||||
let at = rows.iter().position(|row| row.r#type == HuginnCommitReceipt::TYPE).unwrap();
|
||||
rows[at].payload = vec![0xc1];
|
||||
cases.push(("an undecodable receipt", rows));
|
||||
|
||||
let mut rows = healthy_rows();
|
||||
let gone = receipt_of(&rows, 1).receipt_id;
|
||||
rows.retain(|row| row.key != gone);
|
||||
cases.push(("an undense chain", rows));
|
||||
|
||||
let mut rows = healthy_rows();
|
||||
let orphan = prepare(&question_n(5));
|
||||
rows.push(orphan);
|
||||
cases.push(("an orphan", rows));
|
||||
|
||||
let mut rows = healthy_rows();
|
||||
let mut twice = receipt_of(&rows, 2);
|
||||
twice.ordinal = 3;
|
||||
twice.receipt_id = "mind-commit-twice".into();
|
||||
rows.push(cache.prepare_entry_named(&twice.receipt_id, &twice).unwrap().0);
|
||||
cases.push(("a document written by two receipts", rows));
|
||||
|
||||
for (name, rows) in cases {
|
||||
let (mind, store) = faulted_mind(rows);
|
||||
let before = store.rows();
|
||||
let probe = of_kinds(&[K::Question]);
|
||||
let seen = mind.query_at(&probe, 1);
|
||||
let fault = seen.clone().expect_err(name);
|
||||
for as_of in [1, 2, 5] {
|
||||
assert_eq!(mind.query_at(&probe, as_of), seen, "{name} at {as_of}");
|
||||
assert_eq!(oracle_page(&mind, &probe, as_of).expect_err(name), fault, "{name}: the oracle names the same fault");
|
||||
}
|
||||
assert_eq!(mind.query(&probe), seen, "{name}: query answers the held fault");
|
||||
assert_eq!(mind.view(&r(K::Question, &id("question", "Q1"))), Err(fault.clone()), "{name}");
|
||||
let outcome = admit(&mut Mind::open_with(store.clone(), &slug(INSTANCE)).unwrap(), vec![question_n(9)]);
|
||||
assert!(matches!(outcome, crate::admission::PipelineAdmissionOutcome::Refused(ref refusal) if *refusal == fault), "{name}: admit refuses with the fault, {outcome:?}");
|
||||
assert_eq!(store.rows(), before, "{name}: a refused admission writes nothing");
|
||||
let status = mind.status(crate::wire::IndexStatus::Current);
|
||||
assert_eq!(status.persona, crate::wire::PersonaStatus::Absent, "{name}: status stays total");
|
||||
assert_eq!(mind.persona().unwrap(), None, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_outside_its_target_falls_back_to_the_whole_universe() {
|
||||
let mut rows = healthy_rows();
|
||||
let cache = schema_cache().unwrap();
|
||||
// A run claims a question: the role claims cut specs, findings and follow-ups. Admission would
|
||||
// refuse it, so it is planted with its receipt.
|
||||
let planted = mind_run("planted", RunTurn::SelfRun, &[r(K::Question, &id("question", "Q1"))]);
|
||||
let envelope = planted.prepare(&cache).unwrap();
|
||||
let mut receipt = receipt::candidate(&slug(INSTANCE), provenance(Faculty::Hands), &[], std::slice::from_ref(&envelope), 3, now()).unwrap();
|
||||
receipt.receipt_id = receipt.digest().unwrap();
|
||||
rows.push(cache.prepare_entry_named(&receipt.receipt_id, &receipt).unwrap().0);
|
||||
rows.push(envelope);
|
||||
let (mind, _) = faulted_mind(rows);
|
||||
assert!(!mind.image().unwrap().edges_in_target, "the planted edge is outside its role's kinds");
|
||||
let healthy = seeded();
|
||||
assert!(healthy.image().unwrap().edges_in_target);
|
||||
let refused = MindRefusal::from(cultnet_rs::SelectionRefusal::ReferenceOutsideTarget {
|
||||
from_schema_id: K::Run.type_id().into(),
|
||||
from_key: key_of(&planted),
|
||||
role: "claims".into(),
|
||||
to_schema_id: K::Question.type_id().into(),
|
||||
to_key: id("question", "Q1"),
|
||||
});
|
||||
let elsewhere = Citation { target: RecordRef::new(K::CutSpec.type_id(), id("cut_spec", "cut-1.r1")), role: Some("claims".into()) };
|
||||
for selection in [
|
||||
Selection { cited: Some(Incoming { role: "claims".into(), exists: true }), ..Selection::default() },
|
||||
Selection { cites: Some(elsewhere), ..Selection::default() },
|
||||
] {
|
||||
assert_eq!(agree(&mind, &selection, 3), Err(refused.clone()), "the substrate refuses the edge exactly as it would over the whole mind");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_aliases_are_the_declared_ones() {
|
||||
let mut mind = seeded();
|
||||
let mut before = all_rows(&mind, 1);
|
||||
let mut status_changes = 0;
|
||||
for (faculty, documents) in history() {
|
||||
apply(&mut mind, faculty, documents);
|
||||
let after = all_rows(&mind, mind.image().unwrap().head);
|
||||
for (old, new) in before.iter().zip(&after) {
|
||||
if old.view.status != new.view.status {
|
||||
status_changes += 1;
|
||||
}
|
||||
for alias in Alias::ALL {
|
||||
if !STATUS_ALIASES.contains(&alias) {
|
||||
assert_eq!(Row::values(old, alias.name()), Row::values(new, alias.name()), "{} changed under a status change", alias.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
before = after;
|
||||
}
|
||||
assert!(status_changes >= 3, "the history changes statuses ({status_changes})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_back_refuses_a_held_image_that_differs_from_a_fresh_fold() {
|
||||
let store = MemoryStore::new();
|
||||
let mut holder = opened(store.clone(), INSTANCE);
|
||||
seed(&mut holder);
|
||||
assert_eq!(holder.read_back().unwrap(), 4, "a clean store counts every document");
|
||||
let mut other = Mind::open_with(store, &slug(INSTANCE)).unwrap();
|
||||
committed(admit(&mut other, vec![question_n(1)]));
|
||||
let refused = holder.read_back();
|
||||
assert!(matches!(&refused, Err(MindRefusal::Unavailable { detail }) if detail.contains("held image differs from a fresh fold")), "{refused:?}");
|
||||
assert_eq!(other.read_back().unwrap(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_admission_index_names_what_receipts_wrote() {
|
||||
let mind = history_mind();
|
||||
let index = AdmissionIndex::build(&mind.receipts().unwrap()).unwrap();
|
||||
let image: &Image = mind.image().unwrap();
|
||||
for row in &image.rows {
|
||||
assert!(index.contains(row.kind.type_id(), &row.key));
|
||||
}
|
||||
}
|
||||
|
||||
/// A store whose swap can land then err, be lost, and whose next pull can fail: a look that fails
|
||||
/// after a store fault.
|
||||
#[derive(Clone)]
|
||||
struct FailsTheLook {
|
||||
inner: MemoryStore,
|
||||
land_then_err: Arc<AtomicBool>,
|
||||
lose: Arc<AtomicBool>,
|
||||
pull_err: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl CacheBackingStore for FailsTheLook {
|
||||
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
if self.pull_err.swap(false, Ordering::SeqCst) {
|
||||
return Err(anyhow!("the look failed"));
|
||||
}
|
||||
self.inner.pull_all()
|
||||
}
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.push(entry)
|
||||
}
|
||||
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.delete(entry)
|
||||
}
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
|
||||
self.inner.push_all(entries, options)
|
||||
}
|
||||
}
|
||||
|
||||
impl MindStore for FailsTheLook {
|
||||
fn compare_and_swap_batch(&self, expected: &[CultCacheEnvelope], replacements: Vec<CultCacheEnvelope>) -> Result<bool> {
|
||||
if self.lose.swap(false, Ordering::SeqCst) {
|
||||
return Ok(false);
|
||||
}
|
||||
let landed = self.inner.compare_and_swap_batch(expected, replacements)?;
|
||||
if self.land_then_err.swap(false, Ordering::SeqCst) {
|
||||
return Err(anyhow!("the store failed after landing"));
|
||||
}
|
||||
Ok(landed)
|
||||
}
|
||||
}
|
||||
|
||||
fn fails_the_look() -> (Mind<FailsTheLook>, FailsTheLook) {
|
||||
let store = FailsTheLook { inner: MemoryStore::new(), land_then_err: Default::default(), lose: Default::default(), pull_err: Default::default() };
|
||||
let mut mind = opened(store.clone(), INSTANCE);
|
||||
seed(&mut mind);
|
||||
(mind, store)
|
||||
}
|
||||
|
||||
/// One rule for a failed look: the fault is held, reads and admission refuse with it, nothing is
|
||||
/// written, and a restart holds what the store holds and admits at the next ordinal.
|
||||
fn assert_fault_is_held(mind: &mut Mind<FailsTheLook>, store: &FailsTheLook, landed: &[&str]) {
|
||||
assert!(matches!(mind.image(), Err(MindRefusal::Unavailable { .. })));
|
||||
assert!(matches!(mind.query(&of_kinds(&[K::Question])), Err(MindRefusal::Unavailable { .. })));
|
||||
let rows = store.inner.rows();
|
||||
let next = admit(mind, vec![question_n(50)]);
|
||||
assert!(matches!(next, crate::admission::PipelineAdmissionOutcome::Refused(MindRefusal::Unavailable { .. })), "{next:?}");
|
||||
assert_eq!(store.inner.rows(), rows, "a held fault writes nothing");
|
||||
let mut reopened = opened(store.clone(), INSTANCE);
|
||||
held_equals_fresh(&reopened);
|
||||
assert_eq!(reopened.query(&of_kinds(&[K::Question])).unwrap().matched, landed.len() as u32);
|
||||
committed(admit(&mut reopened, vec![question_n(51)]));
|
||||
held_equals_fresh(&reopened);
|
||||
reopened.read_back().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_look_after_a_landed_error_holds_the_fault() {
|
||||
let (mut mind, store) = fails_the_look();
|
||||
store.land_then_err.store(true, Ordering::SeqCst);
|
||||
store.pull_err.store(true, Ordering::SeqCst);
|
||||
let first = admit(&mut mind, vec![question_n(1)]);
|
||||
assert!(matches!(first, crate::admission::PipelineAdmissionOutcome::Refused(MindRefusal::Unavailable { .. })), "{first:?}");
|
||||
assert_fault_is_held(&mut mind, &store, &["Q1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_look_after_a_lost_swap_holds_the_fault() {
|
||||
let (mut mind, store) = fails_the_look();
|
||||
let mut other = opened(store.clone(), INSTANCE);
|
||||
committed(admit(&mut other, vec![question_n(7)]));
|
||||
store.lose.store(true, Ordering::SeqCst);
|
||||
store.pull_err.store(true, Ordering::SeqCst);
|
||||
let lost = admit(&mut mind, vec![question_n(8)]);
|
||||
assert!(matches!(lost, crate::admission::PipelineAdmissionOutcome::Refused(MindRefusal::Unavailable { .. })), "{lost:?}");
|
||||
assert_fault_is_held(&mut mind, &store, &["Q7"]);
|
||||
}
|
||||
|
||||
// ---- the floor: what a read and a landed commit may cost, counted ----
|
||||
|
||||
/// Reads and a landed admission never pull the store: a pull is a decode of the whole mind.
|
||||
#[test]
|
||||
fn reads_and_landed_admissions_pull_the_store_zero_times() {
|
||||
let mut mind = history_mind();
|
||||
let pulls = mind.store().pull_count();
|
||||
let head = mind.image().unwrap().head;
|
||||
mind.query(&Selection::default()).unwrap();
|
||||
mind.query_at(&of_kinds(&[K::Question]), head / 2).unwrap();
|
||||
mind.view(&r(K::Question, &id("question", "Q1"))).unwrap();
|
||||
let _ = mind.status(crate::wire::IndexStatus::Current);
|
||||
let _ = mind.persona();
|
||||
assert_eq!(mind.store().pull_count(), pulls, "a read pulled the store");
|
||||
committed(admit(&mut mind, vec![question_n(99)]));
|
||||
committed(admit(&mut mind, vec![resolution(r(K::Question, &id("question", "Q99")), withdrawn())]));
|
||||
assert_eq!(mind.store().pull_count(), pulls, "a landed swap pulled the store");
|
||||
held_equals_fresh(&mind);
|
||||
}
|
||||
|
||||
/// A lost swap and a store error each look at the store exactly once.
|
||||
#[test]
|
||||
fn a_lost_swap_and_a_store_error_pull_the_store_once_each() {
|
||||
let (mut mind, store) = fails_the_look();
|
||||
let mut other = opened(store.clone(), INSTANCE);
|
||||
committed(admit(&mut other, vec![question_n(7)]));
|
||||
let pulls = store.inner.pull_count();
|
||||
store.lose.store(true, Ordering::SeqCst);
|
||||
admit(&mut mind, vec![question_n(8)]);
|
||||
assert_eq!(store.inner.pull_count(), pulls + 1, "a lost swap looks once");
|
||||
store.land_then_err.store(true, Ordering::SeqCst);
|
||||
admit(&mut mind, vec![question_n(9)]);
|
||||
assert_eq!(store.inner.pull_count(), pulls + 2, "a store error looks once");
|
||||
}
|
||||
|
||||
/// A history of many questions, one of them the only Soul's, one follow-up citing Q1.
|
||||
fn many_rows_mind() -> Mind<MemoryStore> {
|
||||
let mut mind = seeded();
|
||||
for chunk in (1..=40).collect::<Vec<u32>>().chunks(10) {
|
||||
committed(admit(&mut mind, chunk.iter().map(|n| question_n(*n)).collect()));
|
||||
}
|
||||
committed(admit_as(&mut mind, Faculty::Soul, vec![question_n(41)]));
|
||||
committed(admit(&mut mind, vec![follow_up("FU-1", r(K::Question, &id("question", "Q1")))]));
|
||||
mind
|
||||
}
|
||||
|
||||
/// The universe is the narrowing: a selection that names a key, a rare field value or a cited
|
||||
/// target hands the match only its candidates, never the mind.
|
||||
#[test]
|
||||
fn a_selection_reads_its_candidates_and_not_the_mind() {
|
||||
let mind = many_rows_mind();
|
||||
let image = mind.image().unwrap();
|
||||
let (head, total) = (image.head, image.rows.len());
|
||||
assert!(total > 40);
|
||||
assert_eq!(image.universe(&Selection::default(), head).len(), total, "the unfiltered selection is the whole mind");
|
||||
let keyed = Selection { keys: Some(vec![id("question", "Q3")]), ..Selection::default() };
|
||||
assert_eq!(image.universe(&keyed, head).len(), 1, "keys");
|
||||
let rare = with(of_kinds(&[K::Question]), any_of("faculty", &["Soul"]));
|
||||
assert_eq!(image.universe(&rare, head).len(), 1, "a rare field value");
|
||||
assert_eq!(image.universe(&of_kinds(&[K::Question]), head).len(), 41, "a kind is its own rows");
|
||||
let citation = Citation { target: RecordRef::new(K::Question.type_id(), id("question", "Q1")), role: None };
|
||||
let citers = Selection { cites: Some(citation), ..Selection::default() };
|
||||
let universe = image.universe(&citers, head);
|
||||
assert!(universe.len() <= 3 && !universe.is_empty(), "a hop starts from the target's citers: {}", universe.len());
|
||||
assert!(total > 10 * universe.len());
|
||||
assert!(mind.query(&citers).unwrap().matched >= 1);
|
||||
}
|
||||
|
||||
// ---- the narrowing lines the oracle corpus must reach ----
|
||||
|
||||
/// Both hops with the citer's schema excluding the target's: the target row is handed to the
|
||||
/// match only by the line that adds the cites target to a both-hop universe.
|
||||
#[test]
|
||||
fn both_hops_with_a_schema_excluding_the_target_agree() {
|
||||
let mind = history_mind();
|
||||
let head = mind.image().unwrap().head;
|
||||
let rows = all_rows(&mind, head);
|
||||
let mut edges = BTreeSet::new();
|
||||
for row in &rows {
|
||||
for (role, target, _) in Row::references(row) {
|
||||
edges.insert((row.kind, role, target));
|
||||
}
|
||||
}
|
||||
let (mut pages, mut hits) = (0, 0);
|
||||
for (carrier, role, target) in &edges {
|
||||
let schema = kind_of_id(target).map_or(K::Question.type_id().to_string(), |kind| kind.type_id().to_string());
|
||||
let citation = Citation { target: RecordRef::new(schema, target.clone()), role: Some(role.clone()) };
|
||||
for exists in [true, false] {
|
||||
let incoming = Incoming { role: "subject".into(), exists };
|
||||
let plain = Selection { cites: Some(citation.clone()), cited: Some(incoming.clone()), ..of_kinds(&[*carrier]) };
|
||||
let narrowed = with(Selection { projection: "document".into(), ..plain.clone() }, any_of("in_force", &["true"]));
|
||||
for as_of in [head, head / 2] {
|
||||
for selection in [&plain, &narrowed] {
|
||||
if let Ok(page) = agree(&mind, selection, as_of) {
|
||||
pages += 1;
|
||||
hits += usize::from(page.matched > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(pages > 0 && hits > 0, "no both-hop selection with a schema matched anything ({pages} pages)");
|
||||
}
|
||||
|
||||
/// A resolution withdrawn by another: the Resolution schema excludes the cut spec it cites.
|
||||
#[test]
|
||||
fn a_both_hop_selection_finds_a_citer_whose_target_the_schema_excludes() {
|
||||
let mind = history_mind();
|
||||
let selection = Selection {
|
||||
cites: Some(Citation { target: RecordRef::new(K::CutSpec.type_id(), id("cut_spec", "cut-10.r1")), role: None }),
|
||||
cited: Some(Incoming { role: "subject".into(), exists: true }),
|
||||
..of_kinds(&[K::Resolution])
|
||||
};
|
||||
let head = mind.image().unwrap().head;
|
||||
let page = agree(&mind, &selection, head).unwrap();
|
||||
assert_eq!(page.matched, 1, "{page:?}");
|
||||
}
|
||||
|
||||
fn planted_rows(rows: &mut Vec<CultCacheEnvelope>, ordinal: u64, document: &D) {
|
||||
let cache = schema_cache().unwrap();
|
||||
let envelope = document.prepare(&cache).unwrap();
|
||||
let mut receipt = receipt::candidate(&slug(INSTANCE), provenance(Faculty::Hands), &[], std::slice::from_ref(&envelope), ordinal, now()).unwrap();
|
||||
receipt.receipt_id = receipt.digest().unwrap();
|
||||
rows.push(cache.prepare_entry_named(&receipt.receipt_id, &receipt).unwrap().0);
|
||||
rows.push(envelope);
|
||||
}
|
||||
|
||||
/// Two closures in force over one subject, the later sequence arriving first. Admission refuses
|
||||
/// this; a store that holds it must still answer as the oracle does, closers in key order.
|
||||
#[test]
|
||||
fn planted_double_closers_keep_key_order() {
|
||||
let q = r(K::Question, &id("question", "Q1"));
|
||||
let mut rows = healthy_rows();
|
||||
planted_rows(&mut rows, 3, &resolution_n(q.clone(), 2, withdrawn()));
|
||||
planted_rows(&mut rows, 4, &resolution_n(q.clone(), 1, withdrawn()));
|
||||
let (mind, _) = faulted_mind(rows);
|
||||
for as_of in 1..=4 {
|
||||
assert_eq!(Reader::at(&mind, as_of).unwrap().view(&q).unwrap(), oracle_view(&mind, &q, as_of).unwrap(), "at {as_of}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Hands' own gaps ----
|
||||
|
||||
/// A lost swap names the identities that moved beneath it: a written key already stored, a read
|
||||
/// document that changed, and not a read document that is the same.
|
||||
#[test]
|
||||
fn a_conflict_names_the_identities_that_changed() {
|
||||
let (mut mind, store) = fails_the_look();
|
||||
let mut other = opened(store.clone(), INSTANCE);
|
||||
committed(admit(&mut other, vec![question_n(7)]));
|
||||
store.lose.store(true, Ordering::SeqCst);
|
||||
let outcome = admit(&mut mind, vec![question_n(7)]);
|
||||
let crate::admission::PipelineAdmissionOutcome::Conflict { identities } = outcome else { panic!("{outcome:?}") };
|
||||
assert_eq!(identities, vec![r(K::Question, &id("question", "Q7"))], "the written key that was already stored");
|
||||
|
||||
let cited = |mind: &mut Mind<FailsTheLook>| {
|
||||
let mut spec = cut_spec("1", 1);
|
||||
spec.rulings = vec![s(&id("ruling", "R1"))];
|
||||
admit(mind, vec![D::CutSpec(spec)])
|
||||
};
|
||||
committed(admit(&mut mind, vec![D::Ruling(ruling("R1"))]));
|
||||
store.lose.store(true, Ordering::SeqCst);
|
||||
let outcome = cited(&mut mind);
|
||||
let crate::admission::PipelineAdmissionOutcome::Conflict { identities } = outcome else { panic!("{outcome:?}") };
|
||||
assert!(identities.is_empty(), "a read document that did not change is not named: {identities:?}");
|
||||
|
||||
let mut bent = ruling("R1");
|
||||
bent.ruling = "A ruling that moved beneath the holder.".into();
|
||||
store.inner.plant(prepare(&D::Ruling(bent)));
|
||||
store.lose.store(true, Ordering::SeqCst);
|
||||
let outcome = cited(&mut mind);
|
||||
let crate::admission::PipelineAdmissionOutcome::Conflict { identities } = outcome else { panic!("{outcome:?}") };
|
||||
assert_eq!(identities, vec![r(K::Ruling, &id("ruling", "R1"))], "the read document that changed");
|
||||
}
|
||||
|
|
@ -190,13 +190,26 @@ pub(crate) fn candidate(
|
|||
Ok(receipt)
|
||||
}
|
||||
|
||||
/// This mind's admission order: `N`, the count of receipts, when their ordinals are exactly
|
||||
/// `{1..=N}`, read from the held image, which checked the chain once when it was built and
|
||||
/// extends it by one with each commit. Every reader of the ordinal asks here, never by counting
|
||||
/// receipts itself: admission takes `head(self)? + 1` for the next one. A chain that is not dense
|
||||
/// is a held fault that refuses on both sides alike.
|
||||
/// This mind's admission order: `N`, the count of receipts, when their
|
||||
/// ordinals are exactly `{1..=N}`. Every reader of the ordinal asks here,
|
||||
/// never by counting receipts itself: admission takes `head(self)? + 1` for
|
||||
/// the next one, and `AdmissionIndex::build` (`query.rs`) calls it too, so
|
||||
/// `query` and `view` carry the same density check rather than trusting a
|
||||
/// stored ordinal unchecked. `Mind::receipts` is `pub(crate)`, so this crate
|
||||
/// is the only place raw ordinals can be read at all; that keeps this the
|
||||
/// one door, rather than something a doc comment merely asks callers to
|
||||
/// respect. `ordinal` stays display-only on the read side until RS-3 makes
|
||||
/// it the order. A chain that is not dense refuses rather than guessing, on
|
||||
/// both sides alike.
|
||||
pub(crate) fn head<S: MindStore>(mind: &Mind<S>) -> Result<u64, MindRefusal> {
|
||||
Ok(mind.image()?.head)
|
||||
let mut ordinals = mind.receipts()?.into_iter().map(|receipt| receipt.ordinal).collect::<Vec<_>>();
|
||||
ordinals.sort_unstable();
|
||||
let n = ordinals.len() as u64;
|
||||
if ordinals.into_iter().eq(1..=n) {
|
||||
Ok(n)
|
||||
} else {
|
||||
Err(MindRefusal::Unavailable { detail: "receipt ordinals are not 1..=N: found a duplicate or a gap".into() })
|
||||
}
|
||||
}
|
||||
|
||||
/// The versions of a set of envelopes in identity order, so the digest does
|
||||
|
|
@ -252,34 +265,24 @@ pub(crate) fn commit<S: MindStore>(
|
|||
.filter(|read| !writes.iter().any(|write| write.r#type == read.r#type && write.key == read.key))
|
||||
.cloned(),
|
||||
);
|
||||
replacements.push(receipt_envelope.clone());
|
||||
replacements.push(receipt_envelope);
|
||||
let expected: &[CultCacheEnvelope] = &strong_reads;
|
||||
let landed = match MindStore::compare_and_swap_batch(mind.store(), expected, replacements) {
|
||||
Ok(landed) => landed,
|
||||
// Whether the batch landed is unknown, so the holder looks at the store before it answers
|
||||
// anything else; a failed look holds the fault (Mind::refresh), so nothing answers or
|
||||
// writes on a stale image.
|
||||
Err(error) => {
|
||||
let _ = mind.refresh();
|
||||
return Err(unavailable(error));
|
||||
}
|
||||
};
|
||||
if landed {
|
||||
mind.advance(&receipt, receipt_envelope, &writes);
|
||||
return Ok(CommitOutcome::Committed(receipt));
|
||||
}
|
||||
let landed = MindStore::compare_and_swap_batch(mind.store(), expected, replacements).map_err(unavailable)?;
|
||||
mind.refresh()?;
|
||||
let changed = strong_reads
|
||||
.iter()
|
||||
.filter(|read| mind.raw_envelope(&read.r#type, &read.key) != Some(read))
|
||||
.chain(writes.iter().filter(|write| mind.raw_envelope(&write.r#type, &write.key).is_some()));
|
||||
let identities = changed
|
||||
.filter_map(|envelope| {
|
||||
let kind = PipelineKind::ALL.iter().find(|kind| kind.type_id() == envelope.r#type)?;
|
||||
Some(PipelineRef { kind: *kind, id: Short(envelope.key.clone()) })
|
||||
})
|
||||
.collect();
|
||||
Ok(CommitOutcome::Conflict(identities))
|
||||
if !landed {
|
||||
let changed = strong_reads
|
||||
.iter()
|
||||
.filter(|read| mind.raw_envelope(&read.r#type, &read.key) != Some(read))
|
||||
.chain(writes.iter().filter(|write| mind.raw_envelope(&write.r#type, &write.key).is_some()));
|
||||
let identities = changed
|
||||
.filter_map(|envelope| {
|
||||
let kind = PipelineKind::ALL.iter().find(|kind| kind.type_id() == envelope.r#type)?;
|
||||
Some(PipelineRef { kind: *kind, id: Short(envelope.key.clone()) })
|
||||
})
|
||||
.collect();
|
||||
return Ok(CommitOutcome::Conflict(identities));
|
||||
}
|
||||
Ok(CommitOutcome::Committed(receipt))
|
||||
}
|
||||
|
||||
fn unique_identities(versions: &[DocumentVersion]) -> bool {
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ use eureka_pipeline::{
|
|||
RulingAuthority, RunOperator, RunTurn, Slug,
|
||||
};
|
||||
|
||||
use crate::docs::{CitationRole, kind_of_id, kind_of_type};
|
||||
use crate::docs::{CitationRole, Held, kind_of_id, kind_of_type};
|
||||
use crate::query::PipelineDocumentView;
|
||||
use crate::refusal::MindRefusal;
|
||||
|
||||
|
|
@ -68,14 +68,8 @@ const MEMORY_ORIGINS: [&str; 4] = ["Room", "Direct", "Wake", "SelfRun"];
|
|||
/// The one value a presence alias answers with; a row without it answers nothing.
|
||||
const PRESENT: [&str; 1] = ["true"];
|
||||
|
||||
/// The aliases whose values follow a row's status. Every other alias's values are
|
||||
/// fixed when the row is written, so the held image may narrow by them at any
|
||||
/// snapshot and by these only at the head. A test pins that no other alias
|
||||
/// changes across a status change.
|
||||
pub(crate) const STATUS_ALIASES: [Alias; 2] = [Alias::InForce, Alias::Ran];
|
||||
|
||||
impl Alias {
|
||||
pub(crate) const ALL: [Alias; 19] = [
|
||||
const ALL: [Alias; 19] = [
|
||||
Self::Root,
|
||||
Self::InForce,
|
||||
Self::Faculty,
|
||||
|
|
@ -97,7 +91,7 @@ impl Alias {
|
|||
Self::MemoryOrigin,
|
||||
];
|
||||
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Root => "root",
|
||||
Self::InForce => "in_force",
|
||||
|
|
@ -121,7 +115,7 @@ impl Alias {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_name(name: &str) -> Option<Self> {
|
||||
fn from_name(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|alias| alias.name() == name)
|
||||
}
|
||||
|
||||
|
|
@ -199,11 +193,11 @@ fn outcome_name(outcome: &ResolutionOutcome) -> &'static str {
|
|||
|
||||
/// One document as the evaluator sees it: its identity, its ordinal, what it
|
||||
/// answers for each alias, its citation edges, and the view a page projects.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct SelectionRow {
|
||||
pub(crate) kind: PipelineKind,
|
||||
pub(crate) key: String,
|
||||
pub(crate) ordinal: u64,
|
||||
ordinal: u64,
|
||||
values: BTreeMap<&'static str, Vec<String>>,
|
||||
refs: Vec<(CitationRole, PipelineRef)>,
|
||||
pub(crate) view: PipelineDocumentView,
|
||||
|
|
@ -211,28 +205,24 @@ pub(crate) struct SelectionRow {
|
|||
|
||||
impl SelectionRow {
|
||||
/// `base` is the first non-resolution the document reaches through its
|
||||
/// subjects: the row a resolution's `repo` and `cut` are read from; `None`
|
||||
/// is a document that is its own base. The row is the only decoded copy of
|
||||
/// its document: it lives in `view`.
|
||||
/// subjects: the row a resolution's `repo` and `cut` are read from.
|
||||
pub(crate) fn new(
|
||||
kind: PipelineKind,
|
||||
key: &str,
|
||||
base: Option<(&str, &PipelineDocument)>,
|
||||
held: &Held,
|
||||
base: &Held,
|
||||
view: PipelineDocumentView,
|
||||
refs: Vec<(CitationRole, PipelineRef)>,
|
||||
) -> Self {
|
||||
use PipelineDocument as D;
|
||||
let (base_key, base_document) = base.unwrap_or((key, &view.document));
|
||||
let mut values: BTreeMap<&'static str, Vec<String>> = BTreeMap::new();
|
||||
let mut put = |alias: Alias, found: Vec<String>| {
|
||||
values.insert(alias.name(), found);
|
||||
};
|
||||
put(Alias::Root, vec![root_and_local(key).0.to_string()]);
|
||||
put(Alias::Root, vec![root_and_local(&held.key).0.to_string()]);
|
||||
put(Alias::InForce, vec![matches!(view.status, crate::query::PipelineStatus::InForce).to_string()]);
|
||||
put(Alias::Faculty, vec![format!("{:?}", view.admission.provenance.faculty)]);
|
||||
put(
|
||||
Alias::Repo,
|
||||
match base_document {
|
||||
match &base.document {
|
||||
D::Campaign(campaign) => campaign.repos.iter().map(OrgRepo::identity).collect(),
|
||||
D::CutSpec(spec) => vec![spec.repo.identity()],
|
||||
D::CutReport(report) => vec![report.repo.identity()],
|
||||
|
|
@ -246,7 +236,7 @@ impl SelectionRow {
|
|||
);
|
||||
put(
|
||||
Alias::Cut,
|
||||
root_and_local(base_key)
|
||||
root_and_local(&base.key)
|
||||
.1
|
||||
.strip_prefix("cut-")
|
||||
.and_then(|rest| rest.split_once('.'))
|
||||
|
|
@ -254,7 +244,7 @@ impl SelectionRow {
|
|||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
match &view.document {
|
||||
match &held.document {
|
||||
D::Finding(finding) => {
|
||||
put(Alias::Severity, vec![format!("{:?}", finding.severity)]);
|
||||
put(Alias::Confidence, vec![format!("{:?}", finding.confidence)]);
|
||||
|
|
@ -287,12 +277,7 @@ impl SelectionRow {
|
|||
}
|
||||
_ => {}
|
||||
}
|
||||
Self { kind, key: key.to_string(), ordinal: view.admission.ordinal, values, refs, view }
|
||||
}
|
||||
|
||||
/// Each alias this row answers, with its values: what the held image indexes.
|
||||
pub(crate) fn alias_values(&self) -> impl Iterator<Item = (&'static str, &[String])> {
|
||||
self.values.iter().map(|(alias, values)| (*alias, values.as_slice()))
|
||||
Self { kind: held.kind, key: held.key.clone(), ordinal: view.admission.ordinal, values, refs, view }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ use serde_json::Value;
|
|||
use crate::admission::{PipelineAdmissionBatch, PipelineAdmissionOutcome};
|
||||
use crate::mind::Mind;
|
||||
use crate::persona::{PersonaPutOutcome, PersonaStateView};
|
||||
use crate::query::{PipelineDocumentView, PipelineSelectionPage, RootTouched, SemanticQuery};
|
||||
use crate::query::{PipelineDocumentView, PipelineSelectionPage, SemanticQuery};
|
||||
use crate::receipt::{HuginnCommitReceipt, PipelineProvenance};
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::store::MindStore;
|
||||
|
|
@ -98,9 +98,6 @@ pub enum HuginnMindRequest {
|
|||
/// in time. The repos are the asker's to name (her stewardships); the
|
||||
/// instance's own login is dropped from the answer.
|
||||
StewardedActivity { instance: Slug, repos: Vec<OrgRepo>, after: Option<u64> },
|
||||
/// Every root the mind holds a document under, with its newest admission and a campaign's repos in force: the mind's own
|
||||
/// records, one pass at the head.
|
||||
RootsTouched { instance: Slug },
|
||||
}
|
||||
|
||||
/// The most repos one activity read names.
|
||||
|
|
@ -253,7 +250,6 @@ impl HuginnMindRequest {
|
|||
Self::PersonaPut { .. } => "persona_put",
|
||||
Self::SearchSources { .. } => "search_sources",
|
||||
Self::StewardedActivity { .. } => "stewarded_activity",
|
||||
Self::RootsTouched { .. } => "roots_touched",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -267,8 +263,7 @@ impl HuginnMindRequest {
|
|||
| Self::PersonaGet { instance }
|
||||
| Self::PersonaPut { instance, .. }
|
||||
| Self::SearchSources { instance, .. }
|
||||
| Self::StewardedActivity { instance, .. }
|
||||
| Self::RootsTouched { instance } => Some(instance),
|
||||
| Self::StewardedActivity { instance, .. } => Some(instance),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -287,7 +282,6 @@ pub enum HuginnMindResponse {
|
|||
PersonaPut(PersonaPutOutcome),
|
||||
Sources(SourceHits),
|
||||
Activity(RepoActivity),
|
||||
RootsTouched(Vec<RootTouched>),
|
||||
/// The answer did not fit one send and is being held for the client to
|
||||
/// fetch. Nothing in a mind produces this: the daemon's serve module does,
|
||||
/// in place of an answer, and the answer it stands for is the named
|
||||
|
|
@ -370,9 +364,15 @@ impl<S: MindStore> Mind<S> {
|
|||
/// `whoami`, derived from the image every time it is asked, and from the
|
||||
/// index status the caller holds: the mind stores neither.
|
||||
pub fn status(&self, index: IndexStatus) -> MindStatus {
|
||||
let count = |type_id: &str| self.envelopes.get(type_id).map_or(0, |keyed| keyed.len() as u32);
|
||||
let receipts = count(HuginnCommitReceipt::TYPE);
|
||||
let documents = PipelineKind::ALL.iter().map(|kind| count(kind.type_id())).sum();
|
||||
let mut documents = 0_u32;
|
||||
let mut receipts = 0_u32;
|
||||
for envelope in self.envelopes() {
|
||||
if envelope.r#type == HuginnCommitReceipt::TYPE {
|
||||
receipts += 1;
|
||||
} else if PipelineKind::ALL.iter().any(|kind| kind.type_id() == envelope.r#type) {
|
||||
documents += 1;
|
||||
}
|
||||
}
|
||||
MindStatus {
|
||||
instance: self.instance().clone(),
|
||||
schema_epoch: PIPELINE_SCHEMA_EPOCH.to_string(),
|
||||
|
|
@ -417,7 +417,6 @@ mod tests {
|
|||
instance: slug(INSTANCE),
|
||||
query: SourceQuery { text: Line("reconcile".into()), top_k: 5, repo: Some(Short("Huginn".into())) },
|
||||
},
|
||||
HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) },
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -467,7 +466,6 @@ mod tests {
|
|||
text: "x".into(),
|
||||
}],
|
||||
}),
|
||||
HuginnMindResponse::RootsTouched(seeded().roots_touched().unwrap()),
|
||||
HuginnMindResponse::Deferred(DeferredAnswer {
|
||||
manifest: cultnet_rs::pack_content("huginn.mind_response", "package", "", "", "", b"body", 4)
|
||||
.unwrap()
|
||||
|
|
@ -482,7 +480,7 @@ mod tests {
|
|||
#[test]
|
||||
fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() {
|
||||
let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect();
|
||||
assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put", "search_sources", "roots_touched"]);
|
||||
assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put", "search_sources"]);
|
||||
for request in requests() {
|
||||
let declared = request.instance().is_none();
|
||||
assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}");
|
||||
|
|
|
|||
|
|
@ -1,172 +0,0 @@
|
|||
//! What a read costs, measured through the public API alone so the same file
|
||||
//! runs at the base and at the branch. Ignored: it wants a copy of a real
|
||||
//! store and says what it measured instead of asserting.
|
||||
//!
|
||||
//! `FLOOR_STATE` is a directory holding `minds/<instance>/mind.redb`. It is
|
||||
//! copied to a temp dir and never opened in place. `FLOOR_SCALE` (default 1)
|
||||
//! grows the copy with synthetic history to that multiple of its documents;
|
||||
//! `FLOOR_ROOTS` is `spread` (each hundred units under its own root) or
|
||||
//! `same` (one root grows). `FLOOR_INSTANCE` defaults to `eureka`; `FLOOR_SAMPLES` (default 7) is how many times each read is timed, for a base too slow to sample 7 times.
|
||||
//!
|
||||
//! cargo test --release -p huginn-mind --features test-support --test read_floor -- --ignored --nocapture
|
||||
#![cfg(feature = "test-support")]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use chrono::Utc;
|
||||
use cultnet_rs::{Citation, FieldPredicate, Incoming, RecordRef, Selection};
|
||||
use huginn_mind::eureka_pipeline::{PipelineDocument, PipelineKind, PipelinePulse, PipelineRef, Short, Slug};
|
||||
use huginn_mind::oracle::synth_history_at;
|
||||
use huginn_mind::{Faculty, IndexStatus, Mind, PipelineAdmissionBatch, PipelinePageItems, PipelineProvenance};
|
||||
|
||||
fn env(name: &str, default: &str) -> String {
|
||||
std::env::var(name).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
fn rss_kib() -> u64 {
|
||||
std::fs::read_to_string("/proc/self/status")
|
||||
.ok()
|
||||
.and_then(|status| {
|
||||
status.lines().find_map(|line| line.strip_prefix("VmRSS:")?.split_whitespace().next()?.parse().ok())
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn any_of(index: &str, values: &[&str]) -> FieldPredicate {
|
||||
FieldPredicate { index: index.into(), op: "any_of".into(), values: Some(values.iter().map(|v| v.to_string()).collect()), number: None }
|
||||
}
|
||||
|
||||
fn of(kind: PipelineKind, fields: Vec<FieldPredicate>) -> Selection {
|
||||
Selection { schemas: Some(vec![kind.type_id().to_string()]), fields: Some(fields), ..Selection::default() }
|
||||
}
|
||||
|
||||
fn median(mut samples: Vec<Duration>) -> Duration {
|
||||
samples.sort();
|
||||
samples[samples.len() / 2]
|
||||
}
|
||||
|
||||
fn time<T>(mut read: impl FnMut() -> T) -> Duration {
|
||||
let samples: usize = env("FLOOR_SAMPLES", "7").parse().unwrap();
|
||||
median(
|
||||
(0..samples)
|
||||
.map(|_| {
|
||||
let started = Instant::now();
|
||||
std::hint::black_box(read());
|
||||
started.elapsed()
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn keys_of(mind: &Mind<huginn_mind::OwnedRedbMessagePackBackingStore>, kind: PipelineKind) -> Vec<PipelineRef> {
|
||||
let page = mind.query(&Selection { schemas: Some(vec![kind.type_id().to_string()]), limit: Some(5), ..Selection::default() }).unwrap();
|
||||
match page.items {
|
||||
PipelinePageItems::Headers(headers) => headers.into_iter().map(|header| header.id).collect(),
|
||||
PipelinePageItems::Documents(views) => views.into_iter().map(|view| view.id).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn read_floor() {
|
||||
let instance = Slug(env("FLOOR_INSTANCE", "eureka"));
|
||||
let scale: u32 = env("FLOOR_SCALE", "1").parse().unwrap();
|
||||
let spread = env("FLOOR_ROOTS", "spread") == "spread";
|
||||
let source = PathBuf::from(env("FLOOR_STATE", "/state")).join("minds").join(&instance.0).join("mind.redb");
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let target = temp.path().join("minds").join(&instance.0);
|
||||
std::fs::create_dir_all(&target).unwrap();
|
||||
std::fs::copy(&source, target.join("mind.redb")).unwrap();
|
||||
let path = target.join("mind.redb");
|
||||
|
||||
let synthetic = if scale > 1 { synth_history_at(&path, &instance, scale, spread).unwrap() } else { 0 };
|
||||
let size_mib = std::fs::metadata(&path).unwrap().len() / (1024 * 1024);
|
||||
|
||||
let started = Instant::now();
|
||||
let mut mind = Mind::open(temp.path(), &instance).unwrap();
|
||||
let open = started.elapsed();
|
||||
let rss = rss_kib() / 1024;
|
||||
let status = mind.status(IndexStatus::Current);
|
||||
|
||||
let findings = keys_of(&mind, PipelineKind::Finding);
|
||||
let finding = findings.first().expect("the store holds a finding").clone();
|
||||
let root = finding.id.0.split(':').next().unwrap().to_string();
|
||||
let mut one = Selection { keys: Some(vec![finding.id.0.clone()]), projection: "document".into(), ..Selection::default() };
|
||||
one.schemas = Some(vec![PipelineKind::Finding.type_id().to_string()]);
|
||||
|
||||
let run_desc = Selection { descending: true, limit: Some(3), ..of(PipelineKind::Run, vec![any_of("root", &[&root]), any_of("operated_by", &["Mind"])]) };
|
||||
let cites = Selection {
|
||||
cites: Some(Citation { target: RecordRef::new(PipelineKind::Finding.type_id(), finding.id.0.clone()), role: Some("subject".into()) }),
|
||||
..of(PipelineKind::Resolution, vec![])
|
||||
};
|
||||
let stewardship = of(PipelineKind::Stewardship, vec![any_of("root", &[&root])]);
|
||||
let memory = of(PipelineKind::Memory, vec![any_of("root", &[&root]), any_of("memory_origin", &["Room"])]);
|
||||
let follow_up = Selection { limit: Some(20), ..of(PipelineKind::FollowUp, vec![any_of("in_force", &["true"])]) };
|
||||
let three = of(
|
||||
PipelineKind::Finding,
|
||||
vec![any_of("severity", &["High"]), any_of("confidence", &["Confirmed"]), any_of("origin", &["Introduced"])],
|
||||
);
|
||||
let unreported = Selection {
|
||||
cited: Some(Incoming { role: "cut_spec".into(), exists: false }),
|
||||
..of(PipelineKind::CutSpec, vec![any_of("in_force", &["true"])])
|
||||
};
|
||||
|
||||
let paged = |selection: &Selection| {
|
||||
let mut selection = selection.clone();
|
||||
let mut pages = 0;
|
||||
loop {
|
||||
let page = mind.query(&selection).unwrap();
|
||||
pages += 1;
|
||||
match page.next {
|
||||
Some(next) if pages < 3 => selection.cursor = Some(next),
|
||||
_ => return pages,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut rows: Vec<(&str, Duration)> = vec![
|
||||
("whoami/status", time(|| mind.status(IndexStatus::Current))),
|
||||
("persona", time(|| mind.persona().unwrap())),
|
||||
("view", time(|| mind.view(&finding).unwrap())),
|
||||
("keys=1 document", time(|| mind.query(&one).unwrap())),
|
||||
("run root+operated_by desc", time(|| mind.query(&run_desc).unwrap())),
|
||||
("resolution cites subject", time(|| mind.query(&cites).unwrap())),
|
||||
("stewardship root", time(|| mind.query(&stewardship).unwrap())),
|
||||
("memory two fields", time(|| mind.query(&memory).unwrap())),
|
||||
("follow_up in_force paged", time(|| paged(&follow_up))),
|
||||
("finding three fields", time(|| mind.query(&three).unwrap())),
|
||||
("cut_spec in_force cited", time(|| mind.query(&unreported).unwrap())),
|
||||
];
|
||||
let line = [&run_desc, &cites, &stewardship, &memory, &follow_up, &three, &unreported, &one];
|
||||
let first_line = time(|| {
|
||||
for n in 0..25 {
|
||||
let _ = mind.query(line[n % line.len()]);
|
||||
}
|
||||
});
|
||||
rows.push(("first line (25 reads)", first_line));
|
||||
|
||||
let pulse = PipelineDocument::Pulse(PipelinePulse {
|
||||
instance: instance.clone(),
|
||||
label: format!("floor-{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()).as_str().into(),
|
||||
note: "read floor".into(),
|
||||
tempo_vote_beat_s: None,
|
||||
tempo_vote_withdrawn: false,
|
||||
urgency_permille: Some(1),
|
||||
});
|
||||
let provenance = PipelineProvenance { faculty: Faculty::Hands, agent: Short("floor".into()), session: Short("floor".into()), tool: Short("floor".into()) };
|
||||
let started = Instant::now();
|
||||
let outcome = mind.admit(PipelineAdmissionBatch { instance: instance.clone(), provenance, documents: vec![pulse] }, Utc::now());
|
||||
let admit = started.elapsed();
|
||||
let started = Instant::now();
|
||||
let read_back = mind.read_back();
|
||||
let read_back_time = started.elapsed();
|
||||
|
||||
println!("\nFLOOR documents={} receipts={} store_mib={} synthetic_docs={} scale={} roots={}", status.documents, status.receipts, size_mib, synthetic, scale, if spread { "spread" } else { "same" });
|
||||
println!("FLOOR open_ms={:.0} rss_mib={}", open.as_secs_f64() * 1e3, rss);
|
||||
for (name, took) in rows {
|
||||
println!("FLOOR read {:<28} {:>10.1} us", name, took.as_secs_f64() * 1e6);
|
||||
}
|
||||
println!("FLOOR admit_ms={:.0} ({})", admit.as_secs_f64() * 1e3, if matches!(outcome, huginn_mind::PipelineAdmissionOutcome::Committed { .. }) { "committed".to_string() } else { format!("{outcome:?}") });
|
||||
println!("FLOOR read_back_ms={:.0} ({:?})", read_back_time.as_secs_f64() * 1e3, read_back);
|
||||
}
|
||||
|
|
@ -4,8 +4,8 @@
|
|||
//! The mouth is Bifrost's chat ear and mouth (cut `persona-mouth`). Five CultNet document kinds cross
|
||||
//! it, each a positional MessagePack tuple (fields in declaration order, `rmp_serde::to_vec`; the mouth refuses maps): the pending request and its answer, the
|
||||
//! ack, and the send request with its receipt. Their field order is the mouth's, pinned
|
||||
//! by its golden fixtures (`tests/fixtures/persona-chat-v1/` for the pending, ack and refusal kinds, `persona-chat-v2/` for the send
|
||||
//! and its receipt) in both directions. `chat_rudp::RudpChat` is
|
||||
//! by its golden fixtures (`tests/fixtures/persona-chat-v1/`, Bifrost
|
||||
//! `eureka-body/persona-mouth` ab2bdc6) in both directions. `chat_rudp::RudpChat` is
|
||||
//! the RUDP transport that carries them; `Chat` is its seam, and `encode` and
|
||||
//! `decode` are its codec. Room aliases are the mouth's
|
||||
//! full aliases (`#operator:gamecult.org`), which the caller's `--rooms` carries.
|
||||
|
|
@ -20,8 +20,8 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
|||
pub const PENDING_REQUEST: &str = "gamecult.persona.chat_pending_request.v1";
|
||||
pub const PENDING: &str = "gamecult.persona.chat_pending.v1";
|
||||
pub const ACK: &str = "gamecult.persona.chat_ack.v1";
|
||||
pub const SEND_REQUEST: &str = "gamecult.persona.chat_send_request.v2";
|
||||
pub const SEND_RECEIPT: &str = "gamecult.persona.chat_send_receipt.v2";
|
||||
pub const SEND_REQUEST: &str = "gamecult.persona.chat_send_request.v1";
|
||||
pub const SEND_RECEIPT: &str = "gamecult.persona.chat_send_receipt.v1";
|
||||
pub const REFUSAL: &str = "gamecult.persona.chat_refusal.v1";
|
||||
|
||||
/// One earlier line of a room, delivered with a message for its context.
|
||||
|
|
@ -78,8 +78,6 @@ pub enum Refusal {
|
|||
EmptyText,
|
||||
SendFailed,
|
||||
UnknownPersona,
|
||||
/// A send with a basis found the room had moved past it: the receipt names what moved it.
|
||||
RoomMoved,
|
||||
}
|
||||
|
||||
impl Refusal {
|
||||
|
|
@ -92,7 +90,6 @@ impl Refusal {
|
|||
Self::EmptyText => "EmptyText",
|
||||
Self::SendFailed => "SendFailed",
|
||||
Self::UnknownPersona => "UnknownPersona",
|
||||
Self::RoomMoved => "RoomMoved",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -106,7 +103,7 @@ impl Serialize for Refusal {
|
|||
impl<'de> Deserialize<'de> for Refusal {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let name = String::deserialize(deserializer)?;
|
||||
[Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::UnknownPersona, Self::RoomMoved]
|
||||
[Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::UnknownPersona]
|
||||
.into_iter()
|
||||
.find(|refusal| refusal.name() == name)
|
||||
.ok_or_else(|| serde::de::Error::custom("the mouth named a refusal this side does not know"))
|
||||
|
|
@ -121,34 +118,22 @@ pub struct ChatRefusal {
|
|||
pub refusal: Refusal,
|
||||
}
|
||||
|
||||
/// What a send's author had seen of its room: the newest event of the room her input held (none when it held
|
||||
/// none), and when her process began. The mouth refuses the send if another sender's message reached the room
|
||||
/// after that event, or after that time where there is none.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SendBasis {
|
||||
pub seen_event_id: Option<String>,
|
||||
pub since_unix_ms: u64,
|
||||
}
|
||||
|
||||
/// A send. `request_id` is the mouth's transaction id, so a repeat of the same
|
||||
/// id is the same send. No `basis` is her choice standing: the mouth checks nothing.
|
||||
/// id is the same send.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ChatSendRequest {
|
||||
pub request_id: String,
|
||||
pub persona: String,
|
||||
pub room_alias: String,
|
||||
pub text: String,
|
||||
pub basis: Option<SendBasis>,
|
||||
}
|
||||
|
||||
/// The mouth's answer to a send: the event it made, or why it did not. `newer` names the events that moved the
|
||||
/// room, oldest first, exactly when the refusal is `RoomMoved`.
|
||||
/// The mouth's answer to a send: the event it made, or why it did not.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ChatSendReceipt {
|
||||
pub request_id: String,
|
||||
pub event_id: Option<String>,
|
||||
pub refusal: Option<Refusal>,
|
||||
pub newer: Vec<String>,
|
||||
pub refusal: Option<String>,
|
||||
}
|
||||
|
||||
/// A document as the mouth reads it: a positional tuple.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! The chat documents against the mouth's golden bytes (`tests/fixtures/persona-chat-v1/` for the pending, ack and refusal
|
||||
//! kinds, Bifrost `eureka-body/persona-mouth` ab2bdc6; `persona-chat-v2/` for the send and its receipt, copied from Bifrost `eureka-body/optimistic-send-mouth`):
|
||||
//! The chat documents against the mouth's own golden bytes (Bifrost
|
||||
//! `eureka-body/persona-mouth` ab2bdc6, `tests/fixtures/persona-chat-v1/`):
|
||||
//! each decodes into the typed document and the encoder reproduces it byte for
|
||||
//! byte. The mouth reads positional tuples and refuses maps.
|
||||
|
||||
|
|
@ -9,11 +9,8 @@ const REFUSAL_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v
|
|||
const ACK_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v1/gamecult.persona.chat_ack.v1.msgpack");
|
||||
const PENDING_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v1/gamecult.persona.chat_pending.v1.msgpack");
|
||||
const PENDING_REQUEST_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v1/gamecult.persona.chat_pending_request.v1.msgpack");
|
||||
const SENT_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_receipt.v2.sent.msgpack");
|
||||
const ROOM_MOVED_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_receipt.v2.room-moved.msgpack");
|
||||
const NIL_BASIS_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v2.nil-basis.msgpack");
|
||||
const SEEN_AND_SINCE_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v2.seen-and-since.msgpack");
|
||||
const SINCE_ONLY_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v2.since-only.msgpack");
|
||||
const SEND_RECEIPT_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v1/gamecult.persona.chat_send_receipt.v1.msgpack");
|
||||
const SEND_REQUEST_BYTES: &[u8] = include_bytes!("../../tests/fixtures/persona-chat-v1/gamecult.persona.chat_send_request.v1.msgpack");
|
||||
|
||||
fn golden<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(bytes: &[u8], expected: &T) {
|
||||
assert_eq!(&decode::<T>(bytes).unwrap(), expected);
|
||||
|
|
@ -52,10 +49,9 @@ fn a_refusal_is_the_mouths_bytes_and_a_typed_name() {
|
|||
|
||||
#[test]
|
||||
fn a_send_and_its_receipt_are_the_mouths_bytes() {
|
||||
let request = |basis: Option<SendBasis>| ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis };
|
||||
golden(NIL_BASIS_BYTES, &request(None));
|
||||
golden(SEEN_AND_SINCE_BYTES, &request(Some(SendBasis { seen_event_id: Some("$seen".into()), since_unix_ms: 1_793_698_425_998 })));
|
||||
golden(SINCE_ONLY_BYTES, &request(Some(SendBasis { seen_event_id: None, since_unix_ms: 1_793_698_425_998 })));
|
||||
golden(SENT_BYTES, &ChatSendReceipt { request_id: "req-1".into(), event_id: Some("$sent".into()), refusal: None, newer: vec![] });
|
||||
golden(ROOM_MOVED_BYTES, &ChatSendReceipt { request_id: "req-1".into(), event_id: None, refusal: Some(Refusal::RoomMoved), newer: vec!["$a".into(), "$b".into()] });
|
||||
golden(
|
||||
SEND_REQUEST_BYTES,
|
||||
&ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#operator:gamecult.org".into(), text: "hi".into() },
|
||||
);
|
||||
golden(SEND_RECEIPT_BYTES, &ChatSendReceipt { request_id: "req-1".into(), event_id: Some("$sent".into()), refusal: None });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -95,21 +95,7 @@ impl RudpChat {
|
|||
/// Puts one document and, when `answer` names a kind and record key, waits for
|
||||
/// the document the mouth answers it with. Documents of other kinds or keys
|
||||
/// (a late receipt of an earlier send) are skipped.
|
||||
///
|
||||
/// A failed exchange drops the link: a restarted mouth silently ignores packets from a sender it has not connected, so a held link
|
||||
/// would time out on every call after it. The next call opens a fresh one. Nothing is repeated on it: the caller's request id is
|
||||
/// what makes a repeat of a send the same send.
|
||||
fn exchange<T: Serialize>(&self, kind: &str, record_key: &str, document: &T, answer: Option<(&[&str], &str)>) -> Result<Option<(String, Vec<u8>)>> {
|
||||
let result = self.exchange_on_link(kind, record_key, document, answer);
|
||||
if result.is_err()
|
||||
&& let Some(mut link) = self.link.borrow_mut().take()
|
||||
{
|
||||
let _ = link.transport.disconnect(Vec::new());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn exchange_on_link<T: Serialize>(&self, kind: &str, record_key: &str, document: &T, answer: Option<(&[&str], &str)>) -> Result<Option<(String, Vec<u8>)>> {
|
||||
let mut slot = self.link.borrow_mut();
|
||||
if slot.is_none() {
|
||||
*slot = Some(self.open()?);
|
||||
|
|
|
|||
|
|
@ -1,27 +1,13 @@
|
|||
//! The plan windows as one line for a Mind: the one rendering both organs put in front of their
|
||||
//! sessions, from the windows a credential lease granted (`lease_client`).
|
||||
|
||||
use chrono::{DateTime, SecondsFormat, Utc};
|
||||
use model_connector::PlanQuota;
|
||||
|
||||
/// When a window resets: the UTC time alone. An instant is true when read again hours later; "in 4d 11h"
|
||||
/// or "already past" is not.
|
||||
fn resets(at_unix_ms: u64) -> String {
|
||||
let at = i64::try_from(at_unix_ms).ok().and_then(DateTime::<Utc>::from_timestamp_millis).map_or_else(|| at_unix_ms.to_string(), |at| at.to_rfc3339_opts(SecondsFormat::Secs, true));
|
||||
format!("resets at {at}")
|
||||
}
|
||||
|
||||
/// The minute a reading was taken, as a UTC time. An instant, not an age: the line stays true when
|
||||
/// it is read again hours later in a session that cannot refresh it.
|
||||
fn read_at(at_unix_ms: u64) -> String {
|
||||
i64::try_from(at_unix_ms).ok().and_then(DateTime::<Utc>::from_timestamp_millis).map_or_else(|| at_unix_ms.to_string(), |at| at.format("%Y-%m-%dT%H:%MZ").to_string())
|
||||
}
|
||||
|
||||
/// The plan windows as one line for a Mind: each window's percent used, its
|
||||
/// status, when it resets and the minute the reading was taken. Rendered from the readout
|
||||
/// status, when it resets and how old the reading is. Rendered from the readout
|
||||
/// and nothing else, so no number in it is ever a paraphrase; the guidance that
|
||||
/// follows it states the swarm's aim and that nothing enforces it.
|
||||
pub fn render_plan(windows: &[PlanQuota], _now_ms: u64) -> String {
|
||||
pub fn render_plan(windows: &[PlanQuota], now_ms: u64) -> String {
|
||||
let guidance = "The swarm aims to have used about 90% of the weekly allowance at reset; nothing enforces it; you and the other Minds set the tempo.";
|
||||
if windows.is_empty() {
|
||||
return format!("Plan usage: unobserved. {guidance}");
|
||||
|
|
@ -30,48 +16,16 @@ pub fn render_plan(windows: &[PlanQuota], _now_ms: u64) -> String {
|
|||
.iter()
|
||||
.map(|plan| match plan.utilization_permille {
|
||||
Some(permille) => format!(
|
||||
"{} {}.{}% {}, {}, read at {}",
|
||||
"{} {}.{}% {}, resets at unix ms {}, read {}s ago",
|
||||
plan.window,
|
||||
permille / 10,
|
||||
permille % 10,
|
||||
plan.status,
|
||||
resets(plan.resets_at_unix_ms),
|
||||
read_at(plan.observed_at_unix_ms)
|
||||
plan.resets_at_unix_ms,
|
||||
now_ms.saturating_sub(plan.observed_at_unix_ms) / 1000
|
||||
),
|
||||
None => format!("{} expired, {}", plan.window, resets(plan.resets_at_unix_ms)),
|
||||
None => format!("{} expired, resets at unix ms {}", plan.window, plan.resets_at_unix_ms),
|
||||
})
|
||||
.collect();
|
||||
format!("Plan usage: {}. {guidance}", rendered.join("; "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn window(permille: Option<u32>, resets_at_unix_ms: u64, observed_at_unix_ms: u64) -> PlanQuota {
|
||||
PlanQuota { window: "five_hour".into(), utilization_permille: permille, resets_at_unix_ms, status: "allowed".into(), observed_at_unix_ms }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_reads_as_a_time_not_unix_milliseconds() {
|
||||
let now = 1_793_307_000_000 - (4 * 86_400 + 11 * 3600 + 30 * 60) * 1000;
|
||||
let line = render_plan(&[window(Some(423), 1_793_307_000_000, now - 385_639_000)], now);
|
||||
assert!(line.starts_with("Plan usage: five_hour 42.3% allowed, resets at 2026-10-29T20:50:00Z, read at 2026-10-20T22:12Z. "), "{line}");
|
||||
assert!(!line.contains("unix ms"), "{line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reset_is_an_instant_whatever_the_moment_of_rendering() { let reset = 1_793_307_000_000; let at = |now| render_plan(&[window(Some(10), reset, reset - 5000)], now); let before = at(reset - 5000); assert!(before.contains("resets at 2026-10-29T20:50:00Z, read at 2026-10-29T20:49Z"), "{before}"); for now in [reset - 12_000_000, reset, reset + 1000] { assert_eq!(at(now), before, "the line does not depend on when it is rendered"); } assert!(!before.contains("(in ") && !before.contains("already past"), "{before}"); assert_eq!(render_plan(&[window(None, reset, reset)], reset - 12_000_000).split(". ").next().unwrap(), "Plan usage: five_hour expired, resets at 2026-10-29T20:50:00Z"); }
|
||||
#[test]
|
||||
fn the_reading_is_dated_by_the_minute_it_was_taken_and_the_line_does_not_age() {
|
||||
let reset = 1_793_307_000_000;
|
||||
let taken = 1_793_306_999_000; // 20:49:59Z: the minute is cut, not rounded
|
||||
let first = render_plan(&[window(Some(10), reset, taken)], taken);
|
||||
assert!(first.contains(", read at 2026-10-29T20:49Z. "), "{first}");
|
||||
let hours_later = render_plan(&[window(Some(10), reset, taken)], taken + 3 * 3_600_000);
|
||||
assert!(hours_later.contains(", read at 2026-10-29T20:49Z. "), "{hours_later}");
|
||||
assert!(!first.contains(" ago") && !hours_later.contains(" ago"), "{first} {hours_later}");
|
||||
assert!(render_plan(&[window(Some(10), reset, 0)], reset).contains(", read at 1970-01-01T00:00Z. "));
|
||||
assert!(render_plan(&[window(Some(10), reset, u64::MAX)], reset).contains(&format!(", read at {}. ", u64::MAX)), "an instant out of range is printed as the number it is");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,18 +35,7 @@
|
|||
//! third in a row ends the session. Any other failure sends nothing further, acks nothing and
|
||||
//! ends the start; the run is closed Recorded with the failure, so the breaker and the next wake
|
||||
//! see it. Nothing is acked that was not answered, and a repeat of a send carries the same
|
||||
//! request id, so a start that dies between a send and its ack does not repeat it; an answer to a revision line carries a new id,
|
||||
//! so it can repeat a send.
|
||||
//!
|
||||
//! Each send names what her input held of its room (ruling `eureka-body:ruling:send-refused-if-room-moved`):
|
||||
//! the newest message of that room a line the CLI took in showed her. The mouth decides whether the room moved;
|
||||
//! the organ owns only what her input held and whether a reply is her final answer. A send the mouth refuses as
|
||||
//! `RoomMoved` stops that reply at once (the says before it stand, nothing after it is done) and is not a
|
||||
//! refused result: she is handed the messages that interrupted her as her next input, once they have reached
|
||||
//! the organ, to send, change or drop. Her answer to that line is final: it goes out unchecked, as does the reply
|
||||
//! to a flush, which has no next turn to revise in. A message reaches a live session after her rank among the Minds for that message (the Minds it names first), at one
|
||||
//! step per rank
|
||||
//! (ruling `eureka-body:ruling:unaddressed-tell-stagger-ruled`), so the Minds read each other before they answer.
|
||||
//! request id, so a start that dies between a send and its ack repeats no message.
|
||||
//!
|
||||
//! The reply is decoded, never scanned: text that is not one `PersonaReply` is a refused
|
||||
//! result. Chat, persona state and trace are ports; the chat transport is `chat_rudp::RudpChat`,
|
||||
|
|
@ -65,19 +54,18 @@ use std::path::{Path, PathBuf};
|
|||
use anyhow::{Result, anyhow, bail};
|
||||
use chrono::{DateTime, Utc};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use cultnet_rs::{Incoming, Selection};
|
||||
use cultnet_rs::Selection;
|
||||
use eureka_pipeline::{
|
||||
Date, Label, Line, MemoryOrigin, MemorySort, OrgRepo, PipelineDocument, PipelineFollowUp, PipelineKind, PipelineMemory, PipelinePulse, PipelineRef, PipelineResolution, ResolutionOutcome, RunOperator, RunTurn, SALIENCE_MAX_PERMILLE, Short, Slug,
|
||||
TEMPO_VOTE_MAX_S, TEMPO_VOTE_MIN_S, URGENCY_MAX_PERMILLE, pipeline_key,
|
||||
};
|
||||
use eureka_state::HuginnClient;
|
||||
use eureka_state::hold::BLOCKING;
|
||||
use huginn_mind::{HuginnMindResponse, PipelineAdmissionOutcome, PipelineFacts, PipelinePageItems, PipelineStatusSummary, PrAction, RepoActivity, RepoChange, RepoEvent, RootTouched};
|
||||
use huginn_mind::{HuginnMindResponse, PipelineAdmissionOutcome, PipelineFacts, PipelinePageItems, PipelineStatusSummary, PrAction, RepoActivity, RepoChange, RepoEvent};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::chat_client::{Chat, ChatDelivery, ChatSendRequest, ContextLine, Refusal, SendBasis};
|
||||
use crate::chat_client::{Chat, ChatDelivery, ChatSendRequest, ContextLine};
|
||||
use crate::connector::render_plan;
|
||||
use crate::control::{ControlSource, Effective, HeldReason, derive};
|
||||
use crate::heartbeat::{PollTrace, TempoView};
|
||||
|
|
@ -107,13 +95,6 @@ const REFUSALS_PER_BATCH: u32 = 3;
|
|||
/// The most bytes of `earlier` text, as rendered into the line (JSON-quoted), one line carries for one room: the room's tail, newest kept. Each delivery brings its own
|
||||
/// context, so a batch repeats a room's tail per message; `earlier_shown` owns this bound because a line's size decides how soon the session hits its ceiling.
|
||||
const EARLIER_MAX_BYTES_PER_ROOM: usize = 16 * 1024;
|
||||
/// A live session is told a message this many seconds per rank, her rank among the Minds being a stable hash of the Mind and the
|
||||
/// event, the Minds the message names first: the first Mind by that order is told at once, the next after one step. The step is
|
||||
/// calibration, about the time a Mind takes to answer (7 to 13 s observed on 2026-11-03).
|
||||
const STAGGER_STEP_S: u64 = 8;
|
||||
/// Polls a revision waits for the interrupting messages to reach the organ's pending before it is told without them (at most
|
||||
/// `REVISION_POLLS * PERSONA_POLL_S` seconds).
|
||||
const REVISION_POLLS: u32 = 2;
|
||||
/// The environment variables the unit's `persona.env` sets for the persona flags.
|
||||
pub const ENV_ROOMS: &str = "MIND_PERSONA_ROOMS";
|
||||
pub const ENV_OPERATOR: &str = "MIND_PERSONA_OPERATOR";
|
||||
|
|
@ -670,10 +651,10 @@ impl fmt::Display for Failure {
|
|||
Self::Doctrine => f.write_str("a configured doctrine file could not be read"),
|
||||
Self::DoctrineTooLarge => f.write_str("the doctrine files exceed the size bound"),
|
||||
Self::Lease => f.write_str("the credential lease was refused or unavailable"),
|
||||
Self::Session => f.write_str("your session could not be started or ended without answering"),
|
||||
Self::Session => f.write_str("her session could not be started or ended without answering"),
|
||||
Self::Undecodable => f.write_str("the reply is not a persona reply"),
|
||||
Self::OutOfBounds(field) => f.write_str(field),
|
||||
Self::RoomNotAllowed => f.write_str("the reply speaks outside your rooms"),
|
||||
Self::RoomNotAllowed => f.write_str("the reply speaks outside her rooms"),
|
||||
Self::Send => f.write_str("a send was refused or failed"),
|
||||
Self::SelfRun => f.write_str("the Self run could not be started"),
|
||||
Self::Memory => f.write_str("the turn's memories, settles or pulse could not be admitted"),
|
||||
|
|
@ -719,9 +700,6 @@ enum Step {
|
|||
Answered(Option<PipelineRef>, String, Vec<String>),
|
||||
/// The reply could not be decoded: it is told back to her, and sends and acks nothing.
|
||||
Refused(Failure),
|
||||
/// The mouth refused a send because the room moved past what her input held: the room, the rooms sent before it in the
|
||||
/// reply, and the events that moved it. Nothing after the send was done.
|
||||
Stale { room: String, sent: Vec<String>, newer: Vec<String> },
|
||||
/// The start cannot go on; the intent her decoded reply stated still closes the run beside the failure.
|
||||
Failed(Failure, String),
|
||||
}
|
||||
|
|
@ -884,7 +862,35 @@ fn one_process(
|
|||
progress.failure = Some(Failure::Session);
|
||||
return Ok(());
|
||||
};
|
||||
let mut inbox = PersonaInbox::new(organs, control, swarm, config, run, progress, first, started_ms, render_plan(lease.plan_quota(), started_ms));
|
||||
let conversation = first.first().map_or(Conversation::Public, Conversation::of);
|
||||
let mut inbox = PersonaInbox {
|
||||
organs,
|
||||
control,
|
||||
swarm,
|
||||
config,
|
||||
run,
|
||||
progress,
|
||||
rooms,
|
||||
conversation,
|
||||
plan: render_plan(lease.plan_quota(), started_ms),
|
||||
started_ms,
|
||||
told: BTreeSet::new(),
|
||||
start: first,
|
||||
waiting: Vec::new(),
|
||||
told_through: 0,
|
||||
answered_through: 0,
|
||||
written: None,
|
||||
echoed: Vec::new(),
|
||||
echoed_refusals: 0,
|
||||
seen: Shown::default(),
|
||||
retell: None,
|
||||
slot_seen: Vec::new(),
|
||||
slot_read_due_ms: 0,
|
||||
notices: Vec::new(),
|
||||
repos: Vec::new(),
|
||||
repo_head: None,
|
||||
repo_read_due_ms: 0,
|
||||
};
|
||||
drive(organs.clock, child, &mut inbox, remaining_s, &mut std::io::stdout())?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -968,8 +974,6 @@ struct Written {
|
|||
batch: Vec<ChatDelivery>,
|
||||
shown: Shown,
|
||||
refusals: u32,
|
||||
/// The line is a revision (or the retell of one): the reply to it is her final answer.
|
||||
revision: bool,
|
||||
}
|
||||
|
||||
/// Every refused batch not yet told again, merged into one, with the refusal to tell and the most
|
||||
|
|
@ -978,21 +982,6 @@ struct Retell {
|
|||
batch: Vec<ChatDelivery>,
|
||||
why: Failure,
|
||||
refusals: u32,
|
||||
/// An undecodable revision stays a revision: its answer is final.
|
||||
revision: bool,
|
||||
}
|
||||
|
||||
/// A reply stopped by a send the mouth refused as `RoomMoved`, waiting to be handed back to her as her next input: the
|
||||
/// deliveries it answered, where it stopped and what it had sent, and the events that moved the room, which the line waits to
|
||||
/// have reached the organ.
|
||||
#[derive(Default)]
|
||||
struct Revision {
|
||||
batch: Vec<ChatDelivery>,
|
||||
rooms: Vec<String>,
|
||||
sent: Vec<String>,
|
||||
awaiting: Vec<String>,
|
||||
polls: u32,
|
||||
ready: bool,
|
||||
}
|
||||
|
||||
/// A rendered line: its text, what it lets a reply name, and the lines it tells.
|
||||
|
|
@ -1040,18 +1029,6 @@ struct PersonaInbox<'a, C: ControlSource, S: ControlSource> {
|
|||
seen: Shown,
|
||||
/// What refused results left to be told again.
|
||||
retell: Option<Retell>,
|
||||
/// What each room's newest message was among the lines the CLI took in this process: the seq and the event. Filled by `echoed` only:
|
||||
/// a line written and not echoed she has not seen.
|
||||
held: BTreeMap<String, (u64, String)>,
|
||||
/// The reply a stale send stopped, until it is told back.
|
||||
revision: Option<Revision>,
|
||||
/// A revision line, or a flush, was echoed since the last result: that result is her final answer, sent without a basis.
|
||||
echoed_revision: bool,
|
||||
echoed_flush: bool,
|
||||
/// The next line written carries a flush.
|
||||
flush_asked: bool,
|
||||
/// When each untold delivery was first seen by a poll: its stagger runs from there and nothing later moves it.
|
||||
first_seen: BTreeMap<u64, u64>,
|
||||
/// Her Self runs last seen holding the slot, each until a read shows it gone and how it closed: whoever started it, her, the
|
||||
/// heartbeat or an earlier process. Her own start joins it unread. A failed read leaves this as it stood.
|
||||
slot_seen: Vec<PipelineRef>,
|
||||
|
|
@ -1067,48 +1044,7 @@ struct PersonaInbox<'a, C: ControlSource, S: ControlSource> {
|
|||
repo_read_due_ms: u64,
|
||||
}
|
||||
|
||||
impl<'a, C: ControlSource, S: ControlSource> PersonaInbox<'a, C, S> {
|
||||
/// One process's session inbox over its first batch. The caller has read the gate and started the child.
|
||||
#[allow(clippy::too_many_arguments, reason = "one process's state is these few things, and a struct for them would be a second owner")]
|
||||
fn new(organs: &'a Organs<'a>, control: &'a C, swarm: &'a S, config: &'a Config, run: &'a PipelineRef, progress: &'a mut Progress, first: Vec<ChatDelivery>, started_ms: u64, plan: String) -> Self {
|
||||
let rooms = reply_rooms(config, &first);
|
||||
let conversation = first.first().map_or(Conversation::Public, Conversation::of);
|
||||
Self {
|
||||
organs,
|
||||
control,
|
||||
swarm,
|
||||
config,
|
||||
run,
|
||||
progress,
|
||||
rooms,
|
||||
conversation,
|
||||
plan,
|
||||
started_ms,
|
||||
told: BTreeSet::new(),
|
||||
start: first,
|
||||
waiting: Vec::new(),
|
||||
told_through: 0,
|
||||
answered_through: 0,
|
||||
written: None,
|
||||
echoed: Vec::new(),
|
||||
echoed_refusals: 0,
|
||||
seen: Shown::default(),
|
||||
retell: None,
|
||||
held: BTreeMap::new(),
|
||||
revision: None,
|
||||
echoed_revision: false,
|
||||
echoed_flush: false,
|
||||
flush_asked: false,
|
||||
first_seen: BTreeMap::new(),
|
||||
slot_seen: Vec::new(),
|
||||
slot_read_due_ms: 0,
|
||||
notices: Vec::new(),
|
||||
repos: Vec::new(),
|
||||
repo_head: None,
|
||||
repo_read_due_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: ControlSource, S: ControlSource> PersonaInbox<'_, C, S> {
|
||||
/// The `earlier` lines a batch brings now.
|
||||
fn earlier<'d>(&self, deliveries: &'d [ChatDelivery]) -> Vec<Vec<&'d ContextLine>> {
|
||||
earlier_shown(deliveries, &self.told, &self.config.own_sender, self.started_ms)
|
||||
|
|
@ -1123,8 +1059,7 @@ impl<'a, C: ControlSource, S: ControlSource> PersonaInbox<'a, C, S> {
|
|||
let names = sender_names(deliveries);
|
||||
let goals = render_responsibilities(organs.mind, &instance, &names)?;
|
||||
self.repos = goals.repos.clone();
|
||||
let (wear_at, wear_facts) = self.first_repo_read(&goals.open_roots);
|
||||
let wear = render_wear(wear_at, &wear_facts);
|
||||
let wear = self.first_repo_read();
|
||||
let senders = other_senders(self.config, deliveries);
|
||||
let cue = recall::Cue { senders, texts: deliveries.iter().rev().map(|delivery| delivery.text.as_str()).collect(), names: names.clone(), listed: &goals.listed, now: organs.clock.now() };
|
||||
let recalled = recall::select(organs.mind, &cue)?;
|
||||
|
|
@ -1151,7 +1086,7 @@ impl<'a, C: ControlSource, S: ControlSource> PersonaInbox<'a, C, S> {
|
|||
self.told_through = self.told_through.max(through);
|
||||
}
|
||||
self.told.extend(told);
|
||||
self.written = Some(Written { batch, shown, refusals, revision: false });
|
||||
self.written = Some(Written { batch, shown, refusals });
|
||||
input
|
||||
}
|
||||
|
||||
|
|
@ -1179,19 +1114,17 @@ impl<'a, C: ControlSource, S: ControlSource> PersonaInbox<'a, C, S> {
|
|||
}
|
||||
}
|
||||
|
||||
/// The first line's reads for her stewarded repos, as the wear section's facts and the instant they were read at: what is open,
|
||||
/// what the forge cannot show, what others changed in the last three days, the cursor the later reads continue from, then what
|
||||
/// her own mind holds of her machine (`record_wear_facts`). A read that fails leaves the cursor unset, puts one line in the
|
||||
/// section saying repo facts are missing, and never fails the session; a Mind with no repos asks nothing, of the forge or of her
|
||||
/// mind.
|
||||
fn first_repo_read(&mut self, open_roots: &[String]) -> (u64, Vec<WearFact>) {
|
||||
/// The first line's read of the forge for her stewarded repos: what is open, what the forge cannot show, what others changed in the
|
||||
/// last three days, as the wear section, and the cursor the later reads continue from. A read that fails leaves the cursor unset,
|
||||
/// puts one line in the section saying repo facts are missing, and never fails the session; a Mind with no repos asks nothing.
|
||||
fn first_repo_read(&mut self) -> String {
|
||||
if self.repos.is_empty() {
|
||||
return (0, Vec::new());
|
||||
return String::new();
|
||||
}
|
||||
let organs = self.organs;
|
||||
let now = unix_ms(organs.clock.now());
|
||||
self.repo_read_due_ms = now + REPO_READ_EVERY_S * 1000;
|
||||
let mut facts = match organs.mind.stewarded_activity(&self.repos, None) {
|
||||
let facts = match organs.mind.stewarded_activity(&self.repos, None) {
|
||||
Ok(activity) => {
|
||||
self.repo_head = Some(activity.head);
|
||||
wear_facts(&activity, &self.repos, organs.mind.instance(), now)
|
||||
|
|
@ -1201,8 +1134,7 @@ impl<'a, C: ControlSource, S: ControlSource> PersonaInbox<'a, C, S> {
|
|||
vec![WearFact::Missing]
|
||||
}
|
||||
};
|
||||
facts.extend(record_wear_facts(organs.mind, &self.repos, open_roots, now));
|
||||
(now, facts)
|
||||
render_wear(now, &facts)
|
||||
}
|
||||
|
||||
/// Her stewarded repos changed by someone else become one notice, at most once in `REPO_READ_EVERY_S`. A read that fails keeps the cursor
|
||||
|
|
@ -1257,53 +1189,20 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
self.note_repo_changes();
|
||||
let mut pending = self.organs.chat.pending(self.progress.acked)?;
|
||||
pending.sort_by_key(|delivery| delivery.seq);
|
||||
if let Some(revision) = &mut self.revision {
|
||||
revision.polls += 1;
|
||||
revision.ready |= revision.polls >= REVISION_POLLS || revision.awaiting.iter().all(|id| pending.iter().any(|delivery| delivery.event_id == *id));
|
||||
}
|
||||
let revision_ready = self.revision_ready();
|
||||
let Some(oldest) = pending.first() else { return Ok(Polled { pending: self.retell.is_some() || revision_ready || !self.notices.is_empty(), yield_now: false }) };
|
||||
let Some(oldest) = pending.first() else { return Ok(Polled { pending: self.retell.is_some() || !self.notices.is_empty(), yield_now: false }) };
|
||||
if Conversation::of(oldest) != self.conversation {
|
||||
return Ok(Polled { pending: false, yield_now: true });
|
||||
}
|
||||
let untold: Vec<ChatDelivery> = pending.into_iter().filter(|delivery| delivery.seq > self.told_through).take_while(|delivery| Conversation::of(delivery) == self.conversation).collect();
|
||||
// A delivery's stagger runs from the poll that first saw it, so a stream of newer messages moves nobody's clock. The line
|
||||
// is told once any delivery in it is due, whole: she is never shown a message and kept from the ones before it.
|
||||
let now = unix_ms(self.organs.clock.now());
|
||||
self.first_seen.retain(|seq, _| *seq > self.told_through);
|
||||
for delivery in &untold {
|
||||
self.first_seen.entry(delivery.seq).or_insert(now);
|
||||
}
|
||||
let due = revision_ready || untold.iter().any(|delivery| now >= self.first_seen[&delivery.seq] + stagger_ms(self.config, delivery));
|
||||
self.waiting = if due { one_line_of(untold, |batch| message_lines(self.config, batch, &self.earlier(batch)).len()) } else { Vec::new() };
|
||||
Ok(Polled { pending: !self.waiting.is_empty() || self.retell.is_some() || revision_ready || !self.notices.is_empty(), yield_now: false })
|
||||
let untold = pending.into_iter().filter(|delivery| delivery.seq > self.told_through).take_while(|delivery| Conversation::of(delivery) == self.conversation).collect();
|
||||
self.waiting = one_line_of(untold, |batch| message_lines(self.config, batch, &self.earlier(batch)).len());
|
||||
Ok(Polled { pending: !self.waiting.is_empty() || self.retell.is_some() || !self.notices.is_empty(), yield_now: false })
|
||||
}
|
||||
|
||||
fn tell(&mut self) -> Result<String> {
|
||||
let notices = std::mem::take(&mut self.notices).concat();
|
||||
if self.revision_ready()
|
||||
&& let Some(revision) = self.revision.take()
|
||||
{
|
||||
// Her refused words are not repeated: she has them. The messages that interrupted her are the line.
|
||||
let waiting = std::mem::take(&mut self.waiting);
|
||||
let line = self.tell_line(&waiting, Some(&stale_note(&revision)), ¬ices);
|
||||
let mut batch = revision.batch;
|
||||
batch.extend(waiting);
|
||||
batch.sort_by_key(|delivery| delivery.seq);
|
||||
batch.dedup_by_key(|delivery| delivery.seq);
|
||||
let input = self.write(batch, line, 0);
|
||||
if let Some(written) = &mut self.written {
|
||||
written.revision = true;
|
||||
}
|
||||
return Ok(input);
|
||||
}
|
||||
if let Some(Retell { batch, why, refusals, revision }) = self.retell.take() {
|
||||
if let Some(Retell { batch, why, refusals }) = self.retell.take() {
|
||||
let line = self.tell_line(&batch, Some(&refused_note(why)), ¬ices);
|
||||
let input = self.write(batch, line, refusals);
|
||||
if let Some(written) = &mut self.written {
|
||||
written.revision = revision;
|
||||
}
|
||||
return Ok(input);
|
||||
return Ok(self.write(batch, line, refusals));
|
||||
}
|
||||
let batch = std::mem::take(&mut self.waiting);
|
||||
let line = self.tell_line(&batch, None, ¬ices);
|
||||
|
|
@ -1312,24 +1211,16 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
|
||||
fn flush_text(&mut self, why: Why) -> String {
|
||||
if self.written.is_none() {
|
||||
self.written = Some(Written { batch: Vec::new(), shown: Shown::default(), refusals: 0, revision: false });
|
||||
self.written = Some(Written { batch: Vec::new(), shown: Shown::default(), refusals: 0 });
|
||||
}
|
||||
self.flush_asked = true;
|
||||
format!("{TURN_REMINDER}\n\n{}", flush_ask(why))
|
||||
}
|
||||
|
||||
fn echoed(&mut self) {
|
||||
if let Some(Written { batch, shown, refusals, revision }) = self.written.take() {
|
||||
if let Some(Written { batch, shown, refusals }) = self.written.take() {
|
||||
self.echoed_refusals = self.echoed_refusals.max(refusals);
|
||||
for delivery in &batch {
|
||||
if self.held.get(&delivery.room_alias).is_none_or(|(seq, _)| *seq < delivery.seq) {
|
||||
self.held.insert(delivery.room_alias.clone(), (delivery.seq, delivery.event_id.clone()));
|
||||
}
|
||||
}
|
||||
self.echoed.extend(batch);
|
||||
self.seen.add(shown);
|
||||
self.echoed_revision |= revision;
|
||||
self.echoed_flush |= std::mem::take(&mut self.flush_asked);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1340,8 +1231,6 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
fn result(&mut self, line: &str, ok: bool, blocked: bool) -> Result<(bool, bool)> {
|
||||
let batch = std::mem::take(&mut self.echoed);
|
||||
let refused_before = std::mem::take(&mut self.echoed_refusals);
|
||||
let revised = std::mem::take(&mut self.echoed_revision);
|
||||
let final_reply = revised | std::mem::take(&mut self.echoed_flush);
|
||||
if blocked || !ok {
|
||||
self.progress.failure.get_or_insert(Failure::Session);
|
||||
return Ok((false, true));
|
||||
|
|
@ -1349,7 +1238,7 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
let turn = self.progress.turn;
|
||||
self.progress.turn += 1;
|
||||
let step = match structured_output(line) {
|
||||
Some(text) => act(self, &batch, turn, &text, Finality { final_reply, revised })?,
|
||||
Some(text) => act(self, &batch, turn, &text)?,
|
||||
None => {
|
||||
self.record_refusal(&batch, turn)?;
|
||||
Step::Refused(Failure::Undecodable)
|
||||
|
|
@ -1364,20 +1253,11 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
// failed (a batch's third refusal leaves no retell to hold the ack back). Deliveries are
|
||||
// told in seq order, so while one is unanswered below an answered seq, everything
|
||||
// answered lies above it and nothing is acked; the ack follows its answer.
|
||||
// Her final answer lands after she took in every line, so a revision still waiting is answered by it and its note, that a send was not sent, would be false.
|
||||
let spent = if final_reply { self.revision.take().map(|revision| revision.batch) } else { None };
|
||||
self.answered_through = self.answered_through.max(batch.iter().chain(spent.iter().flatten()).map(|delivery| delivery.seq).max().unwrap_or(0));
|
||||
self.answered_through = self.answered_through.max(batch.iter().map(|delivery| delivery.seq).max().unwrap_or(0));
|
||||
if self.progress.refused.is_some_and(|refused| batch.iter().any(|delivery| delivery.seq == refused.lowest)) {
|
||||
self.progress.refused = None;
|
||||
}
|
||||
let unanswered = self
|
||||
.retell
|
||||
.iter()
|
||||
.flat_map(|retell| &retell.batch)
|
||||
.chain(self.written.iter().flat_map(|written| &written.batch))
|
||||
.chain(self.revision.iter().flat_map(|revision| &revision.batch))
|
||||
.map(|delivery| delivery.seq)
|
||||
.min();
|
||||
let unanswered = self.retell.iter().flat_map(|retell| &retell.batch).chain(self.written.iter().flat_map(|written| &written.batch)).map(|delivery| delivery.seq).min();
|
||||
let past_unanswered = unanswered.is_some_and(|lowest| lowest <= self.answered_through);
|
||||
if !past_unanswered && self.progress.failure.is_none() && self.answered_through > self.progress.acked {
|
||||
if self.organs.chat.ack(self.answered_through).is_err() {
|
||||
|
|
@ -1397,30 +1277,6 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
self.progress.answered += 1;
|
||||
Ok((true, false))
|
||||
}
|
||||
Step::Stale { room, sent, newer } => {
|
||||
// Not a refused result: no count, no ack, nothing for the retell. The reply answered nothing; its deliveries wait for the revision's answer.
|
||||
let mut revision = self.revision.take().unwrap_or_default();
|
||||
revision.batch.extend(batch);
|
||||
revision.batch.sort_by_key(|delivery| delivery.seq);
|
||||
revision.batch.dedup_by_key(|delivery| delivery.seq);
|
||||
if !revision.rooms.contains(&room) {
|
||||
revision.rooms.push(room);
|
||||
}
|
||||
for sent in sent {
|
||||
if !revision.sent.contains(&sent) {
|
||||
revision.sent.push(sent);
|
||||
}
|
||||
}
|
||||
for id in newer {
|
||||
if !revision.awaiting.contains(&id) {
|
||||
revision.awaiting.push(id);
|
||||
}
|
||||
}
|
||||
revision.polls = 0;
|
||||
revision.ready = false;
|
||||
self.revision = Some(revision);
|
||||
Ok((true, false))
|
||||
}
|
||||
Step::Refused(why) => {
|
||||
let refusals = refused_before + 1;
|
||||
if refusals >= REFUSALS_PER_BATCH {
|
||||
|
|
@ -1429,10 +1285,8 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
}
|
||||
let mut merged = batch;
|
||||
let mut most = refusals;
|
||||
let mut revision = revised;
|
||||
if let Some(waiting) = self.retell.take() {
|
||||
most = most.max(waiting.refusals);
|
||||
revision |= waiting.revision;
|
||||
merged.extend(waiting.batch);
|
||||
}
|
||||
merged.sort_by_key(|delivery| delivery.seq);
|
||||
|
|
@ -1442,7 +1296,7 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
self.progress.refused = merged
|
||||
.first()
|
||||
.map(|first| Refused { lowest: held.map_or(first.seq, |held| held.lowest.min(first.seq)), why, refusals: held.map_or(most, |held| held.refusals.max(most)) });
|
||||
self.retell = Some(Retell { batch: merged, why, refusals: most, revision });
|
||||
self.retell = Some(Retell { batch: merged, why, refusals: most });
|
||||
Ok((true, false))
|
||||
}
|
||||
Step::Failed(why, intent) => {
|
||||
|
|
@ -1454,14 +1308,6 @@ impl<C: ControlSource, S: ControlSource> SessionInbox for PersonaInbox<'_, C, S>
|
|||
}
|
||||
}
|
||||
|
||||
/// What a stale send's revision line opens with. Her refused words are not in it: she has them. Everything else in the reply was
|
||||
/// dropped with it.
|
||||
fn stale_note(revision: &Revision) -> String {
|
||||
let rooms = revision.rooms.join(", ");
|
||||
let sent = if revision.sent.is_empty() { String::new() } else { format!(" Already sent: {}.", revision.sent.join(", ")) };
|
||||
format!("Your message to {rooms} was not sent: newer messages reached that room first, below. Send it, change it, or drop it; your answer goes out as you give it. If someone has already said it, drop it; saying nothing costs nothing.{sent} Nothing else in that reply was kept: repeat any remember, settle or start_self_run you still want.")
|
||||
}
|
||||
|
||||
/// What a refused batch's next line opens with: which field to correct, and that the refused reply did nothing.
|
||||
fn refused_note(why: Failure) -> String {
|
||||
format!("Your last reply was refused ({why}), so nothing in it was said or kept: answer the same messages again, as one reply.")
|
||||
|
|
@ -1474,30 +1320,16 @@ fn structured_output(line: &str) -> Option<String> {
|
|||
}
|
||||
|
||||
impl<C: ControlSource, S: ControlSource> PersonaInbox<'_, C, S> {
|
||||
/// A revision is told once its interrupters have reached the organ and no revision line is in flight: her answer to that line is final and may have said all, so a second note would be told after it landed.
|
||||
fn revision_ready(&self) -> bool {
|
||||
self.revision.as_ref().is_some_and(|revision| revision.ready) && !self.echoed_revision && !self.written.as_ref().is_some_and(|written| written.revision)
|
||||
}
|
||||
|
||||
/// The trace of a result that gave nothing to decode.
|
||||
fn record_refusal(&self, batch: &[ChatDelivery], turn: u32) -> Result<()> {
|
||||
self.organs.trace.record(&TurnTrace { run: label_of(self.run).into(), turn, at: self.organs.clock.now(), inputs: trace_inputs(self.config, batch), outputs: vec![], outcome: format!("failed: {}", Failure::Undecodable) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a reply is her final answer, which goes out with no basis, and whether it answers a revision line, which gives its
|
||||
/// sends their own request ids: the mouth's transaction id is idempotent, so a revised say that reused an id of the same batch
|
||||
/// would return the old event and lose her new words.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Finality {
|
||||
final_reply: bool,
|
||||
revised: bool,
|
||||
}
|
||||
|
||||
/// What one result does in the world: decode, say, remember, settle, start a Self run, and trace.
|
||||
/// It acks nothing: the caller acks after it, once, from what is still unanswered. `batch` is what
|
||||
/// the result answers.
|
||||
fn act<C: ControlSource, S: ControlSource>(inbox: &PersonaInbox<'_, C, S>, batch: &[ChatDelivery], turn: u32, text: &str, finality: Finality) -> Result<Step> {
|
||||
fn act<C: ControlSource, S: ControlSource>(inbox: &PersonaInbox<'_, C, S>, batch: &[ChatDelivery], turn: u32, text: &str) -> Result<Step> {
|
||||
let (organs, config, run) = (inbox.organs, inbox.config, inbox.run);
|
||||
let instance = organs.mind.instance().clone();
|
||||
let (control, swarm) = (inbox.control, inbox.swarm);
|
||||
|
|
@ -1547,22 +1379,11 @@ fn act<C: ControlSource, S: ControlSource>(inbox: &PersonaInbox<'_, C, S>, batch
|
|||
return Ok(Step::Failed(Failure::Held(reason), reply.intent));
|
||||
}
|
||||
let text = say.text.clone();
|
||||
let request_id = if finality.revised { format!("{batch_id}-r{turn}-{index}") } else { format!("{batch_id}-{index}") };
|
||||
let basis = (!finality.final_reply).then(|| SendBasis { seen_event_id: inbox.held.get(&say.room).map(|(_, event)| event.clone()), since_unix_ms: inbox.started_ms });
|
||||
let sent = ChatSendRequest { request_id, persona: instance.0.clone(), room_alias: say.room.clone(), text: text.clone(), basis };
|
||||
match organs.chat.send(&sent) {
|
||||
Ok(receipt) if receipt.refusal.is_none() && receipt.event_id.is_some() => {}
|
||||
Ok(receipt) if receipt.refusal == Some(Refusal::RoomMoved) && !finality.final_reply => {
|
||||
for unsent in &reply.say[index..] {
|
||||
outputs.push(TraceItem { provenance: "her own".into(), room: unsent.room.clone(), text: format!("not sent: {}", unsent.text) });
|
||||
}
|
||||
organs.trace.record(&record(outputs, format!("stale: {}", say.room)))?;
|
||||
return Ok(Step::Stale { room: say.room.clone(), sent: reply.say[..index].iter().map(|sent| sent.room.clone()).collect(), newer: receipt.newer });
|
||||
}
|
||||
_ => {
|
||||
organs.trace.record(&record(outputs, "failed: send".into()))?;
|
||||
return Ok(Step::Failed(Failure::Send, reply.intent));
|
||||
}
|
||||
let sent = ChatSendRequest { request_id: format!("{batch_id}-{index}"), persona: instance.0.clone(), room_alias: say.room.clone(), text: text.clone() };
|
||||
let delivered = organs.chat.send(&sent).is_ok_and(|receipt| receipt.refusal.is_none() && receipt.event_id.is_some());
|
||||
if !delivered {
|
||||
organs.trace.record(&record(outputs, "failed: send".into()))?;
|
||||
return Ok(Step::Failed(Failure::Send, reply.intent));
|
||||
}
|
||||
outputs.push(TraceItem { provenance: "her own".into(), room: say.room.clone(), text });
|
||||
}
|
||||
|
|
@ -1597,38 +1418,6 @@ fn act<C: ControlSource, S: ControlSource>(inbox: &PersonaInbox<'_, C, S>, batch
|
|||
Ok(Step::Answered(started, reply.intent, opened))
|
||||
}
|
||||
|
||||
/// How long after a poll first sees `delivery` a live session is told it: none in a direct message, otherwise her rank times the
|
||||
/// step. The Minds the message names rank first, by a hash of the Mind and the event, and the rest follow them, ranked the same
|
||||
/// way: the first named Mind hears at once, the others one step apart, so tagging several does not make a chorus. A rank is the
|
||||
/// number of Minds in her set whose hash sorts before hers, from the message and the configured Minds alone (the sender, who will
|
||||
/// not be told its own message, is not counted), so every session computes the same order with no word between them and nobody
|
||||
/// is always last.
|
||||
fn stagger_ms(config: &Config, delivery: &ChatDelivery) -> u64 {
|
||||
if delivery.is_direct {
|
||||
return 0;
|
||||
}
|
||||
let mut minds: Vec<&str> = config.minds.iter().map(String::as_str).chain([config.own_sender.as_str()]).filter(|mind| *mind != delivery.sender).collect();
|
||||
minds.sort_unstable();
|
||||
minds.dedup();
|
||||
let named = |mind: &str| delivery.mentions.iter().any(|mention| mention == mind);
|
||||
let (named_minds, others): (Vec<&str>, Vec<&str>) = minds.into_iter().partition(|mind| named(mind));
|
||||
let (set, before) = if named(&config.own_sender) { (&named_minds, 0) } else { (&others, named_minds.len()) };
|
||||
let mine = (stagger_hash(&config.own_sender, &delivery.event_id), config.own_sender.as_str());
|
||||
let rank = before + set.iter().filter(|mind| (stagger_hash(mind, &delivery.event_id), **mind) < mine).count();
|
||||
rank as u64 * STAGGER_STEP_S * 1000
|
||||
}
|
||||
|
||||
/// FNV-1a over the Mind, a separator and the event, then murmur3's finalizer so a Mind's order against another changes from event to
|
||||
/// event (FNV alone leaves it nearly fixed by the Minds' names): fixed by this definition, so every Mind's process computes the same order.
|
||||
fn stagger_hash(mind: &str, event_id: &str) -> u64 {
|
||||
let mut hash = mind.bytes().chain(std::iter::once(0xff)).chain(event_id.bytes()).fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
|
||||
hash ^= hash >> 33;
|
||||
hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
|
||||
hash ^= hash >> 33;
|
||||
hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
|
||||
hash ^ (hash >> 33)
|
||||
}
|
||||
|
||||
/// The oldest deliveries that share a conversation: the public rooms together, or one direct
|
||||
/// message room alone. A prefix by seq, so an ack through its last never passes an unanswered one,
|
||||
/// and one member's DM text never enters another room's turn.
|
||||
|
|
@ -1801,7 +1590,7 @@ fn close_run(organs: &Organs, run: &PipelineRef, answered: u32, last_intent: Opt
|
|||
subject: run.clone(),
|
||||
sequence: next_sequence(organs.mind, run)?,
|
||||
outcome: ResolutionOutcome::Recorded { reason: reason.as_str().into() },
|
||||
rationale: last_intent.map_or_else(|| "The Persona unit's start ended.".to_string(), |intent| format!("Your last intent: {intent}")).as_str().into(),
|
||||
rationale: last_intent.map_or_else(|| "The Persona unit's start ended.".to_string(), |intent| format!("Her last intent: {intent}")).as_str().into(),
|
||||
resolved_on: date(organs.clock.now()),
|
||||
};
|
||||
match organs.mind.admit(AGENT, label_of(run), vec![PipelineDocument::Resolution(resolution)])? {
|
||||
|
|
@ -2062,14 +1851,6 @@ fn render_responsibilities(mind: &dyn MindPort, instance: &Slug, names: &BTreeMa
|
|||
let open = Selection { descending: true, ..in_force(of_kind(PipelineKind::FollowUp)) };
|
||||
let follow_ups = headers(mind, &open)?;
|
||||
let mut dropped = 0;
|
||||
// Every open follow-up counts as open work for its campaign, whether or not the bound below lets its line show.
|
||||
let mut open_roots: Vec<String> = Vec::new();
|
||||
for follow_up in &follow_ups {
|
||||
let campaign = follow_up.id.id.0.split_once(":follow_up:").map_or("", |(campaign, _)| campaign);
|
||||
if !campaign.is_empty() && !open_roots.iter().any(|root| root == campaign) {
|
||||
open_roots.push(campaign.to_owned());
|
||||
}
|
||||
}
|
||||
if !follow_ups.is_empty() {
|
||||
out.push_str("Open follow-ups, newest first:\n");
|
||||
}
|
||||
|
|
@ -2120,7 +1901,7 @@ fn render_responsibilities(mind: &dyn MindPort, instance: &Slug, names: &BTreeMa
|
|||
if dropped_rulings > 0 {
|
||||
out.push_str(&format!("({dropped_rulings} more cited rulings not shown.)\n"));
|
||||
}
|
||||
Ok(Responsibilities { text: out, listed, open: open_ids, people: open_people, repos, open_roots })
|
||||
Ok(Responsibilities { text: out, listed, open: open_ids, people: open_people, repos })
|
||||
}
|
||||
|
||||
/// The responsibilities section, and the ids of the follow-ups and rulings it lists, which recall
|
||||
|
|
@ -2134,8 +1915,6 @@ struct Responsibilities {
|
|||
people: Vec<String>,
|
||||
/// Her stewardships in force, by repo: the only map from her mind to the repos the forge is asked about.
|
||||
repos: Vec<OrgRepo>,
|
||||
/// The campaigns that hold a follow-up in force in her mind, whether or not the bound showed its line.
|
||||
open_roots: Vec<String>,
|
||||
}
|
||||
|
||||
/// Her latest runs with how each ended, one entry each, newest first. A Self
|
||||
|
|
@ -2150,7 +1929,7 @@ fn recent_runs(mind: &dyn MindPort, instance: &Slug) -> Result<Vec<String>> {
|
|||
for run in runs {
|
||||
let PipelineFacts::Run { label, turn, .. } = &run.facts else { continue };
|
||||
let last = last_closing(mind, &run.id)?;
|
||||
let mut line = format!("{} {turn:?}: {}", label.0, last.as_ref().map_or_else(|| "still open".to_string(), |(.., outcome)| outcome_words(outcome)));
|
||||
let mut line = format!("{} {turn:?}: {}", label.0, last.as_ref().map_or_else(|| "open".to_string(), |(.., outcome)| format!("{outcome:?}")));
|
||||
if let Some((_, id, _)) = &last {
|
||||
let one = Selection { keys: Some(vec![id.id.0.clone()]), projection: "document".into(), ..Selection::default() };
|
||||
let PipelinePageItems::Documents(views) = mind.query(&one)?.items else { bail!("the mind answered headers to a document selection") };
|
||||
|
|
@ -2251,22 +2030,17 @@ fn message_line(config: &Config, label: &str, room: &str, sender: &str, display:
|
|||
/// The most of a run's outcome a notice carries.
|
||||
const NOTICE_OUTCOME_MAX: usize = 200;
|
||||
|
||||
/// A closing in plain words: the reason of a Recorded one, and for the others what they point at.
|
||||
fn outcome_words(outcome: &ResolutionOutcome) -> String {
|
||||
match outcome {
|
||||
/// The organ's own line about her work: `role=organ` and no sender, text quoted and cut, so nothing a run wrote can pass for a
|
||||
/// message or write a field.
|
||||
fn notice_line(run: &str, outcome: &ResolutionOutcome, at_unix_ms: u64) -> String {
|
||||
let words = match outcome {
|
||||
ResolutionOutcome::Recorded { reason } => reason.0.clone(),
|
||||
ResolutionOutcome::Withdrawn { reason } => format!("withdrawn: {}", reason.0),
|
||||
ResolutionOutcome::Superseded { by } => format!("superseded by {}", by.iter().map(|by| by.id.0.as_str()).collect::<Vec<_>>().join(", ")),
|
||||
ResolutionOutcome::Answered { by } => format!("answered by {}", by.id.0),
|
||||
ResolutionOutcome::Fixed { commit, .. } => format!("fixed by {}", commit.0),
|
||||
ResolutionOutcome::Deferred { to } => format!("deferred to {}", to.id.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The organ's own line about her work: `role=organ` and no sender, text quoted and cut, so nothing a run wrote can pass for a
|
||||
/// message or write a field.
|
||||
fn notice_line(run: &str, outcome: &ResolutionOutcome, at_unix_ms: u64) -> String {
|
||||
let words = outcome_words(outcome);
|
||||
};
|
||||
let outcome: String = words.chars().take(NOTICE_OUTCOME_MAX).collect();
|
||||
format!("notice role=organ at={} text={}\n", at_text(at_unix_ms), quoted(&format!("Your Self run {run} ended: {outcome}")))
|
||||
}
|
||||
|
|
@ -2392,11 +2166,6 @@ fn repo_notice_line(activity: &RepoActivity, at_unix_ms: u64) -> Option<String>
|
|||
|
||||
/// The most the wear section may take of a first line.
|
||||
const WEAR_MAX_BYTES: usize = 1536;
|
||||
/// A campaign of hers whose newest admission in her mind is this old or older, and which holds an unreported spec, an open Soul
|
||||
/// finding or an open follow-up, is listed as quiet. It decides only what is listed: nothing gates or scores on it.
|
||||
const STALE_AFTER_DAYS: u64 = 14;
|
||||
/// The most entries one listing wear fact names; the rest are counted.
|
||||
const WEAR_LIST_MAX: usize = 4;
|
||||
|
||||
/// A fact about her machine from the forge.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -2405,47 +2174,22 @@ enum WearFact {
|
|||
Missing,
|
||||
/// The read stopped at a repo's page limit: the older entries there were not read.
|
||||
Capped(String),
|
||||
/// A read of her own mind did not answer; `what` says which facts that leaves absent, not zero.
|
||||
RecordsMissing(String),
|
||||
Awaiting { repo: String, number: u32, author: String, at: u64 },
|
||||
/// A repo the anonymous read cannot see, and the repo the forge's redirect names for it when it names one.
|
||||
Unseen { repo: String, redirect: Option<String> },
|
||||
Changed { repo: String, words: String, at: u64 },
|
||||
Yours { repo: String, number: u32, at: u64 },
|
||||
/// Specs in force with no report, on repos she stewards: each spec's record id and the revision's admission, oldest first.
|
||||
SpecsOnYours(Vec<(String, u64)>),
|
||||
/// The same on repos she does not steward: how many in each campaign (by count, largest first), and the oldest spec's record id and admission.
|
||||
SpecsElsewhere { by_campaign: Vec<(String, usize)>, oldest: (String, u64) },
|
||||
/// Open Soul findings in her mind, by campaign of her slice, blocking first, then largest.
|
||||
SoulFindings(Vec<FindingRow>),
|
||||
/// Campaigns of her slice with open work and no admission in her mind for `STALE_AFTER_DAYS`, by newest admission, oldest first.
|
||||
QuietCampaigns(Vec<(String, u64)>),
|
||||
}
|
||||
|
||||
/// One campaign's open Soul findings in her mind: how many, how many block, the oldest admission, and the most severe blocking
|
||||
/// finding's record id and admission (the oldest among equals) when one blocks.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct FindingRow {
|
||||
campaign: String,
|
||||
open: usize,
|
||||
blocking: usize,
|
||||
oldest: u64,
|
||||
worst_blocking: Option<(String, u64)>,
|
||||
}
|
||||
|
||||
impl WearFact {
|
||||
/// The priority order a full section drops from the end of.
|
||||
fn rank(&self) -> u8 {
|
||||
match self {
|
||||
Self::Missing | Self::RecordsMissing(_) | Self::Capped(_) => 0,
|
||||
Self::Missing | Self::Capped(_) => 0,
|
||||
Self::Awaiting { .. } => 1,
|
||||
Self::Unseen { .. } => 2,
|
||||
Self::Changed { .. } => 3,
|
||||
Self::Yours { .. } => 4,
|
||||
Self::SpecsOnYours(_) => 5,
|
||||
Self::SpecsElsewhere { .. } => 6,
|
||||
Self::SoulFindings(_) => 7,
|
||||
Self::QuietCampaigns(_) => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2456,12 +2200,6 @@ fn plain(name: &str) -> String {
|
|||
name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/') { c } else { '?' }).collect()
|
||||
}
|
||||
|
||||
/// A record id as plain tokens: each `:`-separated part goes through `plain`, so an id read from a record cannot carry a line break
|
||||
/// or a field into the section.
|
||||
fn plain_id(id: &str) -> String {
|
||||
id.split(':').map(plain).collect::<Vec<_>>().join(":")
|
||||
}
|
||||
|
||||
/// The facts a first read gives about her repos, in no order (the renderer orders them): PRs waiting on her, repos the forge cannot
|
||||
/// show, others' changes in the last three days, and PRs she has open.
|
||||
fn wear_facts(activity: &RepoActivity, repos: &[OrgRepo], instance: &Slug, now_ms: u64) -> Vec<WearFact> {
|
||||
|
|
@ -2494,148 +2232,6 @@ fn wear_facts(activity: &RepoActivity, repos: &[OrgRepo], instance: &Slug, now_m
|
|||
facts
|
||||
}
|
||||
|
||||
/// The first `WEAR_LIST_MAX` entries joined by `sep`, then what `more` says of the rest, given how many are left and where they begin.
|
||||
fn listed(entries: Vec<String>, sep: &str, more: impl Fn(usize, usize) -> String) -> String {
|
||||
let left = entries.len().saturating_sub(WEAR_LIST_MAX);
|
||||
let mut text = entries.into_iter().take(WEAR_LIST_MAX).collect::<Vec<_>>().join(sep);
|
||||
if left > 0 {
|
||||
text.push_str(sep);
|
||||
text.push_str(&more(left, WEAR_LIST_MAX));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// A spec in force with no report: its record id, its campaign, its repo, and the revision's admission.
|
||||
struct UnreportedSpec {
|
||||
id: String,
|
||||
campaign: String,
|
||||
repo: String,
|
||||
at: u64,
|
||||
}
|
||||
|
||||
/// An instant of the mind's own records, in unix milliseconds; none when it is not one, so a record that cannot be dated makes its
|
||||
/// read missing and never age 0.
|
||||
fn instant_ms(text: &str) -> Option<u64> {
|
||||
u64::try_from(DateTime::parse_from_rfc3339(text).ok()?.timestamp_millis()).ok()
|
||||
}
|
||||
|
||||
/// The campaign (the root of the id) a record of her mind sits under, as a plain token.
|
||||
fn root_label(id: &PipelineRef) -> String {
|
||||
plain(id.id.0.split(':').next().unwrap_or(""))
|
||||
}
|
||||
|
||||
/// Her slice: the roots whose repos in force meet hers (compared by identity, the forge's spelling being case-blind), each with its
|
||||
/// newest admission. None when one cannot be dated.
|
||||
fn slice_of(roots: &[RootTouched], hers: &[String]) -> Option<Vec<(String, u64)>> {
|
||||
roots
|
||||
.iter()
|
||||
.filter(|root| root.repos.iter().any(|repo| hers.contains(&repo.identity())))
|
||||
.map(|root| Some((root.root.0.clone(), instant_ms(&root.admitted_at)?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every spec in force whose cut has no report, from every page.
|
||||
fn unreported_specs(mind: &dyn MindPort) -> Result<Vec<UnreportedSpec>> {
|
||||
let selection = Selection { cited: Some(Incoming { role: "cut_spec".into(), exists: false }), ..in_force(of_kind(PipelineKind::CutSpec)) };
|
||||
let mut specs = Vec::new();
|
||||
for found in headers(mind, &selection)? {
|
||||
let PipelineFacts::CutSpec { repo, .. } = &found.facts else { continue };
|
||||
let at = instant_ms(&found.admission.admitted_at).ok_or_else(|| anyhow!("a spec's admission has no instant"))?;
|
||||
let campaign = root_label(&found.id);
|
||||
specs.push(UnreportedSpec { id: plain_id(&found.id.id.0), campaign, repo: repo.identity(), at });
|
||||
}
|
||||
Ok(specs)
|
||||
}
|
||||
|
||||
/// The Soul findings in force under the roots of her slice, counted by campaign, from every page, blocking campaigns first and then the largest.
|
||||
fn open_soul_findings(mind: &dyn MindPort, slice: &[(String, u64)]) -> Result<Vec<FindingRow>> {
|
||||
let roots: Vec<&str> = slice.iter().map(|(root, _)| root.as_str()).collect();
|
||||
let selection = any_of(any_of(in_force(of_kind(PipelineKind::Finding)), "faculty", &["Soul"]), "root", &roots);
|
||||
let mut rows: BTreeMap<String, FindingRow> = BTreeMap::new();
|
||||
// Each row's held worst blocking finding's severity, as an index into BLOCKING (0 the worst).
|
||||
let mut held_rank: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for found in headers(mind, &selection)? {
|
||||
let PipelineFacts::Finding { severity, .. } = &found.facts else { continue };
|
||||
let at = instant_ms(&found.admission.admitted_at).ok_or_else(|| anyhow!("a finding's admission has no instant"))?;
|
||||
let campaign = root_label(&found.id);
|
||||
let row = rows.entry(campaign.clone()).or_insert(FindingRow { campaign, open: 0, blocking: 0, oldest: at, worst_blocking: None });
|
||||
row.open += 1;
|
||||
row.oldest = row.oldest.min(at);
|
||||
if let Some(rank) = BLOCKING.iter().position(|name| *name == format!("{severity:?}")) {
|
||||
row.blocking += 1;
|
||||
// The page is in admission order, so the first read at the top severity is the oldest at it.
|
||||
if held_rank.get(&row.campaign).is_none_or(|held| rank < *held) {
|
||||
held_rank.insert(row.campaign.clone(), rank);
|
||||
row.worst_blocking = Some((plain_id(&found.id.id.0), at));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut rows: Vec<FindingRow> = rows.into_values().collect();
|
||||
rows.sort_by(|a, b| b.blocking.cmp(&a.blocking).then_with(|| b.open.cmp(&a.open)).then_with(|| a.campaign.cmp(&b.campaign)));
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// The facts her own mind holds about her machine, derived at the first line and written nowhere: her unreported specs (those on
|
||||
/// her repos named, the rest counted), the open Soul findings of her slice, and the campaigns of her slice that have gone quiet.
|
||||
/// Each read walks every page. A read that fails says so in a fact of its own, and so does every fact that needed it; a quiet
|
||||
/// campaign is listed only when all three reads answered.
|
||||
fn record_wear_facts(mind: &dyn MindPort, repos: &[OrgRepo], open_roots: &[String], now_ms: u64) -> Vec<WearFact> {
|
||||
let hers: Vec<String> = repos.iter().map(OrgRepo::identity).collect();
|
||||
let slice = mind.roots_touched().ok().and_then(|roots| slice_of(&roots, &hers));
|
||||
let specs = unreported_specs(mind).ok();
|
||||
let findings = match &slice {
|
||||
None => None,
|
||||
Some(slice) if slice.is_empty() => Some(Vec::new()),
|
||||
Some(slice) => open_soul_findings(mind, slice).ok(),
|
||||
};
|
||||
let mut facts = Vec::new();
|
||||
let missing = |what: &str| WearFact::RecordsMissing(what.to_owned());
|
||||
if slice.is_none() {
|
||||
facts.push(missing("the campaigns of your repos could not be read, so open Soul findings and quiet campaigns are absent"));
|
||||
}
|
||||
if specs.is_none() {
|
||||
facts.push(missing("specs with no report could not be read, so they and quiet campaigns are absent"));
|
||||
}
|
||||
if slice.is_some() && findings.is_none() {
|
||||
facts.push(missing("open Soul findings could not be read, so they and quiet campaigns are absent"));
|
||||
}
|
||||
if let Some(specs) = &specs {
|
||||
let (mut mine, elsewhere): (Vec<&UnreportedSpec>, Vec<&UnreportedSpec>) = specs.iter().partition(|spec| hers.contains(&spec.repo));
|
||||
mine.sort_by_key(|spec| spec.at);
|
||||
if !mine.is_empty() {
|
||||
facts.push(WearFact::SpecsOnYours(mine.iter().map(|spec| (spec.id.clone(), spec.at)).collect()));
|
||||
}
|
||||
if let Some(oldest) = elsewhere.iter().min_by(|a, b| (a.at, &a.id).cmp(&(b.at, &b.id))) {
|
||||
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
for spec in &elsewhere {
|
||||
*counts.entry(spec.campaign.as_str()).or_default() += 1;
|
||||
}
|
||||
let mut by_campaign: Vec<(String, usize)> = counts.into_iter().map(|(campaign, count)| (campaign.to_owned(), count)).collect();
|
||||
by_campaign.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
facts.push(WearFact::SpecsElsewhere { by_campaign, oldest: (oldest.id.clone(), oldest.at) });
|
||||
}
|
||||
}
|
||||
if let Some(rows) = findings.as_ref().filter(|rows| !rows.is_empty()) {
|
||||
facts.push(WearFact::SoulFindings(rows.clone()));
|
||||
}
|
||||
if let (Some(slice), Some(specs), Some(findings)) = (&slice, &specs, &findings) {
|
||||
let mut quiet: Vec<(String, u64)> = slice
|
||||
.iter()
|
||||
.filter(|(root, newest)| {
|
||||
let campaign = plain(root);
|
||||
let open = specs.iter().any(|spec| spec.campaign == campaign) || findings.iter().any(|row| row.campaign == campaign) || open_roots.contains(root);
|
||||
open && now_ms.saturating_sub(*newest) >= STALE_AFTER_DAYS * 86_400_000
|
||||
})
|
||||
.map(|(root, newest)| (plain(root), *newest))
|
||||
.collect();
|
||||
quiet.sort_by_key(|(_, newest)| *newest);
|
||||
if !quiet.is_empty() {
|
||||
facts.push(WearFact::QuietCampaigns(quiet));
|
||||
}
|
||||
}
|
||||
facts
|
||||
}
|
||||
|
||||
/// `(N h)` under a day, `(N d)` from a day on.
|
||||
fn age_text(now_ms: u64, at_ms: u64) -> String {
|
||||
let hours = now_ms.saturating_sub(at_ms) / 3_600_000;
|
||||
|
|
@ -2661,45 +2257,6 @@ fn render_wear(now_ms: u64, facts: &[WearFact]) -> String {
|
|||
WearFact::Unseen { repo, redirect: Some(to) } => format!("- a repo the forge read cannot see: {repo} (the forge redirects it to {to})\n"),
|
||||
WearFact::Changed { repo, words, at } => format!("- changed by others: {repo}: {words} {}\n", age_text(now_ms, *at)),
|
||||
WearFact::Yours { repo, number, at } => format!("- your open PR: {repo}#{number} {}\n", age_text(now_ms, *at)),
|
||||
WearFact::RecordsMissing(what) => format!("- records are missing: {what}.\n"),
|
||||
WearFact::SpecsOnYours(specs) => {
|
||||
let named = specs.iter().map(|(label, at)| format!("{label} {}", age_text(now_ms, *at))).collect();
|
||||
format!("- specs with no report in your mind, on your repos: {}\n", listed(named, ", ", |left, _| format!("+{left} more")))
|
||||
}
|
||||
WearFact::SpecsElsewhere { by_campaign, oldest: (oldest_id, oldest_at) } => {
|
||||
let count: usize = by_campaign.iter().map(|(_, count)| count).sum();
|
||||
let named = by_campaign.iter().map(|(campaign, count)| format!("{campaign} {count}")).collect();
|
||||
let more = |left: usize, from: usize| {
|
||||
let held: usize = by_campaign[from..].iter().map(|(_, count)| count).sum();
|
||||
format!("+{held} more in {left} {}", if left == 1 { "campaign" } else { "campaigns" })
|
||||
};
|
||||
format!(
|
||||
"- specs with no report in your mind, on repos you do not steward: {count} ({}), oldest {oldest_id} {}\n",
|
||||
listed(named, ", ", more),
|
||||
age_text(now_ms, *oldest_at)
|
||||
)
|
||||
}
|
||||
WearFact::SoulFindings(rows) => {
|
||||
let named = rows
|
||||
.iter()
|
||||
.map(|row| match &row.worst_blocking {
|
||||
Some((id, at)) => format!("{} {}, {} blocking, worst {id} {}", row.campaign, row.open, row.blocking, age_text(now_ms, *at)),
|
||||
None => format!("{} {}, {} blocking, oldest {}", row.campaign, row.open, row.blocking, age_text(now_ms, row.oldest)),
|
||||
})
|
||||
.collect();
|
||||
let more = |left: usize, from: usize| {
|
||||
let (held, blocking) = rows[from..].iter().fold((0, 0), |(held, blocking), row| (held + row.open, blocking + row.blocking));
|
||||
format!("+{held} more, {blocking} blocking, in {left} {}", if left == 1 { "campaign" } else { "campaigns" })
|
||||
};
|
||||
format!("- open Soul findings in your mind: {}\n", listed(named, "; ", more))
|
||||
}
|
||||
WearFact::QuietCampaigns(quiet) => {
|
||||
let named = quiet.iter().map(|(campaign, at)| format!("{campaign} {}", age_text(now_ms, *at))).collect();
|
||||
format!(
|
||||
"- campaigns that touch your repos with open work and no admission in your mind for {STALE_AFTER_DAYS} d or more: {}\n",
|
||||
listed(named, ", ", |left, _| format!("+{left} more"))
|
||||
)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// The tail line is "(N more facts not shown)"; keep room for it whenever a fact is dropped.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -17,7 +17,7 @@ use eureka_state::{ClientError, HuginnClient};
|
|||
use huginn_mind::{
|
||||
Faculty, HuginnMindRequest, HuginnMindResponse, PipelineAdmissionBatch,
|
||||
PipelineAdmissionOutcome, PipelineDocumentSummary, PipelineFacts, PipelineProvenance,
|
||||
PipelineSelectionPage, PipelineStatusSummary, RepoActivity, RootTouched, SemanticQuery,
|
||||
PipelineSelectionPage, PipelineStatusSummary, RepoActivity, SemanticQuery,
|
||||
};
|
||||
|
||||
/// The last `CONSECUTIVE` ended runs over an item, all empty, trip its breaker.
|
||||
|
|
@ -46,11 +46,6 @@ pub trait MindPort {
|
|||
fn stewarded_activity(&self, _repos: &[OrgRepo], _after: Option<u64>) -> Result<RepoActivity> {
|
||||
bail!("this mind port has no forge to read")
|
||||
}
|
||||
/// Every root her mind holds a document under, with its newest admission and a campaign's repos in force. A port that does not
|
||||
/// read a mind refuses.
|
||||
fn roots_touched(&self) -> Result<Vec<RootTouched>> {
|
||||
bail!("this mind port has no roots to read")
|
||||
}
|
||||
/// Admits `documents` as one batch, attributed to `agent` in `session`.
|
||||
fn admit(&self, agent: &str, session: &str, documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome>;
|
||||
}
|
||||
|
|
@ -109,15 +104,6 @@ impl MindPort for HuginnMind<'_> {
|
|||
}
|
||||
}
|
||||
|
||||
fn roots_touched(&self) -> Result<Vec<RootTouched>> {
|
||||
let request = HuginnMindRequest::RootsTouched { instance: self.instance().clone() };
|
||||
match (self.call)(request).map_err(|error| anyhow!("the mind could not be asked: {}", client_error_code(&error)))? {
|
||||
HuginnMindResponse::RootsTouched(roots) => Ok(roots),
|
||||
HuginnMindResponse::Refused(_) => bail!("the mind refused the roots read"),
|
||||
_ => bail!("the mind answered a roots read with something else"),
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(&self, agent: &str, session: &str, documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
|
||||
let batch = PipelineAdmissionBatch {
|
||||
instance: self.instance().clone(),
|
||||
|
|
@ -589,38 +575,6 @@ mod tests {
|
|||
assert!(format!("{:#}", port.stewarded_activity(&repos, None).unwrap_err()).contains("something else"));
|
||||
}
|
||||
|
||||
/// The roots ask goes out as the one `RootsTouched` request naming her instance, a real mind's answer comes back whole through
|
||||
/// `HuginnMind` itself, and a refusal, a client error or any other answer is an error that carries nothing of the refusal.
|
||||
#[test]
|
||||
fn a_roots_read_goes_through_the_port_as_one_request() {
|
||||
let mind = TestMind::seeded();
|
||||
let seen = std::cell::RefCell::new(Vec::new());
|
||||
let broken = std::cell::Cell::new(0u8);
|
||||
let port = HuginnMind::over(Slug(INSTANCE.into()), Box::new(|request| {
|
||||
seen.borrow_mut().push(request.clone());
|
||||
match broken.get() {
|
||||
0 => Ok(mind.answer(request)),
|
||||
1 => Ok(HuginnMindResponse::Refused(huginn_mind::MindRefusal::Unavailable { detail: "canary-roots-detail".into() })),
|
||||
2 => Ok(HuginnMindResponse::View(None)),
|
||||
_ => Err(ClientError::Unencodable { detail: "canary-detail".into() }),
|
||||
}
|
||||
}));
|
||||
let roots = port.roots_touched().unwrap();
|
||||
assert_eq!(seen.borrow()[0], HuginnMindRequest::RootsTouched { instance: Slug(INSTANCE.into()) });
|
||||
let campaign = roots.iter().find(|root| root.root.0 == CAMPAIGN).expect("the seeded campaign is a root");
|
||||
assert_eq!(campaign.repos, [OrgRepo::from(REPO)], "the campaign's repos in force come back through the port");
|
||||
assert!(roots.iter().any(|root| root.root.0 == INSTANCE && root.repos.is_empty()), "{roots:?}");
|
||||
|
||||
broken.set(1);
|
||||
let refused = port.roots_touched().unwrap_err();
|
||||
assert!(format!("{refused:#}").contains("refused the roots read") && !format!("{refused:#}").contains("canary"), "{refused:#}");
|
||||
broken.set(2);
|
||||
assert!(format!("{:#}", port.roots_touched().unwrap_err()).contains("something else"));
|
||||
broken.set(3);
|
||||
let down = port.roots_touched().unwrap_err();
|
||||
assert!(format!("{down:#}").contains("could not be asked") && !format!("{down:#}").contains("canary"), "{down:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_of_another_item_are_not_this_items_runs() {
|
||||
|
||||
|
|
|
|||
|
|
@ -357,7 +357,7 @@ fn the_start_message_is_the_first_thing_written_and_names_the_skill_the_instance
|
|||
let ran = go(vec![Out(result_line())]);
|
||||
assert!(matches!(&ran.events[0], Event::Wrote(_)), "the start precedes the first read: {:?}", ran.events[0]);
|
||||
let written = ran.written();
|
||||
for needle in ["Plan usage: five_hour 42.3% allowed, resets at 2026-10-29T20:50:00Z, read at 2026-10-29T20:33Z", "about 90% of the weekly allowance", "nothing enforces it"] {
|
||||
for needle in ["Plan usage: five_hour 42.3% allowed, resets at unix ms 1793307000000", "about 90% of the weekly allowance", "nothing enforces it"] {
|
||||
assert!(written[0].contains(needle), "the lease grant plan windows reach the child: {needle}: {}", written[0]);
|
||||
}
|
||||
for needle in ["Use the eureka skill.", "yggdrasil", "yggdrasil:run:selfrun-a", AGENT] {
|
||||
|
|
@ -1216,7 +1216,7 @@ fn the_start_message_carries_the_claimed_follow_ups_item_and_id_verbatim() {
|
|||
let mind = claiming(std::slice::from_ref(&claim), vec![brief]);
|
||||
let ran = carry_with(&Seen::of(&mind), vec![Out(result_line())], Some(0), false);
|
||||
let first = &ran.written()[0];
|
||||
assert!(first.starts_with(&start_message(&Slug("yggdrasil".into()), &run_ref("selfrun-a"), &[plan_window()], at_start().timestamp_millis() as u64)), "{first}");
|
||||
assert!(first.starts_with(&start_message(&Slug("yggdrasil".into()), &run_ref("selfrun-a"), &[plan_window()], 1_793_306_000_000)), "{first}");
|
||||
for needle in ["Fix the thing.\nThen report \u{e9}.", claim.id.0.as_str(), "Use the eureka skill."] {
|
||||
assert!(first.contains(needle), "{needle}: {first}");
|
||||
}
|
||||
|
|
@ -1278,7 +1278,7 @@ fn a_mind_query_failure_on_a_claim_fails_the_run_with_the_cause_and_starts_no_ch
|
|||
#[test]
|
||||
fn a_run_without_claims_gets_the_identity_lines_alone() {
|
||||
let ran = go(vec![Out(result_line())]);
|
||||
assert_eq!(ran.written()[0], start_message(&Slug("yggdrasil".into()), &run_ref("selfrun-a"), &[plan_window()], at_start().timestamp_millis() as u64));
|
||||
assert_eq!(ran.written()[0], start_message(&Slug("yggdrasil".into()), &run_ref("selfrun-a"), &[plan_window()], 1_793_306_000_000));
|
||||
}
|
||||
|
||||
// ---- the live session -----------------------------------------------------
|
||||
|
|
@ -1376,8 +1376,6 @@ fn a_brief_derived_while_a_turn_runs_is_written_at_once_counted_at_its_echo_and_
|
|||
assert_eq!(told.len(), 1, "{:?}", ran.written());
|
||||
assert!(told[0].contains(&brief_ref("b1").id.0) && told[0].contains("Survey the noise functions."), "{}", told[0]);
|
||||
assert!(told[0].contains("resolve follow-up") && told[0].contains("Recorded"), "she is told how to close it: {}", told[0]);
|
||||
// The plan line is restated under every brief for the run's life, so it names the instant of the reading, never an age that stops being true.
|
||||
assert!(told[0].contains("read at 2026-10-29T20:33Z") && !told[0].contains(" ago"), "{}", told[0]);
|
||||
assert_eq!(ran.written().len(), 2, "the start message and one tell: {:?}", ran.written());
|
||||
assert!(ran.out.contains("decision Write { tells: true, flush: None } prefix 10 ttl_s 0 idle_s working inbox true written 2 consumed 1\n"), "{}", ran.out);
|
||||
assert_eq!(ran.count(&Event::InputClosed), 0);
|
||||
|
|
|
|||
|
|
@ -135,15 +135,10 @@ impl TestMind {
|
|||
|
||||
/// Admits as Hands, one second after the last admission.
|
||||
pub(crate) fn put(&self, documents: Vec<PipelineDocument>) -> PipelineAdmissionOutcome {
|
||||
self.put_as(Faculty::Hands, documents)
|
||||
}
|
||||
|
||||
/// Admits as `faculty`, one second after the last admission.
|
||||
pub(crate) fn put_as(&self, faculty: Faculty, documents: Vec<PipelineDocument>) -> PipelineAdmissionOutcome {
|
||||
self.now.set(self.now.get() + Duration::seconds(1));
|
||||
let batch = PipelineAdmissionBatch {
|
||||
instance: self.instance.clone(),
|
||||
provenance: PipelineProvenance { faculty, agent: "test".into(), session: "test".into(), tool: "test".into() },
|
||||
provenance: PipelineProvenance { faculty: Faculty::Hands, agent: "test".into(), session: "test".into(), tool: "test".into() },
|
||||
documents,
|
||||
};
|
||||
self.mind.borrow_mut().admit(batch, self.now.get())
|
||||
|
|
@ -162,10 +157,6 @@ impl TestMind {
|
|||
Err(refusal) => HuginnMindResponse::Refused(refusal),
|
||||
},
|
||||
HuginnMindRequest::Admit(batch) => HuginnMindResponse::Admit(self.mind.borrow_mut().admit(batch, self.now.get())),
|
||||
HuginnMindRequest::RootsTouched { .. } => match self.mind.borrow().roots_touched() {
|
||||
Ok(roots) => HuginnMindResponse::RootsTouched(roots),
|
||||
Err(refusal) => HuginnMindResponse::Refused(refusal),
|
||||
},
|
||||
other => panic!("the tests ask nothing else: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -216,11 +207,6 @@ impl MindPort for TestMind {
|
|||
Ok(huginn_mind::RepoActivity { head: after.unwrap_or(0), events: vec![], capped: vec![], open_prs: vec![], unseen: vec![], moved: vec![] })
|
||||
}
|
||||
|
||||
/// The roots of this mind as it holds them: the daemon's answer from the same mind, never a stub.
|
||||
fn roots_touched(&self) -> Result<Vec<huginn_mind::RootTouched>> {
|
||||
self.mind.borrow().roots_touched().map_err(|_| anyhow!("refused"))
|
||||
}
|
||||
|
||||
fn admit(&self, agent: &str, session: &str, documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
|
||||
self.now.set(self.now.get() + Duration::seconds(1));
|
||||
let batch = PipelineAdmissionBatch {
|
||||
|
|
@ -309,15 +295,6 @@ pub(crate) fn campaign_named(slug: &str, title: &str) -> PipelineDocument {
|
|||
})
|
||||
}
|
||||
|
||||
/// A campaign opened on `repos`, with its first target and the one invariant.
|
||||
pub(crate) fn campaign_on(slug: &str, repos: &[&str]) -> Vec<PipelineDocument> {
|
||||
let PipelineDocument::Campaign(mut opened) = campaign_named(slug, slug) else { unreachable!("a campaign") };
|
||||
opened.repos = repos.iter().map(|repo| (*repo).into()).collect();
|
||||
let PipelineDocument::Target(mut first) = target() else { unreachable!("a target") };
|
||||
first.campaign = Slug(slug.into());
|
||||
vec![PipelineDocument::Campaign(opened), PipelineDocument::Target(first)]
|
||||
}
|
||||
|
||||
fn target() -> PipelineDocument {
|
||||
PipelineDocument::Target(PipelineTarget {
|
||||
campaign: Slug(CAMPAIGN.into()),
|
||||
|
|
|
|||
|
|
@ -19,8 +19,8 @@ use mind_body::chat_rudp::{RudpChat, connection_id};
|
|||
const ACK_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_ack.v1.msgpack");
|
||||
const PENDING_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_pending.v1.msgpack");
|
||||
const PENDING_REQUEST_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_pending_request.v1.msgpack");
|
||||
const SEND_RECEIPT_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v2/gamecult.persona.chat_send_receipt.v2.sent.msgpack");
|
||||
const SEND_REQUEST_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v2.nil-basis.msgpack");
|
||||
const SEND_RECEIPT_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_send_receipt.v1.msgpack");
|
||||
const SEND_REQUEST_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_send_request.v1.msgpack");
|
||||
|
||||
const KEY: &str = "connection-key-for-test";
|
||||
const TAG: &str = "cultnet.transport.rudp.v0";
|
||||
|
|
@ -62,12 +62,7 @@ fn answer(kind: &str, record_key: &str, payload: &[u8]) -> CultNetMessage {
|
|||
|
||||
/// The mouth of the Persona `eureka`, whose connection id derives from `key`.
|
||||
fn mouth(key: &str) -> Mouth {
|
||||
mouth_at(key, "127.0.0.1:0")
|
||||
}
|
||||
|
||||
/// The same mouth on a chosen address: a restart binds the address the old one held.
|
||||
fn mouth_at(key: &str, bind: &str) -> Mouth {
|
||||
let socket = UdpSocket::bind(bind).unwrap();
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_millis(20))).unwrap();
|
||||
let address = socket.local_addr().unwrap();
|
||||
let mut server = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::server("mouth-test", socket, connection_id(key))).unwrap();
|
||||
|
|
@ -148,32 +143,6 @@ fn a_request_the_mouth_does_not_answer_ends_in_an_error_not_a_hang() {
|
|||
let mouth = mouth(KEY);
|
||||
let chat = client(&mouth, KEY, "someone-else", Duration::from_millis(600));
|
||||
assert!(chat.pending(0).is_err(), "the mouth answers only its own Persona");
|
||||
let sent = ChatSendRequest { request_id: "r".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into(), basis: None };
|
||||
let sent = ChatSendRequest { request_id: "r".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into() };
|
||||
assert!(chat.send(&sent).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_recovers_from_a_restarted_mouth_on_its_next_call() {
|
||||
let first = mouth(KEY);
|
||||
let address = first.address;
|
||||
let chat = client(&first, KEY, "eureka", Duration::from_millis(1500));
|
||||
assert!(chat.pending(0).is_ok());
|
||||
drop(first);
|
||||
let second = mouth_at(KEY, &address.to_string());
|
||||
assert!(chat.pending(0).is_err(), "the restarted mouth ignores a link it never saw: the call times out");
|
||||
assert_eq!(chat.pending(0).unwrap(), chat_client::decode::<ChatPending>(PENDING_BYTES).unwrap().deliveries, "the next call opens a fresh link");
|
||||
assert_eq!(chat.pending(0).unwrap().len(), 1, "and keeps it");
|
||||
let reads = second.seen.lock().unwrap().iter().filter(|(kind, _)| kind == PENDING_REQUEST).count();
|
||||
assert_eq!(reads, 2, "the restarted mouth read the two requests that reached it on a fresh link");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_send_that_timed_out_is_not_repeated_by_the_client() {
|
||||
let mouth = mouth(KEY);
|
||||
let chat = client(&mouth, KEY, "someone-else", Duration::from_millis(600));
|
||||
let sent = ChatSendRequest { request_id: "r-1".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into(), basis: None };
|
||||
assert!(chat.send(&sent).is_err());
|
||||
chat.ack(1).unwrap();
|
||||
let sends: Vec<_> = mouth.seen.lock().unwrap().iter().filter(|(kind, _)| kind == SEND_REQUEST).map(|(_, payload)| chat_client::decode::<ChatSendRequest>(payload).unwrap().request_id).collect();
|
||||
assert_eq!(sends, ["r-1"], "the send reached the mouth once; a repeat is the caller's, under the same request id");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
“¥req-1¥$sentÀ
|
||||
|
|
@ -0,0 +1 @@
|
|||
”¥req-1¦eureka¶#operator:gamecult.org¢hi
|
||||
|
|
@ -1 +0,0 @@
|
|||
”¥req-1À©RoomMoved’¢$a¢$b
|
||||
|
|
@ -1 +0,0 @@
|
|||
”¥req-1¥$sentÀ<74>
|
||||
|
|
@ -1 +0,0 @@
|
|||
払req-1ヲeurekaウ#swarm:gamecult.org「hiタ
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -10,7 +10,7 @@ mind_body: mod persona
|
|||
mind_body: mod queue
|
||||
mind_body: mod self_run
|
||||
mind_body: mod tempo
|
||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Refusal { Brake , PersonaMismatch , UnknownRoom , EmptyText , SendFailed , UnknownPersona , RoomMoved , }
|
||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Refusal { Brake , PersonaMismatch , UnknownRoom , EmptyText , SendFailed , UnknownPersona , }
|
||||
mind_body::chat_client: const ACK : & str
|
||||
mind_body::chat_client: const PENDING : & str
|
||||
mind_body::chat_client: const PENDING_REQUEST : & str
|
||||
|
|
@ -29,10 +29,9 @@ mind_body::chat_client: struct ChatDelivery # [derive (Clone , Debug , PartialEq
|
|||
mind_body::chat_client: struct ChatPending # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, deliveries: Vec < ChatDelivery >]
|
||||
mind_body::chat_client: struct ChatPendingRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, after_seq: u64]
|
||||
mind_body::chat_client: struct ChatRefusal # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, refusal: Refusal]
|
||||
mind_body::chat_client: struct ChatSendReceipt # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, event_id: Option < String >, refusal: Option < Refusal >, newer: Vec < String >]
|
||||
mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String, basis: Option < SendBasis >]
|
||||
mind_body::chat_client: struct ChatSendReceipt # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, event_id: Option < String >, refusal: Option < String >]
|
||||
mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String]
|
||||
mind_body::chat_client: struct ContextLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[sender: String, text: String, at_unix_ms: u64]
|
||||
mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64]
|
||||
mind_body::chat_rudp: fn connection_id (key_file_text : & str) -> u32
|
||||
mind_body::chat_rudp: impl Chat for RudpChat
|
||||
mind_body::chat_rudp: impl Drop for RudpChat
|
||||
|
|
@ -42,7 +41,7 @@ mind_body::chat_rudp: struct RudpChat pub-fields[]
|
|||
mind_body::cli: fn instance_and_endpoint (args : & [String] , env_endpoint : Option < String > , usage : & str) -> Result < (Slug , SocketAddr) >
|
||||
mind_body::cli: fn operator_name (sudo_user : Option < String > , user : Option < String >) -> String
|
||||
mind_body::cli: fn run (args : & [String] , root : & Path , set_by : & str , now : DateTime < Utc > , out : & mut impl Write , stop_units : & mut dyn FnMut (StopScope < '_ >) -> Result < () > ,) -> Result < () >
|
||||
mind_body::connector: fn render_plan (windows : & [PlanQuota] , _now_ms : u64) -> String
|
||||
mind_body::connector: fn render_plan (windows : & [PlanQuota] , now_ms : u64) -> String
|
||||
mind_body::control: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum HeldReason { BrakeAbsent , BrakeHeld , Undecodable , }
|
||||
mind_body::control: # [derive (Debug , PartialEq , Eq)] pub enum Effective { Held { reason : HeldReason } , Released (Grant) , }
|
||||
mind_body::control: # [derive (Debug , PartialEq , Eq)] pub enum SwarmEffective { Held (HeldReason) , Released , }
|
||||
|
|
@ -107,8 +106,8 @@ mind_body::heartbeat: struct Organs< 'a > pub-fields[seats: & 'a [Seat < 'a >],
|
|||
mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[slug: Slug, public_name: String, handle: String, matrix_id: String, huginn: SocketAddr]
|
||||
mind_body::heartbeat: struct PollTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[at: DateTime < Utc >, tempo_s: u32, instances: Vec < InstanceTrace >, launches: Vec < String >]
|
||||
mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat]
|
||||
mind_body::launch: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum StopScope < 'a > { Mind (& 'a Slug) , Swarm , }
|
||||
mind_body::launch: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Declined { Admission (MindRefusal) , Conflict , AlreadyAdmitted , StartFailed , GrantForOtherInstance , PersonaRunTakesNoClaims , }
|
||||
mind_body::launch: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum StopScope < 'a > { Mind (& 'a Slug) , Swarm , }
|
||||
mind_body::launch: # [derive (Clone , Debug , PartialEq , Eq)] pub enum LaunchOutcome { Launched { run : PipelineRef , } , NotQueued { item : PipelineRef , } , Tripped { run : PipelineRef , question : PipelineRef , } , Busy { run : PipelineRef , } , Refused (Declined) , }
|
||||
mind_body::launch: const START_GRACE_S : i64
|
||||
mind_body::launch: fn open_and_launch (ports : & Ports , request : LaunchRequest) -> Result < LaunchOutcome >
|
||||
|
|
@ -181,7 +180,6 @@ mind_body::persona: impl Trace for Noted < '_ >
|
|||
mind_body::persona: impl WearFact
|
||||
mind_body::persona: impl fmt :: Display for Failure
|
||||
mind_body::persona: impl fmt :: Display for Outcome
|
||||
mind_body::persona: impl< 'a , C : ControlSource , S : ControlSource > PersonaInbox < 'a , C , S >
|
||||
mind_body::persona: impl< C : ControlSource , S : ControlSource > PersonaInbox < '_ , C , S >
|
||||
mind_body::persona: impl< C : ControlSource , S : ControlSource > SessionInbox for PersonaInbox < '_ , C , S >
|
||||
mind_body::persona: pub trait PersonaState { fn instructions (& self) -> Result < String > ; }
|
||||
|
|
@ -212,7 +210,7 @@ mind_body::queue: impl HuginnMind < 'static >
|
|||
mind_body::queue: impl HuginnMind < 'static >: fn new (client : HuginnClient) -> Self
|
||||
mind_body::queue: impl MindPort for HuginnMind < '_ >
|
||||
mind_body::queue: impl< 'a > HuginnMind < 'a >
|
||||
mind_body::queue: pub trait MindPort { fn instance (& self) -> & Slug ; fn query (& self , selection : & Selection) -> Result < PipelineSelectionPage > ; fn query_near (& self , _selection : & Selection , _text : & str , _top_k : u32) -> Result < PipelineSelectionPage > { bail ! ("this mind port has no semantic index") } fn stewarded_activity (& self , _repos : & [OrgRepo] , _after : Option < u64 >) -> Result < RepoActivity > { bail ! ("this mind port has no forge to read") } fn roots_touched (& self) -> Result < Vec < RootTouched > > { bail ! ("this mind port has no roots to read") } fn admit (& self , agent : & str , session : & str , documents : Vec < PipelineDocument >) -> Result < PipelineAdmissionOutcome > ; }
|
||||
mind_body::queue: pub trait MindPort { fn instance (& self) -> & Slug ; fn query (& self , selection : & Selection) -> Result < PipelineSelectionPage > ; fn query_near (& self , _selection : & Selection , _text : & str , _top_k : u32) -> Result < PipelineSelectionPage > { bail ! ("this mind port has no semantic index") } fn stewarded_activity (& self , _repos : & [OrgRepo] , _after : Option < u64 >) -> Result < RepoActivity > { bail ! ("this mind port has no forge to read") } fn admit (& self , agent : & str , session : & str , documents : Vec < PipelineDocument >) -> Result < PipelineAdmissionOutcome > ; }
|
||||
mind_body::queue: struct Held # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[]
|
||||
mind_body::queue: struct HuginnMind< 'a > pub-fields[]
|
||||
mind_body::recall: impl Lane
|
||||
|
|
|
|||
|
|
@ -280,7 +280,7 @@ design touches.
|
|||
| `intent` (reply field) | the turn's trace row `<run>-<turn>`; the last of a start goes into that run's closing resolution `<run>` sequence n | written once per answered result; the start's last one rides the run closure; never edited | she writes it; the organ only records and displays it; nothing reads it to decide |
|
||||
| Committed / Asked memories (the "ledger") | `<instance>:memory:<run>-t<turn>-m<i>` (existing) | open until a resolution settles them (done, declined, wrong) or a Self run takes them on (Deferred) | she does, by `settle` / `for_item`; the organ admits |
|
||||
| Idea memories ("curiosities") | same key grammar | recalled by salience and recency; no lifecycle beyond memory's | she does |
|
||||
| Wear facts (repo lines landed with `repo-activity`; record lines are cut `wear-facts`: specs with no report, open Soul findings, quiet campaigns) | not persisted; derived on a session's first line from the daemon's forge read and from records' admission times | recomputed every first line; disappear when the record moves | the organ derives; the forge owns repo facts and the daemon reads it (`stewarded-activity-from-huginn`); her own mind's records own the rest |
|
||||
| Wear facts (later cut: stale items, PRs waiting, specs with no report) | not persisted; derived at render from records' admission times and the forge index | recomputed every turn; disappear when the record moves | the organ derives; Huginn's index owns the repo facts (`stewarded-activity-from-huginn`) |
|
||||
| Persona state `agencyPressure` | `persona_state.v0` field, ids per pressure | edited only by her and her Self through `persona_put`; static since 2026-10-31 [F 4] | hers (`identity-write-all-visible`); harness writes nothing there (`pressure-home-ruled`: pressures are derived at render each turn) |
|
||||
| Persona state `candidateActions` | `persona_state.v0` field | empty for all eight; nothing writes or reads it | dead today; follow-up `candidate-actions-dead-field` |
|
||||
| Flush `Shown` | in-memory per process, `Written` of the flush line | set at the flush write, consumed by the result that answers it | the write that produced the line (section 6) |
|
||||
|
|
@ -340,30 +340,27 @@ Also read rather than run: serde_json has no `preserve_order` in this workspace
|
|||
|
||||
## 9. Cut sequence
|
||||
|
||||
Landed: **flush-shown** and **turn-core-instruction** (87ff30e), then **repo-activity** (545d631,
|
||||
which is the `stewarded-activity` of earlier revisions): the forge owns repo facts; the daemon
|
||||
reads it and answers `StewardedActivity`; a Mind hears of changes on her first line and by one
|
||||
organ notice on change.
|
||||
|
||||
Still to come, in order:
|
||||
|
||||
1. **wear-facts**: what her own mind holds about what she stewards, with ages, on her first line
|
||||
inside the one wear bound: specs with no report, open Soul findings, campaigns with open work
|
||||
gone quiet (`pressures-from-stewardship-state`; derived at render per `pressure-home-ruled`;
|
||||
spec `cut-wear-facts.r2`).
|
||||
2. **wake-room-tail**: the recent tail of her rooms at the head of every session start and wake
|
||||
1. **flush-shown**: a flush written alone records what it shows (spec admitted). Deploys
|
||||
with 2, not before.
|
||||
2. **turn-core-instruction**: the instruction heads a session's first line (every line when written; see the section 3 note), mailbox lines reworded, the
|
||||
question tails it, `intent` first in the reply and shown back through the run closure (spec
|
||||
admitted; depends on 1).
|
||||
3. **wake-room-tail**: the recent tail of her rooms at the head of every session start and wake
|
||||
(ruled; needs an Imagination pass on its owner, Bifrost serving vs the organ reading Matrix,
|
||||
per follow-up `wake-room-tail`).
|
||||
3. **persona-doctrine-paragraph** then **persona-doctrine-set**: persona.md's Persona-turn
|
||||
4. **stewarded-activity**: Huginn serves recent changes and open PRs of her stewarded repos;
|
||||
rendered under "Your machine" (ruled `stewarded-activity-from-huginn`; Imagination pass).
|
||||
5. **persona-doctrine-paragraph** then **persona-doctrine-set**: persona.md's Persona-turn
|
||||
paragraph (Eureka), then the installer's doctrine list drops CLAUDE.md and gamecult.md and
|
||||
pins the skill commit carrying the paragraph (gamecult-ops). Ruled; independent of the others;
|
||||
the body map records a doctrine pin at 5a294ed, so check what remains before cutting.
|
||||
4. **stewardship memories**: each Mind's Self writes her own memories of what she stewards
|
||||
pins the skill commit carrying the paragraph (gamecult-ops). Ruled; independent of 1 and 2.
|
||||
6. **wear-facts**: pressures derived at render from her stewardship state (stale campaign,
|
||||
spec with no report, PR awaiting her review, open findings), with ages
|
||||
(`pressures-from-stewardship-state`; render-each-turn per `pressure-home-ruled`; waits on 4).
|
||||
7. **stewardship memories**: each Mind's Self writes her own memories of what she stewards
|
||||
(`stewardship-as-body` cut 2; Self runs, not code).
|
||||
5. **body-line**: her release, its deploy time and her tools, derived from the unit's install,
|
||||
so a change to her body is visible as recent.
|
||||
6. **persona-card-compact**: render persona state as a compact card instead of 26-29 KB of
|
||||
8. **body-line**: her release, its deploy time and her tools, derived from the unit's install,
|
||||
so a change to her body is visible as recent (after 2).
|
||||
9. **persona-card-compact**: render persona state as a compact card instead of 26-29 KB of
|
||||
pretty JSON (`persona-instructions-size-bound`).
|
||||
|
||||
No speech-nudge cut: the operator ruled facts-only. The last-spoke-per-room fact belongs to
|
||||
**wake-room-tail**, which reads it from the room tail.
|
||||
cut 3, which reads it from the room tail.
|
||||
|
|
|
|||
|
|
@ -1,94 +0,0 @@
|
|||
# Prior art: held read image over an append-only receipt log
|
||||
|
||||
Serves follow-up `eureka-substrate:follow_up:huginn-materialized-image` ("Prior-art pass first: MVCC read views, LMDB/redb read transactions, Datomic database values, event-sourced projections").
|
||||
Served spec: `eureka-substrate:cut_spec:cut-mind-read-floor.r1` (Huginn branch `hands/eureka-substrate-mind-read-floor`).
|
||||
Session: self-2026-11-02-eureka. Eyes pass, 2026-11-03. Facts with pointers, no recommendation.
|
||||
Method note: 22 tool calls; WebFetch returns a small-model digest of each page, not the raw page. Items marked [not stated] were asked for and the page did not say. Kafka Streams primary docs would not load (redirect shell, 404 on raw site source); Kafka facts are from secondary pages plus KIP-1035 (primary). Datomic on-prem pages were fetched; Datomic Cloud architecture page too.
|
||||
|
||||
## Sources
|
||||
- redb design doc: https://raw.githubusercontent.com/cberner/redb/master/docs/design.md
|
||||
- redb README: https://raw.githubusercontent.com/cberner/redb/master/README.md
|
||||
- redb ReadTransaction API: https://docs.rs/redb/latest/redb/struct.ReadTransaction.html
|
||||
- redb src/transactions.rs (first 100,000 of 129,790 chars read; ReadTransaction/begin_read not in that range): https://raw.githubusercontent.com/cberner/redb/master/src/transactions.rs
|
||||
- LMDB lmdb.h: https://raw.githubusercontent.com/LMDB/lmdb/mdb.master/libraries/liblmdb/lmdb.h
|
||||
- Datomic caching/memory index: https://docs.datomic.com/operation/caching.html
|
||||
- Datomic capacity planning: https://docs.datomic.com/operation/capacity.html
|
||||
- Datomic filters (as-of/since/history): https://docs.datomic.com/reference/filters.html
|
||||
- Datomic Cloud architecture: https://docs.datomic.com/whatis/architecture.html
|
||||
- Fowler, Memory Image: https://martinfowler.com/bliki/MemoryImage.html
|
||||
- Kafka KIP-1035: https://cwiki.apache.org/confluence/display/KAFKA/KIP-1035%3A+StateStore+managed+changelog+offsets
|
||||
- Kafka Streams state restore (secondary): https://www.conduktor.io/kafka-streams/state-restore ; https://developer.confluent.io/courses/kafka-streams/stateful-fault-tolerance/ (search snippets only, not fetched)
|
||||
- Kurrent/EventStoreDB persistent subscriptions (search snippet only): https://docs.kurrent.io/clients/grpc/persistent-subscriptions
|
||||
- The spec itself, read via `view` (ordinal 5487).
|
||||
|
||||
## 1. Current-state reads without reading the log
|
||||
|
||||
- redb: current state is the committed B+tree root; the log is not a separate structure. A read txn "make[s] a private copy of the root of the B+tree" (design.md). Tables are copy-on-write B+trees (README). Reads walk the tree; nothing is replayed.
|
||||
- LMDB: "The entire database is exposed in a memory map, and all data fetches return data directly from the mapped memory" (lmdb.h). Readers run lock-free on a multi-versioned structure.
|
||||
- Datomic: four sort-order indexes over all datoms; queries pick one (Cloud page). The current db "does no filtering, so queries about 'now' pay no penalty for history size" (filters page). A query is answered from persistent-index segments plus the local memory index (capacity/caching pages; forum snippet). The log is read for time-only questions, not for entity reads.
|
||||
- Fowler Memory Image: the application holds current state in RAM; events are the persistence; reads never touch the log.
|
||||
- Kafka Streams: reads go to a local state store (RocksDB or in-memory) materialized from a changelog topic; the changelog is read only to restore (secondary sources; KIP-1035 confirms the store/changelog-offset pairing).
|
||||
- EventStoreDB/Kurrent: read models live in a consumer's own storage; the docs' stated best practice is to store the checkpoint "in the same storage" as the projection and project plus checkpoint in one transaction (search snippet of docs.kurrent.io).
|
||||
|
||||
## 2. As-of / snapshot reads and their cost
|
||||
|
||||
- redb: a read txn is a snapshot of the latest committed state at the moment it begins. Writers never modify committed pages; freed pages are reused only "after all read transactions that could reference it have completed" (design.md). Cost of starting one: registers the snapshot; multi-process mode adds locks and cache invalidation on seeing a new txn id; no figure given [not stated]. Arbitrary past points: only via savepoints. Ephemeral savepoint registers as a read txn; persistent savepoint is stored in the system table, survives restart, must be deallocated, and "saves a copy of the page allocator state", estimated "about 64kB per 1GB of values (assuming 4kb pages)". Restore resets the root and queues later-allocated pages for freeing. ReadTransaction is Send and Sync and "may exist concurrently with writes" (docs.rs). The README and docs.rs say nothing on retention cost beyond that.
|
||||
- LMDB: txn id identifies the snapshot. Long readers cost space: "Read transactions prevent reuse of pages freed by newer write transactions, thus the database can grow quickly"; stale readers from aborted programs "cause further writes to grow the database quickly"; reader table default 126 slots, MDB_READERS_FULL on exhaustion; mdb_txn_reset/renew exist to reuse a handle. Snapshots are only of the newest committed state at txn begin; no as-of-past facility in the doc.
|
||||
- Datomic: as-of(t or instant), since, history, filter are filters over the same indexes (filters page, stated as "appear" for as-of). "Filtering is not free"; time-only questions via as-of "would require a filtering scan of the entire database"; entity-plus-time can jump to the entity's datoms in EAVT then drop later datoms. The database value is immutable; caches hold "only immutable data, so all caches are valid forever" (caching page).
|
||||
- Fowler: no as-of facility described; replay from snapshot reconstructs state at the replayed position.
|
||||
- Kafka Streams: stores keep current value per key; no as-of [not stated].
|
||||
|
||||
## 3. RAM vs paged; history outgrowing RAM
|
||||
|
||||
- redb: page cache exists, with a `cache_metrics` feature; size, eviction, and mmap-vs-pread are [not stated] in the docs fetched. Data size is not bounded by RAM; the file is paged. Old versions occupy file space while a reader or persistent savepoint pins them.
|
||||
- LMDB: whole database is mmapped; the OS pages it. Long readers grow the file, not RAM.
|
||||
- Datomic: indexes live in storage, segments (thousands of datoms) cached in a per-process LRU object cache in the app address space (caches page and "competes with your application for available memory"). Datasets can be "much larger than can fit in memory" (Cloud page). Only the memory index (recent, not-yet-indexed novelty) is held in full: transactor default threshold 32m, max 512m; peers may hold up to memory-index-max per connected database. Past the max the transactor "will radically slow the rate at which it processes transactions" (back pressure). A dataset that fits the peer's object cache gives "very fast reads". Whole-history-in-RAM beyond that is not what Datomic does.
|
||||
- Fowler: "Available RAM must exceed the data the application needs in memory"; mitigation suggested is sending each image only the relevant subset of events.
|
||||
- Kafka Streams: stores are RocksDB (disk) or in-memory; the changelog is on the brokers (secondary).
|
||||
|
||||
## 4. Startup / rebuild cost; checkpoints of derived state
|
||||
|
||||
- redb: quick repair on open reads allocator state from a table; if the recovery flag is set, full repair "walking the B+tree from all active roots" grows with database size (design.md); no timings. Read-only opens skip corruption detection.
|
||||
- LMDB: open maps the file; no rebuild.
|
||||
- Datomic: a peer "builds the memory index from the log before the call to connect returns" (caching page): it replays only the log tail since the last index job; the persistent index is the checkpoint. The transactor does the same before serving. Index jobs are background, "mostly serial", adaptive.
|
||||
- Fowler: replay of all events is "too slow in practice"; the system periodically saves snapshots and recovery loads the latest then replays after it; "Writing and loading snapshots is code you have to build yourself." Restore speed must meet quality-of-service targets.
|
||||
- Kafka Streams: restore replays the store's changelog; secondary sources say a checkpoint file records the changelog offset the local store is consistent up to, restore applies the delta from it and falls back to full replay if lost/inconsistent; the checkpoint is written on graceful shutdown under EOS so a hard crash may force full rebuild. KIP-1035: offsets moved from per-task `.checkpoint` files into the store (RocksDB column family, flushed atomically with data) because a separate file cannot be synced atomically with state.
|
||||
- Kurrent: checkpoint stored with the read model in one transaction.
|
||||
|
||||
## 5. Known divergence failure modes of a held projection or index
|
||||
|
||||
- Kafka KIP-1035: offsets in a file separate from the state cannot be atomically synced with the state; under EOS the task state is wiped when flushing is involved; fallback is full changelog replay. Secondary sources: hard crash forces full rebuild.
|
||||
- Datomic: caches are immutable and "valid forever", so object cache cannot diverge; the memory index is kept current by transactor-to-peer notifications, not invalidation. A missing cache layer segment is reloaded from the next layer (Cloud page). Peer failure to receive a notification mode is [not stated].
|
||||
- Kurrent: a checkpoint stored apart from the projection storage cannot give exactly-once; hence the same-transaction advice.
|
||||
- Fowler: events must be processed reliably and the event store must be reliable; concurrency control is yours; event schema changes may require migrating the log; keep events decoupled from model structure.
|
||||
- LMDB/redb: divergence of a derived structure is not their concern; their hazards are pinned old pages from long or stale readers (LMDB explicit; redb by the freeing rule) and, for redb, compaction refused while a read txn is open.
|
||||
|
||||
## Spec versus the prior art
|
||||
|
||||
Same:
|
||||
- RAM-held fold of the whole log, rebuilt by replay at open, serves current-state reads without touching the log: Fowler Memory Image. Spec's "nothing derived persisted" matches Fowler's base form before snapshots are added.
|
||||
- A single writer with a serial loop and no locks: Fowler cites LMAX single writer thread; the spec cites the daemon's serial loop.
|
||||
- Advance per commit in place, rebuild only after a lost swap or store error: Datomic updates its memory index per transaction on transactor and peers and drops it on index completion; Kafka restores only on state loss.
|
||||
- Index structures narrowing candidates, with the real evaluator deciding: Datomic query chooses among four indexes and filters. The spec's postings are narrowing-only (superset) and `select` decides.
|
||||
- Held-versus-fresh equality as a check: Kafka falls back to full replay; the spec's read_back gate compares held image to a fresh fold. No cited system has an equivalent gate in the pages read.
|
||||
- As-of as a filter over current structures rather than a separate stored view: Datomic as-of filters the same indexes and says filtering is not free; the spec keeps rows with ordinals and re-derives status for as_of when status_changed > as_of.
|
||||
|
||||
Differ:
|
||||
- Persistence of derived state: Fowler (snapshots), Datomic (persistent index plus log tail), Kafka (checkpoint plus changelog delta), Kurrent (checkpoint with read model) all persist a checkpoint or index to bound startup. Spec persists none and re-folds all receipts at open (853 ms at her size per the spec's probe). It states a snapshot file would be "a second truth".
|
||||
- Paging: Datomic and the on-disk stores page segments; Fowler requires RAM above data size. Spec holds all decoded rows, postings and closers in RAM (RSS 637 MB at base; accepted bound is "at or below base"); no paging path in the spec, and 10x tests are in the acceptance table.
|
||||
- Snapshot reads: redb and LMDB give a snapshot of the newest committed state at txn begin and pin pages while open; the spec has one image at head and an `as_of` ordinal filter, and the daemon is serial so no concurrent reader holds a snapshot. Datomic's as-of is a filter over indexes; the spec's is a visibility filter plus status rebuild for rows whose status changed after as_of.
|
||||
- Status at as_of: Datomic as-of filters datoms uniformly. The spec's rows carry derived status that depends on later resolutions, so it carries `status_changed` and a patched arena; no cited system's page describes this mechanism.
|
||||
- Postings narrow only when as_of == head for status aliases (InForce, Ran); Datomic indexes are time-agnostic and filtered after.
|
||||
- Atomicity of derived state and its position: Kafka's KIP-1035 and Kurrent put checkpoint offset and state in one atomic unit. In the spec the image's head is derived in the same fold as its rows and nothing is persisted, so the question does not arise on disk; the in-memory advance after a landed CAS that fails mid-fold calls refresh.
|
||||
- Whole-image rebuild on lost swap: the spec rebuilds fully (126-145 ms per base probe); Datomic and Kafka apply deltas or tail.
|
||||
- Back pressure: Datomic throttles the writer when the memory index outgrows its max; the spec has no such bound on held state.
|
||||
|
||||
## redb read transactions: does MVCC already give the snapshot the spec builds?
|
||||
|
||||
Facts only.
|
||||
- redb's read txn gives a consistent point-in-time view of the stored tables at the newest commit when begun, usable concurrently with writes, with pages pinned until dropped (design.md; docs.rs).
|
||||
- What it hands out is the stored tables: receipts and document envelopes as bytes. It holds no decoded rows, status, postings, closers or citers; the spec's costs (351 ms receipt decode, 807 ms Reader::at, 512 ms rows at base) are derivation over those bytes, none of which redb's snapshot stores [from the spec's probe figures].
|
||||
- A redb txn is a snapshot at one commit, the newest at begin time; reads at earlier commits need savepoints (persistent ones are stored in the file with an allocator-state copy, about 64 kB per 1 GB of values). The spec's `as_of` is a receipt ordinal; redb's snapshots are not addressed by receipt ordinal.
|
||||
- The spec's store is accessed via a CAS store trait (`store.rs`, MemoryStore CAS, compare_and_swap_batch); whether redb's read txn is reachable through that trait was not examined here (Huginn checkout not touched).
|
||||
- The spec's stated reason for no MVCC layer is the daemon's serial loop (`keeps_moves`: "no RwLock, Arc or MVCC layer is added"). Whether the daemon ever holds a read during a write was not examined.
|
||||
- Not stated in sources read: redb read-txn start cost, page-cache size/eviction, whether open readers affect file growth the way LMDB documents.
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
# Persona projector facts (Eyes, read only, 2026-11-03)
|
||||
|
||||
## Part 1: the empty vector
|
||||
|
||||
Read via the eureka-state MCP stdio binary pointed at each daemon (HUGINN_ENDPOINT rudp://10.77.0.1:1787x, EUREKA_INSTANCE=slug; persona_get only). Raw: scratchpad `pers\<mind>.raw`, parsed `pers\<mind>.json`; scripts `pg.py`, `an.py`.
|
||||
|
||||
All 8 Minds have the identical shape. Every one: receipt updated_at 2026-10-31T09:00:01Z; provenance {authority canonical, sourceSystem huginn, sourceDocumentId = slug, sourceUpdatedAt = exportedAt 2026-10-31T09:00:01Z}; 14 top-level keys; compact value 19.6-26 KB (eureka 24.2, libby 19.6, heimdall 20.1, kiko 21.6, aqua 22.3, weksa 20.7, nibu 20.7, void 21.7).
|
||||
- EMPTY in all 8: activationProfile (six empty objects: behavioralDimensions, presentationStrategy, situationalState, stableDispositions, underlyingOrganization, voiceStyle; 143 B); affect.moodDimensions [], affect.needs [], affect.socialBiases [], affect.statusReads [], affect.doctrineStances []; candidateActions.actions []; thoughtMemory.shortTerm [], thoughtMemory.incubation [].
|
||||
- POPULATED in all 8: affect.socialBonds (9 each, ~5.7-6.4 KB, the largest block; prose "summary" plus trust/tension numbers and extensions{numbersAreUnsourcedDefaults:true}); agencyPressure.pressures (7-8, 3.5-4.5 KB); thoughtMemory.memories (5-7, 3.3-5 KB); privateNotes (10-20 strings, 2.2-5.1 KB); values (7-11, 2.4-3.4 KB); presentation (voiceSummary, jurisdiction, homeContext, pronouns, publicHandles, defaultRenderer; 0.6-1 KB); publicName, publicDescription.
|
||||
- Void: voiceSummary "Lofty and wry, from a great height..."; 5 memories, 8 pressures, 9 bonds, 8 values, 17 private notes; vector empty like the rest.
|
||||
|
||||
Where were values last non-empty:
|
||||
- Not for the Minds. Ruling `eureka-body:ruling:persona-workshop-from-lore-and-journeys` (2026-10-30): swarm Persona states are "drafted fresh" from lore, operator words, repo journey narratives; "VoidBot's Discord-era Persona states are not used (discord-taints-training)". Ruling `eureka-body:ruling:persona-workshop-unbraked` (2026-10-31): "All eight Personas were written from the workshop cards plus the operator's verdict notes into each Mind's own Huginn, with a relationship grid Self extrapolated for all 28 pairs". Follow-up `eureka-body:follow_up:persona-seed-at-bring-up`: "all eight Minds hold a persona with one identical updatedAt that no committed step produced" (no tracked seeding script; writer was a hand persona_put). Workshop card files were not found in the Eureka skill repo, gamecult-ops or Huginn docs by my greps (not exhaustive).
|
||||
- Eureka's earlier persona (updated 2026-10-29T19:20Z) already had "activationProfile empty" (Huginn/docs/research/2026-10-30-mind-inheritance-prior-art.md:51). So the vector was empty before the 10-31 write.
|
||||
- Schema: `Huginn/schemas/cultnet/gamecult.persona_state.v0.schema.json` activationProfile is a $ref to six trait maps; VoidBot zod (packages/core/src/persona-state-domain.ts:30-48,74): each trait {mean, plasticity, currentActivation} in 0..1; moodDimensions [{name, value 0..1, source?, updatedAt}]. Huginn test seed (crates/huginn-mind/src/persona.rs:193,198) builds `"activationProfile": traits`, `"moodDimensions": []`.
|
||||
- VoidBot's old Void store: `.voidbot/private/void-self-state.cc` (named in scripts/simulate-void-mood.mjs at 04dc8e3^). On disk `F:\Projects\VoidBot\.voidbot\` holds only `logs\`; no .cc found, so no old values are quotable here. VoidBot's blank-profile seed (packages/core/src/void-self-state-projection.ts:88-95) writes six `{}`, and `moodDimensions: []` (line 143); activationProfile entered the typed model via legacy-state projection at 77ea82f (2026-05-16, readActivationCategory). A mood-drift runner (scripts/run-void-mood-drift.ps1, simulate-void-mood.mjs 400 lines) existed until 04dc8e3 "Delete local Void mood and memory runners" (2026-07-16); physiology moved into the daemon at 15a7c58 and still reads `faceAffect.moodDimensions` (apps/persona-scheduler/src/void-physiology-domain.ts:88; names anger, annoyance, irritation, envy, pride, smugness, playfulness, anxiety, commandForce). VoidBot's friendly export maps `personality: mapActivationProfile(profile.activationProfile)` (scripts/export-persona-friendly-input.ts:139) and mood at :152.
|
||||
- Whether Void's VoidBot-era vector held values before July: not determinable from what is on disk.
|
||||
- Writers today: cut spec r4 (`eureka-substrate:cut_spec:cut-doctrine-persona-in-huginn.r4`): "Writers today are persona_put on the eureka-state MCP and HuginnClient::persona_put in Rust; the huginn CLI has no persona verb ... no organ writes it." Her Persona turn "may rewrite any field (ruling identity-write-all-visible) once it has a write path; it has none yet." I ran no persona_put. Follow-up `eureka-body:follow_up:huginn-cli-persona-verbs`. Follow-up `weksa-lowering:follow_up:persona-state-speech-community` notes the standard has open trait maps and moodDimensions but no speech-community field.
|
||||
|
||||
## Part 2: projectors
|
||||
|
||||
### Huginn today
|
||||
`F:\Projects\Huginn\crates\mind-body\src\persona.rs:367-370` (HEAD 577cae2): `render_instructions` = fixed line "You are the persona whose state follows. Speak and act as it, in your own voice." + `serde_json::to_string_pretty(state)`; no field selection, no omission. Called from the persona fetch (line ~360) when a turn loads her instructions. Pretty JSON adds whitespace over the compact sizes above.
|
||||
|
||||
### VoidBot standard projector
|
||||
`F:\Projects\VoidBot\apps\persona-scheduler\src\persona-standard-state-projector.ts` (4,204 B, one function `projectGamecultPersonaState(identity, state)`):
|
||||
- Pure template, no model. Lines: "<name> is a native VoidBot Persona, not a repo Face."; authority line (canonical vs non-canonical projection); avatar URL/path; publicDescription; then bulleted lists, cap 12 each: Private notes, Values (label: summary), Activation traits (reads profile.activationTraits, a key the schema does not have), Memories, Short-term residue, Agency pressure, Affect needs, Social bonds, Doctrine stances.
|
||||
- Per field it takes the first of summary/claim/description/text/label/id/name; all numbers (trust, tension, intensity, priority, mean/plasticity/currentActivation, moodDimensions values) are dropped. OMITS: activationProfile, moodDimensions, socialBiases, statusReads, candidateActions, presentation (voiceSummary, jurisdiction, pronouns, handles, homeContext), provenance detail, ids, timestamps, extensions.
|
||||
- No sample output found or run (read only).
|
||||
- Richer per-turn path: persona-state-packet-projector.ts (2,203 B) -> persona-memory-projector.ts (`renderPersonaTypedStateSections`, `renderPersonaPressureSections`, `composePersonaMemoryPacket`), persona-social-context-projector.ts, persona-conversation-projector.ts (14.9 KB), persona-turn-prompt-projector.ts (12.4 KB), plus curiosity, relative-chronology, repo-activity projectors. Typed-state affect (packages/core/src/void-self-state-projection.ts ~300-340): top 4 needs, 4 active bonds, 4 status reads by intensity, top 8 moodDimensions by value; if all empty: "- What <name> feels and wants: no explicit affect state yet." Needs render as "Need/<kind> for <target> (<status>, <intensity 2dp>): summary / claim / What rubs / What it wants next". Template plus truncation, numbers printed to 2 dp; not numeric-to-words, not model inference.
|
||||
- Runs in the scheduler per persona turn (persona-turn-assembler.ts); no cache seen in the files read. Yggdrasil runs no VoidBot persona scheduler (Soul finding `eureka-substrate:finding:cut-doctrine-persona-in-huginn.s1.voidbot-path-not-live`: "voidbot.service swarm publisher and voidbot-retrieval only").
|
||||
- Recorded lessons on what prose gained or lost: none located (grep of VoidBot notes/docs/state for activationProfile/moodDimensions found only state/map.yaml:156 on Face affect). Git-commit bodies not read.
|
||||
|
||||
### Ghostlight
|
||||
- Design doc `F:\Projects\Ghostlight\docs\architecture\agent-state-distributions-and-prompt-projection.md` (12.6 KB): canonical latent state / perceived state / prompt projection; "Prompt rendering should be treated as projection, not storage"; projection sections Identity And Role, Cultural Default Frame, Current Presentation Strategy, Current Situation, Relationship Context, Relevant Memory, Goals And Constraints, Listener Model; "What The Prompt Should Not Do": not the sole store, not a full memory dump, not "a taxonomy recital", not omniscient; "compact, selective, and scene-bound". Its six state families (Underlying Organization, Stable Dispositions, Behavioral Dimensions, Presentation Strategy, Voice Style, Situational State) are the activationProfile categories.
|
||||
- Built shape: `docs/architecture/ghostlight-dungeon-mvp.md:324-340` (Projector-Persona-Interpreter membrane). Deterministic code builds a permissioned `SubjectView` (occupancy, knowledge, memories, relationships, pressures, boundaries, executable affordances; private views omit unavailable facts by construction). The Projector is a MODEL organ: receives the view and stimulus, emits "one lived narrative stream: perception, memory, uncertainty, desire, bodily circumstance" in prose, cannot choose an action or emit schema. The Persona sees only identity guidance plus that narrative: no field names, IDs, JSON, tool definitions. Prose is "private derived context, not world truth". Config `GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL` (:479); receipts bind state digest + Projector receipt (:366); membrane has its own behavioral evaluation (:621): replacement by a tool-using agent must show no regression in "voice, embodiment, uncertainty, tonal range, schema leakage, tool-shaped diction"; until then narrative Personas stay prose-only.
|
||||
- Not located: the Rust Projector implementation file (crates/ghostlight/src/controllers.rs is 18k+ lines, not traced), sample outputs, before/after sizes, per-turn vs cached timing.
|
||||
|
||||
### Where the standard says the projection path moves
|
||||
- Operator ruling `eureka-body:ruling:voidbot-retired` (2026-10-22): "The Persona State Standard's read/projection owner moves to Huginn." Follow-up `eureka-body:follow_up:voidbot-retirement` (in force; waits on huginn-prose-index): "Move the Persona State Standard's read/projection/migration path to Huginn".
|
||||
- The checkout F:\Projects\gamecult-ops\docs\persona-state-standard.md still says VoidBot owns read, projection, migration and "no agent should route Persona-state work to Huginn". Cut spec r4 (InForce 2026-11-01) rewrites it: Huginn holds each Mind's canonical state; "VoidBot keeps projection and repo Personas". Cut report `eureka-substrate:cut_report:cut-doctrine-persona-in-huginn.h2` exists; whether it landed on origin was not checked. The ruling and r4 differ on who keeps projection.
|
||||
|
||||
### Mind rulings (huginn query --near, no campaign filter; 14,907 docs; 8-row pages)
|
||||
- `eureka-body:ruling:memory-persona-projection` (2026-10-10): Persona state canonical for lessons; MEMORY.md and files generated from it, provenance projection. File projection, not prompt prose.
|
||||
- `eureka-body:ruling:persona-doctrine-set-ruled`: a Persona turn loads colossus.md and persona.md only. `eureka-body:ruling:persona-session-landed`: leased claude session, result decoded into typed PersonaReply.
|
||||
- No ruling or follow-up found on prose projection of Persona state for the prompt, on `render_instructions`, or on populating activationProfile/moodDimensions.
|
||||
|
||||
## Gaps
|
||||
No persona_put done. Ghostlight Projector code, sample outputs, token counts before/after unknown. Workshop card files not found. Void's pre-July VoidBot values not recoverable on this machine.
|
||||
|
|
@ -193,27 +193,6 @@
|
|||
"required": [
|
||||
"StewardedActivity"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Every root the mind holds a document under, with its newest admission and a campaign's repos in force: the mind's own\nrecords, one pass at the head.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"RootsTouched": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"instance": {
|
||||
"$ref": "#/$defs/Slug"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"instance"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"RootsTouched"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$defs": {
|
||||
|
|
|
|||
|
|
@ -125,21 +125,6 @@
|
|||
"Activity"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"RootsTouched": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/RootTouched"
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"RootsTouched"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "The answer did not fit one send and is being held for the client to\nfetch. Nothing in a mind produces this: the daemon's serve module does,\nin place of an answer, and the answer it stands for is the named\nMessagePack of the `HuginnMindResponse` the mind gave.",
|
||||
"type": "object",
|
||||
|
|
@ -4667,35 +4652,6 @@
|
|||
}
|
||||
]
|
||||
},
|
||||
"RootTouched": {
|
||||
"description": "A root of the mind and the newest admission under it. `repos` is the repo set in force of a root that is an in-force campaign,\nand empty for any other root.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admitted_at": {
|
||||
"type": "string"
|
||||
},
|
||||
"ordinal": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 1
|
||||
},
|
||||
"repos": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/OrgRepo"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"$ref": "#/$defs/Slug"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"root",
|
||||
"admitted_at",
|
||||
"ordinal",
|
||||
"repos"
|
||||
]
|
||||
},
|
||||
"RulingAuthority": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
|
|
|
|||
Loading…
Reference in a new issue