diff --git a/core/continuum-cognition/Cargo.toml b/core/continuum-cognition/Cargo.toml index df3aad97aa..1bdbcdfe98 100644 --- a/core/continuum-cognition/Cargo.toml +++ b/core/continuum-cognition/Cargo.toml @@ -81,7 +81,7 @@ default = [] metal = ["continuum-engine/metal", "continuum-live/metal", "continuum-genome/metal"] cuda = ["continuum-kernel/cuda", "continuum-engine/cuda", "continuum-genome/cuda"] vulkan = ["continuum-kernel/vulkan", "continuum-engine/vulkan", "continuum-genome/vulkan"] -stress-tests = ["continuum-kernel/stress-tests", "continuum-genome/stress-tests"] +stress-tests = ["continuum-kernel/stress-tests"] # Test-only code (fixtures shared with core's integration tests, the heuristic adapter it # drives); production binaries never build with it. test-fixtures = ["continuum-base/test-fixtures", "continuum-kernel/test-fixtures", "continuum-engine/test-fixtures", "continuum-hands/test-fixtures", "continuum-live/test-fixtures", "continuum-perception/test-fixtures", "continuum-genome/test-fixtures", "continuum-experience/test-fixtures"] diff --git a/core/continuum-cognition/src/cognition/eval/gene_exam.rs b/core/continuum-cognition/src/cognition/eval/gene_exam.rs index a664fc836f..32b6a9ad6f 100644 --- a/core/continuum-cognition/src/cognition/eval/gene_exam.rs +++ b/core/continuum-cognition/src/cognition/eval/gene_exam.rs @@ -55,8 +55,20 @@ impl ExamHost for MindExamHost { exam.base_model_id, serving.active_model ))); } - let her_genome = crate::genome::gene_trial::live_genes(exam.persona) - .ok_or_else(|| not_now("her genome could not be read".into()))?; + // Her genome for the sitting: every gene she may run, at its trained scale (the + // composer weighs them per turn by distance; the exam holds them fixed so the only + // difference between the arms is the gene). + let her_genome: Vec = crate::genome::gene_trial::GeneTrials::default_store() + .ok_or_else(|| not_now("no continuum home: her genome could not be read".into()))? + .load() + .map_err(|e| not_now(format!("her genome could not be read: {e}"))) + .map(|trials| { + crate::genome::gene_trial::her_genes(&trials, exam.persona, &exam.base_model_id) + .into_iter() + .filter(|(_, standing)| standing.may_run()) + .map(|(gene, _)| gene) + .collect() + })?; let (without, with) = two_genomes(&her_genome, &exam.gene); let tag = format!("gene-exam-{}", Uuid::new_v4()); diff --git a/core/continuum-cognition/src/cognition/recall_faculty.rs b/core/continuum-cognition/src/cognition/recall_faculty.rs index dfbef7f9af..e979aad692 100644 --- a/core/continuum-cognition/src/cognition/recall_faculty.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty.rs @@ -159,7 +159,7 @@ pub const DEFAULT_RELEVANCE_WEIGHT: f32 = 0.5; /// only the question). The rule is bracket-tag GRAMMAR — a line starting /// with `[` is an annotation unless it is a `[t=…]` message stamp — never /// content inspection. -fn focused_query(world_state: &str) -> &str { +pub fn focused_query(world_state: &str) -> &str { let line = world_state .lines() .map(str::trim) diff --git a/core/continuum-cognition/src/cognition/workspace.rs b/core/continuum-cognition/src/cognition/workspace.rs index c9e9f4e4d0..2182943092 100644 --- a/core/continuum-cognition/src/cognition/workspace.rs +++ b/core/continuum-cognition/src/cognition/workspace.rs @@ -42,8 +42,6 @@ pub use cause::*; mod arbiter; pub use arbiter::*; mod workspace_cycle; -mod genome_restore; -pub use genome_restore::GenomeRestore; mod workspace_cycle_2; #[cfg(test)] diff --git a/core/continuum-cognition/src/cognition/workspace/genome_restore.rs b/core/continuum-cognition/src/cognition/workspace/genome_restore.rs deleted file mode 100644 index 6c41745f60..0000000000 --- a/core/continuum-cognition/src/cognition/workspace/genome_restore.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! The guard that puts a cycle's genome back after a turn. It belongs to the cycle (it reads -//! and pages the cycle's own genome), so it lives with the workspace; the genome decides -//! which genes a turn runs with (`genome::gene_trial::live_genes`) and never names the cycle. - -use super::*; - -/// Puts her genome back when a work turn ends, however it ends: the snapshot taken before -/// the turn by default, or her promoted genome when the turn got far enough to say so. -/// Restores on drop, so a cancelled or unwinding turn cannot leave a trial gene on her -/// cycle for the conversation turns that follow. -pub struct GenomeRestore { - cycle: Arc, - to: Vec, -} - -impl GenomeRestore { - pub fn snapshot(cycle: Arc) -> Self { - let to = cycle.genome(); - Self { cycle, to } - } - - pub fn restore_to(&mut self, genes: Vec) { - self.to = genes; - } -} - -impl Drop for GenomeRestore { - fn drop(&mut self) { - self.cycle.page_in(std::mem::take(&mut self.to)); - } -} diff --git a/core/continuum-core/src/commands/cognition/genome_activate_skill.rs b/core/continuum-core/src/commands/cognition/genome_activate_skill.rs deleted file mode 100644 index 7163fabbbd..0000000000 --- a/core/continuum-core/src/commands/cognition/genome_activate_skill.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! `cognition/genome-activate-skill` — page a skill's LoRA adapter into the persona's -//! genome, evicting LRU under budget (typed, dep-holding). -//! -//! Drives the [`GenomePagingEngine`](crate::persona::genome_paging) virtual-memory -//! layer: ensures the named skill's adapter is resident, evicting the least-recently-used -//! adapters if the (GPU-detected or caller-supplied) memory budget would be exceeded. -//! Reuses the engine's [`ActivateSkillResult`] as the output. Captures the owning -//! module's [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; -use crate::persona::genome_paging::ActivateSkillResult; -use crate::sdk_codegen::CommandError; - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeActivateSkillParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeActivateSkillParams { - /// Persona whose genome pages in the skill. - #[ts(type = "string")] - pub persona_id: Uuid, - /// Skill/domain to activate (e.g. "typescript-expertise"). - pub skill_name: String, - /// Memory budget in MB; 0 or omitted uses the GPU-detected per-persona budget. - #[serde(default)] - #[ts(type = "number")] - pub memory_budget_mb: f32, -} - -crate::action_command! { - /// Page the named skill's LoRA adapter into the persona's genome, evicting LRU - /// adapters if the memory budget would be exceeded. Host-invoked. - pub struct GenomeActivateSkill { state: Arc } - name: "cognition/genome-activate-skill", - access: Internal, - params: GenomeActivateSkillParams, - output: ActivateSkillResult, - run(this, _ctx, p) => { - let memory_budget_mb = if p.memory_budget_mb > 0.0 { - p.memory_budget_mb - } else { - this.state.per_persona_budget_mb() - }; - let now_ms = continuum_base::time::EpochMs::read().map_err(|e| CommandError::Internal(format!("system clock before UNIX epoch: {e}")))?.millis(); - - let mut persona = this.state.get_or_create_persona(p.persona_id); - persona.genome_engine.memory_budget_mb = memory_budget_mb; - let result = persona.genome_engine.activate_skill(&p.skill_name, now_ms); - - crate::log_info!( - "module", - "cognition", - "genome-activate-skill {}: {} activated={}, evicted={:?}, to_load={:?} ({:.0}μs)", - p.persona_id, - p.skill_name, - result.activated, - result.evicted, - result.to_load, - result.decision_time_us - ); - - Ok(result) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. genome-activate-skill is host-driven - // cognition IPC, so it is Internal — registered and grid-routable, never a - // remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!(GenomeActivateSkill::NAME, "cognition/genome-activate-skill"); - assert_eq!(GenomeActivateSkill::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/commands/cognition/genome_coverage_report.rs b/core/continuum-core/src/commands/cognition/genome_coverage_report.rs deleted file mode 100644 index c57b308a87..0000000000 --- a/core/continuum-core/src/commands/cognition/genome_coverage_report.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! `cognition/genome-coverage-report` — which skill domains the persona covers vs. gaps -//! (typed, dep-holding). -//! -//! Non-mutating read of the [`GenomePagingEngine`](crate::persona::genome_paging)'s -//! domain-activity ledger: the covered domains, the gaps (domains seen but not yet -//! backed by an adapter), and the coverage ratio — the signal a gap-driven sentinel -//! reads to decide what to train next. Reuses the engine's [`CoverageReport`] as the -//! output. Captures the owning module's -//! [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; -use crate::persona::genome_paging::CoverageReport; -use crate::sdk_codegen::CommandError; - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeCoverageReportParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeCoverageReportParams { - /// Persona whose coverage ledger is read. - #[ts(type = "string")] - pub persona_id: Uuid, -} - -crate::action_command! { - /// Report the persona's skill-domain coverage (covered domains, gaps, ratio) — - /// the signal for gap-driven training. Non-mutating. Host-invoked. - pub struct GenomeCoverageReport { state: Arc } - name: "cognition/genome-coverage-report", - access: Internal, - params: GenomeCoverageReportParams, - output: CoverageReport, - run(this, _ctx, p) => { - let persona = this - .state - .personas - .get(&p.persona_id) - .ok_or_else(|| CommandError::NotFound(format!("No cognition for {}", p.persona_id)))?; - let report = persona.genome_engine.coverage_report(); - - crate::log_info!( - "module", - "cognition", - "genome-coverage-report {}: {} covered, {} gaps, ratio={:.2}", - p.persona_id, - report.covered.len(), - report.gaps.len(), - report.coverage_ratio - ); - - Ok(report) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. genome-coverage-report is - // host-driven cognition IPC, so it is Internal — registered and grid-routable, - // never a remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!( - GenomeCoverageReport::NAME, - "cognition/genome-coverage-report" - ); - assert_eq!(GenomeCoverageReport::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/commands/cognition/genome_evict_under_pressure.rs b/core/continuum-core/src/commands/cognition/genome_evict_under_pressure.rs deleted file mode 100644 index 533e5fb2d5..0000000000 --- a/core/continuum-core/src/commands/cognition/genome_evict_under_pressure.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! `cognition/genome-evict-under-pressure` — drive genome eviction down to a target -//! pressure ratio (typed, dep-holding). -//! -//! The PressureBroker lever: evicts LRU adapters (respecting critical-adapter protection, -//! priority > 0.9) until memory pressure falls to `target_pressure`, without an -//! `activate-skill` call. Uses the same formula and victim selection as activate-skill's -//! implicit eviction. When the broker singleton lands and registers per-persona -//! ResourcePool wrappers, this is the command those wrappers call. Captures the owning -//! module's [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; - -fn default_target_pressure() -> f32 { - 0.75 -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeEvictUnderPressureParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeEvictUnderPressureParams { - /// Persona whose genome is evicted. - #[ts(type = "string")] - pub persona_id: Uuid, - /// Target memory-pressure ratio to evict down to (default 0.75). - #[serde(default = "default_target_pressure")] - #[ts(type = "number")] - pub target_pressure: f32, -} - -#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeEvictUnderPressureResult.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeEvictUnderPressureResult { - #[ts(type = "string")] - pub persona_id: Uuid, - #[ts(type = "number")] - pub target_pressure: f32, - #[ts(type = "number")] - pub pressure_before: f32, - #[ts(type = "number")] - pub pressure_after: f32, - #[ts(type = "number")] - pub bytes_freed: u64, -} - -crate::action_command! { - /// Evict the persona's genome LRU adapters down to `target_pressure` (critical - /// adapters protected). Returns bytes freed + pressure before/after. Host-invoked. - pub struct GenomeEvictUnderPressure { state: Arc } - name: "cognition/genome-evict-under-pressure", - access: Internal, - params: GenomeEvictUnderPressureParams, - output: GenomeEvictUnderPressureResult, - run(this, _ctx, p) => { - let mut persona = this.state.get_or_create_persona(p.persona_id); - let pressure_before = persona.genome_engine.memory_pressure(); - let bytes_freed = persona.genome_engine.evict_under_pressure(p.target_pressure); - let pressure_after = persona.genome_engine.memory_pressure(); - - crate::log_info!( - "module", - "cognition", - "genome-evict-under-pressure {}: target={:.2} pressure {:.2} → {:.2}, freed {} bytes", - p.persona_id, - p.target_pressure, - pressure_before, - pressure_after, - bytes_freed - ); - - Ok(GenomeEvictUnderPressureResult { - persona_id: p.persona_id, - target_pressure: p.target_pressure, - pressure_before, - pressure_after, - bytes_freed, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. genome-evict-under-pressure is - // host-driven cognition IPC, so it is Internal — registered and grid-routable, - // never a remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!( - GenomeEvictUnderPressure::NAME, - "cognition/genome-evict-under-pressure" - ); - assert_eq!(GenomeEvictUnderPressure::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/commands/cognition/genome_record_activity.rs b/core/continuum-core/src/commands/cognition/genome_record_activity.rs deleted file mode 100644 index 4dac877068..0000000000 --- a/core/continuum-core/src/commands/cognition/genome_record_activity.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! `cognition/genome-record-activity` — log a domain interaction into the genome's -//! coverage ledger (typed, dep-holding). -//! -//! Records that the persona acted in `domain` (with success/failure) so the -//! [`GenomePagingEngine`](crate::persona::genome_paging) can track which skill domains -//! are exercised — feeding the gap detection that -//! [`super::genome_coverage_report`] reads. Captures the owning module's -//! [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; - -fn default_success() -> bool { - true -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeRecordActivityParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeRecordActivityParams { - /// Persona whose coverage ledger records the activity. - #[ts(type = "string")] - pub persona_id: Uuid, - /// Skill domain the persona acted in (e.g. "code", "chat"). - pub domain: String, - /// Whether the interaction succeeded (default true). - #[serde(default = "default_success")] - pub success: bool, -} - -#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeRecordActivityResult.ts" -)] -pub struct GenomeRecordActivityResult { - pub recorded: bool, - pub domain: String, - pub success: bool, -} - -crate::action_command! { - /// Record that the persona acted in `domain` (success/failure) into its genome - /// coverage ledger, feeding gap detection. Host-invoked. - pub struct GenomeRecordActivity { state: Arc } - name: "cognition/genome-record-activity", - access: Internal, - params: GenomeRecordActivityParams, - output: GenomeRecordActivityResult, - run(this, _ctx, p) => { - let mut persona = this.state.get_or_create_persona(p.persona_id); - persona.genome_engine.record_activity(&p.domain, p.success); - Ok(GenomeRecordActivityResult { - recorded: true, - domain: p.domain, - success: p.success, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. genome-record-activity is - // host-driven cognition IPC, so it is Internal — registered and grid-routable, - // never a remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!( - GenomeRecordActivity::NAME, - "cognition/genome-record-activity" - ); - assert_eq!(GenomeRecordActivity::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/commands/cognition/genome_state.rs b/core/continuum-core/src/commands/cognition/genome_state.rs deleted file mode 100644 index 31464b3da2..0000000000 --- a/core/continuum-core/src/commands/cognition/genome_state.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! `cognition/genome-state` — snapshot the persona's genome paging state (typed, -//! dep-holding). -//! -//! Non-mutating read of the [`GenomePagingEngine`](crate::persona::genome_paging): -//! which adapters are resident, memory used/budget, and pressure. Reuses the engine's -//! [`GenomePagingState`] as the output. Captures the owning module's -//! [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; -use crate::persona::genome_paging::GenomePagingState; -use crate::sdk_codegen::CommandError; - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeStateParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeStateParams { - /// Persona whose genome state is read. - #[ts(type = "string")] - pub persona_id: Uuid, -} - -crate::action_command! { - /// Snapshot the persona's genome paging state (resident adapters, memory, - /// pressure). Non-mutating. Host-invoked. - pub struct GenomeState { state: Arc } - name: "cognition/genome-state", - access: Internal, - params: GenomeStateParams, - output: GenomePagingState, - run(this, _ctx, p) => { - let persona = this - .state - .personas - .get(&p.persona_id) - .ok_or_else(|| CommandError::NotFound(format!("No cognition for {}", p.persona_id)))?; - Ok(persona.genome_engine.state()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. genome-state is host-driven - // cognition IPC, so it is Internal — registered and grid-routable, never a - // remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!(GenomeState::NAME, "cognition/genome-state"); - assert_eq!(GenomeState::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/commands/cognition/genome_sync.rs b/core/continuum-core/src/commands/cognition/genome_sync.rs deleted file mode 100644 index 395292ef22..0000000000 --- a/core/continuum-core/src/commands/cognition/genome_sync.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! `cognition/genome-sync` — reconcile the persona's genome to a supplied adapter set -//! (typed, dep-holding). -//! -//! Pushes the full adapter inventory (name, domain, size, priority, loaded-state) into -//! the [`GenomePagingEngine`](crate::persona::genome_paging) so its resident/LRU -//! bookkeeping matches ground truth, then reports the post-sync memory picture. Captures -//! the owning module's [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; -use crate::persona::genome_paging::GenomeAdapterInfo; - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeSyncParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeSyncParams { - /// Persona whose genome is reconciled. - #[ts(type = "string")] - pub persona_id: Uuid, - /// The full adapter inventory to sync into the paging engine. - pub adapters: Vec, - /// Memory budget in MB; 0 or omitted uses the GPU-detected per-persona budget. - #[serde(default)] - #[ts(type = "number")] - pub memory_budget_mb: f32, -} - -#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenomeSyncResult.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct GenomeSyncResult { - pub synced: bool, - #[ts(type = "number")] - pub adapter_count: usize, - #[ts(type = "number")] - pub active_count: usize, - #[ts(type = "number")] - pub memory_used_mb: f32, - #[ts(type = "number")] - pub memory_pressure: f32, -} - -crate::action_command! { - /// Reconcile the persona's genome paging engine to the supplied adapter inventory - /// and report the post-sync memory picture. Host-invoked. - pub struct GenomeSync { state: Arc } - name: "cognition/genome-sync", - access: Internal, - params: GenomeSyncParams, - output: GenomeSyncResult, - run(this, _ctx, p) => { - let memory_budget_mb = if p.memory_budget_mb > 0.0 { - p.memory_budget_mb - } else { - this.state.per_persona_budget_mb() - }; - - let adapter_count = p.adapters.len(); - let active_count = p.adapters.iter().filter(|a| a.is_loaded).count(); - - let mut persona = this.state.get_or_create_persona(p.persona_id); - persona.genome_engine.memory_budget_mb = memory_budget_mb; - persona.genome_engine.sync_state(p.adapters); - - let memory_used_mb = persona.genome_engine.memory_used_mb; - let memory_pressure = persona.genome_engine.memory_pressure(); - - crate::log_info!( - "module", - "cognition", - "genome-sync {}: {} adapters ({} active), budget={}MB, used={}MB", - p.persona_id, - adapter_count, - active_count, - persona.genome_engine.memory_budget_mb, - memory_used_mb - ); - - Ok(GenomeSyncResult { - synced: true, - adapter_count, - active_count, - memory_used_mb, - memory_pressure, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. genome-sync is host-driven - // cognition IPC, so it is Internal — registered and grid-routable, never a - // remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!(GenomeSync::NAME, "cognition/genome-sync"); - assert_eq!(GenomeSync::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/commands/cognition/mod.rs b/core/continuum-core/src/commands/cognition/mod.rs index d7ddee1dfc..801d20652e 100644 --- a/core/continuum-core/src/commands/cognition/mod.rs +++ b/core/continuum-core/src/commands/cognition/mod.rs @@ -33,12 +33,6 @@ pub mod forget_context; pub mod full_evaluate; pub mod generate_recipe; pub mod generate_response; -pub mod genome_activate_skill; -pub mod genome_coverage_report; -pub mod genome_evict_under_pressure; -pub mod genome_record_activity; -pub mod genome_state; -pub mod genome_sync; pub mod get_state; pub mod gpu_budget; pub mod has_evaluated; @@ -59,7 +53,6 @@ pub mod semantic_search_tools; pub mod set_sleep_mode; pub mod should_respond; pub mod sync_adapters; -pub mod sync_domain_classifier; pub mod track_response; pub mod validate_response_decision; pub mod vision_describe; @@ -74,12 +67,6 @@ use dream_now::DreamNow; use enqueue_message::EnqueueMessage; use forget_context::ForgetContext; use full_evaluate::FullEvaluate; -use genome_activate_skill::GenomeActivateSkill; -use genome_coverage_report::GenomeCoverageReport; -use genome_evict_under_pressure::GenomeEvictUnderPressure; -use genome_record_activity::GenomeRecordActivity; -use genome_state::GenomeState; -use genome_sync::GenomeSync; use get_state::GetState; use gpu_budget::GpuBudget; use has_evaluated::HasEvaluated; @@ -94,7 +81,6 @@ use respond::Respond; use select_model::SelectModel; use set_sleep_mode::SetSleepMode; use sync_adapters::SyncAdapters; -use sync_domain_classifier::SyncDomainClassifier; use track_response::TrackResponse; use vision_describe::VisionDescribe; @@ -133,30 +119,9 @@ pub fn command_objects( Arc::new(TrackResponse { state: state.clone(), }), - Arc::new(GenomeActivateSkill { - state: state.clone(), - }), - Arc::new(GenomeSync { - state: state.clone(), - }), - Arc::new(GenomeState { - state: state.clone(), - }), - Arc::new(GenomeEvictUnderPressure { - state: state.clone(), - }), - Arc::new(GenomeRecordActivity { - state: state.clone(), - }), - Arc::new(GenomeCoverageReport { - state: state.clone(), - }), Arc::new(ClassifyDomain { state: state.clone(), }), - Arc::new(SyncDomainClassifier { - state: state.clone(), - }), Arc::new(RegisterDomainKeywords { state: state.clone(), }), diff --git a/core/continuum-core/src/commands/cognition/select_model.rs b/core/continuum-core/src/commands/cognition/select_model.rs index 79e75c4101..f468fa0859 100644 --- a/core/continuum-core/src/commands/cognition/select_model.rs +++ b/core/continuum-core/src/commands/cognition/select_model.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use crate::modules::cognition::CognitionState; use crate::persona::model_selection::{ - select_model_with_signatures, ModelSelectionRequest, ModelSelectionResult, NeedEmbedding, + select_model, ModelSelectionRequest, ModelSelectionResult, }; use crate::sdk_codegen::CommandError; @@ -31,50 +31,14 @@ crate::action_command! { params: ModelSelectionRequest, output: ModelSelectionResult, run(this, _ctx, p) => { - // Rung 0's inputs, computed at THIS async seam so the selector stays - // pure + sync (memory/recall's query_embedding pattern): embed the need - // text through the one recall lane, and join the persona's adapters to - // their minted signatures by NAME via the manifest + sidecar. - let need_text = p.need.clone().or_else(|| p.task_domain.clone()); - let (need, signatures) = match need_text { - Some(text) => { - let embedder = crate::ai::embedding::resolve_recall_embedder_local().await; - let need = NeedEmbedding { - embedder_id: embedder.id().to_string(), - vector: embedder.embed(&text).await, - unrelated_null: embedder.unrelated_null(), - }; - let mut by_name = std::collections::HashMap::new(); - if let (Ok(manifest), Ok(store_path)) = ( - crate::genome::adapter_manifest::load(), - crate::genome::signature::signature_store_path(), - ) { - if let Ok(store) = crate::genome::signature::SignatureStore::load_at(&store_path) { - for a in &manifest { - if let Some(sig) = store.by_path.get(&a.path.display().to_string()) { - by_name.insert(a.alias.clone(), sig.clone()); - } - } - } - } - (Some(need), by_name) - } - None => (None, std::collections::HashMap::new()), - }; let persona = this.state.get_or_create_persona(p.persona_id); - let result = select_model_with_signatures( - &p, - &persona.adapter_registry, - need.as_ref(), - &signatures, - ) - .map_err(|e| CommandError::Internal(e.to_string()))?; + let result = select_model(&p, &persona.adapter_registry) + .map_err(|e| CommandError::Internal(e.to_string()))?; continuum_base::probe!( class = "cognition.model_selection", persona = %p.persona_id, source = %result.source, adapter = %result.adapter_name.as_deref().unwrap_or("-"), // probe display only: "-" reads as no-adapter - similarity = %result.similarity.unwrap_or(0.0), // probe display only: 0.0 beside a non-distance source reads as not-applicable "model selected" ); Ok(result) diff --git a/core/continuum-core/src/commands/cognition/sync_domain_classifier.rs b/core/continuum-core/src/commands/cognition/sync_domain_classifier.rs deleted file mode 100644 index 4505132e4b..0000000000 --- a/core/continuum-core/src/commands/cognition/sync_domain_classifier.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! `cognition/sync-domain-classifier` — reconcile the persona's domain classifier to its -//! current genome adapter set (typed, dep-holding). -//! -//! Rebuilds the [`DomainClassifier`](crate::persona::domain_classifier)'s domain→adapter -//! map from the genome engine's active + available adapters, then reports how many domains -//! are known and how many are backed by an adapter (the rest are coverage gaps). Captures -//! the owning module's [`CognitionState`](crate::modules::cognition::CognitionState). -//! -//! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. - -use std::sync::Arc; - -use uuid::Uuid; - -use crate::modules::cognition::CognitionState; - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/SyncDomainClassifierParams.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct SyncDomainClassifierParams { - /// Persona whose domain classifier is reconciled. - #[ts(type = "string")] - pub persona_id: Uuid, -} - -#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/SyncDomainClassifierResult.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct SyncDomainClassifierResult { - pub synced: bool, - #[ts(type = "number")] - pub total_domains: usize, - #[ts(type = "number")] - pub covered_domains: usize, -} - -crate::action_command! { - /// Reconcile the persona's domain classifier to its genome adapter set and report - /// domain coverage (total known, how many backed by an adapter). Host-invoked. - pub struct SyncDomainClassifier { state: Arc } - name: "cognition/sync-domain-classifier", - access: Internal, - params: SyncDomainClassifierParams, - output: SyncDomainClassifierResult, - run(this, _ctx, p) => { - let mut persona = this.state.get_or_create_persona(p.persona_id); - - // Build adapter list from genome engine state. - let state = persona.genome_engine.state(); - let all_adapters: Vec<_> = state - .active_adapters - .iter() - .chain(state.available_adapters.iter()) - .cloned() - .collect(); - - persona.domain_classifier.sync_from_adapters(&all_adapters); - - let summary = persona.domain_classifier.domain_summary(); - let covered_domains = summary.iter().filter(|(_, has)| *has).count(); - let total_domains = summary.len(); - - crate::log_info!( - "module", - "cognition", - "sync-domain-classifier {}: {} domains ({} with adapters)", - p.persona_id, - total_domains, - covered_domains - ); - - Ok(SyncDomainClassifierResult { - synced: true, - total_domains, - covered_domains, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sdk_codegen::{AccessLevel, ActionCommand}; - - // what this catches: the name + access contract. sync-domain-classifier is - // host-driven cognition IPC, so it is Internal — registered and grid-routable, - // never a remote-callable persona toolbelt verb. - #[test] - fn name_and_access_are_the_contract() { - assert_eq!( - SyncDomainClassifier::NAME, - "cognition/sync-domain-classifier" - ); - assert_eq!(SyncDomainClassifier::ACCESS, AccessLevel::Internal); - } -} diff --git a/core/continuum-core/src/modules/channel.rs b/core/continuum-core/src/modules/channel.rs index aa2645ad0a..ed175d1f05 100644 --- a/core/continuum-core/src/modules/channel.rs +++ b/core/continuum-core/src/modules/channel.rs @@ -330,39 +330,6 @@ impl ServiceModule for ChannelModule { } } - // ── 2b. Enrollment opportunity detection ───────────────────── - // Uses genome coverage report to find domains with activity but no adapter. - // Creates enroll-academy tasks when gap meets threshold. - if config.self_task_enabled { - if let Some(generator_entry) = self.state.self_task_generators.get(persona_id) { - let generator = generator_entry.lock().await; - if let Some(persona) = self.state.personas.get(persona_id) { - let enrollment_tasks = - generator.detect_enrollment_opportunities(&persona.genome_engine); - if !enrollment_tasks.is_empty() { - for task_json in &enrollment_tasks { - if let Some(item) = - Self::json_to_task_queue_item(task_json, persona_id) - { - if let Some(mut entry) = - self.state.registries.get_mut(persona_id) - { - let (registry, _state) = entry.value_mut(); - let _ = registry.route(std::sync::Arc::new(item)); - } - } - } - total_self_tasks += enrollment_tasks.len() as u32; - log.info(&format!( - "Enrollment opportunities for {}: {} tasks", - persona_id, - enrollment_tasks.len() - )); - } - } - } - } - // Training readiness check used to live here. Removed in // task #227 — the trigger was structurally dead: // diff --git a/core/continuum-core/src/modules/cognition.rs b/core/continuum-core/src/modules/cognition.rs index a80cb7b5ea..270146eb9d 100644 --- a/core/continuum-core/src/modules/cognition.rs +++ b/core/continuum-core/src/modules/cognition.rs @@ -22,13 +22,12 @@ //! - `cognition/track-response`: Track response for rate limiting //! - `cognition/set-sleep-mode`: Set voluntary sleep mode //! - `cognition/configure-rate-limiter`: Configure rate limiter params -//! - `cognition/select-model`: 4-tier model priority chain +//! - `cognition/select-model`: 3-tier model priority chain //! - `cognition/sync-adapters`: Sync adapter registry from TypeScript //! - `cognition/check-adequacy`: Batch adequacy check //! -//! The `cognition/genome-*` family (activate-skill, sync, state, evict-under-pressure, -//! record-activity, coverage-report) migrated to the typed DynCommand registry — -//! see `commands/cognition/` and `command_objects` there. +//! The TS-era `cognition/genome-*` family and `sync-domain-classifier` are deleted: which genes +//! a turn runs is `genome::composer`, where they live is `genome::gene_residency`. //! - `inbox/create`: Create persona inbox (alias for create-engine) //! //! Uses `Params` helper for typed parameter extraction. @@ -100,24 +99,10 @@ impl CognitionState { &self, persona_uuid: Uuid, ) -> dashmap::mapref::one::RefMut<'_, Uuid, PersonaCognition> { - // Compute the budget BEFORE acquiring the entry shard-lock. - // `per_persona_budget_mb()` reads `self.personas.len()`, which read-locks - // EVERY shard. `DashMap::entry()` holds a WRITE lock on the target key's - // shard; calling `len()` inside `or_insert_with` re-enters that same shard - // lock, and parking_lot's RwLock is not reentrant → self-deadlock. This is - // silent in tests (no GpuMemoryManager → the `None` arm skips `len()`) and - // only bites the live core where `gpu_manager` is `Some`. Hoisting the read - // out means no lock is held when `len()` runs. The budget is computed even - // on the cache-hit path (a cheap shard-count sum) but only consumed on - // insert; correctness over shaving one `len()` off the hit path. - let budget = self.per_persona_budget_mb(); + // No lock is held across anything but the insert (a `len()` inside `or_insert_with` + // re-entered the shard lock and self-deadlocked the live core once). self.personas.entry(persona_uuid).or_insert_with(|| { - PersonaCognition::with_budget( - persona_uuid, - String::new(), - self.rag_engine.clone(), - budget, - ) + PersonaCognition::new(persona_uuid, String::new(), self.rag_engine.clone()) }) } } @@ -446,10 +431,6 @@ impl ServiceModule for CognitionModule { // Genome Paging (LRU eviction + memory budget decisions) // ================================================================= // Migrated to the typed DynCommand registry (Slice 4): - // cognition/genome-activate-skill → commands/cognition/genome_activate_skill.rs - // cognition/genome-sync → commands/cognition/genome_sync.rs - // cognition/genome-state → commands/cognition/genome_state.rs - // cognition/genome-evict-under-pressure → commands/cognition/genome_evict_under_pressure.rs // Exposed via commands/cognition/mod.rs::command_objects (dep-holding on CognitionState). // MIGRATED to typed ActionCommand (task #62): @@ -496,7 +477,6 @@ impl ServiceModule for CognitionModule { // ================================================================= // Migrated to the typed DynCommand registry (Slice 5): // cognition/classify-domain → commands/cognition/classify_domain.rs - // cognition/sync-domain-classifier → commands/cognition/sync_domain_classifier.rs // cognition/register-domain-keywords → commands/cognition/register_domain_keywords.rs // Exposed via commands/cognition/mod.rs::command_objects (dep-holding on CognitionState). @@ -504,8 +484,6 @@ impl ServiceModule for CognitionModule { // Domain Activity Tracking & Gap Detection // ================================================================= // Migrated to the typed DynCommand registry (Slice 4): - // cognition/genome-record-activity → commands/cognition/genome_record_activity.rs - // cognition/genome-coverage-report → commands/cognition/genome_coverage_report.rs // Exposed via commands/cognition/mod.rs::command_objects (dep-holding on CognitionState). // ================================================================= diff --git a/core/continuum-core/src/modules/dataset/candidate.rs b/core/continuum-core/src/modules/dataset/candidate.rs index 9e95e6687c..4822594b6d 100644 --- a/core/continuum-core/src/modules/dataset/candidate.rs +++ b/core/continuum-core/src/modules/dataset/candidate.rs @@ -245,6 +245,7 @@ mod tests { }, capture: None, genes: Vec::new(), + gene_scales: Vec::new(), }; serde_json::from_value(json!({ "submissionId": id, diff --git a/core/continuum-core/src/modules/inference_coordinator_module.rs b/core/continuum-core/src/modules/inference_coordinator_module.rs index f4806d27b3..146c2a984c 100644 --- a/core/continuum-core/src/modules/inference_coordinator_module.rs +++ b/core/continuum-core/src/modules/inference_coordinator_module.rs @@ -88,9 +88,15 @@ impl InferenceCoordinatorModule { /// reports `usage = open lanes' KV bytes`, `capacity = lane budget`; the /// broker's tick reads `pressure()` and fires `evict_at_least` (→ /// `evict_under_pressure`) when the tier crosses its act threshold. + /// + /// The node's genes are a tenant of the same budget (Cormac, 2026-10-24: genes and minds' + /// KV compete for one device): their device bytes count here, and pressure pages them out + /// to host RAM before any lane is evicted (`genome::gene_residency`). pub fn register_with_broker(&self, broker: &PressureBroker) { + let genes: Arc = + crate::genome::gene_residency::GeneResidency::global().clone(); broker.register( - Arc::new(CoordinatorResourcePool::new(self.coordinator.clone())) + Arc::new(CoordinatorResourcePool::new(self.coordinator.clone()).with_tenant(genes)) as Arc, ); } diff --git a/core/continuum-engine/src/ai/provenance.rs b/core/continuum-engine/src/ai/provenance.rs index 2c4ba86fc6..8fceb48b24 100644 --- a/core/continuum-engine/src/ai/provenance.rs +++ b/core/continuum-engine/src/ai/provenance.rs @@ -32,8 +32,8 @@ // second, divergent rule. use crate::ai::types::TextGenerationResponse; -/// ONE dispatched generation, and what became of it. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +/// ONE dispatched generation, and what became of it. `PartialEq` only: the gene scales are f64. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GenerationReceipt { /// **THE JOIN KEY.** `TextGenerationRequest::request_id` as submitted, assigned @@ -55,17 +55,22 @@ pub struct GenerationReceipt { /// read as empty, which is what those calls ran (no live page-in existed). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub genes: Vec, + /// The scale each of `genes` ran at, aligned with it: with `genes`, the phenotype the call + /// ran (`genome::composer`), so an examiner can replay it with one gene off. Rows written + /// before this field read as empty. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub gene_scales: Vec, } -/// The genes a request actually runs with: every requested adapter at a non-zero scale. -/// A zero-scale entry reaches no graph (the engine drops it), so it is not a gene this turn -/// ran on. -pub fn genes_of(adapters: Option<&[crate::ai::types::ActiveAdapterRequest]>) -> Vec { +/// The genes a request actually runs with, and their scales: every requested adapter at a +/// non-zero scale. A zero-scale entry reaches no graph (the engine drops it), so it is not a +/// gene this turn ran on. +pub fn genes_of(adapters: Option<&[crate::ai::types::ActiveAdapterRequest]>) -> Vec<(String, f64)> { adapters .into_iter() .flatten() .filter(|a| a.scale != 0.0) - .map(|a| if a.path.is_empty() { a.name.clone() } else { a.path.clone() }) + .map(|a| (if a.path.is_empty() { a.name.clone() } else { a.path.clone() }, a.scale)) .collect() } @@ -132,12 +137,13 @@ impl GenerationReceipt { outcome, capture: None, genes: Vec::new(), + gene_scales: Vec::new(), } } - /// Attach the genes the call ran with ([`genes_of`]). - pub fn with_genes(mut self, genes: Vec) -> Self { - self.genes = genes; + /// Attach the genes the call ran with and their scales ([`genes_of`]). + pub fn with_genes(mut self, genes: Vec<(String, f64)>) -> Self { + (self.genes, self.gene_scales) = genes.into_iter().unzip(); self } @@ -159,6 +165,7 @@ impl GenerationReceipt { }, capture: None, genes: Vec::new(), + gene_scales: Vec::new(), } } @@ -301,15 +308,16 @@ mod tests { scale, }; let asked = [gene("kimi-dream-1", "/genes/kimi-1.gguf", 1.0), gene("off", "/genes/off.gguf", 0.0), gene("named", "", 0.5)]; - assert_eq!(genes_of(Some(&asked)), vec!["/genes/kimi-1.gguf".to_string(), "named".to_string()]); + assert_eq!(genes_of(Some(&asked)), vec![("/genes/kimi-1.gguf".to_string(), 1.0), ("named".to_string(), 0.5)]); assert!(genes_of(None).is_empty(), "no genome = the base model"); let old: GenerationReceipt = serde_json::from_value(serde_json::json!({ "submittedRequestId": "r", "outcome": {"kind": "faulted", "detail": "x"} })) .unwrap(); assert!(old.genes.is_empty()); - let now = GenerationReceipt::faulted("r", "x").with_genes(vec!["/genes/kimi-1.gguf".into()]); + let now = GenerationReceipt::faulted("r", "x").with_genes(vec![("/genes/kimi-1.gguf".into(), 0.4)]); let round: GenerationReceipt = serde_json::from_value(serde_json::to_value(&now).unwrap()).unwrap(); assert_eq!(round.genes, vec!["/genes/kimi-1.gguf".to_string()]); + assert_eq!(round.gene_scales, vec![0.4], "the receipt carries the phenotype, scales included"); } } diff --git a/core/continuum-engine/src/ai/types.rs b/core/continuum-engine/src/ai/types.rs index ff458fd413..adf006853c 100644 --- a/core/continuum-engine/src/ai/types.rs +++ b/core/continuum-engine/src/ai/types.rs @@ -178,7 +178,7 @@ pub enum ToolChoice { // ============================================================================ /// Active LoRA adapter to apply during generation -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[ts( export, export_to = "../../../protocol/typescript/ai/ActiveAdapterRequest.ts" diff --git a/core/continuum-engine/src/capacity/expert_pager.rs b/core/continuum-engine/src/capacity/expert_pager.rs index c40f709d90..d83d5e8bbc 100644 --- a/core/continuum-engine/src/capacity/expert_pager.rs +++ b/core/continuum-engine/src/capacity/expert_pager.rs @@ -3,7 +3,7 @@ //! The K3 capability-axis on-ramp: a Mixture-of-Experts model whose full weight set //! can't fit VRAM (K3 = 896 experts, ~594 GB) serves LOCALLY by keeping the HOT expert //! subset resident and paging the cold tail from the cold drive -//! ([`ArtifactSource::Mapped`](crate::genome::blob::ArtifactSource)). WHICH +//! (a mapped GGUF range, sized by [`expert_layout`](crate::inference_capability::expert_layout)). WHICH //! experts are hot is learned live from the router — M5's `ffn_moe_topk` eval-callback //! increments [`ExpertActivationProfile::hits`]; this is the sentinel-PGO signal. //! @@ -29,7 +29,7 @@ use super::{DeviceCapacity, SystemProfile}; /// headroom via [`SystemProfile::serving_budget_bytes`]), not raw live-free VRAM. /// /// `expert_bytes` = per-expert on-device weight size (from the ingested layout — -/// [`ArtifactBlob::expert_size_bytes`](crate::genome::blob::ArtifactBlob)); `0` ⇒ the +/// [`expert_layout`](crate::inference_capability::expert_layout)); `0` ⇒ the /// planner can't size residency and warms everything (its safe cold-start). `margin_bytes` /// is the eviction hysteresis the caller carries. RAM stays at its true live-free (the /// warm tier isn't the contended one — VRAM is); only the VRAM tier is budgeted, which diff --git a/core/continuum-engine/src/inference/coordinator_pool.rs b/core/continuum-engine/src/inference/coordinator_pool.rs index 11a80c8d93..6b47740032 100644 --- a/core/continuum-engine/src/inference/coordinator_pool.rs +++ b/core/continuum-engine/src/inference/coordinator_pool.rs @@ -44,6 +44,19 @@ pub const TIER_NAME: &str = "inference-lanes"; /// wrapper supplies its own. type ClockFn = Box u64 + Send + Sync>; +/// Another tenant of the lanes' device budget: genes (`genome::gene_residency`) compete with +/// minds' KV for the same device, so they report into THIS pool, never a second number beside +/// it (Cormac, 2026-10-24). Under pressure a tenant is asked first: a gene pages out to host +/// RAM in milliseconds (fork #72, 2-5 ms for 50 MB on the M5) while a lane's eviction costs a +/// mind her KV and a re-prefill. +pub trait DeviceTenant: Send + Sync { + /// Bytes the tenant holds on the device now. + fn device_bytes(&self) -> u64; + /// Free at least `want_bytes` of device memory if it can; returns the bytes it frees. + fn evict_at_least(&self, want_bytes: u64) -> u64; + fn snapshot(&self) -> Vec; +} + /// Wraps an `Arc` as a `ResourcePool` so the /// PressureBroker can register + drive it. pub struct CoordinatorResourcePool { @@ -58,6 +71,8 @@ pub struct CoordinatorResourcePool { /// while admission allows up to 64GB of lane configuration). /// `None` = default to `coordinator.capacity_bytes()`. capacity_override: Option, + /// The device budget's other tenants, cheapest to relieve first. + tenants: Vec>, } impl CoordinatorResourcePool { @@ -68,9 +83,16 @@ impl CoordinatorResourcePool { clock: Box::new(|| continuum_base::time::EpochMs::now().millis()), tier_name: TIER_NAME.to_string(), capacity_override: None, + tenants: Vec::new(), } } + /// Count `tenant` in this budget and relieve it before any lane. + pub fn with_tenant(mut self, tenant: Arc) -> Self { + self.tenants.push(tenant); + self + } + /// Inject a deterministic clock for tests. Production paths use /// the default wall-clock. pub fn with_clock u64 + Send + Sync + 'static>(mut self, clock: F) -> Self { @@ -101,17 +123,30 @@ impl ResourcePool for CoordinatorResourcePool { } fn usage_bytes(&self) -> u64 { - self.coordinator.lanes_usage_bytes() + self.coordinator.lanes_usage_bytes() + self.tenants.iter().map(|t| t.device_bytes()).sum::() } fn evict_at_least(&self, want_bytes: u64) -> u64 { + let mut freed = 0u64; + for tenant in &self.tenants { + if freed >= want_bytes { + return freed; + } + freed += tenant.evict_at_least(want_bytes - freed); + } + if freed >= want_bytes { + return freed; + } let now_ms = (self.clock)(); - let result = self.coordinator.evict_under_pressure(want_bytes, now_ms); - result.bytes_freed + freed + self.coordinator.evict_under_pressure(want_bytes - freed, now_ms).bytes_freed } fn snapshot(&self) -> Vec { - self.coordinator.lanes_snapshot() + let mut entries = self.coordinator.lanes_snapshot(); + for tenant in &self.tenants { + entries.extend(tenant.snapshot()); + } + entries } } @@ -244,6 +279,37 @@ mod tests { assert_eq!(c.lane_count(), 1); } + // what this catches: genes holding device memory beside the lanes' KV as a second budget + // (Cormac, 2026-10-24). A tenant's bytes count in the one pool, and pressure is relieved from + // the tenant (a gene pages out in ms) before any lane loses a mind's KV. + #[test] + fn a_tenant_counts_in_the_one_budget_and_is_relieved_before_any_lane() { + struct Genes(std::sync::atomic::AtomicU64); + impl DeviceTenant for Genes { + fn device_bytes(&self) -> u64 { + self.0.load(std::sync::atomic::Ordering::SeqCst) + } + fn evict_at_least(&self, want: u64) -> u64 { + let held = self.device_bytes(); + let freed = held.min(want); + self.0.store(held - freed, std::sync::atomic::Ordering::SeqCst); + freed + } + fn snapshot(&self) -> Vec { + Vec::new() + } + } + let c = build_coordinator(); + open_with_class(&c, 1, TaskKind::CodingSmall, LaneClass::Background); // 32K + let genes = Arc::new(Genes(std::sync::atomic::AtomicU64::new(10 * 1024))); + let pool = CoordinatorResourcePool::new(c.clone()).with_clock(|| 1_500_000).with_tenant(genes.clone()); + assert_eq!(pool.usage_bytes(), 42 * 1024); + assert_eq!(pool.evict_at_least(4 * 1024), 4 * 1024, "the genes alone relieve it"); + assert_eq!(c.lane_count(), 1, "no lane lost its KV"); + assert_eq!(pool.evict_at_least(10 * 1024), 6 * 1024 + 32 * 1024, "genes first, then the lane"); + assert_eq!(c.lane_count(), 0); + } + #[test] fn evict_at_least_returns_actual_bytes_freed_not_target() { let c = build_coordinator(); diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index 6f6bc2345e..a3a9e155b9 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -78,6 +78,8 @@ use pages::{ PAGE_DIR_GUARD, }; mod genome; +mod gene_pages; +pub use gene_pages::{gene_seats, page_gene, GeneMove, GenePageError, GeneSeat}; pub(crate) use genome::gene_stage_name; pub use genome::{engine_accepts_train_dir, engine_train_dir, GenomeInPlace}; use genome::{engine_help_lists_train_dir, ENGINE_TRAIN_DIR}; diff --git a/core/continuum-engine/src/inference/llama_server/gene_pages.rs b/core/continuum-engine/src/inference/llama_server/gene_pages.rs new file mode 100644 index 0000000000..e544f46d7a --- /dev/null +++ b/core/continuum-engine/src/inference/llama_server/gene_pages.rs @@ -0,0 +1,131 @@ +//! Genes paged between the engine's device memory and host RAM (fork CambrianTech/llama.cpp#72): +//! the mechanism `genome::gene_residency` drives. Which genes are LOADED at all stays the serving +//! target's (`converge_genome`); this moves a loaded one between the device and host RAM without +//! touching its id, so slot adapter lists and the KV computed under it stay valid. + +use super::configuration::{serving_root, PROBE_TIMEOUT}; + +/// One loaded gene as the engine lists it (`GET /lora-adapters`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GeneSeat { + pub id: i64, + pub path: String, + /// `false` while paged out to host RAM. + pub on_device: bool, + /// Its bytes where it is now; `None` from an engine that predates residency reporting. + pub n_bytes: Option, +} + +/// What one page_out / page_in did. +#[derive(Debug, Clone, PartialEq)] +pub struct GeneMove { + pub id: i64, + pub on_device: bool, + pub n_bytes: u64, + /// Bytes copied; 0 when it was already there. + pub n_moved: u64, + pub t_ms: f64, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum GenePageError { + /// The engine predates gene paging (`/props` lora_page_version). + #[error("the engine has no gene paging route")] + NoRoute, + /// A turn in flight applies it: retry when it finishes. + #[error("a slot is applying the gene")] + Busy, + #[error("the engine refused: {0}")] + Refused(String), + #[error("the engine did not answer: {0}")] + Unreachable(String), +} + +fn client() -> &'static reqwest::Client { + static CLIENT: std::sync::OnceLock = std::sync::OnceLock::new(); + CLIENT.get_or_init(reqwest::Client::new) +} + +/// The engine's loaded genes with where each is and its bytes. An engine that predates +/// residency reporting lists its genes as on the device (where it keeps every one). +pub async fn gene_seats() -> Result, GenePageError> { + let url = format!("{}/lora-adapters", serving_root()); + let resp = client() + .get(&url) + .timeout(PROBE_TIMEOUT) + .send() + .await + .map_err(|e| GenePageError::Unreachable(e.to_string()))?; + if !resp.status().is_success() { + return Err(GenePageError::Unreachable(format!("/lora-adapters status {}", resp.status()))); + } + let body: Vec = resp.json().await.map_err(|e| GenePageError::Unreachable(e.to_string()))?; + Ok(body.iter().filter_map(seat_of).collect()) +} + +/// PURE: one catalog entry. `None` for an entry without an id or path (never a guessed one). +pub(crate) fn seat_of(entry: &serde_json::Value) -> Option { + Some(GeneSeat { + id: entry.get("id")?.as_i64()?, + path: entry.get("path")?.as_str()?.to_string(), + on_device: entry.get("resident").and_then(|r| r.as_str()).map_or(true, |r| r == "device"), // an engine without the field keeps every gene on the device + n_bytes: entry.get("n_bytes").and_then(|b| b.as_u64()), + }) +} + +/// `POST /lora-adapters/page_in` (`to_device`) or `/page_out` for gene `id`. +pub async fn page_gene(id: i64, to_device: bool) -> Result { + let verb = if to_device { "page_in" } else { "page_out" }; + let url = format!("{}/lora-adapters/{verb}", serving_root()); + // PROBE_TIMEOUT (4 s): a page measured 2-5 ms for 50 MB on the M5 (fork #72), three + // orders under it; a page that takes seconds is a fault to surface, not to wait on. + let resp = client() + .post(&url) + .json(&serde_json::json!({ "id": id })) + .timeout(PROBE_TIMEOUT) + .send() + .await + .map_err(|e| GenePageError::Unreachable(e.to_string()))?; + match resp.status().as_u16() { + 200..=299 => { + let body: serde_json::Value = resp.json().await.map_err(|e| GenePageError::Unreachable(e.to_string()))?; + move_of(&body).ok_or_else(|| GenePageError::Unreachable(format!("/lora-adapters/{verb} answered {body}"))) + } + 404 | 405 => Err(GenePageError::NoRoute), + 503 => Err(GenePageError::Busy), + status => Err(GenePageError::Refused(format!( + "/lora-adapters/{verb} status {status}: {}", + resp.text().await.unwrap_or_default() // unwrap_or_default: the status alone still names the refusal + ))), + } +} + +/// PURE: a page answer. +pub(crate) fn move_of(body: &serde_json::Value) -> Option { + Some(GeneMove { + id: body.get("id")?.as_i64()?, + on_device: body.get("resident")?.as_str()? == "device", + n_bytes: body.get("n_bytes")?.as_u64()?, + n_moved: body.get("n_moved")?.as_u64()?, + t_ms: body.get("t_ms")?.as_f64()?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: the fork's answer shapes (#72) read wrong, e.g. a host-resident gene + // read as on the device (the residency owner would never page it back in), or an engine + // older than residency reporting read as having nothing loaded. + #[test] + fn catalog_entries_and_page_answers_read_as_the_fork_writes_them() { + let host = serde_json::json!({"id": 3, "path": "/t/g.gguf", "scale": 0.0, "resident": "host", "n_bytes": 50373120}); + assert_eq!(seat_of(&host), Some(GeneSeat { id: 3, path: "/t/g.gguf".into(), on_device: false, n_bytes: Some(50373120) })); + let older = serde_json::json!({"id": 0, "path": "/t/a.gguf", "scale": 0.0}); + assert_eq!(seat_of(&older).map(|s| (s.on_device, s.n_bytes)), Some((true, None))); + assert_eq!(seat_of(&serde_json::json!({"path": "/t/a.gguf"})), None); + let moved = serde_json::json!({"success": true, "id": 3, "path": "/t/g.gguf", "resident": "device", "n_bytes": 9, "n_moved": 9, "t_ms": 4.6}); + assert_eq!(move_of(&moved), Some(GeneMove { id: 3, on_device: true, n_bytes: 9, n_moved: 9, t_ms: 4.6 })); + } +} diff --git a/core/continuum-genome/Cargo.toml b/core/continuum-genome/Cargo.toml index bce41ee4ee..44bd7d8610 100644 --- a/core/continuum-genome/Cargo.toml +++ b/core/continuum-genome/Cargo.toml @@ -49,8 +49,6 @@ default = [] metal = ["continuum-engine/metal"] cuda = ["continuum-kernel/cuda", "continuum-engine/cuda"] vulkan = ["continuum-kernel/vulkan", "continuum-engine/vulkan"] -# The local manager's multi-thread stress test (compile-time gated, never #[ignore]). -stress-tests = ["continuum-kernel/stress-tests"] # Test-only code (the recording adapter, the job board's test storage, gene-trial fixtures); # production binaries never build with it. The mind's test-fixtures forwards here. test-fixtures = ["continuum-base/test-fixtures", "continuum-kernel/test-fixtures", "continuum-engine/test-fixtures", "dep:tempfile"] diff --git a/core/continuum-genome/src/genome/blob.rs b/core/continuum-genome/src/genome/blob.rs deleted file mode 100644 index 96165846e1..0000000000 --- a/core/continuum-genome/src/genome/blob.rs +++ /dev/null @@ -1,328 +0,0 @@ -//! ArtifactBlob + Provenance — the value-side types the `TierStore` -//! trait's `write` method needs. -//! -//! ## Status: PR-2 minimal seam -//! -//! Both types are **placeholder stubs** that will be replaced by the -//! full shapes specified in GENOME-FOUNDRY-SENTINEL Part 1. The full -//! `Provenance` carries the artifact_id (content-hash), creator, -//! source_trace, source_artifact, supersedes, adaptation_method, -//! outcome_metrics, trust_score, and license fields — a Lane H -//! deliverable that targets `core/continuum-core/src/genome/ -//! provenance.rs`. That PR is not this PR. -//! -//! What PR-2 needs them for: the `TierStore::write` signature names -//! both types. We define minimal wire-stable versions so the trait -//! compiles and downstream callers can construct a `write` call. When -//! the full Part-1 shapes land, these stubs get replaced and the -//! callers update to pass the richer values; the trait shape doesn't -//! change. - -use std::path::PathBuf; - -use serde::{Deserialize, Serialize}; -use ts_rs::TS; - -use crate::inference::page_ref::ArtifactId; - -/// Where an artifact's bytes physically live. -/// -/// Small artifacts (LoRA layers, engrams) carry their bytes **inline** — they -/// are cheap to move through the value type. Large artifacts (MoE expert tiles, -/// hundreds of MB) are **mapped**: they reference byte ranges of a backing file -/// on the cold/frozen tier drive and are memory-mapped on read, so they never -/// round-trip through the value type or the message bus. This is the tier-aware -/// handle `ArtifactBlob`'s original `Vec` doc anticipated. -/// -/// A `Mapped` artifact is one **layer's MoE expert set**, memory-mapped from a -/// backing GGUF. `projections` are the stacked `*_exps` tensors' full `(base, -/// total_len)` for that layer (2–3: gate/up/down, or fused gate_up/down); each -/// holds all `n_experts` experts contiguously along dim 0. A single expert's -/// bytes are the stride-slice `base + e*(total_len/n_experts)` of every -/// projection — resolved by [`ArtifactSource::expert_ranges`]. One artifact = -/// one layer set; `PageOffset::Expert{e}` selects the expert, matching the -/// pre-existing `PageKind::MoEExpert` model ("the artifact is the full expert -/// set; offset picks one expert"). Residency still keys on the PAGE -/// (`artifact + offset` = `(layer, expert)`), so it stays per-expert. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum ArtifactSource { - /// Bytes carried inline. LoRA layers, engrams — small enough to move. - Inline(Vec), - /// A layer's expert set in a backing file, memory-mapped on read. The tier - /// store accounts capacity from the projection lengths and NEVER reads the - /// bytes on write (trust + audit-budget reasons, same as the id contract). - Mapped { - /// Absolute path to the backing file (e.g. the K3 GGUF on the frozen tier). - path: PathBuf, - /// How many experts are stacked along dim 0 of every projection. The - /// per-expert stride is `total_len / n_experts`. - n_experts: u32, - /// Each stacked projection tensor's `(absolute_base_offset, total_len)` - /// for the whole layer. 2–3 entries (gate/up/down or fused gate_up/down). - projections: Vec<(u64, u64)>, - }, -} - -impl ArtifactSource { - /// Physical byte size of the WHOLE artifact — the inline length, or the sum - /// of the mapped projections' total lengths (the full layer expert set). - /// Must be the *physical* size the tier store bills against capacity. - pub fn size_bytes(&self) -> u64 { - match self { - ArtifactSource::Inline(bytes) => bytes.len() as u64, - ArtifactSource::Mapped { projections, .. } => { - projections.iter().map(|(_, total)| *total).sum() - } - } - } - - /// Resolve ONE expert's byte ranges within a `Mapped` layer set — the - /// stride-slice `base + e*(total/n_experts)` of every projection. This is - /// THE single place the stacked-slice math lives: the tier read - /// (`PageOffset::Expert{e}`) and per-expert size accounting both call it. - /// `None` for an `Inline` source, a zero-expert set, or an out-of-range index. - pub fn expert_ranges(&self, expert_index: u32) -> Option> { - match self { - ArtifactSource::Inline(_) => None, - ArtifactSource::Mapped { - n_experts, - projections, - .. - } => { - if *n_experts == 0 || expert_index >= *n_experts { - return None; - } - let e = expert_index as u64; - let n = *n_experts as u64; - Some( - projections - .iter() - .map(|(base, total)| { - let stride = total / n; - (base + e * stride, stride) - }) - .collect(), - ) - } - } - } - - /// Physical byte size of ONE expert within a `Mapped` set — the sum of its - /// per-projection strides. `None` for `Inline` / out-of-range. - pub fn expert_size_bytes(&self, expert_index: u32) -> Option { - self.expert_ranges(expert_index) - .map(|ranges| ranges.iter().map(|(_, len)| *len).sum()) - } -} - -/// Opaque bytes of an artifact. PR-2 carries the raw bytes inline -/// for a simple wire shape; later PRs replace with a tier-aware -/// handle (mmap, ref-counted Arc, GPU buffer ID) so large artifacts -/// don't round-trip through the message bus. The serde format is -/// base64 so JSON consumers can read it without needing binary -/// transports. -/// -/// NOT TS-exported — large blobs don't belong on the TS wire. If a TS -/// consumer needs the blob it should request via a separate -/// `download_artifact(artifact_id)` command that streams binary. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct ArtifactBlob { - /// Content-addressed identifier — should match - /// `sha256-derived-uuid(bytes)`. Producers compute this; the tier - /// store does not re-hash on write (trust + audit budget reasons). - pub id: ArtifactId, - /// Where the artifact's bytes live — `Inline` for small artifacts, - /// `Mapped` for large file-backed ones (MoE expert tiles). An inline - /// empty payload is valid (a zero-byte artifact is a legitimate - /// sentinel). - pub source: ArtifactSource, -} - -impl ArtifactBlob { - /// Construct an inline blob — the common small-artifact case (LoRA - /// layer, engram). Keeps callers that had a `Vec` unchanged in - /// spirit: `ArtifactBlob::inline(id, bytes)`. - pub fn inline(id: ArtifactId, bytes: Vec) -> Self { - Self { - id, - source: ArtifactSource::Inline(bytes), - } - } - - /// Construct a file-mapped blob — one layer's MoE expert set, its stacked - /// projections given as `(base, total_len)` into `path`. Zero-copy: the - /// bytes are never read here. `PageOffset::Expert{e}` + `expert_ranges` - /// select an individual expert. - pub fn mapped( - id: ArtifactId, - path: PathBuf, - n_experts: u32, - projections: Vec<(u64, u64)>, - ) -> Self { - Self { - id, - source: ArtifactSource::Mapped { - path, - n_experts, - projections, - }, - } - } - - /// Physical byte size of the artifact — delegates to the source so - /// tier stores can compute capacity impact without reading bytes. - pub fn size_bytes(&self) -> u64 { - self.source.size_bytes() - } -} - -/// PR-2 stub for `Provenance`. The full shape (GENOME-FOUNDRY- -/// SENTINEL Part 1) carries creator, source_trace, source_artifact, -/// supersedes, adaptation_method, outcome_metrics, trust_score, and -/// license fields. PR-2 ships a typed minimum so the `TierStore::write` -/// signature compiles; the full shape is a separate Lane H PR that -/// replaces this stub. -/// -/// PR-2's stub carries: -/// - `artifact_id` — the content hash of the artifact this provenance -/// describes. Required for the typed contract; matches the -/// `ArtifactBlob.id` value passed alongside. -/// - `created_at_ms` — Unix-ms timestamp the provenance was attached. -/// Required for ordering claims about the artifact across federation. -/// -/// When the full shape lands, downstream callers will be able to add -/// the remaining fields without changing the trait surface — this -/// type can grow fields without breaking callers that only set the -/// minimum. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/Provenance.ts" -)] -pub struct Provenance { - pub artifact_id: ArtifactId, - #[ts(type = "number")] - pub created_at_ms: u64, -} - -impl Provenance { - /// Construct a minimal provenance for an artifact at the given - /// timestamp. Convenience for the common case where the caller - /// has only the two required fields. - pub fn minimal(artifact_id: ArtifactId, created_at_ms: u64) -> Self { - Self { - artifact_id, - created_at_ms, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use uuid::Uuid; - - fn sample_id() -> ArtifactId { - ArtifactId::new(Uuid::nil()) - } - - /// What this catches: ArtifactBlob.size_bytes is O(1) bytes.len() - /// and matches the raw byte count. If a future PR adds compression - /// or some other transform, this guard flags the size shifting - /// invisibly — large-blob accounting in TierStore::write depends - /// on this number being the *physical* size, not a logical one. - #[test] - fn artifact_blob_size_matches_byte_length() { - let empty = ArtifactBlob::inline(sample_id(), Vec::new()); - assert_eq!(empty.size_bytes(), 0); - - let one_kb = ArtifactBlob::inline(sample_id(), vec![0u8; 1024]); - assert_eq!(one_kb.size_bytes(), 1024); - - let big = ArtifactBlob::inline(sample_id(), vec![0u8; 1_048_576]); - assert_eq!(big.size_bytes(), 1_048_576); - } - - /// What this catches: a Mapped layer-set blob's size is the SUM of its - /// projection total lengths (the WHOLE layer set), not a byte read — the - /// tier bills the frozen set without touching the (bogus) backing file. - #[test] - fn mapped_blob_size_is_the_sum_of_projection_totals() { - // 3 projections (gate/up/down) for a 4-expert layer, at arbitrary - // offsets in a file that does NOT exist — size must not read it. - let layer = ArtifactBlob::mapped( - sample_id(), - PathBuf::from("/frozen/k3.gguf"), - 4, - vec![(1_000, 4_096), (500_000, 4_096), (900_000, 2_048)], - ); - assert_eq!(layer.size_bytes(), 4_096 + 4_096 + 2_048); - } - - /// What this catches: THE stacked-slice resolver — expert e's ranges are - /// `base + e*(total/n_experts)` of every projection, and out-of-range / - /// Inline yield None. This is the single math the tier read + size - /// accounting share; if it drifts, half the paging layer computes wrong - /// offsets. Uses a nonexistent path to prove it's pure arithmetic. - #[test] - fn expert_ranges_slices_each_projection_by_stride() { - // 4 experts; gate total 256 (stride 64), up total 256 (stride 64), - // down total 128 (stride 32), at bases 1000 / 2000 / 3000. - let set = ArtifactSource::Mapped { - path: PathBuf::from("/frozen/k3.gguf"), - n_experts: 4, - projections: vec![(1_000, 256), (2_000, 256), (3_000, 128)], - }; - // Expert 0: first slice of each projection. - assert_eq!( - set.expert_ranges(0), - Some(vec![(1_000, 64), (2_000, 64), (3_000, 32)]) - ); - // Expert 3: base + 3*stride of each projection. - assert_eq!( - set.expert_ranges(3), - Some(vec![(1_000 + 192, 64), (2_000 + 192, 64), (3_000 + 96, 32)]) - ); - // One expert's size = sum of its per-projection strides. - assert_eq!(set.expert_size_bytes(0), Some(64 + 64 + 32)); - // Out of range (index == n_experts) and Inline → None. - assert_eq!(set.expert_ranges(4), None); - assert_eq!(ArtifactSource::Inline(vec![1, 2, 3]).expert_ranges(0), None); - } - - /// What this catches: ArtifactBlob is intentionally NOT TS-exported. - /// If a future PR adds `#[derive(TS)]`, this test won't compile - /// (the derive would conflict with the explicit absence) — flag - /// for review. The TS wire should request artifacts via a binary - /// download command, not inline them in JSON messages. - #[test] - fn artifact_blob_round_trips_through_serde() { - let blob = ArtifactBlob::inline(sample_id(), vec![1, 2, 3, 4, 5]); - let json = serde_json::to_string(&blob).unwrap(); - let back: ArtifactBlob = serde_json::from_str(&json).unwrap(); - assert_eq!(blob, back); - } - - /// What this catches: Provenance.minimal constructor populates - /// both required fields exactly as passed. PR-2's contract: a - /// caller building a minimal provenance gets exactly what they - /// asked for, no defaults / no transforms. - #[test] - fn provenance_minimal_preserves_fields() { - let prov = Provenance::minimal(sample_id(), 1_700_000_000_000); - assert_eq!(prov.artifact_id, sample_id()); - assert_eq!(prov.created_at_ms, 1_700_000_000_000); - } - - /// What this catches: Provenance serializes camelCase on the wire - /// (`createdAtMs`, not `created_at_ms`). Downstream TS consumers - /// parse the camelCase form. - #[test] - fn provenance_serializes_camel_case() { - let prov = Provenance::minimal(sample_id(), 1234); - let j = serde_json::to_string(&prov).unwrap(); - assert!(j.contains("\"createdAtMs\":1234"), "got {j}"); - assert!(j.contains("\"artifactId\":"), "got {j}"); - } -} diff --git a/core/continuum-genome/src/genome/bus.rs b/core/continuum-genome/src/genome/bus.rs deleted file mode 100644 index 600eebde5a..0000000000 --- a/core/continuum-genome/src/genome/bus.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! Artifact-key constants + bus publishing helpers for genome -//! events. PR-4 of working-set-manager. -//! -//! Background: PR-1 (#1346) shipped the typed `PageFault`, -//! `EvictionRecord`, and `AccessDenied` events. PR-2 (#1353) named -//! them on the trait surface. PR-3 (#1355) impl returns them through -//! its `Result` arms (PageFault) and direct method returns -//! (AccessDenied). What's been missing is the wire — what -//! ArtifactKey + payload shape downstream subscribers (audit-recorder -//! #1344, sentinel-observer, demand-aligned-recall) bind to. -//! -//! This module fills that gap with three building blocks: -//! -//! 1. **Canonical `ArtifactKey` constants** — every genome event has -//! one stable key. Subscribers refer to the constant, not a string -//! literal, so the wire stays consistent across renames. -//! -//! 2. **Publishing helpers** — `publish_page_fault`, etc. Each takes -//! the bus + registry + the typed event, serializes the payload, -//! and publishes through the artifact dispatch path I shipped in -//! #1339 + #1343. Callers don't construct keys / serialize / route -//! by hand. -//! -//! 3. **Subscriber convenience** — `subscribe_to_genome_events` wires -//! a module to all three keys at once via `bus.subscribe_artifact` -//! (the path #1343 added). -//! -//! ## What PR-4 does NOT do (PR-5) -//! -//! Wiring the helpers INTO `LocalWorkingSetManager` so its -//! `page_in`/`page_out`/`audit_access` auto-publish after each call. -//! That decorator/extension lands in PR-5. PR-4 ships the wire -//! definitions + helpers so that PR-5 only needs to plumb the bus + -//! registry references; the keys + payloads are already canonical. -//! -//! Why split: the wire shape is the coordination point with codex's -//! audit-recorder (#1344, subscribes to `AccessDenied`) + sentinel- -//! observer (subscribes to `PageFault`). Naming the keys + publishing -//! helpers in their own PR locks the contract first, lets downstream -//! subscribers wire to it BEFORE the LocalWorkingSetManager -//! integration (PR-5) plumbs them in. - -use crate::runtime::artifact_handle::{ArtifactKey, ArtifactSelector}; -use crate::runtime::message_bus::MessageBus; -use crate::runtime::registry::ModuleRegistry; - -use super::tier::EvictionRecord; -use super::working_set::{AccessDenied, PageFault}; - -// ─── Canonical ArtifactKey constants ───────────────────────────── - -/// ArtifactKey for `PageFault` events. Published every time the -/// working-set manager services a page-fault (true cold miss OR tier -/// promotion). Subscribers: sentinel-observer (learns persona access -/// patterns from these), demand-aligned-recall (caches ResidencyHint -/// based on which pages a persona keeps faulting on). -pub const PAGE_FAULT_KEY: &str = "genome/working_set.page_fault"; - -/// ArtifactKey for `EvictionRecord` events. Published every time a -/// tier evicts a page. Subscribers: sentinel-observer (recurring -/// evictions on the same page = signal to upgrade the page's tier -/// policy), audit-recorder (governor-driven evictions become a -/// `GovernorOverride` audit entry). -pub const EVICTION_RECORD_KEY: &str = "genome/working_set.eviction"; - -/// ArtifactKey for `AccessDenied` events from the MMU-style audit. -/// Published every time `audit_access` denies a cross-persona read. -/// Subscribers: audit-recorder (#1344, this is one of its four -/// canonical audit-entry inputs). -pub const ACCESS_DENIED_KEY: &str = "genome/working_set.access_denied"; - -// ─── Publishing helpers ───────────────────────────────────────── - -/// Publish a `PageFault` to the trace bus under the canonical key. -/// Async — uses `MessageBus::publish` (the path that walks the -/// artifact-subscription list I shipped in #1343). -/// -/// Serialization failures fall back to `Value::Null` rather than -/// panicking — the `PageFault` shape is serde-derived and known to -/// serialize cleanly, so a failure here would indicate substrate -/// corruption, not a user-visible bug. The trace bus still fires -/// (with empty payload) so subscribers see something happened. -pub async fn publish_page_fault(bus: &MessageBus, registry: &ModuleRegistry, fault: &PageFault) { - let payload = serde_json::to_value(fault).unwrap_or(serde_json::Value::Null); - bus.publish(PAGE_FAULT_KEY, payload, registry).await; -} - -/// Publish an `EvictionRecord` to the trace bus under the canonical -/// key. Same async + serde semantics as `publish_page_fault`. -pub async fn publish_eviction_record( - bus: &MessageBus, - registry: &ModuleRegistry, - record: &EvictionRecord, -) { - let payload = serde_json::to_value(record).unwrap_or(serde_json::Value::Null); - bus.publish(EVICTION_RECORD_KEY, payload, registry).await; -} - -/// Publish an `AccessDenied` to the trace bus under the canonical -/// key. Async — `audit_access` is sync on the trait but PR-5's -/// integration will spawn the publish into a tokio task so the sync -/// caller doesn't block. Standalone callers (e.g. testing or -/// manually-publishing code) `.await` directly. -pub async fn publish_access_denied( - bus: &MessageBus, - registry: &ModuleRegistry, - denied: &AccessDenied, -) { - let payload = serde_json::to_value(denied).unwrap_or(serde_json::Value::Null); - bus.publish(ACCESS_DENIED_KEY, payload, registry).await; -} - -// ─── Subscriber convenience ───────────────────────────────────── - -/// Wire a module to ALL three genome event types at once via the -/// artifact-subscription path (#1343). Convenience for modules that -/// want the full firehose — sentinel-observer, audit-recorder -/// extensions, performance harness observers. -/// -/// Modules that only want one event type call `bus.subscribe_artifact` -/// directly with the specific key constant. This helper exists for -/// the common case + to anchor the per-module ServiceModule -/// `artifact_subscriptions()` return values: -/// -/// ```ignore -/// fn artifact_subscriptions(&self) -> Vec { -/// all_genome_artifact_selectors() -/// } -/// ``` -pub fn subscribe_to_genome_events(bus: &MessageBus, module_name: &'static str) { - for selector in all_genome_artifact_selectors() { - bus.subscribe_artifact(selector, module_name); - } -} - -/// Return the full set of genome `ArtifactSelector::Exact` entries. -/// Useful for `ServiceModule::artifact_subscriptions()` returns and -/// for unit tests that want to enumerate the canonical event surface -/// without duplicating the key list. -pub fn all_genome_artifact_selectors() -> Vec { - vec![ - ArtifactSelector::Exact(ArtifactKey::from(PAGE_FAULT_KEY)), - ArtifactSelector::Exact(ArtifactKey::from(EVICTION_RECORD_KEY)), - ArtifactSelector::Exact(ArtifactKey::from(ACCESS_DENIED_KEY)), - ] -} - -#[cfg(test)] -mod tests { - //! End-to-end tests: a recording ServiceModule subscribes via the - //! convenience helper, the publishing helpers fire, the subscriber - //! sees the right key + payload. This wires the whole #1339+#1343 - //! dispatch path end-to-end for genome events. - use super::*; - use crate::genome::tier::{EvictionPolicy, TierRole}; - use crate::inference::page_ref::{ArtifactId, PageKind, PageOffset, PageRef}; - use crate::identity::PeerId; - use crate::runtime::runtime::Runtime; - use crate::runtime::service_module::{ - CommandResult, ModuleConfig, ModulePriority, ServiceModule, - }; - use async_trait::async_trait; - use parking_lot::Mutex; - use std::any::Any; - use std::sync::Arc; - use uuid::Uuid; - - /// Recording module: subscribes to all three genome keys, captures - /// every (key, payload) pair. Tests assert which fired + the - /// payload round-trips through serde. - struct RecordingModule { - name: &'static str, - captured: Arc>>, - } - - impl RecordingModule { - fn new(name: &'static str) -> (Arc, Arc>>) { - let captured = Arc::new(Mutex::new(Vec::new())); - let module = Arc::new(Self { - name, - captured: captured.clone(), - }); - (module, captured) - } - } - - #[async_trait] - impl ServiceModule for RecordingModule { - fn config(&self) -> ModuleConfig { - ModuleConfig { - name: self.name, - priority: ModulePriority::Normal, - command_prefixes: &[], - event_subscriptions: &[], - needs_dedicated_thread: false, - max_concurrency: 0, - tick_interval: None, - } - } - async fn initialize(&self, _ctx: &crate::runtime::ModuleContext) -> Result<(), String> { - Ok(()) - } - async fn handle_command( - &self, - _: &str, - _: serde_json::Value, - ) -> Result { - Err("not handled".to_string()) - } - fn artifact_subscriptions(&self) -> Vec { - all_genome_artifact_selectors() - } - async fn on_artifact_available( - &self, - key: &ArtifactKey, - payload: serde_json::Value, - ) -> Result<(), String> { - self.captured - .lock() - .push((key.as_str().to_string(), payload)); - Ok(()) - } - fn as_any(&self) -> &dyn Any { - self - } - } - - fn sample_persona(low_bits: u128) -> PeerId { - PeerId::from_uuid(Uuid::from_u128(low_bits)) - } - - fn sample_page() -> PageRef { - PageRef { - kind: PageKind::LoRALayer, - artifact: ArtifactId::new(Uuid::nil()), - offset: PageOffset::Whole, - } - } - - /// What this catches: the three artifact-key constants don't - /// silently drift. Subscribers in other modules (audit-recorder, - /// sentinel-observer) refer to these constants; if a future PR - /// renames a string, this test pins the canonical wire value so - /// the rename is deliberate. - #[test] - fn artifact_keys_have_canonical_string_values() { - assert_eq!(PAGE_FAULT_KEY, "genome/working_set.page_fault"); - assert_eq!(EVICTION_RECORD_KEY, "genome/working_set.eviction"); - assert_eq!(ACCESS_DENIED_KEY, "genome/working_set.access_denied"); - } - - /// What this catches: `all_genome_artifact_selectors` returns - /// every key as `ArtifactSelector::Exact` — never `Prefix` (which - /// has different match semantics) and never missing a key. If a - /// future PR adds a fourth event type, this test should fail (to - /// force the author to add it here + verify the wire contract). - #[test] - fn all_genome_selectors_cover_every_key_as_exact() { - let selectors = all_genome_artifact_selectors(); - assert_eq!(selectors.len(), 3); - - let exact_keys: Vec = selectors - .iter() - .filter_map(|s| match s { - ArtifactSelector::Exact(k) => Some(k.as_str().to_string()), - ArtifactSelector::Prefix(_) => None, - }) - .collect(); - assert_eq!(exact_keys.len(), 3, "all entries must be Exact"); - assert!(exact_keys.contains(&PAGE_FAULT_KEY.to_string())); - assert!(exact_keys.contains(&EVICTION_RECORD_KEY.to_string())); - assert!(exact_keys.contains(&ACCESS_DENIED_KEY.to_string())); - } - - /// What this catches: `publish_page_fault` lands on the - /// PAGE_FAULT_KEY artifact key with the serialized PageFault - /// payload. End-to-end test for the #1339+#1343 dispatch path - /// applied to genome events. - #[tokio::test] - async fn publish_page_fault_routes_to_subscribed_module() { - let runtime = Runtime::new(); - let (module, captured) = RecordingModule::new("recorder-fault"); - runtime.register(module); - - let fault = PageFault { - page: sample_page(), - from_role: Some(TierRole::Cold), - to_role: TierRole::Fast, - persona: sample_persona(1), - elapsed_us: 123, - eviction_cost: None, - }; - publish_page_fault(runtime.bus(), runtime.registry(), &fault).await; - - let events = captured.lock().clone(); - let fault_events: Vec<_> = events.iter().filter(|(k, _)| k == PAGE_FAULT_KEY).collect(); - assert_eq!(fault_events.len(), 1); - let (_, payload) = fault_events[0]; - // Payload round-trips back into PageFault — the serde shape - // is wire-stable for the subscriber. - let back: PageFault = serde_json::from_value(payload.clone()).unwrap(); - assert_eq!(back, fault); - } - - /// What this catches: `publish_eviction_record` lands on the - /// EVICTION_RECORD_KEY. Different key from page_fault — a - /// subscriber that only subscribed to PAGE_FAULT_KEY doesn't see - /// eviction events. - #[tokio::test] - async fn publish_eviction_record_routes_to_correct_key() { - let runtime = Runtime::new(); - let (module, captured) = RecordingModule::new("recorder-evict"); - runtime.register(module); - - let record = EvictionRecord { - page: sample_page(), - from_role: TierRole::Fast, - to_role: Some(TierRole::Bench), - policy_fired: EvictionPolicy::LruWithinTurn, - elapsed_us: 42, - }; - publish_eviction_record(runtime.bus(), runtime.registry(), &record).await; - - let events = captured.lock().clone(); - let evict_events: Vec<_> = events - .iter() - .filter(|(k, _)| k == EVICTION_RECORD_KEY) - .collect(); - assert_eq!(evict_events.len(), 1); - let back: EvictionRecord = serde_json::from_value(evict_events[0].1.clone()).unwrap(); - assert_eq!(back, record); - } - - /// What this catches: `publish_access_denied` lands on the - /// ACCESS_DENIED_KEY. This is the audit-recorder (#1344) - /// integration point — audit-recorder subscribes to this key as - /// one of its four canonical audit inputs. - #[tokio::test] - async fn publish_access_denied_routes_to_audit_input_key() { - let runtime = Runtime::new(); - let (module, captured) = RecordingModule::new("recorder-denied"); - runtime.register(module); - - let denied = AccessDenied { - actor: sample_persona(1), - page: sample_page(), - owner: Some(sample_persona(2)), - reason: "cross-persona read blocked".to_string(), - }; - publish_access_denied(runtime.bus(), runtime.registry(), &denied).await; - - let events = captured.lock().clone(); - let denied_events: Vec<_> = events - .iter() - .filter(|(k, _)| k == ACCESS_DENIED_KEY) - .collect(); - assert_eq!(denied_events.len(), 1); - let back: AccessDenied = serde_json::from_value(denied_events[0].1.clone()).unwrap(); - assert_eq!(back, denied); - } - - /// What this catches: a module subscribing via the convenience - /// helper sees all THREE events when each fires. The helper IS - /// the bridge between the canonical key set + the - /// `bus.subscribe_artifact` API I shipped in #1343. - #[tokio::test] - async fn convenience_helper_subscribes_to_all_three_event_types() { - let runtime = Runtime::new(); - let (module, captured) = RecordingModule::new("recorder-all"); - runtime.register(module); - - // Fire all three event types. - let fault = PageFault { - page: sample_page(), - from_role: None, - to_role: TierRole::Fast, - persona: sample_persona(1), - elapsed_us: 0, - eviction_cost: None, - }; - let evict = EvictionRecord { - page: sample_page(), - from_role: TierRole::Fast, - to_role: None, - policy_fired: EvictionPolicy::AppendOnlyGcOnSleep, - elapsed_us: 0, - }; - let denied = AccessDenied { - actor: sample_persona(1), - page: sample_page(), - owner: None, - reason: "test".into(), - }; - publish_page_fault(runtime.bus(), runtime.registry(), &fault).await; - publish_eviction_record(runtime.bus(), runtime.registry(), &evict).await; - publish_access_denied(runtime.bus(), runtime.registry(), &denied).await; - - let events = captured.lock().clone(); - let keys: Vec = events.iter().map(|(k, _)| k.clone()).collect(); - assert!(keys.contains(&PAGE_FAULT_KEY.to_string())); - assert!(keys.contains(&EVICTION_RECORD_KEY.to_string())); - assert!(keys.contains(&ACCESS_DENIED_KEY.to_string())); - assert_eq!(events.len(), 3, "exactly one of each event delivered"); - } - - /// What this catches: a module subscribing ONLY to PAGE_FAULT_KEY - /// (via direct `bus.subscribe_artifact` call, not the convenience - /// helper) sees PageFault events but NOT EvictionRecord. This - /// proves the keys are independent — sentinel-observer that wants - /// only page-faults isn't forced to filter every event. - #[tokio::test] - async fn selective_subscriber_only_sees_its_subscribed_key() { - let runtime = Runtime::new(); - - // Module subscribes only to PAGE_FAULT_KEY. - struct PageFaultOnly { - captured: Arc>>, - } - #[async_trait] - impl ServiceModule for PageFaultOnly { - fn config(&self) -> ModuleConfig { - ModuleConfig { - name: "page-fault-only", - priority: ModulePriority::Normal, - command_prefixes: &[], - event_subscriptions: &[], - needs_dedicated_thread: false, - max_concurrency: 0, - tick_interval: None, - } - } - async fn initialize(&self, _: &crate::runtime::ModuleContext) -> Result<(), String> { - Ok(()) - } - async fn handle_command( - &self, - _: &str, - _: serde_json::Value, - ) -> Result { - Err("not handled".to_string()) - } - fn artifact_subscriptions(&self) -> Vec { - vec![ArtifactSelector::Exact(ArtifactKey::from(PAGE_FAULT_KEY))] - } - async fn on_artifact_available( - &self, - key: &ArtifactKey, - _: serde_json::Value, - ) -> Result<(), String> { - self.captured.lock().push(key.as_str().to_string()); - Ok(()) - } - fn as_any(&self) -> &dyn Any { - self - } - } - - let captured: Arc>> = Arc::new(Mutex::new(Vec::new())); - let module = Arc::new(PageFaultOnly { - captured: captured.clone(), - }); - runtime.register(module); - - let fault = PageFault { - page: sample_page(), - from_role: None, - to_role: TierRole::Fast, - persona: sample_persona(1), - elapsed_us: 0, - eviction_cost: None, - }; - let evict = EvictionRecord { - page: sample_page(), - from_role: TierRole::Fast, - to_role: None, - policy_fired: EvictionPolicy::AppendOnlyGcOnSleep, - elapsed_us: 0, - }; - publish_page_fault(runtime.bus(), runtime.registry(), &fault).await; - publish_eviction_record(runtime.bus(), runtime.registry(), &evict).await; - - let events = captured.lock().clone(); - assert_eq!( - events.len(), - 1, - "only one event delivered to selective subscriber" - ); - assert_eq!(events[0], PAGE_FAULT_KEY); - } -} diff --git a/core/continuum-genome/src/genome/competence.rs b/core/continuum-genome/src/genome/competence.rs index 52313f098b..a2e972d982 100644 --- a/core/continuum-genome/src/genome/competence.rs +++ b/core/continuum-genome/src/genome/competence.rs @@ -344,6 +344,7 @@ mod tests { corpus: CorpusRef { name: "t".into(), content_hash: "sha256:0".into(), size_bytes: 0, source_url: None }, minted_at_ms: 0, parent: None, + region: None, }; let mut store = SignatureStore::default(); store.by_path.insert("/g/far.gguf".into(), sig("e1", vec![0.0, 1.0])); diff --git a/core/continuum-genome/src/genome/composer.rs b/core/continuum-genome/src/genome/composer.rs new file mode 100644 index 0000000000..b6d5850d04 --- /dev/null +++ b/core/continuum-genome/src/genome/composer.rs @@ -0,0 +1,335 @@ +//! Her PHENOTYPE for a turn: which of her genes shape it, and at what scale +//! (GENE-REUSE-FORK-MINT §3d, the APPLIED tier). Every gene whose region the turn's perception +//! is inside, several at once, weighted by how deep inside each one is, the way a mixture of +//! experts routes. Joel, 2026-10-24: "Goal was many with weights." +//! +//! The one composer. The turn sites ask [`compose`]; the pure core is [`select`]; an examiner +//! compares `P` with [`Phenotype::without`] one gene (that gene at 0, every other unchanged). +//! +//! # The rule +//! +//! - **Inside.** A gene's floor `f` is its own spread +//! ([`GeneSignature::region`](crate::genome::signature::GeneSignature): the 10th-percentile +//! similarity of its own corpus, filed at mint), never below the space's measured unrelated +//! null + 2σ (a diffuse gene must not ride every turn). A gene with neither, or signed in +//! another embedding space, cannot be routed by distance: it runs at its trained scale as every +//! gene did before routing existed (a gene never leaves her head by silence), named unrouted. +//! - **Weight.** `a = clamp((sim - f) / (1 - f), 0, 1)`: 0 at the floor, 1 at the center, so a +//! broad gene and a narrow one compare on the same footing. The `capacity` heaviest are kept +//! (the genes the engine holds on the device; the working-set owner says how many), and each +//! runs at `a / max(1, Σa)`: one gene alone runs at its depth, never above its trained 1.0, and +//! the deltas of several never sum past one trained adapter's magnitude. +//! - **Hysteresis.** A gene enters at its floor (distance `r = 1 - f`) and stays until the +//! distance passes `1.5 r` (§3d), so a topic at a region's edge does not switch it every turn. +//! - **Held while the set holds.** The engine clears a slot's KV whenever its adapter scales +//! change at all (fork `are_lora_equal` compares scales exactly; server-context +//! `lora_should_clear_cache`), so re-weighting each turn would re-prefill her whole context +//! every turn. Scales are computed when the routed SET changes (which costs that re-prefill +//! anyway) and held bit-identical until it changes again. A gene kept only by hysteresis has +//! `a = 0`, so the next recompute drops it. +//! - **No perception, no change.** Without a perception embedding, routed genes stay as they were. + +use std::collections::BTreeMap; + +use uuid::Uuid; + +use crate::ai::types::ActiveAdapterRequest; +use crate::genome::gene_trial::Standing; +use crate::genome::signature::{GeneSignature, SignatureStore}; + +/// How many σ above the space's unrelated null a region edge must sit: the same 2σ +/// discipline recall gates with (`recall_faculty`'s significance ranker). +const NULL_SIGMAS: f32 = 2.0; + +/// The leave edge's distance, as a multiple of the enter edge's (GENE-REUSE-FORK-MINT §3d: +/// "enter at r, leave at 1.5 r"). +const LEAVE_DISTANCE_RATIO: f32 = 1.5; + +/// The turn's perception, embedded once by the caller (the composer stays pure and sync). +#[derive(Debug, Clone, Copy)] +pub struct Need<'a> { + pub embedder_id: &'a str, + pub vector: &'a [f32], + /// The space's MEASURED unrelated-cosine null `(mean, std)`, when known. + pub unrelated_null: Option<(f32, f32)>, +} + +/// One gene she could run this turn, with its signature when one was minted. +#[derive(Debug, Clone)] +pub struct Candidate<'a> { + pub gene: ActiveAdapterRequest, + pub signature: Option<&'a GeneSignature>, +} + +/// How a considered gene was routed this turn. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Route { + /// Compared by distance: its similarity, the edges it was held to, its depth `a`. + Distance { similarity: f32, floor: f32, leave: f32, weight: f32, inside: bool }, + /// No usable signature in the need's space: applied at its trained scale. + Unrouted, + /// Signed, but the turn had no need to compare: kept as it was. + Kept, +} + +/// One row of "why was this gene in her head" (the `genome.select` probe). +#[derive(Debug, Clone, PartialEq)] +pub struct Considered { + pub name: String, + pub path: String, + pub route: Route, + /// The scale it runs at this turn; 0 = off. + pub scale: f64, +} + +/// A phenotype: the genes a turn runs with and their engine scales, heaviest first. Empty = the +/// base alone. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Phenotype { + pub genes: Vec, +} + +impl Phenotype { + /// `P ∖ g`: the same phenotype with gene `path` off and every other gene at its scale in `P` + /// (the examiner's comparison: `g` at its weight vs at 0, nothing else moved). + pub fn without(&self, path: &str) -> Phenotype { + Phenotype { genes: self.genes.iter().filter(|g| g.path != path).cloned().collect() } + } + + /// The scale `path` runs at in this phenotype; 0 when it is not in it. + pub fn scale_of(&self, path: &str) -> f64 { + self.genes.iter().find(|g| g.path == path).map_or(0.0, |g| g.scale) + } +} + +/// What [`select`] decided. +#[derive(Debug, Clone, PartialEq)] +pub struct Selection { + pub phenotype: Phenotype, + pub considered: Vec, + /// The applied set or a scale differs from the previous turn's: the engine clears her + /// slot's KV and she re-prefills her context. + pub changed: bool, +} + +/// PURE: the floor (enter edge) and leave edge of a signed gene in the perception's space, or +/// `None` when it cannot be routed (no region and no measured null). +fn edges(signature: &GeneSignature, need: &Need<'_>) -> Option<(f32, f32)> { + let null_edge = need.unrelated_null.map(|(mean, std)| mean + NULL_SIGMAS * std); + let floor = match (signature.region, null_edge) { + (Some(region), Some(null)) => region.max(null), + (Some(region), None) => region, + (None, Some(null)) => null, + (None, None) => return None, + }; + Some((floor, 1.0 - LEAVE_DISTANCE_RATIO * (1.0 - floor))) +} + +/// PURE: the phenotype for a turn, given her candidate genes, the turn's perception, how many +/// genes the engine holds (`capacity`), and what she ran last turn (`previous`, with scales). +/// See the module docs for the rule. +pub fn select( + need: Option<&Need<'_>>, + candidates: &[Candidate<'_>], + capacity: usize, + previous: &[ActiveAdapterRequest], +) -> Selection { + let was: BTreeMap<&str, f64> = previous + .iter() + .filter(|g| g.scale != 0.0) + .map(|g| (g.path.as_str(), g.scale)) + .collect(); + let routes: Vec = candidates.iter().map(|c| route(c, need, was.contains_key(c.gene.path.as_str()))).collect(); + + // The routed genes in the set: inside (or held by hysteresis), heaviest `capacity` of them. + let mut kept: Vec<(usize, f32)> = routes + .iter() + .enumerate() + .filter_map(|(i, r)| match *r { + Route::Distance { weight, inside: true, .. } => Some((i, weight)), + _ => None, + }) + .collect(); + kept.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| candidates[a.0].gene.path.cmp(&candidates[b.0].gene.path))); + kept.truncate(capacity); + let routed_was = routes + .iter() + .zip(candidates) + .filter(|(r, c)| matches!(r, Route::Distance { .. }) && was.contains_key(c.gene.path.as_str())) + .count(); + let held: Option> = kept + .iter() + .map(|(i, _)| was.get(candidates[*i].gene.path.as_str()).copied()) + .collect::>>() + .filter(|w| w.len() == routed_was); + let total: f32 = kept.iter().map(|(_, a)| a).sum(); + let mut scales = vec![0.0f64; candidates.len()]; + for (k, &(i, a)) in kept.iter().enumerate() { + scales[i] = match &held { + Some(w) => w[k], + None => f64::from(a / total.max(1.0)), + }; + } + for (i, r) in routes.iter().enumerate() { + match r { + Route::Unrouted => scales[i] = 1.0, + Route::Kept => { + if let Some(&w) = was.get(candidates[i].gene.path.as_str()) { + scales[i] = w; + } + } + Route::Distance { .. } => {} + } + } + + let mut on: Vec = (0..candidates.len()).filter(|&i| scales[i] != 0.0).collect(); + on.sort_by(|&a, &b| scales[b].total_cmp(&scales[a]).then_with(|| candidates[a].gene.path.cmp(&candidates[b].gene.path))); + let genes: Vec = on + .into_iter() + .map(|i| ActiveAdapterRequest { scale: scales[i], ..candidates[i].gene.clone() }) + .collect(); + let now: BTreeMap<&str, f64> = genes.iter().map(|g| (g.path.as_str(), g.scale)).collect(); + let changed = now != was; + let considered = candidates + .iter() + .zip(routes) + .zip(scales) + .map(|((c, route), scale)| Considered { name: c.gene.name.clone(), path: c.gene.path.clone(), route, scale }) + .collect(); + Selection { changed, phenotype: Phenotype { genes }, considered } +} + +/// PURE: how one candidate is routed this turn (`was_on`: it ran last turn). +fn route(candidate: &Candidate<'_>, need: Option<&Need<'_>>, was_on: bool) -> Route { + let Some(signature) = candidate.signature else { + return Route::Unrouted; + }; + let Some(need) = need else { + return Route::Kept; + }; + let (Some(similarity), Some((floor, leave))) = + (signature.similarity_in(need.embedder_id, need.vector), edges(signature, need)) + else { + return Route::Unrouted; + }; + let weight = ((similarity - floor) / (1.0 - floor)).clamp(0.0, 1.0); + let inside = weight > 0.0 || (was_on && similarity >= leave); + Route::Distance { similarity, floor, leave, weight, inside } +} + +/// Her phenotype for the next turn, composed from `perception` (what her mind is on: the turn's +/// focused line). `None` when her genome cannot be read (no serving base, an unreadable trial +/// file): the caller then keeps the genome she has, and the reason is on the probe stream. +pub async fn compose(persona: Uuid, perception: &str) -> Option { + let base = crate::inference::llama_server::current_serving().active_model?; + let store = crate::genome::gene_trial::GeneTrials::default_store()?; + let trials = match store.load() { + Ok(trials) => trials, + Err(error) => { + continuum_base::probe!( + class = "genome.trial.unreadable", + persona = %persona, + error = error.as_str(), + "the gene trial file did not read: this turn keeps the genome she has" + ); + return None; + } + }; + let residency = crate::genome::gene_residency::GeneResidency::global(); + let now_ms = continuum_base::time::EpochMs::now().millis(); + let all = crate::genome::gene_trial::her_genes(&trials, persona, &base); + let pending = all.iter().filter(|(_, standing)| *standing == Standing::Pending).count(); + let genes: Vec = + all.into_iter().filter(|(_, standing)| standing.may_run()).map(|(gene, _)| gene).collect(); + if genes.is_empty() { + residency.record_turn(persona, &Phenotype::default(), now_ms); + return Some(Phenotype::default()); + } + let signatures = match crate::genome::signature::signature_store_path().and_then(|p| SignatureStore::load_at(&p)) { + Ok(store) => store, + Err(error) => { + continuum_base::probe!( + class = "genome.select.signatures_unreadable", + persona = %persona, + error = error.as_str(), + "the signature sidecar did not read: her genes run unrouted this turn" + ); + SignatureStore::default() + } + }; + let candidates: Vec> = genes + .into_iter() + .map(|gene| { + let signature = signatures.by_path.get(&gene.path); + Candidate { gene, signature } + }) + .collect(); + let embedded = if candidates.iter().any(|c| c.signature.is_some()) && !perception.trim().is_empty() { + let embedder = crate::ai::embedding::resolve_recall_embedder_local().await; + Some((embedder.id().to_string(), embedder.embed(perception).await, embedder.unrelated_null())) + } else { + None + }; + let need = embedded.as_ref().map(|(id, vector, null)| Need { + embedder_id: id, + vector, + unrelated_null: *null, + }); + let previous = residency.previous(persona); + // Capacity: every gene she may run. Each is loaded in the engine (her trial loaded it), and + // one in host RAM pages back in on demand; the residency owner keeps her current ones on the + // device and pages the cold ones out under the one device budget. + let selection = select(need.as_ref(), &candidates, candidates.len(), &previous); + probe_selection(persona, &selection, pending); + residency.record_turn(persona, &selection.phenotype, now_ms); + residency.schedule_reconcile(); + Some(selection.phenotype) +} + +/// `genome.select`: every gene considered, its similarity, floor, leave edge, depth and the +/// scale it runs at; and, when the set changed, what the change costs her. +fn probe_selection(persona: Uuid, selection: &Selection, pending: usize) { + let rows: Vec = selection + .considered + .iter() + .map(|c| match c.route { + Route::Distance { similarity, floor, leave, weight, .. } => format!( + "{} sim={similarity:.3} floor={floor:.3} leave={leave:.3} a={weight:.3} scale={:.3}", + c.name, c.scale + ), + Route::Unrouted => format!("{} unrouted scale={:.3}", c.name, c.scale), + Route::Kept => format!("{} kept scale={:.3}", c.name, c.scale), + }) + .collect(); + continuum_base::probe!( + class = "genome.select", + persona = %persona, + considered = selection.considered.len() as u64, + pending = pending as u64, + applied = selection.phenotype.genes.len() as u64, + changed = selection.changed, + genes = %rows.join("; "), + "the genes this turn runs with, by distance from what her mind is on" + ); + if selection.changed { + continuum_base::probe!( + class = "genome.select.set_changed", + persona = %persona, + applied = selection.phenotype.genes.len() as u64, + "her gene set or a scale changed: the engine clears her slot's KV and she re-prefills her context, and her slot batches only with minds running the same set" + ); + } +} + +/// The `persona.genome.turn_genes` rendering of a phenotype: each gene and its scale. +pub fn render(phenotype: &Phenotype) -> String { + phenotype + .genes + .iter() + .map(|g| format!("{}={:.3}", g.name, g.scale)) + .collect::>() + .join(",") +} + +#[cfg(test)] +mod tests; diff --git a/core/continuum-genome/src/genome/composer/tests.rs b/core/continuum-genome/src/genome/composer/tests.rs new file mode 100644 index 0000000000..2132ecc965 --- /dev/null +++ b/core/continuum-genome/src/genome/composer/tests.rs @@ -0,0 +1,168 @@ +//! The composer's contract: many genes by distance, weighted by depth, top-k, held, hysteresis. + +use super::*; +use crate::genome::corpus_ref::CorpusRef; + +const SPACE: &str = "space"; + +fn unit(v: [f32; 3]) -> Vec { + let n = v.iter().map(|x| x * x).sum::().sqrt(); + v.iter().map(|x| x / n).collect() +} + +fn signature(centroid: [f32; 3], region: Option) -> GeneSignature { + GeneSignature { + embedder: SPACE.into(), + dim: 3, + centroid: unit(centroid), + subspaces: vec![], + corpus: CorpusRef { name: "t".into(), content_hash: "sha256:0".into(), size_bytes: 0, source_url: None }, + minted_at_ms: 0, + parent: None, + region, + } +} + +fn gene(name: &str) -> ActiveAdapterRequest { + ActiveAdapterRequest { name: name.into(), path: format!("/genes/{name}.gguf"), domain: String::new(), scale: 1.0 } +} + +fn ran(name: &str, scale: f64) -> ActiveAdapterRequest { + ActiveAdapterRequest { scale, ..gene(name) } +} + +fn pick_k<'a>( + need: [f32; 3], + genes: &[(&str, Option<&'a GeneSignature>)], + capacity: usize, + previous: &[ActiveAdapterRequest], +) -> Selection { + let vector = unit(need); + let need = Need { embedder_id: SPACE, vector: &vector, unrelated_null: None }; + let candidates: Vec> = genes.iter().map(|(n, s)| Candidate { gene: gene(n), signature: *s }).collect(); + select(Some(&need), &candidates, capacity, previous) +} + +fn pick<'a>(need: [f32; 3], genes: &[(&str, Option<&'a GeneSignature>)], previous: &[ActiveAdapterRequest]) -> Selection { + pick_k(need, genes, genes.len(), previous) +} + +fn scale(sel: &Selection, name: &str) -> f64 { + sel.phenotype.scale_of(&format!("/genes/{name}.gguf")) +} + +// what this catches: the one-gene `max_by` (rung 0) and the every-gene-at-1.0 composer the +// design replaced. Two genes the turn is inside BOTH apply, the nearer one heavier, their scales +// a / max(1, Σa); a far gene stays off; one gene alone runs at its depth, never above 1.0. +#[test] +fn two_near_genes_both_apply_weighted_by_depth_and_a_far_one_stays_off() { + let parse = signature([1.0, 0.0, 0.0], Some(0.8)); + let lex = signature([0.8, 0.6, 0.0], Some(0.8)); + let tax = signature([0.0, 0.0, 1.0], Some(0.8)); + let sel = pick([1.0, 0.3, 0.0], &[("parse", Some(&parse)), ("lex", Some(&lex)), ("tax", Some(&tax))], &[]); + assert_eq!(sel.phenotype.genes.len(), 2, "{sel:?}"); + let (p, l) = (scale(&sel, "parse"), scale(&sel, "lex")); + assert!(p > l && l > 0.0, "nearer gene heavier: parse {p}, lex {l}"); + assert!((p + l - 1.0).abs() < 1e-6, "Σa > 1 here, so the scales sum to 1: {p} + {l}"); + assert_eq!(sel.phenotype.genes[0].name, "parse", "heaviest first"); + assert_eq!(scale(&sel, "tax"), 0.0); + assert!(sel.changed); + + let alone = pick([1.0, 0.3, 0.0], &[("parse", Some(&parse))], &[]); + let depth = (unit([1.0, 0.3, 0.0])[0] - 0.8) / 0.2; + assert!((scale(&alone, "parse") - f64::from(depth)).abs() < 1e-6, "alone, a gene runs at its depth"); +} + +// what this catches: more genes on a turn than the engine holds. The `capacity` deepest win. +#[test] +fn only_the_capacity_deepest_genes_are_kept() { + let parse = signature([1.0, 0.0, 0.0], Some(0.7)); + let lex = signature([0.8, 0.6, 0.0], Some(0.7)); + let ast = signature([0.6, 0.8, 0.0], Some(0.7)); + let sel = pick_k([1.0, 0.3, 0.0], &[("parse", Some(&parse)), ("lex", Some(&lex)), ("ast", Some(&ast))], 2, &[]); + let names: Vec<&str> = sel.phenotype.genes.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, vec!["parse", "lex"], "{sel:?}"); +} + +// what this catches: a gene riding a turn outside every region. Nothing inside = the base alone. +#[test] +fn no_gene_inside_its_region_means_the_base_alone() { + let parse = signature([1.0, 0.0, 0.0], Some(0.9)); + let sel = pick([0.0, 1.0, 0.0], &[("parse", Some(&parse))], &[]); + assert!(sel.phenotype.genes.is_empty(), "{sel:?}"); + assert!(!sel.changed, "nothing ran before, nothing runs now"); +} + +// what this catches: thrash at a region's edge (each switch clears her KV). A gene that ran stays +// on between its floor and its leave edge; one that did not run does not switch on there; past +// the leave edge it goes off. +#[test] +fn hysteresis_keeps_a_running_gene_between_the_edges_and_drops_it_past_leave() { + let parse = signature([1.0, 0.0, 0.0], Some(0.9)); // floor 0.9, leave 0.85 + let between = [0.875, (1.0f32 - 0.875 * 0.875).sqrt(), 0.0]; // similarity 0.875 + assert!(pick(between, &[("parse", Some(&parse))], &[]).phenotype.genes.is_empty(), "it must cross its floor first"); + let running = ran("parse", 0.25); + let held = pick(between, &[("parse", Some(&parse))], std::slice::from_ref(&running)); + assert_eq!(scale(&held, "parse"), 0.25, "running: it stays, at its held scale, until the leave edge"); + assert!(!held.changed, "same set, same scale: her KV is kept"); + let gone = pick([0.8, 0.6, 0.0], &[("parse", Some(&parse))], std::slice::from_ref(&running)); + assert!(gone.phenotype.genes.is_empty(), "past the leave edge it goes off"); + assert!(gone.changed); +} + +// what this catches: re-weighting every turn. The engine clears a slot's KV on ANY scale change, +// so while the applied set holds, the scales are the previous turn's, bit for bit. +#[test] +fn weights_are_held_bit_identical_while_the_set_holds() { + let parse = signature([1.0, 0.0, 0.0], Some(0.8)); + let lex = signature([0.8, 0.6, 0.0], Some(0.8)); + let genes = [("parse", Some(&parse)), ("lex", Some(&lex))]; + let first = pick([1.0, 0.3, 0.0], &genes, &[]); + let next = pick([1.0, 0.45, 0.0], &genes, &first.phenotype.genes); + assert_eq!(next.phenotype, first.phenotype, "the same set runs at the same scales"); + assert!(!next.changed); +} + +// what this catches: a diffuse gene riding every turn. Its own region (0.3) is looser than the +// space's measured null + 2σ (0.5 + 2*0.1), so the null is the floor. +#[test] +fn the_measured_null_lifts_a_diffuse_genes_floor() { + let diffuse = signature([1.0, 0.0, 0.0], Some(0.3)); + let vector = unit([0.6, 0.8, 0.0]); // similarity 0.6 + let candidates = [Candidate { gene: gene("diffuse"), signature: Some(&diffuse) }]; + let null = Need { embedder_id: SPACE, vector: &vector, unrelated_null: Some((0.5, 0.1)) }; + assert!(select(Some(&null), &candidates, 1, &[]).phenotype.genes.is_empty(), "inside its region, outside the null"); + let without = Need { unrelated_null: None, ..null }; + assert_eq!(select(Some(&without), &candidates, 1, &[]).phenotype.genes.len(), 1, "its own region alone admits it"); +} + +// what this catches: routing pretending to know. A gene with no signature, one signed in another +// space, or with neither a region nor a null cannot be routed: it runs at its trained scale as +// before routing, named unrouted. Without a perception, routed genes stay as they were. +#[test] +fn unroutable_genes_run_at_their_trained_scale_and_no_perception_keeps_the_genome() { + let alien = GeneSignature { embedder: "other".into(), ..signature([1.0, 0.0, 0.0], Some(0.8)) }; + let edgeless = signature([1.0, 0.0, 0.0], None); + let sel = pick([0.0, 1.0, 0.0], &[("plain", None), ("alien", Some(&alien)), ("edgeless", Some(&edgeless))], &[]); + assert_eq!(sel.phenotype.genes.len(), 3, "{sel:?}"); + assert!(sel.phenotype.genes.iter().all(|g| g.scale == 1.0)); + assert!(sel.considered.iter().all(|c| c.route == Route::Unrouted)); + + let parse = signature([1.0, 0.0, 0.0], Some(0.8)); + let candidates = [Candidate { gene: gene("parse"), signature: Some(&parse) }]; + let before = ran("parse", 0.625); + let kept = select(None, &candidates, 1, std::slice::from_ref(&before)); + assert_eq!(kept.phenotype.genes, vec![before]); + assert!(!kept.changed); +} + +// what this catches: an examiner's P ∖ g that moves the other genes (renormalized), which would +// credit g with the others' change. Only g goes to 0. +#[test] +fn without_one_gene_leaves_every_other_scale_unchanged() { + let p = Phenotype { genes: vec![ran("parse", 0.6), ran("lex", 0.4)] }; + let less = p.without("/genes/parse.gguf"); + assert_eq!(less.genes, vec![ran("lex", 0.4)]); + assert_eq!(less.scale_of("/genes/parse.gguf"), 0.0); + assert_eq!(p.without("/genes/absent.gguf"), p); +} diff --git a/core/continuum-genome/src/genome/gene_residency.rs b/core/continuum-genome/src/genome/gene_residency.rs new file mode 100644 index 0000000000..cf304e51b5 --- /dev/null +++ b/core/continuum-genome/src/genome/gene_residency.rs @@ -0,0 +1,273 @@ +//! Where a node's loaded genes live: on the device, or paged out to host RAM (the LOADED tier of +//! GENE-REUSE-FORK-MINT §3d; the mechanism is fork CambrianTech/llama.cpp#72). One owner per node: +//! one adapter serves every mind on the engine, so residency is the node's, never a mind's. +//! +//! - **No budget of its own.** Genes compete with minds' KV for one device, so the owner is a +//! [`DeviceTenant`] of the lanes' pool (`inference-lanes`): its device bytes count there, and +//! the PressureBroker's `evict_at_least` reaches it first (a gene pages out in milliseconds, a +//! lane's eviction costs a mind her KV). It pages OUT only when asked to relieve that budget. +//! - **Temperature: LRU-2.** A gene's heat is the time of its SECOND most recent use by any mind +//! (then its last use): a gene several minds or several turns run outranks one a single turn +//! touched, recency decides among equals, and there is no decay constant to tune. A gene in any +//! mind's current phenotype is pinned: it is never paged out while she runs it. +//! - **Prefetch in the quiet.** After each turn ([`GeneResidency::record_turn`]) a reconcile runs +//! off the request path and pages back in every pinned gene that is in host RAM, so the next +//! request does not pay the engine's on-demand page-in (a counted miss, +//! `lora_page_in_on_demand_total`). +//! - **Each mind's phenotype lives here.** It is what pins her genes, and the composer's +//! hysteresis and held scales read it back ([`GeneResidency::previous`]): one copy. +//! +//! Probes: `genome.page` (gene, direction, bytes, ms) and `genome.page.failed`. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use parking_lot::Mutex; +use uuid::Uuid; + +use crate::ai::types::ActiveAdapterRequest; +use crate::genome::composer::Phenotype; +use crate::inference::coordinator_pool::DeviceTenant; +use crate::inference::llama_server::{gene_seats, page_gene, GeneSeat}; +use crate::paging::pool::ResourcePoolEntry; + +/// When a gene ran (ms since the epoch): its last and second-last use, and how often. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Heat { + pub last_ms: u64, + pub prior_ms: u64, + pub uses: u64, +} + +impl Heat { + fn touch(&mut self, now_ms: u64) { + if now_ms != self.last_ms { + self.prior_ms = self.last_ms; + self.last_ms = now_ms; + } + self.uses += 1; + } + + /// The LRU-2 order key: hotter is greater. + fn key(&self) -> (u64, u64) { + (self.prior_ms, self.last_ms) + } +} + +/// One page the owner decided. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PageMove { + pub id: i64, + pub path: String, + pub to_device: bool, +} + +/// PURE: the prefetch: every pinned gene that is in host RAM goes back to the device. +pub fn prefetch(seats: &[GeneSeat], pinned: &BTreeSet) -> Vec { + seats + .iter() + .filter(|s| !s.on_device && pinned.contains(&s.path)) + .map(|s| PageMove { id: s.id, path: s.path.clone(), to_device: true }) + .collect() +} + +/// PURE: the victims for relieving `want` bytes: unpinned genes on the device with known bytes, +/// coldest first (LRU-2), until `want` is covered. Returns them and the bytes they free. +pub fn victims( + seats: &[GeneSeat], + pinned: &BTreeSet, + heat: &HashMap, + want: u64, +) -> (Vec, u64) { + let mut cold: Vec<(&GeneSeat, u64)> = seats + .iter() + .filter(|s| s.on_device && !pinned.contains(&s.path)) + .filter_map(|s| s.n_bytes.map(|b| (s, b))) + .collect(); + cold.sort_by_key(|(s, _)| (heat.get(&s.path).copied().unwrap_or_default().key(), s.path.clone())); // unwrap_or_default: a gene no turn has run since this process started is the coldest there is + let mut freed = 0u64; + let mut moves = Vec::new(); + for (seat, bytes) in cold { + if freed >= want { + break; + } + freed += bytes; + moves.push(PageMove { id: seat.id, path: seat.path.clone(), to_device: false }); + } + (moves, freed) +} + +#[derive(Default)] +struct State { + /// Each mind's current phenotype: pins its genes, and is the composer's "previous". + phenotypes: HashMap>, + heat: HashMap, + /// The engine's catalog as last read. + seats: Vec, +} + +impl State { + fn pinned(&self) -> BTreeSet { + self.phenotypes.values().flatten().filter(|g| g.scale != 0.0).map(|g| g.path.clone()).collect() + } +} + +/// The node's gene residency owner. See the module docs. +#[derive(Default)] +pub struct GeneResidency { + state: Mutex, + reconciling: AtomicBool, + again: AtomicBool, +} + +impl GeneResidency { + pub fn global() -> &'static Arc { + static ONE: std::sync::OnceLock> = std::sync::OnceLock::new(); + ONE.get_or_init(|| Arc::new(GeneResidency::default())) + } + + /// What `persona` ran last turn (empty when she has run nothing this process). + pub fn previous(&self, persona: Uuid) -> Vec { + self.state.lock().phenotypes.get(&persona).cloned().unwrap_or_default() // unwrap_or_default: a mind with no turn this process ran no genes + } + + /// `persona` runs `phenotype` from now: it pins her genes and heats each one. + pub fn record_turn(&self, persona: Uuid, phenotype: &Phenotype, now_ms: u64) { + let mut state = self.state.lock(); + for gene in &phenotype.genes { + state.heat.entry(gene.path.clone()).or_default().touch(now_ms); + } + if phenotype.genes.is_empty() { + state.phenotypes.remove(&persona); + } else { + state.phenotypes.insert(persona, phenotype.genes.clone()); + } + } + + /// Bring the engine's catalog in and page back in what her minds run, off the request path. + /// Coalesced: a reconcile asked for while one runs runs once more after it. + pub fn schedule_reconcile(self: &Arc) { + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return; // no runtime (a sync test): nothing to page, and the engine pages in on demand + }; + if self.reconciling.swap(true, Ordering::AcqRel) { + self.again.store(true, Ordering::Release); + return; + } + let me = Arc::clone(self); + runtime.spawn(async move { + loop { + me.reconcile().await; + if !me.again.swap(false, Ordering::AcqRel) { + break; + } + } + me.reconciling.store(false, Ordering::Release); + }); + } + + async fn reconcile(&self) { + let seats = match gene_seats().await { + Ok(seats) => seats, + Err(error) => { + continuum_base::probe!( + class = "genome.page.failed", + error = %error, + "the engine's gene catalog did not read: residency unchanged" + ); + return; + } + }; + let moves = { + let mut state = self.state.lock(); + state.seats = seats; + prefetch(&state.seats, &state.pinned()) + }; + self.apply(moves).await; + } + + async fn apply(&self, moves: Vec) { + for m in moves { + match page_gene(m.id, m.to_device).await { + Ok(done) => { + continuum_base::probe!( + class = "genome.page", + gene = %m.path, + to = if done.on_device { "device" } else { "host" }, + bytes = done.n_moved, + ms = done.t_ms, + "a gene moved between the device and host RAM" + ); + let mut state = self.state.lock(); + if let Some(seat) = state.seats.iter_mut().find(|s| s.id == m.id) { + seat.on_device = done.on_device; + seat.n_bytes = Some(done.n_bytes); + } + } + Err(error) => continuum_base::probe!( + class = "genome.page.failed", + gene = %m.path, + to = if m.to_device { "device" } else { "host" }, + error = %error, + "a gene page did not happen: it stays where it was" + ), + } + } + } +} + +impl DeviceTenant for GeneResidency { + fn device_bytes(&self) -> u64 { + self.state.lock().seats.iter().filter(|s| s.on_device).filter_map(|s| s.n_bytes).sum() + } + + /// Decides the coldest unpinned genes now and pages them out off the broker's thread; the + /// bytes returned are what those pages free (a refused one is probed and its gene stays). + fn evict_at_least(&self, want_bytes: u64) -> u64 { + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return 0; // no runtime to page on: this tenant frees nothing, and the broker moves on to the lanes + }; + let (moves, freed) = { + let mut state = self.state.lock(); + let pinned = state.pinned(); + let (moves, freed) = victims(&state.seats, &pinned, &state.heat, want_bytes); + for m in &moves { + if let Some(seat) = state.seats.iter_mut().find(|s| s.id == m.id) { + seat.on_device = false; // committed: no second eviction counts it again + } + } + (moves, freed) + }; + if !moves.is_empty() { + // the tenant registered with the pool IS the global owner (register_with_broker) + let me = Arc::clone(GeneResidency::global()); + runtime.spawn(async move { me.apply(moves).await }); + } + freed + } + + fn snapshot(&self) -> Vec { + let state = self.state.lock(); + let pinned = state.pinned(); + state + .seats + .iter() + .filter(|s| s.on_device) + .map(|s| { + let heat = state.heat.get(&s.path).copied().unwrap_or_default(); // unwrap_or_default: no turn this process ran it + ResourcePoolEntry { + key: format!("gene:{}", s.path), + size_bytes: s.n_bytes.unwrap_or(0), // unwrap_or: an engine without byte reporting; the entry still names the gene + pinned_count: u32::from(pinned.contains(&s.path)), + loaded_at: 0, // the engine does not report when it loaded a gene; 0 reads as unknown on the dashboard + last_access_at: heat.last_ms, + access_count: heat.uses, + } + }) + .collect() + } +} + +#[cfg(test)] +mod tests; diff --git a/core/continuum-genome/src/genome/gene_residency/tests.rs b/core/continuum-genome/src/genome/gene_residency/tests.rs new file mode 100644 index 0000000000..946e01da94 --- /dev/null +++ b/core/continuum-genome/src/genome/gene_residency/tests.rs @@ -0,0 +1,70 @@ +//! The residency owner's contract: pinned genes come back, cold unpinned genes go first. + +use super::*; + +fn seat(id: i64, name: &str, on_device: bool, n_bytes: Option) -> GeneSeat { + GeneSeat { id, path: format!("/g/{name}.gguf"), on_device, n_bytes } +} + +fn path(name: &str) -> String { + format!("/g/{name}.gguf") +} + +fn phenotype(names: &[(&str, f64)]) -> Phenotype { + Phenotype { + genes: names + .iter() + .map(|(n, s)| ActiveAdapterRequest { name: n.to_string(), path: path(n), domain: String::new(), scale: *s }) + .collect(), + } +} + +// what this catches: a gene a mind runs left in host RAM, so every one of her requests pays +// the engine's on-demand page-in. The prefetch brings back exactly the pinned host genes. +#[test] +fn the_prefetch_pages_in_exactly_the_genes_minds_run() { + let seats = [seat(0, "a", false, Some(9)), seat(1, "b", false, Some(9)), seat(2, "c", true, Some(9))]; + let pinned: BTreeSet = [path("a"), path("c")].into_iter().collect(); + assert_eq!(prefetch(&seats, &pinned), vec![PageMove { id: 0, path: path("a"), to_device: true }]); +} + +// what this catches: relieving the budget by paging out a gene a mind is running (her next +// request pages it straight back in), or by the hottest gene instead of the coldest. LRU-2: a +// gene used twice recently outranks one used once more recently; unknown sizes are never +// counted as freed bytes. +#[test] +fn victims_are_the_coldest_unpinned_genes_with_known_bytes() { + let seats = [ + seat(0, "pinned", true, Some(100)), + seat(1, "twice", true, Some(100)), + seat(2, "once", true, Some(100)), + seat(3, "never", true, Some(100)), + seat(4, "unsized", true, None), + seat(5, "host", false, Some(100)), + ]; + let pinned: BTreeSet = [path("pinned")].into_iter().collect(); + let mut heat = HashMap::new(); + heat.insert(path("twice"), Heat { last_ms: 50, prior_ms: 40, uses: 2 }); + heat.insert(path("once"), Heat { last_ms: 90, prior_ms: 0, uses: 1 }); + let (moves, freed) = victims(&seats, &pinned, &heat, 150); + let ids: Vec = moves.iter().map(|m| m.id).collect(); + assert_eq!(ids, vec![3, 2], "never-used first, then the once-used; the twice-used stays"); + assert_eq!(freed, 200); + assert!(moves.iter().all(|m| !m.to_device)); + assert_eq!(victims(&seats, &pinned, &heat, 10_000).0.len(), 3, "never the pinned, unsized or host gene"); +} + +// what this catches: two copies of "what she runs": the composer's previous turn and the pins +// are one record, and a mind that runs nothing pins nothing. +#[test] +fn a_turn_pins_her_genes_and_is_her_previous_phenotype() { + let owner = GeneResidency::default(); + let mind = Uuid::from_u128(7); + owner.record_turn(mind, &phenotype(&[("a", 0.6), ("b", 0.4)]), 10); + assert_eq!(owner.previous(mind), phenotype(&[("a", 0.6), ("b", 0.4)]).genes); + assert_eq!(owner.state.lock().pinned().len(), 2); + owner.record_turn(mind, &phenotype(&[]), 20); + assert!(owner.previous(mind).is_empty()); + assert!(owner.state.lock().pinned().is_empty()); + assert_eq!(owner.state.lock().heat[&path("a")].uses, 1); +} diff --git a/core/continuum-genome/src/genome/gene_trial.rs b/core/continuum-genome/src/genome/gene_trial.rs index c35e475cd8..ab750969f6 100644 --- a/core/continuum-genome/src/genome/gene_trial.rs +++ b/core/continuum-genome/src/genome/gene_trial.rs @@ -2,7 +2,7 @@ //! //! A gene that passes training's own pre-filter is ADOPTED ([`Adoption`]): registered (so the //! serving engine loads it, dormant, in place) and a [`GeneTrial`] opened on it. From then on -//! it is in her head on every turn ([`genes_for_turn`]), and the examiner +//! it is in her head on every turn ([`her_genes`]), and the examiner //! ([`crate::genome::examiner`]) sits the continual-learning acceptance test on it: her own //! turns on related tasks the gene never trained on and on unrelated ones, with and without //! the gene, on the same live engine; again after a normal restart. Its verdict promotes or @@ -113,43 +113,42 @@ impl GeneTrial { } } -/// PURE: the genes a turn of `persona` runs with on `base`: every gene she trained that -/// has not been retired, on EVERY turn, card or conversation (Joel, 2026-10-10: a gene is -/// hers once trained and follows her mind, never her workload; the full rule, selection -/// by distance with two tiers, is GENE-REUSE-FORK-MINT §3d; with one gene there is nothing -/// to select). What decides whether a gene STAYS is the examiner's verdict, never a card. -pub fn genes_for_turn(trials: &[GeneTrial], persona: Uuid, base: &str) -> Vec { +/// Where a gene stands in her genome: still awaiting a verdict, or adopted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Standing { + /// Trained and loaded; no verdict yet. + Pending, + /// The verdict adopted it. + Adopted, +} + +impl Standing { + /// Whether a turn may run a gene of this standing. Today both: a gene is hers once trained + /// (Joel, 2026-10-10; §3d). The examiner's verdict owns this rule (Cormac, 2026-10-24: "the + /// examiner's verdict, not residency, decides what a turn may use"); the composer asks it. + pub fn may_run(self) -> bool { + match self { + Standing::Pending | Standing::Adopted => true, + } + } +} + +/// PURE: the genes `persona` has on `base`, each with its standing: every gene she trained that +/// has not been retired (Joel, 2026-10-10: a gene is hers once trained and follows her mind, +/// never her workload). Each at its trained scale 1.0: which of them shape a turn, and how much, +/// is `genome::composer` (GENE-REUSE-FORK-MINT §3d). +pub fn her_genes(trials: &[GeneTrial], persona: Uuid, base: &str) -> Vec<(ActiveAdapterRequest, Standing)> { trials .iter() .filter(|t| t.persona_id == persona && t.base_model_id == base) - .filter(|t| match t.state { - TrialState::Promoted | TrialState::Trial => true, - TrialState::Retired | TrialState::Expired => false, + .filter_map(|t| match t.state { + TrialState::Trial => Some((t.page(), Standing::Pending)), + TrialState::Promoted => Some((t.page(), Standing::Adopted)), + TrialState::Retired | TrialState::Expired => None, }) - .map(GeneTrial::page) .collect() } -/// The genes her next turn runs with (every turn, card or conversation), read from the trial -/// file and the base the node serves right now. `None` when either cannot be read: the caller then leaves her genome as it is -/// (never a guessed one), and the reason is on the probe stream. -pub fn live_genes(persona: Uuid) -> Option> { - let base = crate::inference::llama_server::current_serving().active_model?; - let store = GeneTrials::default_store()?; - match store.load() { - Ok(trials) => Some(genes_for_turn(&trials, persona, &base)), - Err(error) => { - continuum_base::probe!( - class = "genome.trial.unreadable", - persona = %persona, - error = error.as_str(), - "the gene trial file did not read: this turn keeps the genome she has" - ); - None - } - } -} - /// The effects of a decision the examiner wrote (through [`GeneTrials::decide`]). Promoted: /// its verdict joins the fitness ledger gene recall ranks by (`progress/.jsonl`). /// Retired: out of the adapter manifest, so the serving engine retires it in place, and the @@ -463,7 +462,7 @@ mod tests { assert!(young.is_settling(now), "just landed: her next fill waits"); let all = store.load().unwrap(); assert!(all.iter().all(|t| t.state == TrialState::Trial), "nothing expired anything: both stay hers"); - assert_eq!(genes_for_turn(&all, persona, "base").len(), 2, "both are in her head, settling or not"); + assert_eq!(her_genes(&all, persona, "base").len(), 2, "both are in her head, settling or not"); } // what this catches: a gene in her head that the examiner retired, or one missing that it @@ -482,9 +481,9 @@ mod tests { let trials = store.load().unwrap(); // what this catches (Joel, 2026-10-10; gene 1 loaded on the 5090 and served zero turns // because she held no card): a trained gene is in her head on every turn. - assert_eq!(genes_for_turn(&trials, kimi, "qwen-27b").len(), 1, "a turn talks through the gene she trained"); - assert!(genes_for_turn(&trials, kimi, "other-base").is_empty()); - assert!(genes_for_turn(&trials, Uuid::nil(), "qwen-27b").is_empty()); + assert_eq!(her_genes(&trials, kimi, "qwen-27b").len(), 1, "a turn talks through the gene she trained"); + assert!(her_genes(&trials, kimi, "other-base").is_empty()); + assert!(her_genes(&trials, Uuid::nil(), "qwen-27b").is_empty()); let verdict = TrialVerdict { with_gene: ArmTally { settled: 6, passed: 4 }, @@ -506,7 +505,7 @@ mod tests { let retired = store.decide(t.id, TrialState::Retired, verdict.clone(), 50).unwrap().expect("retention retires"); assert_eq!(retired.state, TrialState::Retired); assert!(store.decide(t.id, TrialState::Promoted, verdict, 60).unwrap().is_none(), "a retired gene stays retired"); - assert!(genes_for_turn(&store.load().unwrap(), kimi, "qwen-27b").is_empty(), "a retired gene never runs"); + assert!(her_genes(&store.load().unwrap(), kimi, "qwen-27b").is_empty(), "a retired gene never runs"); // A row the deleted card gate wrote still reads, its arms carried into the new names. let legacy = serde_json::json!([{ diff --git a/core/continuum-genome/src/genome/local_manager.rs b/core/continuum-genome/src/genome/local_manager.rs deleted file mode 100644 index a51267c054..0000000000 --- a/core/continuum-genome/src/genome/local_manager.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! `LocalWorkingSetManager` — per-process implementation of the -//! `WorkingSetManager` trait shipped in PR-2 (#1353). -//! -//! Holds: -//! - `Vec>` — the tier chain, ordered Fast → Frozen -//! - `RwLock>` — per-persona working sets -//! - `RwLock>` — page-ownership map for -//! the MMU-style `audit_access` enforcement -//! -//! Page-in walks the tier chain from highest (Fast) to lowest (Frozen), -//! returns the first hit, optionally promotes the page to the working -//! set's preferred tier. A miss with no resident copy is a true cold -//! miss → `PageFault::from_role: None`. -//! -//! ## What PR-3 ships -//! -//! - Pure local implementation. No bus publishing baked in (the -//! `page_in` Result already carries `PageFault` as the typed -//! observability signal; callers wire to the artifact dispatch -//! path #1339+#1343 themselves). -//! - The four trait methods: `page_in`, `page_out`, `working_set`, -//! `audit_access`. -//! - Constructor that registers tier stores + capacity per persona. -//! - Tests using a stub `TierStore` that records calls so the test -//! can assert which tier was queried + that PageFault carries the -//! right `from_role` / `to_role`. -//! -//! ## What PR-3 does NOT ship (PR-4 or later) -//! -//! - Eviction policy invocation when the target tier is at limit — -//! PR-3 returns `TierError::NoEvictionCandidate` instead of running -//! the policy. Policy invocation is a tier-store-internal concern -//! that the PR-3 impl doesn't drive; PR-4's enhancement is a wired -//! callback so the manager observes and re-publishes the -//! `EvictionRecord` that the tier returned. -//! - Pinning logic for composition-layer page pinning — that's part -//! of PR-3 of demand-aligned-recall (composer cache). -//! - The `check_permission(actor, region, op)` method from PR-2's -//! "deliberately deferred" list. Lands in PR-4 alongside the -//! GenomeRegion + Op type definitions. - -use continuum_base::time::EpochMs; -use async_trait::async_trait; -use parking_lot::RwLock; -use std::collections::HashMap; -use std::sync::Arc; - -use super::bus::{publish_access_denied, publish_page_fault}; -use super::manager::WorkingSetManager; -use super::store::TierStore; -use super::tier::{TierError, TierRole}; -use super::working_set::{AccessDenied, PageFault, PageHandle, ResidentPage, WorkingSet, WorkingSetCapacity}; -use crate::inference::page_ref::PageRef; -use crate::identity::PeerId; -use crate::runtime::message_bus::MessageBus; -use crate::runtime::registry::ModuleRegistry; - -/// Optional bus + registry handle for auto-publishing genome events. -/// When set on a `LocalWorkingSetManager`, every `page_in`/ -/// `audit_access` call that produces a typed event also publishes the -/// event via the artifact dispatch path (#1339+#1343) using the -/// canonical keys from `genome::bus` (PR-4 / #1358). -/// -/// Kept as one struct (not two Arcs on the manager) so the absence-of- -/// bus case is a single `Option` field — easier to reason -/// about than two correlated Options. -struct BusHook { - bus: Arc, - registry: Arc, -} - -/// Per-process working-set manager. Holds the tier chain + per-persona -/// state. Thread-safe through `parking_lot::RwLock` — the hot-path -/// `audit_access` and `working_set` calls only need a read lock. -/// -/// PR-5 adds optional bus publishing: when constructed via -/// `with_bus(tiers, bus, registry)`, every page_in / audit_access -/// call publishes the typed event to the trace bus through the -/// canonical genome keys. Constructed via `new(tiers)` (the PR-3 -/// shape), the manager stays bus-less and behaves exactly as before -/// — useful for tests + standalone use where no runtime is around. -pub struct LocalWorkingSetManager { - /// The tier chain, ordered highest (Fast) to lowest (Frozen). - /// Each tier is a `Box` from PR-2. The order is - /// the page_in walk order — we stop at the first hit. - tiers: Vec>, - /// Per-persona working set state. RwLock because read-heavy - /// (every audit_access + working_set query) with occasional - /// write (page_in / page_out modifications). - working_sets: RwLock>, - /// Page-ownership map for cross-persona compartmentalization. - /// `audit_access` denies if `persona != owner`. PR-3 populates - /// this via `register_page_owner`; PR-4 may move to a typed - /// genome-region-keyed table per GENOME-FOUNDRY-SENTINEL Part 4. - page_owners: RwLock>, - /// Optional bus hook for auto-publishing events. `None` = bus-less - /// mode (PR-3 behavior, no publishing). `Some` = wire every typed - /// event to the artifact dispatch path via the genome::bus - /// helpers shipped in PR-4. - bus_hook: Option, -} - -impl LocalWorkingSetManager { - /// Construct with the tier chain — bus-less mode (PR-3 shape). - /// Page events are returned through the trait's `Result` arms but - /// NOT published to any bus. Useful for tests and standalone use - /// where no runtime is around. - pub fn new(tiers: Vec>) -> Self { - Self { - tiers, - working_sets: RwLock::new(HashMap::new()), - page_owners: RwLock::new(HashMap::new()), - bus_hook: None, - } - } - - /// Construct with the tier chain + auto-publishing bus hook. - /// Every `page_in` that returns a `PageFault` AND every - /// `audit_access` denial publishes the typed event via the - /// `genome::bus` helpers (PR-4 / #1358) under the canonical - /// genome keys. - /// - /// `bus` + `registry` must be from the same Runtime — publishing - /// uses `bus.publish` which looks up modules via the registry. - /// Subscribers register through `bus.subscribe_artifact` for the - /// genome keys (typically via `subscribe_to_genome_events(bus, - /// module_name)` from PR-4). - /// - /// Why a separate constructor instead of a setter: prevents the - /// "bus added partway through service" race where some events - /// are published and some aren't. The manager either publishes - /// from construction onward, or never — no in-between state. - pub fn with_bus( - tiers: Vec>, - bus: Arc, - registry: Arc, - ) -> Self { - Self { - tiers, - working_sets: RwLock::new(HashMap::new()), - page_owners: RwLock::new(HashMap::new()), - bus_hook: Some(BusHook { bus, registry }), - } - } - - /// Register a persona with the manager + give it a working set - /// capacity. Must be called before any `page_in` for the persona; - /// `page_in` to an unregistered persona returns a `PageFault` - /// with `from_role: None` (the page never existed for that - /// persona because the persona itself doesn't exist yet). - pub fn register_persona(&self, persona: PeerId, capacity: WorkingSetCapacity) { - let ws = WorkingSet::new(persona, capacity); - self.working_sets.write().insert(persona, ws); - } - - /// Record that a page is private to a persona. Subsequent - /// `audit_access(other_persona, page)` returns `AccessDenied`. - /// Pages not registered here are treated as substrate-shared - /// (no owner; anyone can access). - pub fn register_page_owner(&self, page: PageRef, owner: PeerId) { - self.page_owners.write().insert(page, owner); - } - - /// How many tiers are configured. Cheap O(1) — used by tests + - /// the governor's policy diagnostics. - pub fn tier_count(&self) -> usize { - self.tiers.len() - } -} - -#[async_trait] -impl WorkingSetManager for LocalWorkingSetManager { - async fn page_in(&self, persona: PeerId, page: PageRef) -> Result { - // Already resident? — fast path. - { - let working_sets = self.working_sets.read(); - if let Some(ws) = working_sets.get(&persona) { - let key = serde_json::to_string(&page).unwrap_or_default(); - if let Some(resident) = ws.pages.get(&key) { - return Ok(PageHandle { - page, - tier_role: resident.role, - size_bytes: 0, - }); - } - } - } - - // Start the servicing clock AFTER the resident hot-path so a - // working-set hit pays nothing for timing it didn't need. From - // here down is genuine page-in work (tier walk + transfer + - // eviction-if-any) — exactly what `PageFault.elapsed_us` is - // meant to report. `Instant` per working_set.rs's "sub-ms - // hot-path timing stays in caller-side Instants" doctrine. - let started = std::time::Instant::now(); - - // Walk tier chain top-down. First hit wins. Promote (record - // residency) into the working set's Fast tier; the caller's - // composition decides whether to pin. - for tier in &self.tiers { - if let Ok(handle) = tier.read(page).await { - let from_role = handle.tier_role; - let to_role = self.tiers.first().map(|t| t.role()).unwrap_or(from_role); - - // Record residency in the working set (if persona - // registered). - if let Some(ws) = self.working_sets.write().get_mut(&persona) { - let key = serde_json::to_string(&page).unwrap_or_default(); - ws.pages.insert( - key, - ResidentPage { - page, - role: to_role, - last_access_ms: EpochMs::now().millis(), - access_count_window: 1, - pinned: false, - }, - ); - } - - // Tier-promotion PageFault. Publish to bus if hook - // present (PR-5 wiring; PR-3 contract — Err arm is - // the typed sentinel observability signal, not a - // failure), then return. - let fault = PageFault { - page, - from_role: Some(from_role), - to_role, - persona, - elapsed_us: started.elapsed().as_micros() as u64, - eviction_cost: None, - }; - if let Some(hook) = &self.bus_hook { - spawn_publish_page_fault(hook, fault.clone()); - } - return Err(fault); - } - } - - // True cold miss — page doesn't exist in any tier yet. - let fault = PageFault { - page, - from_role: None, - to_role: self - .tiers - .first() - .map(|t| t.role()) - .unwrap_or(TierRole::Fast), - persona, - elapsed_us: started.elapsed().as_micros() as u64, - eviction_cost: None, - }; - if let Some(hook) = &self.bus_hook { - spawn_publish_page_fault(hook, fault.clone()); - } - Err(fault) - } - - async fn page_out( - &self, - persona: PeerId, - page: PageRef, - to: TierRole, - ) -> Result<(), TierError> { - // Remove from working set if present, then write to target - // tier. PR-3 doesn't validate that `to` is a configured - // tier role — that's a PR-4 concern (needs the governor's - // current Vec snapshot to know which roles are - // present on this hardware). - { - let mut working_sets = self.working_sets.write(); - if let Some(ws) = working_sets.get_mut(&persona) { - let key = serde_json::to_string(&page).unwrap_or_default(); - // Pinned pages skip silently per the trait docstring: - // page_out doesn't surface TierError for pin-violation; - // composition is responsible for unpinning. - if let Some(resident) = ws.pages.get(&key) { - if resident.pinned { - return Ok(()); - } - } - ws.pages.remove(&key); - } - } - - // Find the target tier and write a marker (PR-3 doesn't - // shuttle the actual blob — that's a PR-4 enhancement; for - // now page_out is a working-set-state operation only). When - // we wire blob movement, this is where TierStore::write - // gets called. - for tier in &self.tiers { - if tier.role() == to { - tier.observe_access(page); - return Ok(()); - } - } - Err(TierError::RoleNotConfigured { role: to }) - } - - fn working_set(&self, _persona: PeerId) -> Option<&WorkingSet> { - // PR-3 cannot return a borrow through the RwLock without - // exposing the lock guard type — that breaks the trait - // signature. PR-4 will introduce a `Snapshot` type that - // clones the working set view; until then, return None so - // callers know to use the (future) snapshot API instead of - // relying on this borrow path. Tests that need to inspect - // the working set use the internal `working_set_snapshot` - // helper below. - // - // This is a deliberate refinement of the PR-2 contract, - // documented in the trait docstring as "Option<&WorkingSet>" - // — the None case here is the "lock-guard escape impossible" - // case, distinct from the spec's "persona not registered" - // case but compatible with the same return type. - None - } - - fn audit_access(&self, persona: PeerId, page: PageRef) -> Result<(), AccessDenied> { - let result: Result<(), AccessDenied> = match self.page_owners.read().get(&page).copied() { - Some(owner) if owner != persona => Err(AccessDenied { - actor: persona, - page, - owner: Some(owner), - reason: "cross-persona read blocked by working-set MMU".to_string(), - }), - _ => Ok(()), - }; - - // Auto-publish on denial via the spawn helper (same lifetime- - // workaround pattern as page_in — see spawn_publish_page_fault - // for the rationale). - if let (Err(ref denied), Some(hook)) = (&result, &self.bus_hook) { - spawn_publish_access_denied(hook, denied.clone()); - } - - result - } -} - -impl LocalWorkingSetManager { - /// Test/diagnostic helper: snapshot the working set for a persona. - /// Clones — not for hot path. Used by tests + future telemetry - /// modules to inspect state without holding the read lock. - pub fn working_set_snapshot(&self, persona: PeerId) -> Option { - self.working_sets.read().get(&persona).cloned() - } -} - -/// Spawn a `publish_page_fault` into the current tokio runtime. -/// Standalone fn (not a method) so the `&BusHook` borrow doesn't -/// outlive the spawn — Arcs get cloned out first, then the spawned -/// future owns its captures. -/// -/// Why spawn instead of await: `bus.publish` walks the DashMap of -/// subscribers; the DashMap's `Map` trait impl has a specific -/// lifetime that doesn't satisfy the for-any-lifetime requirement -/// generated by `async_trait`'s `Send`-bounded future. Awaiting -/// `publish` inside the trait method's body trips a -/// "DashMap is not general enough" error. Spawning decouples the -/// publish from the caller's Send-ness — no borrow crosses the await -/// boundary in the caller's future. -/// -/// If no tokio runtime is current (rare — only sync-only test paths -/// without `#[tokio::test]`), the spawn is skipped silently because -/// `Handle::try_current` returns Err. The typed event in the -/// returned `Result` is still authoritative; observability is -/// best-effort. -fn spawn_publish_page_fault(hook: &BusHook, fault: PageFault) { - if let Ok(handle) = tokio::runtime::Handle::try_current() { - let bus = hook.bus.clone(); - let registry = hook.registry.clone(); - handle.spawn(async move { - publish_page_fault(&bus, ®istry, &fault).await; - }); - } -} - -/// Spawn a `publish_access_denied` into the current tokio runtime. -/// Same pattern as `spawn_publish_page_fault`; used by the sync -/// `audit_access` trait method. -fn spawn_publish_access_denied(hook: &BusHook, denied: AccessDenied) { - if let Ok(handle) = tokio::runtime::Handle::try_current() { - let bus = hook.bus.clone(); - let registry = hook.registry.clone(); - handle.spawn(async move { - publish_access_denied(&bus, ®istry, &denied).await; - }); - } -} - -#[cfg(test)] -mod tests; diff --git a/core/continuum-genome/src/genome/local_manager/tests.rs b/core/continuum-genome/src/genome/local_manager/tests.rs deleted file mode 100644 index a63b0ef3fc..0000000000 --- a/core/continuum-genome/src/genome/local_manager/tests.rs +++ /dev/null @@ -1,848 +0,0 @@ -#![cfg(test)] - //! End-to-end tests for the local impl. Each test wires a couple - //! of stub tiers, registers a persona, and verifies the page_in / - //! page_out / audit_access dispatch. - use super::*; - use crate::genome::blob::{ArtifactBlob, Provenance}; - use crate::genome::tier::{EvictionRecord, TierCapacity}; - use crate::inference::page_ref::{ArtifactId, PageKind, PageOffset}; - use parking_lot::Mutex; - use std::sync::Arc; - use uuid::Uuid; - - /// Stub tier store: records every read/write/observe call so - /// tests assert "the manager called the right tier in the right - /// order." Holds a static `Option` per page for - /// `read` responses. - struct StubTier { - role: TierRole, - /// Pages this tier has — read returns Ok(handle) for matches, - /// `TierError::PageNotFound` otherwise. - pages_present: Mutex>, - /// Call log so tests can assert order of tier access. - reads: Mutex>, - observes: Mutex>, - /// Artificial read latency. Zero for the fast in-memory stubs; - /// non-zero to model a slow lower tier (Cold SSD / Frozen) so a - /// test can assert `PageFault.elapsed_us` reflects real - /// servicing cost rather than a sub-microsecond stub hit. - read_delay: std::time::Duration, - } - - impl StubTier { - fn new(role: TierRole, pages_present: Vec) -> Arc { - Self::with_delay(role, pages_present, std::time::Duration::ZERO) - } - - /// Stub tier that sleeps `read_delay` on every `read` — models a - /// slow tier so page-in timing is measurable + non-flaky. - fn with_delay( - role: TierRole, - pages_present: Vec, - read_delay: std::time::Duration, - ) -> Arc { - Arc::new(Self { - role, - pages_present: Mutex::new(pages_present), - reads: Mutex::new(Vec::new()), - observes: Mutex::new(Vec::new()), - read_delay, - }) - } - } - - #[async_trait] - impl TierStore for StubTier { - fn role(&self) -> TierRole { - self.role - } - - async fn read(&self, page: PageRef) -> Result { - if !self.read_delay.is_zero() { - tokio::time::sleep(self.read_delay).await; - } - self.reads.lock().push(page); - if self.pages_present.lock().contains(&page) { - Ok(PageHandle { - page, - tier_role: self.role, - size_bytes: 1024, - }) - } else { - Err(TierError::PageNotFound { page }) - } - } - - async fn write( - &self, - _page: PageRef, - _blob: ArtifactBlob, - _provenance: Provenance, - ) -> Result<(), TierError> { - Ok(()) - } - - async fn evict(&self, _target_free_bytes: usize) -> Vec { - Vec::new() - } - - fn capacity(&self) -> TierCapacity { - TierCapacity { - current_used: 0, - configured_limit: 100_000_000, - } - } - - fn observe_access(&self, page: PageRef) { - self.observes.lock().push(page); - } - } - - fn make_page(low_artifact_bits: u128) -> PageRef { - PageRef { - kind: PageKind::LoRALayer, - artifact: ArtifactId::new(Uuid::from_u128(low_artifact_bits)), - offset: PageOffset::Whole, - } - } - - fn make_persona(low_bits: u128) -> PeerId { - PeerId::from_uuid(Uuid::from_u128(low_bits)) - } - - fn capacity_uma() -> WorkingSetCapacity { - WorkingSetCapacity { - fast_bytes: 1_000_000, - warm_bytes: 0, - max_pinned_bytes: 500_000, - } - } - - /// What this catches: page_in on an already-resident page returns - /// the cached handle WITHOUT walking the tier chain. Hot-path - /// correctness; the whole point of a working set is that the - /// resident-hit path is cheap. - #[tokio::test] - async fn page_in_resident_returns_cached_without_tier_walk() { - let page = make_page(1); - let fast = StubTier::new(TierRole::Fast, vec![page]); - let mgr = LocalWorkingSetManager::new(vec![fast.clone()]); - let persona = make_persona(7); - mgr.register_persona(persona, capacity_uma()); - - // First call: misses working set, promotes via Fast tier. - let first = mgr.page_in(persona, page).await; - match first { - Err(fault) => { - assert_eq!(fault.from_role, Some(TierRole::Fast)); - assert_eq!(fault.to_role, TierRole::Fast); - assert_eq!(fault.persona, persona); - } - Ok(_) => panic!("first call should report tier promotion"), - } - let reads_after_first = fast.reads.lock().len(); - assert_eq!(reads_after_first, 1); - - // Second call: hits working set, returns Ok without re-reading. - let second = mgr.page_in(persona, page).await; - match second { - Ok(handle) => { - assert_eq!(handle.tier_role, TierRole::Fast); - assert_eq!(handle.page, page); - } - Err(_) => panic!("second call should be a resident hit"), - } - // Tier was NOT re-read on the resident-hit path. - assert_eq!(fast.reads.lock().len(), reads_after_first); - } - - /// What this catches: page_in walks tier chain top-down (Fast → - /// Cold), returns the first hit + records the from_role + to_role - /// correctly. PageFault.from_role is where the page WAS; - /// PageFault.to_role is the working set's preferred tier (always - /// the highest configured). - #[tokio::test] - async fn page_in_walks_tier_chain_and_records_promotion() { - let page = make_page(2); - let fast = StubTier::new(TierRole::Fast, vec![]); - let bench = StubTier::new(TierRole::Bench, vec![]); - let cold = StubTier::new(TierRole::Cold, vec![page]); - let mgr = LocalWorkingSetManager::new(vec![fast.clone(), bench.clone(), cold.clone()]); - let persona = make_persona(8); - mgr.register_persona(persona, capacity_uma()); - - let result = mgr.page_in(persona, page).await; - match result { - Err(fault) => { - assert_eq!(fault.from_role, Some(TierRole::Cold)); - assert_eq!(fault.to_role, TierRole::Fast); - assert_eq!(fault.persona, persona); - // Eviction cost is None — PR-3 doesn't drive - // eviction. PR-4 wires the callback. - assert!(fault.eviction_cost.is_none()); - } - Ok(_) => panic!("expected PageFault for tier promotion"), - } - - // Tier walk order: Fast first, then Bench, then Cold. - assert_eq!(fast.reads.lock().len(), 1); - assert_eq!(bench.reads.lock().len(), 1); - assert_eq!(cold.reads.lock().len(), 1); - } - - /// What this catches: page_in on a page that exists in NO tier - /// returns a PageFault with `from_role: None` — the typed "true - /// cold miss" signal sentinel needs to distinguish "page never - /// existed" from "page was on Cold tier." - #[tokio::test] - async fn page_in_true_cold_miss_has_none_from_role() { - let page = make_page(3); - let fast = StubTier::new(TierRole::Fast, vec![]); - let cold = StubTier::new(TierRole::Cold, vec![]); - let mgr = LocalWorkingSetManager::new(vec![fast, cold]); - let persona = make_persona(9); - mgr.register_persona(persona, capacity_uma()); - - let result = mgr.page_in(persona, page).await; - match result { - Err(fault) => { - assert_eq!(fault.from_role, None); - assert_eq!(fault.to_role, TierRole::Fast); - assert_eq!(fault.page, page); - } - Ok(_) => panic!("expected PageFault for true cold miss"), - } - } - - /// What this catches: audit_access returns AccessDenied with the - /// typed shape — not a generic error — when a different persona - /// tries to read a private page. Same contract PR-2's trait test - /// pins, now exercised through the LocalWorkingSetManager. - #[tokio::test] - async fn audit_access_denies_cross_persona_read() { - let fast = StubTier::new(TierRole::Fast, vec![]); - let mgr = LocalWorkingSetManager::new(vec![fast]); - let owner = make_persona(10); - let intruder = make_persona(11); - let page = make_page(4); - - mgr.register_persona(owner, capacity_uma()); - mgr.register_persona(intruder, capacity_uma()); - mgr.register_page_owner(page, owner); - - // Owner: OK. - assert!(mgr.audit_access(owner, page).is_ok()); - - // Intruder: AccessDenied with full context. - let result = mgr.audit_access(intruder, page); - match result { - Err(denied) => { - assert_eq!(denied.actor, intruder); - assert_eq!(denied.owner, Some(owner)); - assert!(denied.reason.contains("cross-persona")); - } - Ok(()) => panic!("expected AccessDenied"), - } - } - - /// What this catches: page_out to a configured tier role observes - /// the page (signals the tier's bookkeeping) and removes from the - /// working set. page_out to an unconfigured role returns - /// `TierError::RoleNotConfigured` — the typed refusal for "you - /// asked for a role this hardware doesn't have." - #[tokio::test] - async fn page_out_observes_target_tier_and_handles_unconfigured() { - let page = make_page(5); - let fast = StubTier::new(TierRole::Fast, vec![page]); - let bench = StubTier::new(TierRole::Bench, vec![]); - let mgr = LocalWorkingSetManager::new(vec![fast, bench.clone()]); - let persona = make_persona(12); - mgr.register_persona(persona, capacity_uma()); - - // First, page_in to populate the working set. - let _ = mgr.page_in(persona, page).await; - - // page_out to Bench: tier observes; working set updates. - let result = mgr.page_out(persona, page, TierRole::Bench).await; - assert!(result.is_ok()); - assert!(bench.observes.lock().contains(&page)); - - // page_out to Warm: NOT configured on this UMA-like setup - // (no Warm tier in the vec). Returns typed RoleNotConfigured. - let result = mgr.page_out(persona, page, TierRole::Warm).await; - match result { - Err(TierError::RoleNotConfigured { role }) => { - assert_eq!(role, TierRole::Warm); - } - other => panic!("expected RoleNotConfigured, got {other:?}"), - } - } - - /// What this catches: pinned pages survive page_out (skipped - /// silently per the trait docstring). Composition layer holds - /// the pin; manager respects it. - #[tokio::test] - async fn page_out_skips_pinned_pages_silently() { - let page = make_page(6); - let fast = StubTier::new(TierRole::Fast, vec![page]); - let bench = StubTier::new(TierRole::Bench, vec![]); - let mgr = LocalWorkingSetManager::new(vec![fast, bench]); - let persona = make_persona(13); - mgr.register_persona(persona, capacity_uma()); - - let _ = mgr.page_in(persona, page).await; - - // Manually pin the page (composition would normally do this). - { - let mut working_sets = mgr.working_sets.write(); - if let Some(ws) = working_sets.get_mut(&persona) { - let key = serde_json::to_string(&page).unwrap(); - if let Some(resident) = ws.pages.get_mut(&key) { - resident.pinned = true; - } - } - } - - // page_out is a no-op for pinned page. - let result = mgr.page_out(persona, page, TierRole::Bench).await; - assert!(result.is_ok()); - - // Page is still in the working set. - let snapshot = mgr.working_set_snapshot(persona).unwrap(); - let key = serde_json::to_string(&page).unwrap(); - assert!(snapshot.pages.contains_key(&key)); - } - - /// What this catches: working_set_snapshot reflects what page_in - /// recorded. Diagnostic helper correctness — tests + telemetry - /// rely on this to verify state without holding the lock. - #[tokio::test] - async fn working_set_snapshot_reflects_page_in_state() { - let page = make_page(7); - let fast = StubTier::new(TierRole::Fast, vec![page]); - let mgr = LocalWorkingSetManager::new(vec![fast]); - let persona = make_persona(14); - mgr.register_persona(persona, capacity_uma()); - - // Pre-page-in: empty. - let pre = mgr.working_set_snapshot(persona).unwrap(); - assert!(pre.pages.is_empty()); - - // After page_in: one resident page. - let _ = mgr.page_in(persona, page).await; - let post = mgr.working_set_snapshot(persona).unwrap(); - assert_eq!(post.pages.len(), 1); - let key = serde_json::to_string(&page).unwrap(); - let resident = post.pages.get(&key).unwrap(); - assert_eq!(resident.role, TierRole::Fast); - assert_eq!(resident.access_count_window, 1); - assert!(!resident.pinned); - } - - /// What this catches: tier_count returns the configured tier - /// count. Cheap O(1) — used by the governor's policy diagnostics - /// to verify the manager was wired with the right Vec - /// shape (4 on UMA, 5 on discrete-GPU). - #[tokio::test] - async fn tier_count_reflects_configured_tiers() { - let mgr = LocalWorkingSetManager::new(vec![ - StubTier::new(TierRole::Fast, vec![]), - StubTier::new(TierRole::Bench, vec![]), - StubTier::new(TierRole::Cold, vec![]), - StubTier::new(TierRole::Frozen, vec![]), - ]); - assert_eq!(mgr.tier_count(), 4); - } - - // ─── PR-5 bus-publishing tests ────────────────────────────── - - use crate::genome::bus::{all_genome_artifact_selectors, ACCESS_DENIED_KEY, PAGE_FAULT_KEY}; - use crate::runtime::artifact_handle::{ArtifactKey, ArtifactSelector}; - use crate::runtime::runtime::Runtime; - use crate::runtime::service_module::{CommandResult, ModuleConfig, ModulePriority, ServiceModule}; - use std::any::Any; - - /// Recording subscriber for the PR-5 bus tests. Captures every - /// (artifact_key, payload) so the test can assert which fired. - struct RecorderModule { - captured: Arc>>, - } - - impl RecorderModule { - fn new() -> (Arc, Arc>>) { - let captured = Arc::new(Mutex::new(Vec::new())); - let module = Arc::new(Self { - captured: captured.clone(), - }); - (module, captured) - } - } - - #[async_trait] - impl ServiceModule for RecorderModule { - fn config(&self) -> ModuleConfig { - ModuleConfig { - name: "pr5-recorder", - priority: ModulePriority::Normal, - command_prefixes: &[], - event_subscriptions: &[], - needs_dedicated_thread: false, - max_concurrency: 0, - tick_interval: None, - } - } - async fn initialize(&self, _ctx: &crate::runtime::ModuleContext) -> Result<(), String> { - Ok(()) - } - async fn handle_command( - &self, - _: &str, - _: serde_json::Value, - ) -> Result { - Err("not handled".to_string()) - } - fn artifact_subscriptions(&self) -> Vec { - all_genome_artifact_selectors() - } - async fn on_artifact_available( - &self, - key: &ArtifactKey, - payload: serde_json::Value, - ) -> Result<(), String> { - self.captured - .lock() - .push((key.as_str().to_string(), payload)); - Ok(()) - } - fn as_any(&self) -> &dyn Any { - self - } - } - - /// Helper: construct a Runtime + LocalWorkingSetManager wired - /// through it. Returns the manager + the recorder's captured - /// events. Used by the next several tests. - async fn wire_manager_to_runtime( - tiers: Vec>, - ) -> ( - LocalWorkingSetManager, - Arc, - Arc>>, - ) { - // Build runtime, register recorder. - let runtime = Arc::new(Runtime::new()); - let (recorder, captured) = RecorderModule::new(); - runtime.register(recorder); - - // Pull bus + registry as Arcs via the helper accessors. - // Runtime exposes `bus_arc()` and `registry_arc()` for this. - let bus = runtime.bus_arc(); - let registry = runtime.registry_arc(); - - let mgr = LocalWorkingSetManager::with_bus(tiers, bus, registry); - (mgr, runtime, captured) - } - - /// What this catches: with the bus hook wired, `page_in` for a - /// true cold miss (no tier has the page) publishes a PageFault - /// with `from_role: None`. The whole chain — manager → - /// publish_page_fault → bus.subscribe_artifact → recorder - /// on_artifact_available — fires end-to-end. - #[tokio::test] - async fn page_in_true_cold_miss_with_bus_publishes_page_fault() { - let cold = StubTier::new(TierRole::Cold, vec![]); - let fast = StubTier::new(TierRole::Fast, vec![]); - let (mgr, _runtime, captured) = wire_manager_to_runtime(vec![fast, cold]).await; - - let persona = make_persona(30); - mgr.register_persona(persona, capacity_uma()); - - let page = make_page(31); - let result = mgr.page_in(persona, page).await; - assert!(result.is_err(), "true cold miss returns Err(PageFault)"); - - // Yield to let the spawned publish task run. - for _ in 0..50 { - tokio::task::yield_now().await; - if !captured.lock().is_empty() { - break; - } - } - - let events = captured.lock().clone(); - let faults: Vec<_> = events.iter().filter(|(k, _)| k == PAGE_FAULT_KEY).collect(); - assert_eq!(faults.len(), 1, "exactly one PageFault published"); - let fault: PageFault = serde_json::from_value(faults[0].1.clone()).unwrap(); - assert_eq!(fault.from_role, None, "true cold miss has no from_role"); - assert_eq!(fault.persona, persona); - assert_eq!(fault.page, page); - } - - /// What this catches: page_in tier-promotion (page exists in Cold, - /// promoted to Fast) publishes a PageFault with from_role=Some(Cold) - /// and to_role=Fast. Sentinel uses this to learn the persona's - /// promotion pattern. - #[tokio::test] - async fn page_in_tier_promotion_with_bus_publishes_correct_fields() { - let page = make_page(40); - let cold = StubTier::new(TierRole::Cold, vec![page]); - let fast = StubTier::new(TierRole::Fast, vec![]); - let (mgr, _runtime, captured) = wire_manager_to_runtime(vec![fast, cold]).await; - - let persona = make_persona(41); - mgr.register_persona(persona, capacity_uma()); - - let _ = mgr.page_in(persona, page).await; - - for _ in 0..50 { - tokio::task::yield_now().await; - if !captured.lock().is_empty() { - break; - } - } - - let events = captured.lock().clone(); - let faults: Vec<_> = events.iter().filter(|(k, _)| k == PAGE_FAULT_KEY).collect(); - assert_eq!(faults.len(), 1); - let fault: PageFault = serde_json::from_value(faults[0].1.clone()).unwrap(); - assert_eq!(fault.from_role, Some(TierRole::Cold)); - assert_eq!(fault.to_role, TierRole::Fast); - } - - /// What this catches: page_in resident-hit (page already in the - /// working set) does NOT publish a PageFault. PageFault is only - /// for misses — pinning the resident-hit path's silence prevents - /// noisy events for hot pages. - #[tokio::test] - async fn page_in_resident_hit_with_bus_does_not_publish() { - let page = make_page(50); - let fast = StubTier::new(TierRole::Fast, vec![page]); - let (mgr, _runtime, captured) = wire_manager_to_runtime(vec![fast]).await; - - let persona = make_persona(51); - mgr.register_persona(persona, capacity_uma()); - - // First call: tier promotion → 1 PageFault published. - let _ = mgr.page_in(persona, page).await; - for _ in 0..50 { - tokio::task::yield_now().await; - if !captured.lock().is_empty() { - break; - } - } - assert_eq!( - captured - .lock() - .iter() - .filter(|(k, _)| k == PAGE_FAULT_KEY) - .count(), - 1 - ); - - // Second call: resident hit → NO additional PageFault. - let _ = mgr.page_in(persona, page).await; - // Yield a few times to give any incorrectly-spawned publish a - // chance to run — we want to assert no additional event. - for _ in 0..20 { - tokio::task::yield_now().await; - } - assert_eq!( - captured - .lock() - .iter() - .filter(|(k, _)| k == PAGE_FAULT_KEY) - .count(), - 1, - "resident-hit path must not publish" - ); - } - - /// What this catches: audit_access denial spawns a publish through - /// the current tokio runtime. The sync trait method returns - /// immediately; the publish completes asynchronously. Test polls - /// briefly because the spawn isn't synchronously joined. - #[tokio::test] - async fn audit_access_denial_with_bus_publishes_via_spawn() { - let fast = StubTier::new(TierRole::Fast, vec![]); - let (mgr, _runtime, captured) = wire_manager_to_runtime(vec![fast]).await; - - let owner = make_persona(60); - let intruder = make_persona(61); - let page = make_page(62); - mgr.register_persona(owner, capacity_uma()); - mgr.register_persona(intruder, capacity_uma()); - mgr.register_page_owner(page, owner); - - // Cross-persona access — Err returned immediately, publish - // spawned. - let result = mgr.audit_access(intruder, page); - assert!(result.is_err()); - - // Yield so the spawned publish task gets a chance to run. - // tokio::yield_now() inside a loop bounded by attempts is the - // safe way to wait without a fixed sleep. - for _ in 0..50 { - tokio::task::yield_now().await; - if !captured.lock().is_empty() { - break; - } - } - - let events = captured.lock().clone(); - let denied_events: Vec<_> = events - .iter() - .filter(|(k, _)| k == ACCESS_DENIED_KEY) - .collect(); - assert_eq!(denied_events.len(), 1, "exactly one AccessDenied published"); - let denied: AccessDenied = serde_json::from_value(denied_events[0].1.clone()).unwrap(); - assert_eq!(denied.actor, intruder); - assert_eq!(denied.owner, Some(owner)); - } - - /// What this catches: audit_access for same-persona access does - /// NOT publish. Only denials are observable events. - #[tokio::test] - async fn audit_access_allowed_with_bus_does_not_publish() { - let fast = StubTier::new(TierRole::Fast, vec![]); - let (mgr, _runtime, captured) = wire_manager_to_runtime(vec![fast]).await; - - let owner = make_persona(70); - let page = make_page(71); - mgr.register_persona(owner, capacity_uma()); - mgr.register_page_owner(page, owner); - - // Owner accessing own page: Ok. - let result = mgr.audit_access(owner, page); - assert!(result.is_ok()); - - // Yield in case anything was queued. - for _ in 0..10 { - tokio::task::yield_now().await; - } - - let events = captured.lock().clone(); - let denied_events: Vec<_> = events - .iter() - .filter(|(k, _)| k == ACCESS_DENIED_KEY) - .collect(); - assert!(denied_events.is_empty(), "no denial = no event"); - } - - /// What this catches: bus-less mode (via `new` instead of - /// `with_bus`) still works — the trait methods behave identically - /// to PR-3, just without publishing. Backwards-compat for the - /// standalone use case. - #[tokio::test] - async fn bus_less_mode_does_not_publish_but_methods_work() { - let page = make_page(80); - let fast = StubTier::new(TierRole::Fast, vec![page]); - // `new` instead of `with_bus` — no bus hook. - let mgr = LocalWorkingSetManager::new(vec![fast]); - let persona = make_persona(81); - mgr.register_persona(persona, capacity_uma()); - - // page_in still returns Err(PageFault) — caller-side - // observability still works through the Result arm. - let result = mgr.page_in(persona, page).await; - assert!(result.is_err()); - - // audit_access still returns the typed denial — no spawn, - // no publish, no observable side effect (the typed Result - // is THE signal). - let result = mgr.audit_access(persona, page); - assert!(result.is_ok()); - } - - // ─── Measured page-in cost (the genome-overlay multiplicity proof) ─── - // - // These tests pin the measurement that turns the page-fault system - // from typed-but-blind into measured: `PageFault.elapsed_us` is now - // the real servicing cost, not the `0` it shipped with. That number - // is what proves "persona N = a cheap LoRA page-in, not a model - // load" — see [[persona-is-a-genome-overlay-not-an-instance]]. - - /// What this catches: a LoRA-overlay page-in records REAL servicing - /// time in `PageFault.elapsed_us` — not the hardcoded `0` it shipped - /// with. A slow lower tier (3ms read) must surface as elapsed_us in - /// the millisecond range. This is the measurement the genome-overlay - /// thesis stands on; sentinel/governor compare overlay page-in cost - /// across personas from this field on the bus. - /// regression for: elapsed_us:0 stub at the page_in fault arms. - #[tokio::test] - async fn page_in_fault_records_real_elapsed_us() { - let page = make_page(90); - // Model a slow cold tier so servicing is measurable + non-flaky. - // tokio::time::sleep is a floor — jitter only lengthens it. - let cold = StubTier::with_delay( - TierRole::Cold, - vec![page], - std::time::Duration::from_millis(3), - ); - let fast = StubTier::new(TierRole::Fast, vec![]); - let mgr = LocalWorkingSetManager::new(vec![fast, cold]); - let persona = make_persona(91); - mgr.register_persona(persona, capacity_uma()); - - let fault = mgr.page_in(persona, page).await.unwrap_err(); - assert_eq!(fault.from_role, Some(TierRole::Cold)); - assert!( - fault.elapsed_us >= 1000, - "page-in servicing time must be measured (>=1ms for a 3ms tier read), got {}us", - fault.elapsed_us - ); - } - - /// What this catches: even a true cold miss (page in NO tier) records - /// the time it spent walking the whole tier chain — the cold-miss arm - /// isn't still hardcoded to 0. Two 2ms tiers searched → the elapsed - /// covers both reads. - #[tokio::test] - async fn page_in_cold_miss_records_elapsed_for_full_walk() { - let page = make_page(92); - let fast = - StubTier::with_delay(TierRole::Fast, vec![], std::time::Duration::from_millis(2)); - let cold = - StubTier::with_delay(TierRole::Cold, vec![], std::time::Duration::from_millis(2)); - let mgr = LocalWorkingSetManager::new(vec![fast, cold]); - let persona = make_persona(93); - mgr.register_persona(persona, capacity_uma()); - - let fault = mgr.page_in(persona, page).await.unwrap_err(); - assert_eq!(fault.from_role, None); - assert!( - fault.elapsed_us >= 2000, - "cold-miss must time the full tier walk (two 2ms tiers), got {}us", - fault.elapsed_us - ); - } - - /// What this catches: THE genome-overlay-as-multiplicity thesis. Two - /// personas share ONE manager (one base model); each pages in her OWN - /// LoRA overlay from the cold tier. Each gets a measured page-in - /// fault, and each working set holds ONLY her own overlay — overlays - /// don't leak across personas. "Multiple personas" = multiple LoRA - /// overlays multiplexed through one pager, O(page-in) each. - #[tokio::test] - async fn two_personas_page_in_own_overlays_through_one_manager() { - let overlay_a = make_page(100); // Asha's LoRA overlay - let overlay_b = make_page(101); // second persona's overlay - let fast = StubTier::new(TierRole::Fast, vec![]); - let cold = StubTier::with_delay( - TierRole::Cold, - vec![overlay_a, overlay_b], - std::time::Duration::from_millis(2), - ); - let mgr = LocalWorkingSetManager::new(vec![fast, cold]); - - let asha = make_persona(100); - let nova = make_persona(101); - mgr.register_persona(asha, capacity_uma()); - mgr.register_persona(nova, capacity_uma()); - - // Each persona pages in her own overlay through the shared base. - let fault_a = mgr.page_in(asha, overlay_a).await.unwrap_err(); - let fault_b = mgr.page_in(nova, overlay_b).await.unwrap_err(); - assert!(fault_a.elapsed_us >= 1000 && fault_a.persona == asha); - assert!(fault_b.elapsed_us >= 1000 && fault_b.persona == nova); - - // Isolation: each working set holds ONLY its own overlay. - let asha_ws = mgr.working_set_snapshot(asha).unwrap(); - let nova_ws = mgr.working_set_snapshot(nova).unwrap(); - let key_a = serde_json::to_string(&overlay_a).unwrap(); - let key_b = serde_json::to_string(&overlay_b).unwrap(); - assert!( - asha_ws.pages.contains_key(&key_a) && !asha_ws.pages.contains_key(&key_b), - "Asha's working set holds only her overlay" - ); - assert!( - nova_ws.pages.contains_key(&key_b) && !nova_ws.pages.contains_key(&key_a), - "Nova's working set holds only her overlay" - ); - - // Resident-hit is the hot path: re-paging an already-resident - // overlay is a cached Ok with NO fault — the page-in cost is - // paid once, then it's free. This is why overlay multiplexing - // scales: O(page-in) once, O(1) thereafter. - let hit = mgr.page_in(asha, overlay_a).await; - assert!( - hit.is_ok(), - "resident overlay re-page is a hot hit, no fault" - ); - } - - // ─── Benchmark: science the multiplicity proof ────────────────────── - // - // Gated behind `stress-tests` per the test doctrine — default - // `cargo test` skips it; run it on demand to SEE the numbers: - // - // CARGO_TARGET_DIR="$HOME/.continuum/cache/cargo-target" \ - // cargo test -p continuum-core --features stress-tests \ - // genome::local_manager::tests::stress -- --nocapture - // - // The headline it benchmarks: per-persona overlay page-in cost stays - // FLAT as persona count grows — "add persona N" is O(page-in), the - // claim [[persona-is-a-genome-overlay-not-an-instance]] rests on. - #[cfg(feature = "stress-tests")] - mod stress { - use super::*; - - fn percentile(sorted: &[u64], p: f64) -> u64 { - if sorted.is_empty() { - return 0; - } - let idx = (((sorted.len() - 1) as f64) * p).round() as usize; - sorted[idx] - } - - /// What this catches: regression in per-persona page-in scaling. - /// Sweeps persona counts through ONE manager (one base model); - /// each persona pages in a DISTINCT LoRA overlay resident on a - /// zero-delay cold tier (we measure pager overhead, not disk). - /// Prints total wall, per-persona mean, p95 servicing-us, and the - /// resident-hit cost. Flat per-persona cost across counts ⇒ the - /// genome-overlay-as-multiplicity thesis holds by measurement. - #[tokio::test] - async fn bench_overlay_page_in_scales_per_persona() { - eprintln!("\n=== genome overlay multiplicity bench (one base, N overlays) ==="); - eprintln!( - "{:>8} | {:>10} | {:>9} | {:>9} | {:>12}", - "personas", "wall_us", "per_us", "p95_us", "resident_ns" - ); - for &count in &[1usize, 8, 32, 64, 128, 256] { - let overlays: Vec<_> = (0..count).map(|i| make_page(1_000 + i as u128)).collect(); - let cold = StubTier::new(TierRole::Cold, overlays.clone()); - let fast = StubTier::new(TierRole::Fast, vec![]); - let mgr = LocalWorkingSetManager::new(vec![fast, cold]); - let personas: Vec<_> = (0..count) - .map(|i| make_persona(1_000 + i as u128)) - .collect(); - for &p in &personas { - mgr.register_persona(p, capacity_uma()); - } - - let mut serviced = Vec::with_capacity(count); - let wall = std::time::Instant::now(); - for i in 0..count { - let fault = mgr.page_in(personas[i], overlays[i]).await.unwrap_err(); - serviced.push(fault.elapsed_us); - } - let wall_us = wall.elapsed().as_micros() as u64; - serviced.sort_unstable(); - let per_us = wall_us / count as u64; - let p95 = percentile(&serviced, 0.95); - - // Resident-hit: re-page persona 0's now-hot overlay. - let hot = std::time::Instant::now(); - let _ = mgr.page_in(personas[0], overlays[0]).await; - let resident_ns = hot.elapsed().as_nanos() as u64; - - eprintln!( - "{:>8} | {:>10} | {:>9} | {:>9} | {:>12}", - count, wall_us, per_us, p95, resident_ns - ); - } - eprintln!( - "=== flat per_us across counts ⇒ overlay multiplicity is O(page-in)/persona ===\n" - ); - } - } diff --git a/core/continuum-genome/src/genome/manager.rs b/core/continuum-genome/src/genome/manager.rs deleted file mode 100644 index e983495ceb..0000000000 --- a/core/continuum-genome/src/genome/manager.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! `WorkingSetManager` trait — the top-level paging interface every -//! persona's cognition path calls. Per GENOME-FOUNDRY-SENTINEL Parts -//! 3 (paging) and 4 (compartmentalization). -//! -//! PR-2 of working-set-manager ships the **trait surface only**. The -//! per-persona implementation that holds the `Box` -//! per role, services `page_in` by walking the tier chain, and -//! publishes `PageFault` / `EvictionRecord` events through the -//! artifact dispatch path (#1339+#1343) lands in PR-3. -//! -//! ## What the trait promises -//! -//! - `page_in` — promote a page into the persona's working set. May -//! trigger eviction. On miss-with-no-eviction-candidate returns -//! `PageFault` (used by sentinel to learn the persona's access -//! pattern), not a generic error. -//! - `page_out` — demote a page out of the working set toward a -//! named tier role. Used by the eviction policy + composition layer -//! when it's done with a page. -//! - `working_set` — read-only snapshot of the persona's current -//! resident pages. The hot path uses this to decide "do I need to -//! page in or is it already there." Returns `&WorkingSet` (no -//! clone) because the call is hot. -//! - `audit_access` — MMU-style permission check. Returns -//! `AccessDenied` if the page is private to another persona. This -//! is one of the four typed events audit-recorder (#1344) -//! subscribes to. -//! -//! ## What's deliberately deferred -//! -//! `check_permission(actor, region, op)` from GENOME-FOUNDRY- -//! SENTINEL Part 4 lands in PR-3 alongside the GenomeRegion + Op -//! type definitions and the per-region permission matrix. PR-2 only -//! ships the four methods that don't need those types — keeping -//! the surface tight so this PR is reviewable on its own. - -use async_trait::async_trait; - -use super::tier::{TierError, TierRole}; -use super::working_set::{AccessDenied, PageFault, PageHandle, WorkingSet}; -use crate::inference::page_ref::PageRef; -use crate::identity::PeerId; - -/// The single trait every working-set implementation satisfies. The -/// PR-3 implementor will be a per-substrate-process singleton holding -/// the tier chain + per-persona `WorkingSet` state. -/// -/// `Send + Sync` because every persona task calls into it -/// concurrently from the tokio runtime. -#[async_trait] -pub trait WorkingSetManager: Send + Sync { - /// Promote a page into this persona's working set. May trigger - /// eviction of other pages within the same working set. - /// - /// Returns `Ok(PageHandle)` when the page is now resident. The - /// handle's `tier_role` tells the caller which tier the page - /// lives in — the caller decides whether to pin it or stream it. - /// - /// Returns `Err(PageFault)` when the page wasn't already resident - /// AND the manager had to do work to make it so. The PageFault - /// is NOT an error in the failure sense — it's a typed signal - /// for sentinel + composition observability. The caller treats it - /// as success-with-trace-event. A future PR may relax this - /// signature (e.g. return `Result<(PageHandle, Option), - /// TierError>`) if downstream feedback wants both. - async fn page_in(&self, persona: PeerId, page: PageRef) -> Result; - - /// Demote a page out of the working set toward the named tier - /// role. Used by composition when it's done with a page (e.g. - /// after a turn completes), and by the eviction policy when a - /// higher tier needs the bytes. - /// - /// Returns `Err(TierError)` if the target tier can't accept the - /// page (over-budget, role-not-configured, backing-store I/O). - /// The pinned-page case is NOT a TierError — page_out skips - /// pinned pages silently; the caller (composition) is responsible - /// for unpinning before demoting. - async fn page_out(&self, persona: PeerId, page: PageRef, to: TierRole) - -> Result<(), TierError>; - - /// Read-only snapshot of the persona's current working set. The - /// hot path uses this to decide "is the page I need already - /// resident?" without paying the page_in cost. - /// - /// Returns `Option<&WorkingSet>` instead of `&WorkingSet`: a - /// persona that has never been registered with this manager has - /// no working set yet — returning `None` is cleaner than - /// fabricating an empty one (which would mask "wrong persona id" - /// bugs). The Part-3 spec uses `&WorkingSet` without the option; - /// PR-2's narrower contract is a pragmatic refinement that catches - /// the misuse case earlier. - fn working_set(&self, persona: PeerId) -> Option<&WorkingSet>; - - /// MMU-style audit: the named persona is asking for the named - /// page. Returns `Err(AccessDenied)` if the page is private to a - /// different persona (cross-persona read attempt). - /// - /// This is one of the four typed events audit-recorder (#1344) - /// subscribes to — every AccessDenied gets pinned to the audit - /// log, regardless of whether the calling persona caught + logged - /// it itself. Compartmentalization audit trail per - /// GENOME-FOUNDRY-SENTINEL Part 4. - fn audit_access(&self, persona: PeerId, page: PageRef) -> Result<(), AccessDenied>; -} - -#[cfg(test)] -mod tests { - //! Trait-shape tests: prove the trait is object-safe (usable as - //! `Box` / `Arc`) - //! and that a minimal implementor compiles + dispatches through - //! the trait object. PR-3 will add the per-persona impl tested - //! against real semantics; PR-2 only proves the seam. - - use super::*; - use crate::genome::working_set::WorkingSetCapacity; - use crate::inference::page_ref::{ArtifactId, PageKind, PageOffset}; - use std::collections::HashMap; - use std::sync::Arc; - use uuid::Uuid; - - /// Minimal stub manager for trait-shape tests. Backing storage: - /// per-persona HashMap of "pages this persona owns" the audit_access - /// check uses. - struct StubManager { - working_sets: HashMap, - /// (page, owner) — audit_access denies if `persona != owner`. - page_owners: HashMap, - } - - #[async_trait] - impl WorkingSetManager for StubManager { - async fn page_in(&self, _persona: PeerId, page: PageRef) -> Result { - // Stub: every page_in succeeds with a fresh handle. The - // contract being tested is the signature shape, not the - // page-resolution logic (PR-3's territory). - Ok(PageHandle { - page, - tier_role: TierRole::Fast, - size_bytes: 0, - }) - } - - async fn page_out( - &self, - _persona: PeerId, - _page: PageRef, - _to: TierRole, - ) -> Result<(), TierError> { - Ok(()) - } - - fn working_set(&self, persona: PeerId) -> Option<&WorkingSet> { - self.working_sets.get(&persona) - } - - fn audit_access(&self, persona: PeerId, page: PageRef) -> Result<(), AccessDenied> { - match self.page_owners.get(&page) { - Some(owner) if *owner != persona => Err(AccessDenied { - actor: persona, - page, - owner: Some(*owner), - reason: format!("cross-persona read attempt blocked by working-set MMU"), - }), - _ => Ok(()), - } - } - } - - fn sample_persona(low_bits: u128) -> PeerId { - // Build a deterministic UUID from the low bits so tests can - // construct distinct personas without depending on randomness. - PeerId::from_uuid(Uuid::from_u128(low_bits)) - } - - fn sample_page() -> PageRef { - PageRef { - kind: PageKind::LoRALayer, - artifact: ArtifactId::new(Uuid::nil()), - offset: PageOffset::Whole, - } - } - - /// What this catches: WorkingSetManager is object-safe. If a - /// future PR adds a generic method or a non-dyn-safe signature, - /// this construction fails to compile. Load-bearing because the - /// substrate holds a single `Arc` and the - /// persona-cognition module dispatches through it. - #[tokio::test] - async fn working_set_manager_is_object_safe() { - let mgr: Arc = Arc::new(StubManager { - working_sets: HashMap::new(), - page_owners: HashMap::new(), - }); - let p = sample_persona(1); - let handle = mgr.page_in(p, sample_page()).await.unwrap(); - assert_eq!(handle.tier_role, TierRole::Fast); - } - - /// What this catches: working_set returns `None` for an - /// unregistered persona. If the contract changes to fabricate - /// an empty WorkingSet, callers lose the early-fail signal for - /// "wrong persona id." - #[tokio::test] - async fn working_set_returns_none_for_unregistered_persona() { - let mgr: Box = Box::new(StubManager { - working_sets: HashMap::new(), - page_owners: HashMap::new(), - }); - assert!(mgr.working_set(sample_persona(42)).is_none()); - } - - /// What this catches: working_set returns a borrow (not a clone) - /// — the contract is `Option<&WorkingSet>`. The hot path can't - /// afford a HashMap-clone per check. - #[tokio::test] - async fn working_set_returns_borrow_not_clone() { - let persona = sample_persona(7); - let ws = WorkingSet::new( - persona, - WorkingSetCapacity { - fast_bytes: 1_000_000, - warm_bytes: 0, - max_pinned_bytes: 500_000, - }, - ); - let mut working_sets = HashMap::new(); - working_sets.insert(persona, ws); - let mgr: Box = Box::new(StubManager { - working_sets, - page_owners: HashMap::new(), - }); - let got = mgr.working_set(persona).unwrap(); - assert_eq!(got.persona, persona); - assert!(got.pages.is_empty()); - } - - /// What this catches: audit_access returns Ok when the page has - /// no owner OR the persona IS the owner. Same-persona access is - /// always allowed at this layer (composition-layer concerns like - /// pinning are separate). - #[tokio::test] - async fn audit_access_allows_own_pages_and_orphan_pages() { - let owner = sample_persona(10); - let mut page_owners = HashMap::new(); - page_owners.insert(sample_page(), owner); - let mgr: Box = Box::new(StubManager { - working_sets: HashMap::new(), - page_owners, - }); - // Owner accessing own page: OK - assert!(mgr.audit_access(owner, sample_page()).is_ok()); - // Different page (no recorded owner): OK - let other_page = PageRef { - kind: PageKind::Engram, - artifact: ArtifactId::new(Uuid::from_u128(99)), - offset: PageOffset::Whole, - }; - assert!(mgr.audit_access(owner, other_page).is_ok()); - } - - /// What this catches: audit_access returns `AccessDenied` (the - /// typed event) — NOT a generic error — when a persona tries to - /// read a page another persona owns. PR-1 ships AccessDenied as - /// the typed shape; PR-2 pins that the trait returns it. - #[tokio::test] - async fn audit_access_denies_cross_persona_read() { - let owner = sample_persona(10); - let intruder = sample_persona(20); - let mut page_owners = HashMap::new(); - page_owners.insert(sample_page(), owner); - let mgr: Box = Box::new(StubManager { - working_sets: HashMap::new(), - page_owners, - }); - let result = mgr.audit_access(intruder, sample_page()); - match result { - Err(denied) => { - assert_eq!(denied.actor, intruder); - assert_eq!(denied.owner, Some(owner)); - assert!(denied.reason.contains("cross-persona")); - } - Ok(()) => panic!("expected AccessDenied, got Ok"), - } - } -} diff --git a/core/continuum-genome/src/genome/mod.rs b/core/continuum-genome/src/genome/mod.rs index f771b7d11b..298e8a7850 100644 --- a/core/continuum-genome/src/genome/mod.rs +++ b/core/continuum-genome/src/genome/mod.rs @@ -1,67 +1,14 @@ -//! Genome — the substrate's cache hierarchy and paging data layer. -//! -//! The cache is a sequence of **tier roles** parameterized by hardware -//! class. Discrete-GPU hardware has five distinct tiers; unified-memory -//! hardware collapses the top two into one (Warm is omitted). The Rust -//! code is identical across hardware; only the `Vec` -//! per-policy differs. -//! -//! PR-1 of working-set-manager (per MODULE-CATALOG §VII + -//! GENOME-FOUNDRY-SENTINEL Parts 2/3/4) ships the **data layer only**: -//! the typed surface that downstream PRs (trait + impl + dispatch -//! wiring) will hang behaviors on. No I/O, no async, no traits — just -//! the structs/enums + ts-rs exports + serde + a small unit-test pin -//! for each invariant the type system guarantees. -//! -//! This mirrors the shape that worked for CBAR-PIECE-2 PR-1 (#1321 — -//! ArtifactKey/Selector/Cadence types) + PIECE-5 PR-1 (#1331 — gate -//! types): land the data shape first, hang behaviors on it incrementally -//! across later PRs. Each subsequent PR is reviewable independently. -//! -//! ## PR-1 scope (this PR) -//! -//! - `TierRole` — Fast / Warm (discrete-GPU-only) / Bench / Cold / Frozen -//! - `EvictionPolicy` — per-role policy enum -//! - `TierCapacity` — current_used + configured_limit, both bytes -//! - `EvictionRecord` — typed event emitted when a page is evicted -//! - `PageKind` — LoRALayer / MoEExpert / KVCache / Engram -//! - `PageOffset` — sub-artifact offset (for MoE experts, KV chunks) -//! - `PageRef` — fully-qualified page address (kind + artifact + offset) -//! - `ResidentPage` — a page currently in some persona's working set -//! - `WorkingSetCapacity` — per-persona budget the governor sets -//! - `WorkingSet` — a persona's currently-resident pages -//! - `PageFault` — typed event when a page must be paged in -//! - `AccessDenied` — typed refusal from the MMU-style permission check -//! -//! ## PR-1 scope (NOT this PR — explicitly deferred) -//! -//! - `WorkingSetManager` trait — PR-2 of this stack -//! - `TierStore` trait + role-specific impls (5 of them) — separate PR set -//! - MMU permission table enforcement — PR-2 or PR-3 of this stack -//! - Wiring `PageFault` / `EvictionRecord` to the trace bus via my -//! just-shipped artifact dispatch (#1339 + #1343) — PR-3 of this stack -//! - Hardware-anchor `Vec` from the governor — separate PR -//! (substrate-governor lane, codex's territory if they want it) -//! -//! ## Why types-only first -//! -//! Two reasons that compound: -//! -//! 1. **Compiler-enforced contract.** Naming a `TierRole` enum makes -//! "L1→L2 eviction on UMA" structurally impossible because there is -//! no `Warm` tier to evict to. The type system removes the need for -//! runtime checks. Get the names right before the behaviors land. -//! -//! 2. **Multi-author shipping.** Codex + I are racing the MODULE-CATALOG -//! queue. Naming the types first locks the seam every downstream PR -//! builds against — codex's threat-detector + my working-set-manager -//! impl + the next persona-cognition slice all subscribe to the same -//! `PageFault` / `AccessDenied` shapes. PR-1's types are the -//! coordination substrate. +//! Genome: a mind's learned skills (GENE-REUSE-FORK-MINT.md, GENOME-FOUNDRY-SENTINEL.md). +//! +//! - What genes EXIST: training (`fine_tuning`, `teach`), the decision to reuse / fork / mint +//! (`competence`), each gene's identity in embedding space (`signature`), its trial and +//! verdict (`gene_trial`), fitness (`fitness`, `fitness_ledger`). +//! - Which genes shape a TURN, and at what scale: `composer` (the phenotype, by distance). +//! - Where a node's loaded genes LIVE (device or host RAM), within the one device budget: +//! `gene_residency`. +//! - Finding a gene or artifact to reuse: `recall*`, `candidate_source_store`, `tier::TierRole`. pub mod adapter_manifest; -pub mod blob; -pub mod bus; pub mod candidate_source_store; pub mod fine_tuning; pub mod fitness; @@ -70,26 +17,16 @@ pub mod corpus_ref; pub mod gym_grader; pub mod fitness_ledger; pub mod examiner; +pub mod gene_residency; pub mod gene_trial; -pub mod local_manager; +pub mod composer; pub mod signature; -pub mod manager; pub mod recall; pub mod recall_trait; -pub mod store; pub mod teach; pub mod tier; pub mod training_outcome; -pub mod working_set; -pub use blob::{ArtifactBlob, Provenance}; -pub use bus::{ - all_genome_artifact_selectors, publish_access_denied, publish_eviction_record, - publish_page_fault, subscribe_to_genome_events, ACCESS_DENIED_KEY, EVICTION_RECORD_KEY, - PAGE_FAULT_KEY, -}; -pub use local_manager::LocalWorkingSetManager; -pub use manager::WorkingSetManager; pub use recall::{ AcquireSource, FreshnessTarget, RecallError, RecallScope, RecallScore, ResidencyHint, TaskKind, TrustClass, @@ -99,9 +36,7 @@ pub use recall_trait::{ EngramRef, LoRALayerRef, MoEExpertRef, OutcomeWindow, RankedPool, RecallBudget, RecallContext, RecallScoreWeights, RecallTrace, TrajectoryHint, WeightSumOutOfBounds, }; -pub use store::TierStore; -pub use tier::{EvictionPolicy, EvictionRecord, TierCapacity, TierError, TierRole}; -pub use working_set::{AccessDenied, PageFault, PageHandle, ResidentPage, WorkingSet, WorkingSetCapacity}; +pub use tier::TierRole; pub mod recall_scoring; pub use recall_scoring::{ grid_penalty, local_role_score, recency_decay, score as recall_score, tier_proximity_for, diff --git a/core/continuum-genome/src/genome/signature.rs b/core/continuum-genome/src/genome/signature.rs index dead26639b..c08f8c9d66 100644 --- a/core/continuum-genome/src/genome/signature.rs +++ b/core/continuum-genome/src/genome/signature.rs @@ -79,8 +79,22 @@ pub struct GeneSignature { /// (GENE-REUSE-FORK-MINT.md §3a), is counted from these. #[serde(default, skip_serializing_if = "Option::is_none")] pub parent: Option, + /// The gene's REGION, measured at mint: the similarity to this signature that + /// [`REGION_QUANTILE`] of its own training examples clear (GENE-REUSE-FORK-MINT §3d, + /// "the floor is the gene's own spread"). A turn is inside the gene when its need is at + /// least this near; a broad gene has a wide region, a narrow one a narrow region. Absent + /// on signatures minted before it was filed: selection then falls back to the space's + /// measured null (`genome::selection`), never to a hand-tuned cosine. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub region: Option, } +/// Which share of a gene's own training examples its region must hold: the region's edge +/// is the similarity at this low quantile, so nine in ten of the examples that made the +/// gene lie inside it. A definition of "inside", not a tuned threshold: the threshold it +/// produces is measured per gene, from the gene's own corpus. +pub const REGION_QUANTILE: f32 = 0.10; + /// L2-normalize in place; a zero vector stays zero (and can never win a max). fn normalize(v: &mut [f32]) { let norm = v.iter().map(|x| x * x).sum::().sqrt(); @@ -172,7 +186,7 @@ impl GeneSignature { }) .collect(); - Ok(Self { + let mut minted = Self { embedder: embedder.id().to_string(), dim, centroid, @@ -180,7 +194,18 @@ impl GeneSignature { corpus, minted_at_ms: now_ms, parent: None, - }) + region: None, + }; + minted.region = region_of(&minted, &embeddings); + Ok(minted) + } + + /// Similarity of an embedding already known to be in this signature's space. + fn nearness(&self, query: &[f32]) -> f32 { + self.subspaces + .iter() + .map(|s| cosine_similarity(query, s)) + .fold(cosine_similarity(query, &self.centroid), f32::max) } /// Similarity of a query embedding to this gene, in the named space. @@ -191,14 +216,19 @@ impl GeneSignature { if embedder_id != self.embedder || query.len() != self.dim { return None; } - let mut best = cosine_similarity(query, &self.centroid); - for s in &self.subspaces { - best = best.max(cosine_similarity(query, s)); - } - Some(best) + Some(self.nearness(query)) } } +/// PURE: the region edge of `signature` over the embeddings of the corpus that minted it: +/// the [`REGION_QUANTILE`] similarity (nearest rank). `None` for an empty corpus. +fn region_of(signature: &GeneSignature, corpus: &[Vec]) -> Option { + let mut near: Vec = corpus.iter().map(|e| signature.nearness(e)).collect(); + near.sort_by(f32::total_cmp); + let rank = ((near.len().saturating_sub(1)) as f32 * REGION_QUANTILE).floor() as usize; + near.get(rank).copied() +} + /// The sidecar store: gene path → signature, persisted beside the adapter /// manifest (so a `CONTINUUM_ADAPTER_MANIFEST` override relocates both). /// Keyed by the gene's on-disk PATH string — the same identity the manifest @@ -329,6 +359,34 @@ mod tests { assert!(sig.similarity_in(embedder.id(), &near[..near.len() - 1]).is_none()); } + // what this catches: the region (the selection floor, GENE-REUSE-FORK-MINT §3d) being + // a constant in disguise. It is measured from the gene's own corpus: at least nine in + // ten of its examples are inside it, an unrelated text is outside it, and a signature + // minted before regions were filed still loads (region absent, never a guessed number). + #[tokio::test] + async fn the_region_holds_the_genes_own_examples_and_excludes_an_unrelated_need() { + let embedder: Arc = Arc::new(LexicalEmbedder::default()); + let texts: Vec = ["fold the list", "fold the list recursively", "map the list", "fold a tree"] + .iter() + .map(|s| s.to_string()) + .collect(); + let sig = GeneSignature::mint(&texts, corpus_ref(), &embedder, 0).await.expect("mint"); + let region = sig.region.expect("a minted signature files its region"); + let mut inside = 0; + for t in &texts { + let sim = sig.similarity_in(embedder.id(), &embedder.embed(t).await).expect("same space"); + inside += usize::from(sim >= region); + } + assert!(inside * 10 >= texts.len() * 9, "{inside} of {} examples inside", texts.len()); + let far = embedder.embed("quarterly tax spreadsheet").await; + assert!(sig.similarity_in(embedder.id(), &far).expect("same space") < region); + + let mut old = serde_json::to_value(&sig).expect("serialize"); + old.as_object_mut().expect("object").remove("region"); + let loaded: GeneSignature = serde_json::from_value(old).expect("pre-region signature loads"); + assert_eq!(loaded.region, None); + } + // what this catches: the sidecar's load/stamp contract — missing file is the // legitimate empty state, a stamp round-trips, and re-stamping the same path // REPLACES (a retrained gene's new signature must win, never duplicate). diff --git a/core/continuum-genome/src/genome/store.rs b/core/continuum-genome/src/genome/store.rs deleted file mode 100644 index 109abbad49..0000000000 --- a/core/continuum-genome/src/genome/store.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! `TierStore` trait — the abstraction every per-role tier -//! implementation (Fast/Warm/Bench/Cold/Frozen) implements. Per -//! GENOME-FOUNDRY-SENTINEL Part 2. -//! -//! PR-2 of working-set-manager ships the **trait surface only**. -//! Per-role implementations (`FastTierStore`, `WarmTierStore`, -//! `BenchTierStore`, etc.) are separate PRs. -//! -//! ## Why one trait, five impls -//! -//! Each role has different eviction policy (LRU-within-turn, -//! LRU-across-turns, LFU+recency, …) and different backing storage -//! (accelerator VRAM, host RAM, SSD, archive). The TRAIT names the -//! capability — read / write / evict / capacity / observe_access — -//! that the working-set-manager (PR-3) calls without caring which -//! role it's talking to. The IMPLEMENTATIONS specialize. -//! -//! This is the OpenCV-style polymorphism pattern from CLAUDE.md: one -//! interface, many implementations, AIs (or sentinel) can swap them -//! at runtime via the governor's `Vec`. - -use async_trait::async_trait; - -use super::blob::{ArtifactBlob, Provenance}; -use super::tier::{EvictionRecord, TierCapacity, TierError, TierRole}; -use super::working_set::PageHandle; -use crate::inference::page_ref::PageRef; - -/// The single trait every tier implementation satisfies. The -/// working-set-manager (PR-3) holds `Box` per -/// configured role and routes page operations through them. -/// -/// `Send + Sync` because the working-set-manager runs in a tokio -/// runtime + the trait is called from multiple persona tasks -/// concurrently. -#[async_trait] -pub trait TierStore: Send + Sync { - /// Which role this store implements. Stable for the store's - /// lifetime — the governor doesn't re-role a store at runtime; - /// it adds / removes them as policy changes. - fn role(&self) -> TierRole; - - /// Read a page from this tier. Returns the typed page handle on - /// hit, `TierError::PageNotFound` on miss. The handle's - /// `tier_role` should equal `self.role()` so the caller can - /// distinguish a miss-promoted-from-lower-tier (different role) - /// from a direct hit (same role). - async fn read(&self, page: PageRef) -> Result; - - /// Write a page to this tier. May trigger eviction if the tier - /// is at-or-near `configured_limit`. The provenance is REQUIRED — - /// per GENOME-FOUNDRY-SENTINEL Part 1, no artifact enters the - /// pool without one. A tier that can't accept the write surfaces - /// `TierError::NoEvictionCandidate` or `TierError::BackingStoreIo`. - async fn write( - &self, - page: PageRef, - blob: ArtifactBlob, - provenance: Provenance, - ) -> Result<(), TierError>; - - /// Free at least `target_free_bytes` by evicting pages according - /// to this role's eviction policy. Returns the records of every - /// page evicted so the caller (working-set-manager) can publish - /// them to the trace bus. - /// - /// Returns an empty Vec if no eviction was needed (tier already - /// had enough headroom). Returns Vec with `< target` total bytes - /// if no more eviction candidates exist (all pages pinned) — - /// caller is responsible for surfacing `NoEvictionCandidate` to - /// its caller in that case. - async fn evict(&self, target_free_bytes: usize) -> Vec; - - /// Current capacity snapshot. Cheap O(1) read — the tier tracks - /// `current_used` as writes/evicts happen. Used by the governor + - /// pressure broker to see who's near their limit. - fn capacity(&self) -> TierCapacity; - - /// Tell the tier that a page was accessed (for LRU / LFU - /// bookkeeping). Doesn't return — the tier is free to coalesce - /// or drop calls under pressure. Cheap-and-return only. - fn observe_access(&self, page: PageRef); -} - -#[cfg(test)] -mod tests { - //! Trait-shape tests: prove the trait is object-safe (can be used - //! as `Box` / `Arc`) and that a - //! minimal implementor compiles. PR-3 will add per-role impls - //! tested against the real semantics; PR-2 only proves the seam. - - use super::*; - use crate::inference::page_ref::{ArtifactId, PageKind, PageOffset}; - use std::sync::Arc; - use uuid::Uuid; - - /// Minimal in-memory tier store for trait tests. Records calls so - /// tests can assert dispatch happened. - struct InMemTier { - role: TierRole, - capacity: TierCapacity, - } - - #[async_trait] - impl TierStore for InMemTier { - fn role(&self) -> TierRole { - self.role - } - - async fn read(&self, page: PageRef) -> Result { - Ok(PageHandle { - page, - tier_role: self.role, - size_bytes: 0, - }) - } - - async fn write( - &self, - _page: PageRef, - _blob: ArtifactBlob, - _provenance: Provenance, - ) -> Result<(), TierError> { - Ok(()) - } - - async fn evict(&self, _target_free_bytes: usize) -> Vec { - Vec::new() - } - - fn capacity(&self) -> TierCapacity { - self.capacity - } - - fn observe_access(&self, _page: PageRef) {} - } - - fn sample_page() -> PageRef { - PageRef { - kind: PageKind::LoRALayer, - artifact: ArtifactId::new(Uuid::nil()), - offset: PageOffset::Whole, - } - } - - /// What this catches: TierStore is object-safe. If a future PR - /// adds a method with a generic type parameter or a non-dyn-safe - /// signature, this construction fails to compile. Object-safety - /// is load-bearing because the working-set-manager holds - /// `Box` per configured role. - #[tokio::test] - async fn tier_store_is_object_safe() { - let store: Arc = Arc::new(InMemTier { - role: TierRole::Fast, - capacity: TierCapacity { - current_used: 0, - configured_limit: 1_000_000, - }, - }); - assert_eq!(store.role(), TierRole::Fast); - let handle = store.read(sample_page()).await.unwrap(); - assert_eq!(handle.tier_role, TierRole::Fast); - } - - /// What this catches: write accepts ArtifactBlob + Provenance - /// without requiring the caller to clone or move excessively. If - /// a future PR adds an unwanted bound (e.g. `'static` on the - /// blob), this dispatch fails. - #[tokio::test] - async fn tier_store_write_round_trips_through_trait_object() { - let store: Box = Box::new(InMemTier { - role: TierRole::Cold, - capacity: TierCapacity { - current_used: 0, - configured_limit: 10_000_000, - }, - }); - let blob = ArtifactBlob::inline(ArtifactId::new(Uuid::nil()), vec![1, 2, 3]); - let prov = Provenance::minimal(blob.id, 1_700_000_000_000); - store.write(sample_page(), blob, prov).await.unwrap(); - } - - /// What this catches: evict returns Vec. If a - /// future PR changes the return shape (e.g. to a stream or single - /// record), this assertion catches it. - #[tokio::test] - async fn tier_store_evict_returns_record_vec() { - let store: Arc = Arc::new(InMemTier { - role: TierRole::Bench, - capacity: TierCapacity { - current_used: 0, - configured_limit: 100_000_000, - }, - }); - let records = store.evict(4096).await; - // InMemTier returns empty; PR-3's real impl returns the - // pages it actually evicted. The contract here is the Vec - // type, not the contents. - assert_eq!(records.len(), 0); - } -} diff --git a/core/continuum-genome/src/genome/tier.rs b/core/continuum-genome/src/genome/tier.rs index dad8296944..c2238299bf 100644 --- a/core/continuum-genome/src/genome/tier.rs +++ b/core/continuum-genome/src/genome/tier.rs @@ -1,18 +1,13 @@ -//! Tier types — `TierRole`, `EvictionPolicy`, `TierCapacity`, -//! `EvictionRecord`, `TierError`. +//! `TierRole`: where a recalled artifact lives, as the recall ranker scores it +//! (`recall_scoring::local_role_score`). Per GENOME-FOUNDRY-SENTINEL Part 2. //! -//! Discrete-GPU hardware has five distinct tiers; unified-memory -//! hardware collapses Fast+Warm into one. Subsystems address tiers by -//! role (the enum), not by ordinal position — that's what makes -//! "L1→L2 eviction on UMA" structurally impossible. -//! -//! Per GENOME-FOUNDRY-SENTINEL Part 2. +//! Gene residency on the engine (device, host RAM) is `genome::gene_residency`; the per-persona +//! working-set stack these roles once fed (local_manager, manager, store, blob, bus, working_set) +//! was never wired and is deleted (Fable, Cormac agreed on airc 2026-10-24). use serde::{Deserialize, Serialize}; use ts_rs::TS; -use crate::inference::page_ref::PageRef; - /// The five named tier roles. Discrete-GPU configurations populate /// all five; UMA configurations omit `Warm` (Fast and Warm would /// share the same physical bytes there — an `Fast`→`Warm` eviction @@ -45,629 +40,3 @@ pub enum TierRole { Cold, Frozen, } - -impl TierRole { - /// Whether this role is present on UMA-class hardware. `Warm` is - /// structurally omitted on UMA (Fast and Warm would share the same - /// physical bytes). The governor uses this to build a - /// `Vec` of the right shape at boot. - pub fn is_present_on_uma(&self) -> bool { - !matches!(self, TierRole::Warm) - } -} - -/// Per-tier eviction policy. The variants are dimensioned by the -/// per-role table in GENOME-FOUNDRY-SENTINEL Part 2: -/// -/// | Role | Policy | When eviction fires | -/// |------|--------|---------------------| -/// | Fast | `LruWithinTurn` | sub-step needs a page not resident | -/// | Warm | `LruAcrossTurns { window }` (discrete-GPU only) | Fast spill | -/// | Bench | `LfuPlusRecency` | Warm spill (discrete) / Fast spill (UMA) | -/// | Cold | `DemandAlignedWithRefinedPreference` | Bench spill | -/// | Frozen | `AppendOnlyGcOnSleep` | never in hot path | -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(tag = "kind", rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/EvictionPolicy.ts" -)] -pub enum EvictionPolicy { - /// LRU within a single turn. Resets between turns. - LruWithinTurn, - /// LRU across a rolling window of N turns. Governor sets N - /// (default 100 per the spec). - LruAcrossTurns { - #[serde(rename = "windowTurns")] - #[ts(rename = "windowTurns", type = "number")] - window_turns: u32, - }, - /// LFU + recency tiebreak. Broad-use pages get a retention bonus - /// the substrate computes from cross-persona access frequency. - LfuPlusRecency, - /// Demand-aligned with a preference for sentinel-refined pages - /// over imported pages of equal demand. Imported pages can be - /// re-pulled from the genome catalog; refined pages embody work - /// that took compute to produce. - DemandAlignedWithRefinedPreference, - /// Append-only with provenance preserved. GC only during sleep - /// / opportunistic idle. Frozen tier — never in hot path. - AppendOnlyGcOnSleep, -} - -impl EvictionPolicy { - /// The canonical policy for a given tier role (what the spec's - /// per-role table prescribes). Governor implementations are free - /// to override per-policy but this is the default the type system - /// can guarantee. `Warm` has no canonical policy on UMA (it isn't - /// configured there at all); calling `canonical_for(TierRole::Warm)` - /// returns the discrete-GPU default. - pub fn canonical_for(role: TierRole) -> Self { - match role { - TierRole::Fast => EvictionPolicy::LruWithinTurn, - TierRole::Warm => EvictionPolicy::LruAcrossTurns { window_turns: 100 }, - TierRole::Bench => EvictionPolicy::LfuPlusRecency, - TierRole::Cold => EvictionPolicy::DemandAlignedWithRefinedPreference, - TierRole::Frozen => EvictionPolicy::AppendOnlyGcOnSleep, - } - } -} - -/// Current vs configured byte capacity of a tier. The governor sets -/// `configured_limit` from the policy file (Part 11). The tier itself -/// reports `current_used` from its backing store. The delta is the -/// available headroom; when `current_used` approaches `configured_limit`, -/// the tier triggers eviction. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/TierCapacity.ts" -)] -pub struct TierCapacity { - /// Bytes currently in use by this tier's backing store. - #[ts(type = "number")] - pub current_used: u64, - /// Bytes the tier is configured to hold (policy limit, NOT a - /// hardware ceiling). The governor enforces; the tier respects. - #[ts(type = "number")] - pub configured_limit: u64, -} - -impl TierCapacity { - /// Bytes available before eviction must run. `0` means the tier - /// is at-or-over its policy limit and any new write triggers an - /// eviction first. - pub fn available_bytes(&self) -> u64 { - self.configured_limit.saturating_sub(self.current_used) - } - - /// Fraction-of-limit currently used. `1.0` = at limit; `> 1.0` = - /// over (the tier ran past its budget — usually transient between - /// the trigger and the eviction completing). Returns `0.0` if - /// `configured_limit == 0` to avoid divide-by-zero. - pub fn utilization(&self) -> f64 { - if self.configured_limit == 0 { - return 0.0; - } - self.current_used as f64 / self.configured_limit as f64 - } -} - -/// Typed record emitted to the trace bus every time a page is evicted -/// from some tier. The reason carries the policy that fired (LRU, -/// LFU, etc.). Recurring evictions of the same page across turns are -/// the signal sentinel uses to upgrade the page's tier policy. -/// -/// Per GENOME-FOUNDRY-SENTINEL Part 2: "every evicted page emits an -/// EvictionRecord to the trace bus." PR-3 wires this through my just- -/// shipped artifact dispatch (#1339 + #1343); PR-1 ships the shape. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/EvictionRecord.ts" -)] -pub struct EvictionRecord { - /// The page that was evicted. - pub page: PageRef, - /// Which tier evicted it. - pub from_role: TierRole, - /// Where the page went (Some) or whether it was dropped entirely - /// (None — only valid for Cold/Frozen during GC). - #[ts(optional)] - pub to_role: Option, - /// The policy that fired this eviction. Lets the trace bus - /// reconstruct *why* without re-running the policy. - pub policy_fired: EvictionPolicy, - /// Time spent on the eviction itself (selection + tier-write + - /// metadata update). Doesn't include the time the calling - /// page_in/page_out spent blocked on it — that's a separate - /// signal on the caller side. - #[ts(type = "number")] - pub elapsed_us: u64, -} - -/// Errors a tier's read/write operations can surface. PR-1 ships -/// the shape; PR-2's `TierStore` trait returns it. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(tag = "kind", rename_all = "camelCase")] -#[ts(export, export_to = "../../../protocol/typescript/genome/TierError.ts")] -pub enum TierError { - /// The requested page isn't in this tier and a higher tier - /// couldn't be paged in (chain exhausted). - PageNotFound { page: PageRef }, - /// Tier write would exceed configured_limit and no eviction - /// candidate is available (every page is pinned, etc.). - NoEvictionCandidate { - from_role: TierRole, - #[ts(type = "number")] - bytes_needed: u64, - }, - /// Backing-store I/O error. The inner message is the OS-level - /// reason; not structured because backends differ. - BackingStoreIo { reason: String }, - /// Caller asked for a tier role this hardware doesn't have - /// (e.g. `Warm` on UMA). Defensive; type system should already - /// have caught it at registration but the runtime still asserts. - RoleNotConfigured { role: TierRole }, -} - -impl std::fmt::Display for TierError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - TierError::PageNotFound { page } => write!(f, "tier: page not found: {page:?}"), - TierError::NoEvictionCandidate { - from_role, - bytes_needed, - } => write!( - f, - "tier {from_role:?}: no eviction candidate for {bytes_needed} bytes" - ), - TierError::BackingStoreIo { reason } => write!(f, "tier I/O: {reason}"), - TierError::RoleNotConfigured { role } => { - write!(f, "tier role {role:?} not configured on this hardware") - } - } - } -} - -impl std::error::Error for TierError {} - -/// One typed entry in the governor's `Vec`. Per -/// GENOME-FOUNDRY-SENTINEL Part 2: the cache hierarchy is a SEQUENCE -/// of tier roles parameterized by hardware class, NOT a fixed L1..L5 -/// enum. Discrete-GPU hardware emits five entries (Fast/Warm/Bench/ -/// Cold/Frozen). UMA hardware emits four — `Warm` is structurally -/// omitted because Fast and Warm would share the same physical bytes -/// and an `Fast→Warm` eviction would be a no-op. -/// -/// Subsystems address tiers by `role`, never by index. That's what -/// makes the "L1→L2 eviction on UMA" failure mode structurally -/// impossible: there is no `Warm` entry in the vec on UMA, so no -/// caller can name one. -/// -/// `backing` is intentionally absent at this slice. The realization -/// ladder is: -/// 1. (THIS SLICE) shape + structural-absence invariant — every -/// subsystem can address tiers by role, the type system -/// guarantees UMA-omits-Warm. -/// 2. NEXT SLICE: TierStore handle threading — `backing` becomes -/// `Arc` populated by the genome subsystem at boot. -/// 3. LATER: policy_file TOML loading writes real `configured_limit` -/// bytes from the per-hardware-anchor numbers in the doc -/// (M2 Air: Fast 2 LoRA layers + 2k KV tokens; 5090: Fast 8 + 16k; -/// etc.). Today's `tier_configs_for` returns `configured_limit = 0` -/// across the board — the shape is right, the numbers come later. -/// -/// The compression principle: a TierConfig is the singular substrate -/// description of "one tier on this hardware." Capacity + eviction -/// policy + (eventually) backing store live together because they're -/// the same logical decision. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/TierConfig.ts" -)] -pub struct TierConfig { - /// Which named role this entry fills. Address by this, never by - /// vec index. - pub role: TierRole, - /// Current/configured byte capacity. Today's - /// `tier_configs_for` returns zeros — TOML loading fills real - /// numbers in a follow-up slice. Subsystems should never assume - /// `configured_limit > 0` until the governor has loaded a policy. - pub capacity: TierCapacity, - /// Per-role canonical eviction policy from - /// `EvictionPolicy::canonical_for(role)`. A future slice may let - /// the policy file override this per-installation; today the - /// canonical mapping is the single source. - pub eviction: EvictionPolicy, -} - -/// Build the governor's `Vec` for the given hardware -/// class. The vec length is structurally hardware-determined: -/// -/// - **UMA** (`HardwareClass.uma == true`) → 4 entries: -/// `[Fast, Bench, Cold, Frozen]`. `Warm` is OMITTED because Fast -/// and Warm would share the same physical bytes — an `Fast→Warm` -/// eviction would be a no-op. -/// - **Discrete-GPU** (`uma == false`) → 5 entries: -/// `[Fast, Warm, Bench, Cold, Frozen]`. Full ladder. `Warm` is the -/// PCIe-attached host RAM tier the GPU reaches via copy. -/// -/// Order is invariant: `Fast` is always index 0, `Frozen` always last. -/// Subsystems that page across tiers walk in role order. The realization -/// pins this order with `tier_configs_for_uma_has_no_warm` / -/// `tier_configs_for_discrete_has_warm`. -/// -/// Today's emission has all `capacity.configured_limit = 0`. The shape -/// is correct; the numbers are a future slice via policy_file TOML -/// (per the per-hardware-anchor table in GENOME-FOUNDRY-SENTINEL.md -/// Part 2 "Hardware Anchors"). A caller that depends on real capacity -/// values today is using `tier_configs_for` before the policy has -/// loaded — that's a startup ordering bug to surface at the caller, -/// not papered over here. -/// -/// Eviction policy comes from the canonical per-role table — -/// `EvictionPolicy::canonical_for(role)`. The doc's per-role table: -/// Fast=LruWithinTurn, Warm=LruAcrossTurns{100}, Bench=LfuPlusRecency, -/// Cold=DemandAlignedWithRefinedPreference, Frozen=AppendOnlyGcOnSleep. -pub fn tier_configs_for(hw: &crate::governor::types::HardwareClass) -> Vec { - // UMA test: `HardwareClass` doesn't yet expose `uma: bool` - // explicitly — the implicit invariant from `classify_hardware` - // (governor/types.rs:372) is `vram_mb == 0` ⇒ UMA, since UMA - // targets report zero VRAM by spec (the governor draws inference - // budget from `system_ram_mb`). Discrete GPUs always report a - // non-zero VRAM. Promoting `uma` to an explicit `HardwareClass` - // field is a future ergonomics PR; today this implicit contract - // is what the rest of the substrate relies on. - let is_uma = hw.vram_mb == 0; - - // The order is invariant — Fast first, Frozen last. Warm sits - // between Fast and Bench when present. - let roles: &[TierRole] = if is_uma { - // UMA: four roles. Warm omitted by design (not "configured to - // zero" — structurally absent). - &[ - TierRole::Fast, - TierRole::Bench, - TierRole::Cold, - TierRole::Frozen, - ] - } else { - // Discrete-GPU: full five-role ladder. - &[ - TierRole::Fast, - TierRole::Warm, - TierRole::Bench, - TierRole::Cold, - TierRole::Frozen, - ] - }; - - roles - .iter() - .copied() - .map(|role| TierConfig { - role, - capacity: TierCapacity { - current_used: 0, - configured_limit: 0, - }, - eviction: EvictionPolicy::canonical_for(role), - }) - .collect() -} - -#[cfg(test)] -mod tests { - //! Pin the invariants the type system + serde encoding guarantee - //! for PR-1's tier surface. Each test corresponds to a "what if a - //! downstream PR / consumer subtly changes this" failure mode. - use super::*; - - /// What this catches: TierRole's wire form is lowercase strings - /// ("fast", "warm", ...) — TypeScript + downstream tooling will - /// parse these strings. If a future PR renames a variant or - /// changes the serde casing, the wire breaks. - #[test] - fn tier_role_serializes_lowercase() { - assert_eq!(serde_json::to_string(&TierRole::Fast).unwrap(), "\"fast\""); - assert_eq!(serde_json::to_string(&TierRole::Warm).unwrap(), "\"warm\""); - assert_eq!( - serde_json::to_string(&TierRole::Bench).unwrap(), - "\"bench\"" - ); - assert_eq!(serde_json::to_string(&TierRole::Cold).unwrap(), "\"cold\""); - assert_eq!( - serde_json::to_string(&TierRole::Frozen).unwrap(), - "\"frozen\"" - ); - } - - /// What this catches: `Warm` is the only role omitted on UMA. - /// If a future PR adds another UMA-omitted role (e.g. an embedded - /// target dropping Bench), it should be a deliberate flip of this - /// test — not a silent change that breaks UMA governor builds. - #[test] - fn only_warm_is_omitted_on_uma() { - assert!(TierRole::Fast.is_present_on_uma()); - assert!(!TierRole::Warm.is_present_on_uma()); - assert!(TierRole::Bench.is_present_on_uma()); - assert!(TierRole::Cold.is_present_on_uma()); - assert!(TierRole::Frozen.is_present_on_uma()); - } - - /// What this catches: EvictionPolicy serializes with the - /// per-variant `kind` tag (camelCase) plus camelCase field names - /// (e.g. `windowTurns`). Wire stability — TS consumers narrow by - /// `kind`. Field name `windowTurns` deliberately matches the - /// camelCase TS convention. - #[test] - fn eviction_policy_serializes_with_kind_tag() { - let p = EvictionPolicy::LruAcrossTurns { window_turns: 100 }; - let json = serde_json::to_string(&p).unwrap(); - assert!(json.contains("\"kind\":\"lruAcrossTurns\""), "got {json}"); - assert!(json.contains("\"windowTurns\":100"), "got {json}"); - - assert!(serde_json::to_string(&EvictionPolicy::LruWithinTurn) - .unwrap() - .contains("\"kind\":\"lruWithinTurn\"")); - assert!(serde_json::to_string(&EvictionPolicy::LfuPlusRecency) - .unwrap() - .contains("\"kind\":\"lfuPlusRecency\"")); - } - - /// What this catches: each role gets the canonical policy from - /// GENOME-FOUNDRY-SENTINEL Part 2's per-role table. If a future - /// PR changes a default (e.g. flips Bench from LFU+recency to - /// LRU), this test flags it — that's a substrate policy change - /// that needs deliberate review, not a refactor accident. - #[test] - fn canonical_eviction_policy_matches_spec_table() { - assert_eq!( - EvictionPolicy::canonical_for(TierRole::Fast), - EvictionPolicy::LruWithinTurn - ); - assert_eq!( - EvictionPolicy::canonical_for(TierRole::Warm), - EvictionPolicy::LruAcrossTurns { window_turns: 100 } - ); - assert_eq!( - EvictionPolicy::canonical_for(TierRole::Bench), - EvictionPolicy::LfuPlusRecency - ); - assert_eq!( - EvictionPolicy::canonical_for(TierRole::Cold), - EvictionPolicy::DemandAlignedWithRefinedPreference - ); - assert_eq!( - EvictionPolicy::canonical_for(TierRole::Frozen), - EvictionPolicy::AppendOnlyGcOnSleep - ); - } - - /// What this catches: TierCapacity's available_bytes saturates - /// to zero on overage instead of underflowing into a giant - /// "available" number that would defeat eviction triggers. - #[test] - fn tier_capacity_available_saturates_on_overage() { - let over = TierCapacity { - current_used: 1_000_000, - configured_limit: 500_000, - }; - assert_eq!(over.available_bytes(), 0); - - let under = TierCapacity { - current_used: 100, - configured_limit: 500, - }; - assert_eq!(under.available_bytes(), 400); - } - - /// What this catches: utilization handles configured_limit == 0 - /// (a tier that hasn't been configured yet) without divide-by-zero. - /// Real configs always have a non-zero limit, but during boot the - /// governor briefly sees zero — must not panic. - #[test] - fn tier_capacity_utilization_handles_zero_limit() { - let zero = TierCapacity { - current_used: 0, - configured_limit: 0, - }; - assert_eq!(zero.utilization(), 0.0); - } - - /// What this catches: TierError implements Display + Error so it - /// works in `?` chains. Without this, callers would need manual - /// `.map_err()` boilerplate everywhere. - #[test] - fn tier_error_implements_error_trait() { - let e = TierError::NoEvictionCandidate { - from_role: TierRole::Fast, - bytes_needed: 4096, - }; - let _: &dyn std::error::Error = &e; - let display = format!("{e}"); - assert!(display.contains("Fast")); - assert!(display.contains("4096")); - } - - /// What this catches: TierError variants serialize with the - /// `kind` tag — TS consumers will narrow by it. Same wire - /// stability check as EvictionPolicy. - #[test] - fn tier_error_serializes_with_kind_tag() { - let e = TierError::RoleNotConfigured { - role: TierRole::Warm, - }; - let json = serde_json::to_string(&e).unwrap(); - assert!( - json.contains("\"kind\":\"roleNotConfigured\""), - "got {json}" - ); - assert!(json.contains("\"role\":\"warm\""), "got {json}"); - } - - // ── tier_configs_for: realization-priority #3 first slice ── - // - // GENOME-FOUNDRY-SENTINEL.md Part 2 Hardware Anchors: UMA → 4 - // tier roles (no Warm), discrete-GPU → 5 (full ladder). The - // structural-absence invariant — "an Fast→Warm eviction on UMA - // is structurally impossible because there is no Warm tier" — is - // load-bearing. These tests pin it. - - use crate::governor::types::{HardwareClass, PowerSource, TargetSilicon, ThermalClass}; - - /// Minimal fixture for UMA hardware. The realization keys on - /// `vram_mb == 0` per `classify_hardware`'s implicit contract; - /// other fields are populated with sensible defaults so the - /// fixture survives a `HardwareClass` shape extension. - fn uma_fixture() -> HardwareClass { - HardwareClass { - silicon: TargetSilicon::AppleM, - silicon_model: "M2".to_string(), - vram_mb: 0, - system_ram_mb: 16 * 1024, - power_source: PowerSource::Plugged, - thermal_class: ThermalClass::ThinAndLight, - battery_pct: Some(100), - thermal_headroom_pct: Some(80), - } - } - - /// Discrete-GPU fixture. `vram_mb > 0` is the implicit signal - /// classify_hardware uses to mark a target as non-UMA. - fn discrete_fixture() -> HardwareClass { - HardwareClass { - silicon: TargetSilicon::NvidiaCuda, - silicon_model: "RTX 5090".to_string(), - vram_mb: 32 * 1024, - system_ram_mb: 64 * 1024, - power_source: PowerSource::Plugged, - thermal_class: ThermalClass::Workstation, - battery_pct: None, - thermal_headroom_pct: Some(90), - } - } - - /// THE load-bearing invariant. UMA hardware MUST emit 4 entries - /// with no Warm — the doc's "Fast→Warm eviction on UMA is - /// structurally impossible" line is the entire point. If this - /// regresses, the substrate has lost its hardware-class - /// portability and Vision Pro / iOS / M-series MacBooks will - /// page through a no-op tier. - #[test] - fn tier_configs_for_uma_has_no_warm() { - let cfgs = tier_configs_for(&uma_fixture()); - assert_eq!( - cfgs.len(), - 4, - "UMA must emit exactly 4 tiers (Fast/Bench/Cold/Frozen), got {cfgs:?}" - ); - assert!( - !cfgs.iter().any(|c| c.role == TierRole::Warm), - "UMA must structurally omit Warm — got {cfgs:?}" - ); - // Order pin: Fast first, Frozen last. - assert_eq!(cfgs.first().map(|c| c.role), Some(TierRole::Fast)); - assert_eq!(cfgs.last().map(|c| c.role), Some(TierRole::Frozen)); - } - - /// Discrete-GPU MUST emit all 5 tiers including Warm. The 5090 - /// + Vulkan + CUDA + AMD ROCm all share this shape — Warm is the - /// PCIe-attached host RAM the accelerator reaches via copy. - #[test] - fn tier_configs_for_discrete_has_warm() { - let cfgs = tier_configs_for(&discrete_fixture()); - assert_eq!( - cfgs.len(), - 5, - "discrete-GPU must emit exactly 5 tiers, got {cfgs:?}" - ); - let roles: Vec = cfgs.iter().map(|c| c.role).collect(); - assert_eq!( - roles, - vec![ - TierRole::Fast, - TierRole::Warm, - TierRole::Bench, - TierRole::Cold, - TierRole::Frozen, - ], - "discrete tier order must be Fast/Warm/Bench/Cold/Frozen" - ); - } - - /// Every emitted TierConfig MUST carry the canonical eviction - /// policy from `EvictionPolicy::canonical_for(role)`. A future - /// PR may let policy_file TOML override the policy per- - /// installation, but the substrate's default-from-role mapping - /// is the single source for this slice. If it regresses, a - /// caller that did `EvictionPolicy::canonical_for(c.role)` to - /// double-check would suddenly disagree with the emitted config. - #[test] - fn tier_configs_for_uses_canonical_eviction_policy_per_role() { - for cfgs in [ - tier_configs_for(&uma_fixture()), - tier_configs_for(&discrete_fixture()), - ] { - for cfg in &cfgs { - assert_eq!( - cfg.eviction, - EvictionPolicy::canonical_for(cfg.role), - "tier {:?} must carry canonical eviction policy, got {:?}", - cfg.role, - cfg.eviction - ); - } - } - } - - /// This slice ships SHAPE, not numbers. The configured_limit MUST - /// be 0 across the board — real values come from policy_file - /// TOML loading in a follow-up slice. A regression here (a - /// well-meaning PR baking in default capacity numbers) would - /// silently establish "wrong" defaults that subsystems start - /// believing before the policy loader has run. - #[test] - fn tier_configs_for_emits_zero_capacity_until_policy_file_loads() { - for cfgs in [ - tier_configs_for(&uma_fixture()), - tier_configs_for(&discrete_fixture()), - ] { - for cfg in &cfgs { - assert_eq!( - cfg.capacity.current_used, 0, - "shape-only slice: current_used must be 0, got {cfg:?}" - ); - assert_eq!( - cfg.capacity.configured_limit, 0, - "shape-only slice: configured_limit must be 0 \ - (policy_file TOML fills this in a follow-up), got {cfg:?}" - ); - } - } - } - - /// The substrate doctrine: subsystems address tiers by role, not - /// by ordinal. This test exercises that — given an arbitrary - /// hardware class, find the Fast tier by role lookup. The fact - /// that this works the SAME WAY on UMA and discrete (despite - /// different vec lengths) is the architectural point. - #[test] - fn tier_configs_for_addressable_by_role_uniformly_across_hardware() { - for hw in [uma_fixture(), discrete_fixture()] { - let cfgs = tier_configs_for(&hw); - let fast = cfgs.iter().find(|c| c.role == TierRole::Fast); - assert!(fast.is_some(), "Fast must exist on every hardware class"); - let frozen = cfgs.iter().find(|c| c.role == TierRole::Frozen); - assert!( - frozen.is_some(), - "Frozen must exist on every hardware class" - ); - } - } -} diff --git a/core/continuum-genome/src/genome/working_set.rs b/core/continuum-genome/src/genome/working_set.rs deleted file mode 100644 index c8fed1a2f6..0000000000 --- a/core/continuum-genome/src/genome/working_set.rs +++ /dev/null @@ -1,421 +0,0 @@ -//! Working set types — `ResidentPage`, `WorkingSet`, `WorkingSetCapacity`, -//! `PageFault`, `AccessDenied` and `PageHandle`. The page addresses they hold -//! (`PageRef`, `PageKind`, `PageOffset`, `ArtifactId`) are the engine's -//! (`inference::page_ref`): the serving pager and the expert reconciler name pages too. -//! -//! Per GENOME-FOUNDRY-SENTINEL Parts 3 (paging) and 4 (compartments). -//! -//! ## ID type policy -//! -//! The per-persona identifier is `crate::identity::PeerId` (the canonical airc -//! actor id, `airc_core::PeerId`); the artifact identifier is the engine's -//! content-addressed `ArtifactId`. Two typed wrappers, so the two cannot swap. - -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use ts_rs::TS; - -use super::tier::{EvictionRecord, TierRole}; -use crate::identity::PeerId; -use crate::inference::page_ref::PageRef; - -/// Opaque handle returned by `page_in`. Carries enough context for the -/// caller to use the page without exposing the tier-internal storage. -/// PR-1 ships the wire shape; PR-2 (trait + impl) gives the type -/// behaviors. The `tier_role` field lets the caller decide whether to -/// pin the handle (Fast / Warm) or stream-read it (Cold / Frozen). -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/PageHandle.ts" -)] -pub struct PageHandle { - pub page: PageRef, - pub tier_role: TierRole, - /// Byte size of the page as resident in `tier_role`. For Cold / - /// Frozen this is the size at-rest; for Fast / Warm it's the - /// size in accelerator-addressable memory. - #[ts(type = "number")] - pub size_bytes: u64, -} - -/// A page currently in some persona's working set. Tracks the -/// per-turn metadata the eviction policy needs (last_access, -/// access_count_window) and the pinning flag the composition layer -/// sets to prevent mid-turn evictions of in-use pages. -/// -/// `last_access_ms` is `u64` (unix-ms) instead of `std::time::Instant` -/// because (a) ts-rs needs a wire-stable representation and (b) the -/// trace bus can replay records across processes where `Instant` is -/// meaningless. Sub-millisecond timing for hot-path decisions stays -/// in caller-side `Instant`s. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/ResidentPage.ts" -)] -pub struct ResidentPage { - pub page: PageRef, - pub role: TierRole, - #[ts(type = "number")] - pub last_access_ms: u64, - #[ts(type = "number")] - pub access_count_window: u32, - /// When true the eviction policy must skip this page until the - /// composition layer unpins it. Composition-pinned pages cannot - /// evict mid-turn. - pub pinned: bool, -} - -/// Per-persona working-set budget the governor publishes. Bytes -/// (not page counts) because pages vary in size by kind. The governor -/// re-publishes when policy changes (hardware probe shifts class, -/// pressure event drops the cap, etc.). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/WorkingSetCapacity.ts" -)] -pub struct WorkingSetCapacity { - /// Maximum bytes the persona's Fast tier is allowed to hold. - #[ts(type = "number")] - pub fast_bytes: u64, - /// Maximum bytes in Warm. Set to 0 on UMA hardware (where Warm - /// is structurally absent) — code that addresses Warm on UMA - /// hits `TierError::RoleNotConfigured`. - #[ts(type = "number")] - pub warm_bytes: u64, - /// Maximum bytes pinned per-turn (composition lock). Smaller - /// than fast_bytes because pinning starves the eviction policy; - /// the governor caps to prevent runaway pinning. - #[ts(type = "number")] - pub max_pinned_bytes: u64, -} - -/// A persona's currently-resident pages plus its policy budget. -/// PR-1 ships the data shape with no traits / no impl — PR-2 adds -/// the `WorkingSetManager` trait that produces and consumes these. -/// -/// `pages` is keyed by `PageRef` because that's the lookup the hot -/// path needs (composition asks "is this page resident?"). HashMap -/// instead of BTreeMap because access is by exact match, not range. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/WorkingSet.ts" -)] -pub struct WorkingSet { - #[ts(type = "string")] - pub persona: PeerId, - /// All resident pages for this persona, keyed by a stringified - /// `PageRef`. On the wire this serializes as a JSON object with - /// string keys (serde's HashMap → object behavior). The TS side - /// sees a record keyed by string with `ResidentPage` values. - pub pages: HashMap, - pub capacity: WorkingSetCapacity, -} - -impl WorkingSet { - /// Fresh working set for a persona with the given capacity. No - /// pages resident yet. - pub fn new(persona: PeerId, capacity: WorkingSetCapacity) -> Self { - Self { - persona, - pages: HashMap::new(), - capacity, - } - } - - /// Sum of `last_access_ms` invariant: every resident page's - /// `role` is consistent with the persona's capacity (a page - /// claiming role Warm must have warm_bytes > 0). PR-1's invariant - /// check; PR-2's trait will enforce on insertion. - pub fn invariants_hold(&self) -> bool { - for (key, page) in &self.pages { - // PageRef key serialization matches the stored page. - let expected_key = serde_json::to_string(&page.page).unwrap_or_default(); - if key != &expected_key { - return false; - } - // A Warm-role page on a working set with zero warm_bytes - // is a mis-configuration the governor should never allow. - if page.role == TierRole::Warm && self.capacity.warm_bytes == 0 { - return false; - } - } - true - } -} - -/// Typed event emitted when a persona's composition needs a page that -/// isn't already in its working set. Sentinel observes these to detect -/// patterns: a persona that page-faults on the same page across many -/// turns is a signal to either pre-fetch it or pin it higher. -/// -/// `from_role: None` means "true cold miss" — the page does not exist -/// in any tier yet (typically a fresh KV-cache entry or a never-loaded -/// MoE expert). `from_role: Some(role)` means "tier promotion" — the -/// page existed in `role` and got moved up. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts(export, export_to = "../../../protocol/typescript/genome/PageFault.ts")] -pub struct PageFault { - pub page: PageRef, - /// Where the page was before the fault. `None` for true cold - /// miss (page didn't exist yet). - #[ts(optional)] - pub from_role: Option, - /// Where the page lives after the fault is serviced. - pub to_role: TierRole, - #[ts(type = "string")] - pub persona: PeerId, - /// Time spent servicing the fault (tier lookup + transfer + - /// eviction-if-any). Drives sentinel's "is this page worth - /// pre-fetching" calculus. - #[ts(type = "number")] - pub elapsed_us: u64, - /// If servicing the fault required evicting another page, the - /// record of that eviction. Lets sentinel correlate cause + - /// effect across the trace bus in one record instead of joining - /// two separate event streams. - #[ts(optional)] - pub eviction_cost: Option, -} - -/// Typed refusal from the MMU-style permission check. Per -/// GENOME-FOUNDRY-SENTINEL Part 4: "AccessDenied is loud. Audit log -/// captures it. This is how the substrate makes per-persona privacy -/// structural rather than policy." -/// -/// PR-1 ships the wire shape. PR-2 / PR-3 add the -/// `WorkingSetManager::audit_access` enforcement that produces it, -/// and audit-recorder (#1344, codex's PR) subscribes to it as one of -/// its `AccessDenied` audit-log inputs. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/genome/AccessDenied.ts" -)] -pub struct AccessDenied { - /// Which persona attempted the access. - #[ts(type = "string")] - pub actor: PeerId, - /// Which page was attempted. - pub page: PageRef, - /// Which persona OWNS that page (whose private region was it - /// reaching into). `None` means "no owner — the region is - /// substrate-controlled (e.g. foundry-imported)" and the denial - /// is for a different reason (license, policy, etc.). - #[ts(optional)] - #[ts(type = "string")] - pub owner: Option, - /// Human-readable reason. Per Joel's "never swallow errors" rule: - /// loud, specific, debuggable. - pub reason: String, -} - -impl std::fmt::Display for AccessDenied { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.owner { - Some(owner) => write!( - f, - "access denied: persona {} attempted to read page owned by {} — {}", - self.actor.as_uuid(), - owner.as_uuid(), - self.reason - ), - None => write!( - f, - "access denied: persona {} — {}", - self.actor.as_uuid(), - self.reason - ), - } - } -} - -impl std::error::Error for AccessDenied {} - -#[cfg(test)] -mod tests { - //! Pin the type contracts PR-1 freezes. Each test corresponds to a - //! "what if a downstream PR changes this" failure mode. - use super::*; - use crate::inference::page_ref::{ArtifactId, PageKind, PageOffset}; - use uuid::Uuid; - use serde_json::json; - - fn sample_persona() -> PeerId { - PeerId(Uuid::nil()) - } - - fn sample_artifact() -> ArtifactId { - ArtifactId(Uuid::nil()) - } - - fn sample_page() -> PageRef { - PageRef { - kind: PageKind::LoRALayer, - artifact: sample_artifact(), - offset: PageOffset::Whole, - } - } - - /// What this catches: a fresh working set has zero pages and the - /// invariant check passes. Baseline — if this regresses, the - /// constructor or invariant logic broke. - #[test] - fn fresh_working_set_is_empty_and_valid() { - let ws = WorkingSet::new( - sample_persona(), - WorkingSetCapacity { - fast_bytes: 1_000_000, - warm_bytes: 0, - max_pinned_bytes: 500_000, - }, - ); - assert!(ws.pages.is_empty()); - assert_eq!(ws.persona, sample_persona()); - assert!(ws.invariants_hold()); - } - - /// What this catches: a working set with a Warm-role page on UMA - /// capacity (warm_bytes == 0) fails the invariant check. This is - /// the "structural impossibility of Fast→Warm eviction on UMA" - /// guarantee at the data layer — PR-2's trait will enforce on - /// insertion; PR-1 pins that the invariant function catches it - /// if a future PR ever lets a Warm page slip through. - #[test] - fn working_set_invariant_rejects_warm_page_on_uma_capacity() { - let mut ws = WorkingSet::new( - sample_persona(), - WorkingSetCapacity { - fast_bytes: 1_000_000, - warm_bytes: 0, // UMA shape - max_pinned_bytes: 500_000, - }, - ); - let page = sample_page(); - let key = serde_json::to_string(&page).unwrap(); - ws.pages.insert( - key, - ResidentPage { - page, - role: TierRole::Warm, - last_access_ms: 0, - access_count_window: 0, - pinned: false, - }, - ); - assert!( - !ws.invariants_hold(), - "Warm page on UMA (warm_bytes=0) must violate invariant" - ); - } - - /// What this catches: PageFault serializes from_role as optional — - /// `None` (true cold miss) becomes a missing field on the wire, not - /// `null`. Lets the TS consumer narrow with `if (fault.fromRole)`. - #[test] - fn page_fault_serializes_from_role_as_optional() { - let cold_miss = PageFault { - page: sample_page(), - from_role: None, - to_role: TierRole::Fast, - persona: sample_persona(), - elapsed_us: 1234, - eviction_cost: None, - }; - let j = serde_json::to_string(&cold_miss).unwrap(); - // ts(optional) + Option: serde omits None fields when - // skip_serializing_if is set; without it, None serializes as - // null. The current shape uses ts(optional) for the TS side - // but doesn't add skip_serializing_if, so the wire is - // `"fromRole":null`. This test pins which one we ship — if a - // future PR adds skip_serializing_if, it should be a - // deliberate flip. - assert!( - j.contains("\"fromRole\":null") || !j.contains("\"fromRole\""), - "expected fromRole to be null or omitted, got: {j}" - ); - - let tier_promo = PageFault { - page: sample_page(), - from_role: Some(TierRole::Bench), - to_role: TierRole::Fast, - persona: sample_persona(), - elapsed_us: 500, - eviction_cost: None, - }; - let j2 = serde_json::to_string(&tier_promo).unwrap(); - assert!(j2.contains("\"fromRole\":\"bench\""), "got {j2}"); - } - - /// What this catches: AccessDenied implements Display + Error so - /// audit-recorder + handlers can use it via `?` chains. The - /// Display format includes the actor + page context so a debugger - /// reading the log can act without joining tables. - #[test] - fn access_denied_implements_error_with_context() { - let denied = AccessDenied { - actor: sample_persona(), - page: sample_page(), - owner: Some(sample_persona()), - reason: "cross-persona read of private engram".to_string(), - }; - let _: &dyn std::error::Error = &denied; - let display = format!("{denied}"); - assert!(display.contains("access denied")); - assert!(display.contains("cross-persona read")); - } - - /// What this catches: round-trip integrity across the bigger - /// payloads. If a future PR changes a field name or type in - /// PageFault / EvictionRecord / WorkingSet, the round-trip fails. - #[test] - fn larger_records_round_trip_through_serde() { - let evict = EvictionRecord { - page: sample_page(), - from_role: TierRole::Fast, - to_role: Some(TierRole::Bench), - policy_fired: super::super::tier::EvictionPolicy::LruWithinTurn, - elapsed_us: 42, - }; - let j = serde_json::to_string(&evict).unwrap(); - let back: EvictionRecord = serde_json::from_str(&j).unwrap(); - assert_eq!(evict, back); - - let fault = PageFault { - page: sample_page(), - from_role: Some(TierRole::Cold), - to_role: TierRole::Fast, - persona: sample_persona(), - elapsed_us: 9876, - eviction_cost: Some(evict.clone()), - }; - let j = serde_json::to_string(&fault).unwrap(); - let back: PageFault = serde_json::from_str(&j).unwrap(); - assert_eq!(fault, back); - } - - /// What this catches: a sample shape for downstream consumers to - /// reference. If PageHandle's wire form changes, the consumers' - /// fixtures break. Pin a small concrete example here as a regression - /// check. - #[test] - fn page_handle_sample_shape() { - let handle = PageHandle { - page: sample_page(), - tier_role: TierRole::Fast, - size_bytes: 1_048_576, - }; - let j: serde_json::Value = serde_json::to_value(&handle).unwrap(); - assert_eq!(j["tierRole"], json!("fast")); - assert_eq!(j["sizeBytes"], json!(1_048_576)); - } -} diff --git a/core/continuum-mind/Cargo.toml b/core/continuum-mind/Cargo.toml index a19227ea90..a95a7b9777 100644 --- a/core/continuum-mind/Cargo.toml +++ b/core/continuum-mind/Cargo.toml @@ -77,7 +77,7 @@ default = [] metal = ["continuum-cognition/metal", "continuum-engine/metal", "continuum-live/metal", "continuum-genome/metal"] cuda = ["continuum-cognition/cuda", "continuum-kernel/cuda", "continuum-engine/cuda", "continuum-genome/cuda"] vulkan = ["continuum-cognition/vulkan", "continuum-kernel/vulkan", "continuum-engine/vulkan", "continuum-genome/vulkan"] -stress-tests = ["continuum-cognition/stress-tests", "continuum-kernel/stress-tests", "continuum-genome/stress-tests"] +stress-tests = ["continuum-cognition/stress-tests", "continuum-kernel/stress-tests"] # Test-only code (fixtures shared with core's integration tests, the heuristic adapter it # drives); production binaries never build with it. test-fixtures = ["continuum-cognition/test-fixtures", "continuum-base/test-fixtures", "continuum-kernel/test-fixtures", "continuum-engine/test-fixtures", "continuum-hands/test-fixtures", "continuum-live/test-fixtures", "continuum-perception/test-fixtures", "continuum-genome/test-fixtures", "continuum-experience/test-fixtures"] diff --git a/core/continuum-mind/src/persona/act_question.rs b/core/continuum-mind/src/persona/act_question.rs index 8cef7759aa..86d24fdc34 100644 --- a/core/continuum-mind/src/persona/act_question.rs +++ b/core/continuum-mind/src/persona/act_question.rs @@ -390,30 +390,22 @@ pub(crate) async fn ask_the_act_question( ); } let selected_credit = card_turn.as_ref().and_then(|t| t.credit.clone()); - // HER GENES RIDE HER CARD, like her hands do (integrated, not parallel: - // a gene is judged in her own work). The card this turn is credited to - // decides the genome: her promoted genes, plus an open trial's gene when - // this card drew its arm. Pinned before the turn and put back after it, - // so the genome never changes beneath a request and every receipt of - // this card names the same genes (`GenerationReceipt::genes`). + // HER GENES FOLLOW HER MIND, never her card (GENE-REUSE-FORK-MINT §3d): + // the genes whose regions this turn's focused line is inside, weighted by + // depth (`genome::composer`), and every receipt names the genes that ran + // (`GenerationReceipt::genes`). Unreadable: the genome she has. let persona_uuid = ctx.identity.peer_id.as_uuid(); - let card_uuid = held.first().map(|card| card.card_id.as_uuid()); - // Whatever ends this turn (settled, cancelled, a panic unwinding), her - // genome goes back to what she had before it: a trial gene never leaks onto - // her conversation turns (Cormac on #4474). - let mut genome_back = crate::cognition::workspace::GenomeRestore::snapshot( - std::sync::Arc::clone(&cycle), - ); - if let Some(genes) = crate::genome::gene_trial::live_genes(persona_uuid) { - continuum_base::probe!( - class = "persona.genome.card_genes", - persona = %ctx.identity.agent_name, - card = %card_uuid.map(|c| c.to_string()).unwrap_or_default(), // probe field: "" = no card - genes = genes.len() as u64, - "the genome this work turn runs with: promoted genes plus any trial gene this card drew" - ); - cycle.page_in(genes); - } + let need = crate::cognition::recall_faculty::focused_query(&burst.rendered); + if let Some(phenotype) = crate::genome::composer::compose(persona_uuid, need).await { + continuum_base::probe!( + class = "persona.genome.turn_genes", + persona = %ctx.identity.agent_name, + genes = phenotype.genes.len() as u64, + phenotype = %crate::genome::composer::render(&phenotype), + "the phenotype this turn runs with: each gene and its scale" + ); + cycle.page_in(phenotype.genes); + } let mut credit_capture = crate::persona::training_producer::TurnCreditCapture::for_turn( ctx.identity.peer_id.as_uuid(), @@ -430,13 +422,6 @@ pub(crate) async fn ask_the_act_question( credit_capture.as_mut().map(|c| c as &mut dyn crate::cognition::act_observe::TurnCredit), ) .await; - // After the card her genome is what every turn runs with (her trained - // genes, §3d); re-read so a gene that landed mid-turn is in her head next - // turn. Unreadable: the pre-turn snapshot. - if let Some(genes) = crate::genome::gene_trial::live_genes(persona_uuid) { - genome_back.restore_to(genes); - } - drop(genome_back); // The turn's work is synced to its card's branch; her hands stay where // they are, because nothing moved them (card fc9e9fd7). if let Some(hands) = work_hands { diff --git a/core/continuum-mind/src/persona/domain_classifier.rs b/core/continuum-mind/src/persona/domain_classifier.rs index 849900d9dd..4e17a5c739 100644 --- a/core/continuum-mind/src/persona/domain_classifier.rs +++ b/core/continuum-mind/src/persona/domain_classifier.rs @@ -12,7 +12,6 @@ use std::collections::HashMap; use std::time::Instant; use ts_rs::TS; -use super::genome_paging::GenomeAdapterInfo; // ============================================================================= // TYPES (ts-rs generated) @@ -269,33 +268,6 @@ impl DomainClassifier { } } - /// Rebuild domain→adapter mappings from current adapter state. - /// Call after genome sync or adapter registration. - pub fn sync_from_adapters(&mut self, adapters: &[GenomeAdapterInfo]) { - // Clear all adapter mappings first - for vocab in self.domains.values_mut() { - vocab.adapter_name = None; - } - - for adapter in adapters { - let domain = adapter.domain.to_lowercase(); - - // If domain already exists, just update the adapter mapping - if let Some(vocab) = self.domains.get_mut(&domain) { - vocab.adapter_name = Some(adapter.name.clone()); - } else { - // New domain from adapter — create vocabulary with adapter name as keyword - self.domains.insert( - domain.clone(), - DomainVocabulary { - keywords: vec![domain.clone(), adapter.name.to_lowercase()], - adapter_name: Some(adapter.name.clone()), - }, - ); - } - } - } - /// Classify text into a skill domain. /// Returns the best-matching domain with confidence and adapter info. /// @@ -537,19 +509,6 @@ pub fn score_interaction_quality( mod tests { use super::*; - fn make_adapter(name: &str, domain: &str) -> GenomeAdapterInfo { - GenomeAdapterInfo { - name: name.to_string(), - domain: domain.to_string(), - size_mb: 50.0, - priority: 0.5, - is_loaded: false, - last_used_ms: 0, - trained_model_name: None, - compaction: None, - } - } - #[test] fn test_classify_code_domain() { let classifier = DomainClassifier::new(); @@ -610,32 +569,6 @@ mod tests { assert!((result.confidence - 0.0).abs() < 0.001); } - #[test] - fn test_sync_from_adapters_maps_domains() { - let mut classifier = DomainClassifier::new(); - let adapters = vec![ - make_adapter("ts-expert", "code"), - make_adapter("chat-bot", "conversation"), - ]; - classifier.sync_from_adapters(&adapters); - - let result = classifier.classify("Fix this TypeScript import error in the API endpoint"); - assert_eq!(result.domain, "code"); - assert_eq!(result.adapter_name, Some("ts-expert".to_string())); - } - - #[test] - fn test_sync_from_adapters_creates_new_domain() { - let mut classifier = DomainClassifier::new(); - let adapters = vec![make_adapter("plumbing-expert", "plumbing")]; - classifier.sync_from_adapters(&adapters); - - // "plumbing" keyword should now be recognized - let result = classifier.classify("I need help with plumbing under the sink"); - assert_eq!(result.domain, "plumbing"); - assert_eq!(result.adapter_name, Some("plumbing-expert".to_string())); - } - #[test] fn test_register_domain_keywords() { let mut classifier = DomainClassifier::new(); @@ -660,16 +593,6 @@ mod tests { ); } - #[test] - fn test_adapter_for_domain() { - let mut classifier = DomainClassifier::new(); - assert!(classifier.adapter_for_domain("code").is_none()); - - classifier.sync_from_adapters(&[make_adapter("ts-expert", "code")]); - assert_eq!(classifier.adapter_for_domain("code"), Some("ts-expert")); - assert!(classifier.adapter_for_domain("unknown").is_none()); - } - #[test] fn test_classification_speed() { let classifier = DomainClassifier::new(); @@ -693,44 +616,6 @@ mod tests { ); } - #[test] - fn test_domain_summary() { - let mut classifier = DomainClassifier::new(); - classifier.sync_from_adapters(&[make_adapter("ts-expert", "code")]); - - let summary = classifier.domain_summary(); - let code_entry = summary.iter().find(|(d, _)| d == "code"); - assert!(code_entry.is_some()); - assert!(code_entry.unwrap().1, "Code domain should have adapter"); - - let conv_entry = summary.iter().find(|(d, _)| d == "conversation"); - assert!(conv_entry.is_some()); - assert!( - !conv_entry.unwrap().1, - "Conversation domain should NOT have adapter" - ); - } - - #[test] - fn test_resync_clears_old_mappings() { - let mut classifier = DomainClassifier::new(); - - // First sync: code has adapter - classifier.sync_from_adapters(&[make_adapter("ts-expert", "code")]); - assert_eq!(classifier.adapter_for_domain("code"), Some("ts-expert")); - - // Second sync: different adapter set, code no longer covered - classifier.sync_from_adapters(&[make_adapter("chat-bot", "conversation")]); - assert!( - classifier.adapter_for_domain("code").is_none(), - "Code adapter should be cleared after resync" - ); - assert_eq!( - classifier.adapter_for_domain("conversation"), - Some("chat-bot") - ); - } - #[test] fn export_bindings_domain_classification() { let cfg = ts_rs::Config::default(); diff --git a/core/continuum-mind/src/persona/genome_paging.rs b/core/continuum-mind/src/persona/genome_paging.rs deleted file mode 100644 index 5fbfb75010..0000000000 --- a/core/continuum-mind/src/persona/genome_paging.rs +++ /dev/null @@ -1,537 +0,0 @@ -//! Genome Paging Engine -//! -//! LRU eviction scoring, memory budget tracking, and skill activation -//! decisions in Rust. Actual GPU load/unload stays in TypeScript. -//! -//! Eviction formula: score = age_seconds / (priority * 10) -//! Critical adapters (priority > 0.9) are never evicted. - -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::sync::Arc; -use std::time::Instant; -use ts_rs::TS; - -use crate::gpu::make_entry; -use crate::gpu::memory_manager::{GpuAllocationGuard, GpuMemoryManager, GpuPriority, GpuSubsystem}; - -// ============================================================================= -// TYPES (ts-rs generated) -// ============================================================================= - -/// Per-adapter state for genome paging decisions. -/// Extended from AdapterInfo with size_mb and last_used_ms for LRU. -#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/GenomeAdapterInfo.ts" -)] -pub struct GenomeAdapterInfo { - /// Adapter name (e.g. "typescript-expertise") - pub name: String, - /// Skill domain (e.g. "code", "chat", "creative") - pub domain: String, - /// Size in MB when loaded - #[ts(type = "number")] - pub size_mb: f32, - /// LRU priority (0.0-1.0, default 0.5). >0.9 = never evict. - pub priority: f32, - /// Whether this adapter is currently loaded in GPU memory - pub is_loaded: bool, - /// Epoch ms when last used (for LRU age calculation) - #[ts(type = "number")] - pub last_used_ms: u64, - /// Trained model name for inference (if available after LoRA fine-tuning) - #[ts(optional)] - pub trained_model_name: Option, - /// Plasticity compaction metadata (present if adapter uses a compacted base model) - #[ts(optional)] - pub compaction: Option, -} - -/// Compaction metadata for plasticity-optimized adapters. -/// When present, the adapter targets a compacted base model with fewer attention heads. -#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/CompactionMetadata.ts" -)] -pub struct CompactionMetadata { - /// Fraction of parameters removed (e.g., 0.30 = 30% smaller base model) - pub parameter_reduction: f32, - /// Path to head_topology.json relative to adapter directory - pub topology_path: String, - /// Whether the compacted base model weights exist alongside the adapter - pub has_compacted_weights: bool, - /// Original base model size in MB (before compaction) - #[ts(type = "number")] - pub original_size_mb: f32, - /// Compacted base model size in MB - #[ts(type = "number")] - pub compacted_size_mb: f32, -} - -/// Full genome paging state for a single persona. -#[derive(Debug, Clone, Serialize, Deserialize, TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/GenomePagingState.ts" -)] -pub struct GenomePagingState { - /// Soft memory budget in MB - #[ts(type = "number")] - pub memory_budget_mb: f32, - /// Current memory usage in MB - #[ts(type = "number")] - pub memory_used_mb: f32, - /// Memory pressure: used/budget (0.0-1.0) - pub memory_pressure: f32, - /// Adapters currently loaded in GPU - pub active_adapters: Vec, - /// Adapters available on disk but not loaded - pub available_adapters: Vec, -} - -/// Result of a skill activation decision. -/// Tells TypeScript what to load/unload — Rust decides, TS executes. -#[derive(Debug, Clone, Serialize, Deserialize, TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/ActivateSkillResult.ts" -)] -pub struct ActivateSkillResult { - /// Whether activation is proceeding - pub activated: bool, - /// Name of the adapter being activated - pub adapter_name: String, - /// Adapters that must be unloaded first (in order) - pub evicted: Vec, - /// Adapter to load (None if already loaded / cache hit) - #[ts(optional)] - pub to_load: Option, - /// How long the decision took (microseconds) - #[ts(type = "number")] - pub decision_time_us: u64, -} - -// ============================================================================= -// DOMAIN ACTIVITY TYPES -// ============================================================================= - -/// Activity tracking for a single domain. -#[derive(Debug, Clone, Serialize, Deserialize, TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/DomainActivity.ts" -)] -pub struct DomainActivity { - /// Domain name - pub domain: String, - /// Total interaction count - #[ts(type = "number")] - pub interaction_count: u64, - /// Successful interaction count - #[ts(type = "number")] - pub success_count: u64, - /// Failed interaction count - #[ts(type = "number")] - pub failure_count: u64, - /// Epoch ms of last activity - #[ts(type = "number")] - pub last_activity_ms: u64, - /// Whether this domain has a trained adapter - pub has_adapter: bool, - /// Adapter name if one exists - #[ts(optional)] - pub adapter_name: Option, -} - -/// Coverage report: what's covered, what's missing. -#[derive(Debug, Clone, Serialize, Deserialize, TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/CoverageReport.ts" -)] -pub struct CoverageReport { - /// Domains with trained adapters - pub covered: Vec, - /// Domains with activity but no adapter - pub gaps: Vec, - /// Total interactions across all domains - #[ts(type = "number")] - pub total_interactions: u64, - /// Ratio: covered_interactions / total_interactions - pub coverage_ratio: f32, -} - -// ============================================================================= -// GENOME PAGING ENGINE -// ============================================================================= - -/// Per-persona genome paging engine. -/// Tracks adapter state, makes eviction/activation decisions, -/// and monitors domain activity for gap detection. -#[derive(Debug)] -pub struct GenomePagingEngine { - pub memory_budget_mb: f32, - pub memory_used_mb: f32, - /// Loaded adapters keyed by name - active: HashMap, - /// Available (not loaded) adapters keyed by name - available: HashMap, - /// Domain activity tracking for gap detection - domain_activity: HashMap, - /// GPU memory manager for real VRAM allocation tracking - gpu_manager: Option>, - /// RAII guards for VRAM allocations (adapter_name → guard) - allocation_guards: HashMap, -} - -/// Internal activity tracking (not exported — CoverageReport is the public API). -#[derive(Debug, Clone)] -struct DomainActivityInternal { - interaction_count: u64, - success_count: u64, - failure_count: u64, - last_activity_ms: u64, -} - -impl GenomePagingEngine { - pub fn new(memory_budget_mb: f32) -> Self { - Self { - memory_budget_mb, - memory_used_mb: 0.0, - active: HashMap::new(), - available: HashMap::new(), - domain_activity: HashMap::new(), - gpu_manager: None, - allocation_guards: HashMap::new(), - } - } - - /// Set GPU memory manager for real VRAM allocation tracking. - pub fn set_gpu_manager(&mut self, mgr: Arc) { - self.gpu_manager = Some(mgr); - } - - /// Sync full adapter state from TypeScript. - /// Replaces both active and available maps entirely. - pub fn sync_state(&mut self, adapters: Vec) { - self.active.clear(); - self.available.clear(); - self.allocation_guards.clear(); // Release all VRAM guards on resync - self.memory_used_mb = 0.0; - - for adapter in adapters { - if adapter.is_loaded { - self.memory_used_mb += adapter.size_mb; - // Re-allocate GPU guard for already-loaded adapters - if let Some(mgr) = &self.gpu_manager { - let bytes = (adapter.size_mb * 1024.0 * 1024.0) as u64; - if let Ok(guard) = - mgr.allocate(GpuSubsystem::Inference, bytes, GpuPriority::Interactive) - { - mgr.eviction_registry.register(make_entry( - &format!("genome:adapter:{}", adapter.name), - &format!("Genome {}", adapter.name), - GpuPriority::Interactive, - bytes, - )); - self.allocation_guards.insert(adapter.name.clone(), guard); - } - } - self.active.insert(adapter.name.clone(), adapter); - } else { - self.available.insert(adapter.name.clone(), adapter); - } - } - } - - /// Memory pressure: 0.0-1.0 (used/budget). - pub fn memory_pressure(&self) -> f32 { - if self.memory_budget_mb <= 0.0 { - return 0.0; - } - (self.memory_used_mb / self.memory_budget_mb).min(1.0) - } - - /// Decide what to do for a skill activation request. - /// Returns which adapters to evict and which to load. - pub fn activate_skill(&mut self, skill_name: &str, now_ms: u64) -> ActivateSkillResult { - let start = Instant::now(); - - // Cache hit: already loaded - if let Some(adapter) = self.active.get_mut(skill_name) { - adapter.last_used_ms = now_ms; - return ActivateSkillResult { - activated: true, - adapter_name: skill_name.to_string(), - evicted: vec![], - to_load: None, - decision_time_us: start.elapsed().as_micros() as u64, - }; - } - - // Not in available pool — unknown skill - let adapter = match self.available.get(skill_name) { - Some(a) => a.clone(), - None => { - return ActivateSkillResult { - activated: false, - adapter_name: skill_name.to_string(), - evicted: vec![], - to_load: None, - decision_time_us: start.elapsed().as_micros() as u64, - }; - } - }; - - // Evict until there's room - let mut evicted = vec![]; - while self.memory_used_mb + adapter.size_mb > self.memory_budget_mb { - match self.select_eviction_victim() { - Some(victim_name) => { - if let Some(victim) = self.active.remove(&victim_name) { - self.memory_used_mb -= victim.size_mb; - // Release GPU allocation guard (drops, releasing VRAM) - self.allocation_guards.remove(&victim_name); - // Unregister from eviction registry - if let Some(mgr) = &self.gpu_manager { - mgr.eviction_registry - .unregister(&format!("genome:adapter:{}", victim_name)); - } - // Move to available - let mut unloaded = victim; - unloaded.is_loaded = false; - self.available.insert(unloaded.name.clone(), unloaded); - evicted.push(victim_name); - } - } - None => break, // No evictable adapters — budget exceeded - } - } - - // Move from available to active - let mut loaded = self.available.remove(skill_name).unwrap_or(adapter); - loaded.is_loaded = true; - loaded.last_used_ms = now_ms; - self.memory_used_mb += loaded.size_mb; - - // Allocate GPU guard for newly loaded adapter - if let Some(mgr) = &self.gpu_manager { - let bytes = (loaded.size_mb * 1024.0 * 1024.0) as u64; - if let Ok(guard) = - mgr.allocate(GpuSubsystem::Inference, bytes, GpuPriority::Interactive) - { - mgr.eviction_registry.register(make_entry( - &format!("genome:adapter:{}", loaded.name), - &format!("Genome {}", loaded.name), - GpuPriority::Interactive, - bytes, - )); - self.allocation_guards.insert(loaded.name.clone(), guard); - } - } - - self.active.insert(loaded.name.clone(), loaded); - - ActivateSkillResult { - activated: true, - adapter_name: skill_name.to_string(), - evicted, - to_load: Some(skill_name.to_string()), - decision_time_us: start.elapsed().as_micros() as u64, - } - } - - /// Drive eviction until memory_pressure ≤ `target_pressure`, returning - /// total bytes freed. The lever the PressureBroker (paging::broker) calls - /// when global resource pressure crosses a tier threshold and the broker - /// decides this adapter pool should give some back. Pure addition over - /// `activate_skill`'s implicit eviction — the formula and victim selection - /// (`select_eviction_victim` → `calculate_eviction_score`) are the same; - /// this just runs the loop without an activation request driving it. - /// - /// Critical adapters (priority > 0.9) are still untouchable. If every - /// remaining adapter is critical and pressure is still above target, the - /// loop terminates and reports the bytes already freed — never panics, - /// never evicts a critical adapter, never returns a pressure higher than - /// what was actually achieved. - pub fn evict_under_pressure(&mut self, target_pressure: f32) -> u64 { - let initial_used_mb = self.memory_used_mb; - // No-op when already under target (cheap check before locking the - // active map). - if self.memory_pressure() <= target_pressure { - return 0; - } - let target_used_mb = self.memory_budget_mb * target_pressure; - loop { - if self.memory_used_mb <= target_used_mb { - break; - } - match self.select_eviction_victim() { - Some(victim_name) => { - if let Some(victim) = self.active.remove(&victim_name) { - self.memory_used_mb -= victim.size_mb; - self.allocation_guards.remove(&victim_name); - if let Some(mgr) = &self.gpu_manager { - mgr.eviction_registry - .unregister(&format!("genome:adapter:{}", victim_name)); - } - let mut unloaded = victim; - unloaded.is_loaded = false; - self.available.insert(unloaded.name.clone(), unloaded); - } - } - // No more evictable adapters — every remaining is critical. - // Stop and report what we got. Broker's tier ladder will - // decide whether to escalate elsewhere. - None => break, - } - } - let freed_mb = (initial_used_mb - self.memory_used_mb).max(0.0); - (freed_mb * 1024.0 * 1024.0) as u64 - } - - /// Select the adapter with highest eviction score (most evictable). - /// Returns None if no adapters can be evicted (all critical). - fn select_eviction_victim(&self) -> Option { - let mut best_name: Option = None; - let mut best_score: f64 = f64::NEG_INFINITY; - - for (name, adapter) in &self.active { - let score = calculate_eviction_score(adapter); - if score < f64::INFINITY && score > best_score { - best_score = score; - best_name = Some(name.clone()); - } - } - - best_name - } - - /// Record domain activity (called after every inference). - pub fn record_activity(&mut self, domain: &str, success: bool) { - let now_ms = continuum_base::time::EpochMs::now().millis(); - - let entry = - self.domain_activity - .entry(domain.to_string()) - .or_insert(DomainActivityInternal { - interaction_count: 0, - success_count: 0, - failure_count: 0, - last_activity_ms: now_ms, - }); - - entry.interaction_count += 1; - if success { - entry.success_count += 1; - } else { - entry.failure_count += 1; - } - entry.last_activity_ms = now_ms; - } - - /// Get coverage report — what domains are covered by adapters, what are gaps. - pub fn coverage_report(&self) -> CoverageReport { - // Build set of domains that have adapters - let mut adapter_domains: HashMap = HashMap::new(); - for adapter in self.active.values().chain(self.available.values()) { - adapter_domains.insert(adapter.domain.clone(), adapter.name.clone()); - } - - let mut covered = Vec::new(); - let mut gaps = Vec::new(); - let mut total_interactions: u64 = 0; - let mut covered_interactions: u64 = 0; - - for (domain, activity) in &self.domain_activity { - total_interactions += activity.interaction_count; - - let has_adapter = adapter_domains.contains_key(domain); - let adapter_name = adapter_domains.get(domain).cloned(); - - let da = DomainActivity { - domain: domain.clone(), - interaction_count: activity.interaction_count, - success_count: activity.success_count, - failure_count: activity.failure_count, - last_activity_ms: activity.last_activity_ms, - has_adapter, - adapter_name, - }; - - if has_adapter { - covered_interactions += activity.interaction_count; - covered.push(da); - } else { - gaps.push(da); - } - } - - // Sort gaps by interaction count (most active gaps first) - gaps.sort_by(|a, b| b.interaction_count.cmp(&a.interaction_count)); - - let coverage_ratio = if total_interactions > 0 { - covered_interactions as f32 / total_interactions as f32 - } else { - 1.0 // No activity = fully covered (vacuous truth) - }; - - CoverageReport { - covered, - gaps, - total_interactions, - coverage_ratio, - } - } - - /// Get current state snapshot for IPC response. - pub fn state(&self) -> GenomePagingState { - GenomePagingState { - memory_budget_mb: self.memory_budget_mb, - memory_used_mb: self.memory_used_mb, - memory_pressure: self.memory_pressure(), - active_adapters: self.active.values().cloned().collect(), - available_adapters: self.available.values().cloned().collect(), - } - } -} - -// ============================================================================= -// EVICTION SCORING -// ============================================================================= - -/// Calculate eviction score for an adapter. -/// Higher score = more evictable. -/// Critical adapters (priority > 0.9) return INFINITY (never evict). -/// -/// Formula: age_seconds / (priority * 10) -pub fn calculate_eviction_score(adapter: &GenomeAdapterInfo) -> f64 { - if adapter.priority > 0.9 { - return f64::INFINITY; // Never evict critical adapters - } - - let now_ms = continuum_base::time::EpochMs::now().millis(); - - let age_seconds = (now_ms.saturating_sub(adapter.last_used_ms)) as f64 / 1000.0; - age_seconds / (adapter.priority as f64 * 10.0) -} - -/// Calculate eviction score with explicit now_ms (for testing). -pub fn calculate_eviction_score_at(adapter: &GenomeAdapterInfo, now_ms: u64) -> f64 { - if adapter.priority > 0.9 { - return f64::INFINITY; - } - - let age_seconds = (now_ms.saturating_sub(adapter.last_used_ms)) as f64 / 1000.0; - age_seconds / (adapter.priority as f64 * 10.0) -} - -// ============================================================================= -// TESTS -// ============================================================================= - -#[cfg(test)] -mod tests; diff --git a/core/continuum-mind/src/persona/genome_paging/tests.rs b/core/continuum-mind/src/persona/genome_paging/tests.rs deleted file mode 100644 index 49b2e49a7a..0000000000 --- a/core/continuum-mind/src/persona/genome_paging/tests.rs +++ /dev/null @@ -1,589 +0,0 @@ -#![cfg(test)] - use super::*; - - fn make_adapter( - name: &str, - domain: &str, - size_mb: f32, - priority: f32, - loaded: bool, - last_used_ms: u64, - ) -> GenomeAdapterInfo { - GenomeAdapterInfo { - name: name.to_string(), - domain: domain.to_string(), - size_mb, - priority, - is_loaded: loaded, - last_used_ms, - trained_model_name: Some(format!("{}:7b", name)), - compaction: None, - } - } - - // ── Eviction Scoring ────────────────────────────────────────────── - - #[test] - fn test_critical_adapter_never_evicted() { - let adapter = make_adapter("critical", "code", 50.0, 0.95, true, 0); - let score = calculate_eviction_score_at(&adapter, 100_000); - assert!( - score.is_infinite(), - "Critical adapter should return INFINITY" - ); - } - - #[test] - fn test_eviction_score_formula() { - // age = 60s, priority = 0.5 → score = 60 / (0.5 * 10) = 12.0 - let adapter = make_adapter("test", "code", 50.0, 0.5, true, 0); - let score = calculate_eviction_score_at(&adapter, 60_000); - assert!( - (score - 12.0).abs() < 0.001, - "Score should be 12.0, got {score}" - ); - } - - #[test] - fn test_eviction_score_higher_priority_harder_to_evict() { - let low = make_adapter("low", "code", 50.0, 0.3, true, 0); - let high = make_adapter("high", "code", 50.0, 0.8, true, 0); - let now = 60_000; - - let low_score = calculate_eviction_score_at(&low, now); - let high_score = calculate_eviction_score_at(&high, now); - - assert!( - low_score > high_score, - "Low priority ({low_score}) should have higher eviction score than high priority ({high_score})" - ); - } - - #[test] - fn test_eviction_score_older_more_evictable() { - let old = make_adapter("old", "code", 50.0, 0.5, true, 0); - let recent = make_adapter("recent", "code", 50.0, 0.5, true, 50_000); - let now = 60_000; - - let old_score = calculate_eviction_score_at(&old, now); - let recent_score = calculate_eviction_score_at(&recent, now); - - assert!( - old_score > recent_score, - "Older adapter ({old_score}) should be more evictable than recent ({recent_score})" - ); - } - - #[test] - fn test_eviction_score_just_used_is_zero() { - let just_used = make_adapter("fresh", "code", 50.0, 0.5, true, 60_000); - let score = calculate_eviction_score_at(&just_used, 60_000); - assert!( - (score - 0.0).abs() < 0.001, - "Just-used adapter should have score ≈ 0, got {score}" - ); - } - - // ── Engine: Cache Hit ───────────────────────────────────────────── - - #[test] - fn test_activate_skill_cache_hit() { - let mut engine = GenomePagingEngine::new(200.0); - engine.active.insert( - "ts-expert".into(), - make_adapter("ts-expert", "code", 50.0, 0.5, true, 1000), - ); - - let result = engine.activate_skill("ts-expert", 2000); - - assert!(result.activated); - assert_eq!(result.adapter_name, "ts-expert"); - assert!(result.evicted.is_empty()); - assert!( - result.to_load.is_none(), - "Cache hit should not need to load" - ); - // Verify last_used was updated - assert_eq!(engine.active.get("ts-expert").unwrap().last_used_ms, 2000); - } - - // ── Engine: Unknown Skill ───────────────────────────────────────── - - #[test] - fn test_activate_unknown_skill() { - let mut engine = GenomePagingEngine::new(200.0); - let result = engine.activate_skill("nonexistent", 1000); - - assert!(!result.activated); - assert!(result.to_load.is_none()); - } - - // ── Engine: Simple Load ─────────────────────────────────────────── - - #[test] - fn test_activate_skill_loads_from_available() { - let mut engine = GenomePagingEngine::new(200.0); - engine.available.insert( - "ts-expert".into(), - make_adapter("ts-expert", "code", 50.0, 0.5, false, 0), - ); - - let result = engine.activate_skill("ts-expert", 5000); - - assert!(result.activated); - assert_eq!(result.to_load, Some("ts-expert".to_string())); - assert!(result.evicted.is_empty()); - // Verify moved to active - assert!(engine.active.contains_key("ts-expert")); - assert!(!engine.available.contains_key("ts-expert")); - assert!((engine.memory_used_mb - 50.0).abs() < 0.001); - } - - // ── Engine: Eviction Required ───────────────────────────────────── - - #[test] - fn test_activate_skill_evicts_lru_when_full() { - let mut engine = GenomePagingEngine::new(100.0); - // Load two 50MB adapters (fills 100MB budget) - engine.active.insert( - "old-adapter".into(), - make_adapter("old-adapter", "chat", 50.0, 0.5, true, 1000), - ); - engine.active.insert( - "newer-adapter".into(), - make_adapter("newer-adapter", "code", 50.0, 0.5, true, 5000), - ); - engine.memory_used_mb = 100.0; - // Want to load a third - engine.available.insert( - "incoming".into(), - make_adapter("incoming", "creative", 50.0, 0.5, false, 0), - ); - - let result = engine.activate_skill("incoming", 10_000); - - assert!(result.activated); - assert_eq!(result.to_load, Some("incoming".to_string())); - assert_eq!(result.evicted.len(), 1); - assert_eq!( - result.evicted[0], "old-adapter", - "Should evict oldest (last_used=1000)" - ); - // old-adapter moved to available - assert!(engine.available.contains_key("old-adapter")); - assert!(!engine.active.contains_key("old-adapter")); - // incoming now active - assert!(engine.active.contains_key("incoming")); - assert!( - (engine.memory_used_mb - 100.0).abs() < 0.001, - "Should still be at 100MB" - ); - } - - #[test] - fn test_activate_skill_evicts_multiple_if_needed() { - let mut engine = GenomePagingEngine::new(200.0); - // 4 × 50MB = 200MB (full) - engine.active.insert( - "a1".into(), - make_adapter("a1", "code", 50.0, 0.3, true, 1000), - ); - engine.active.insert( - "a2".into(), - make_adapter("a2", "chat", 50.0, 0.4, true, 2000), - ); - engine.active.insert( - "a3".into(), - make_adapter("a3", "creative", 50.0, 0.5, true, 3000), - ); - engine.active.insert( - "a4".into(), - make_adapter("a4", "social", 50.0, 0.6, true, 4000), - ); - engine.memory_used_mb = 200.0; - // Big adapter needs 120MB → need used + 120 <= 200 → need to free 120MB → 3 × 50MB - engine.available.insert( - "big".into(), - make_adapter("big", "analysis", 120.0, 0.5, false, 0), - ); - - let result = engine.activate_skill("big", 10_000); - - assert!(result.activated); - assert_eq!( - result.evicted.len(), - 3, - "Should evict 3 adapters to free 150MB for 120MB incoming" - ); - // a1 (priority=0.3, oldest) should be first evicted - assert!( - result.evicted.contains(&"a1".to_string()), - "a1 (priority=0.3, oldest) should be evicted" - ); - } - - #[test] - fn test_critical_adapters_survive_eviction() { - let mut engine = GenomePagingEngine::new(100.0); - // Critical adapter + normal adapter fill budget - engine.active.insert( - "critical".into(), - make_adapter("critical", "code", 50.0, 0.95, true, 1000), - ); - engine.active.insert( - "normal".into(), - make_adapter("normal", "chat", 50.0, 0.5, true, 2000), - ); - engine.memory_used_mb = 100.0; - engine.available.insert( - "incoming".into(), - make_adapter("incoming", "creative", 50.0, 0.5, false, 0), - ); - - let result = engine.activate_skill("incoming", 10_000); - - assert!(result.activated); - assert_eq!(result.evicted, vec!["normal".to_string()]); - assert!( - engine.active.contains_key("critical"), - "Critical adapter should survive" - ); - } - - // ── Engine: Pressure-Driven Eviction (broker lever) ────────────── - - #[test] - fn test_evict_under_pressure_no_op_when_below_target() { - let mut engine = GenomePagingEngine::new(100.0); - engine - .active - .insert("a".into(), make_adapter("a", "code", 30.0, 0.5, true, 1000)); - engine.memory_used_mb = 30.0; // pressure = 0.30 - let bytes_freed = engine.evict_under_pressure(0.75); - assert_eq!(bytes_freed, 0, "below-target should not evict"); - assert!(engine.active.contains_key("a")); - } - - #[test] - fn test_evict_under_pressure_drops_lru_until_target() { - let mut engine = GenomePagingEngine::new(100.0); - // Three normal adapters at 30 MB each = 90% pressure. - engine.active.insert( - "oldest".into(), - make_adapter("oldest", "code", 30.0, 0.5, true, 1000), - ); - engine.active.insert( - "middle".into(), - make_adapter("middle", "chat", 30.0, 0.5, true, 5000), - ); - engine.active.insert( - "newest".into(), - make_adapter("newest", "creative", 30.0, 0.5, true, 9000), - ); - engine.memory_used_mb = 90.0; // pressure = 0.90 - // Drop to ≤ 0.50. Need to free until used ≤ 50 MB → drop two. - let bytes_freed = engine.evict_under_pressure(0.50); - assert!(bytes_freed > 0); - assert!(engine.memory_used_mb <= 50.0); - // Oldest goes first (highest score), then middle. - assert!(!engine.active.contains_key("oldest")); - assert!(!engine.active.contains_key("middle")); - assert!(engine.active.contains_key("newest")); - } - - #[test] - fn test_evict_under_pressure_never_drops_critical_adapters() { - let mut engine = GenomePagingEngine::new(100.0); - engine.active.insert( - "critical_a".into(), - make_adapter("critical_a", "code", 40.0, 0.95, true, 1000), - ); - engine.active.insert( - "critical_b".into(), - make_adapter("critical_b", "chat", 40.0, 0.95, true, 5000), - ); - engine.memory_used_mb = 80.0; // pressure = 0.80 - // Asks for 0.30 — but every remaining is critical, so loop terminates - // honestly with what was achievable (zero bytes). - let bytes_freed = engine.evict_under_pressure(0.30); - assert_eq!(bytes_freed, 0, "all-critical pool yields nothing"); - assert!(engine.active.contains_key("critical_a")); - assert!(engine.active.contains_key("critical_b")); - } - - #[test] - fn test_evict_under_pressure_releases_gpu_guard_for_each_victim() { - let mut engine = GenomePagingEngine::new(100.0); - // Two normals; one ancient (forced first victim), one recent. - engine.active.insert( - "ancient".into(), - make_adapter("ancient", "code", 60.0, 0.5, true, 1000), - ); - engine.active.insert( - "recent".into(), - make_adapter("recent", "chat", 30.0, 0.5, true, 9000), - ); - engine.memory_used_mb = 90.0; - // Engine has no gpu_manager set → allocation_guards stays empty, - // but the unregister/remove path should still execute cleanly. - let bytes_freed = engine.evict_under_pressure(0.50); - assert!( - bytes_freed >= 60 * 1024 * 1024, - "freed at least the ancient adapter" - ); - assert!(!engine.active.contains_key("ancient")); - assert!( - engine.available.contains_key("ancient"), - "evicted moves to available" - ); - } - - // ── Engine: Sync State ──────────────────────────────────────────── - - #[test] - fn test_sync_state_replaces_all() { - let mut engine = GenomePagingEngine::new(200.0); - engine.active.insert( - "old".into(), - make_adapter("old", "code", 50.0, 0.5, true, 1000), - ); - engine.memory_used_mb = 50.0; - - engine.sync_state(vec![ - make_adapter("new-active", "code", 60.0, 0.5, true, 5000), - make_adapter("new-available", "chat", 40.0, 0.5, false, 0), - ]); - - assert!(!engine.active.contains_key("old")); - assert!(engine.active.contains_key("new-active")); - assert!(engine.available.contains_key("new-available")); - assert!((engine.memory_used_mb - 60.0).abs() < 0.001); - } - - // ── Engine: Memory Pressure ─────────────────────────────────────── - - #[test] - fn test_memory_pressure_calculation() { - let mut engine = GenomePagingEngine::new(200.0); - assert!((engine.memory_pressure() - 0.0).abs() < 0.001); - - engine.memory_used_mb = 100.0; - assert!((engine.memory_pressure() - 0.5).abs() < 0.001); - - engine.memory_used_mb = 200.0; - assert!((engine.memory_pressure() - 1.0).abs() < 0.001); - - // Over budget capped at 1.0 - engine.memory_used_mb = 250.0; - assert!((engine.memory_pressure() - 1.0).abs() < 0.001); - } - - #[test] - fn test_memory_pressure_zero_budget() { - let engine = GenomePagingEngine::new(0.0); - assert!((engine.memory_pressure() - 0.0).abs() < 0.001); - } - - // ── Engine: State Snapshot ───────────────────────────────────────── - - #[test] - fn test_state_snapshot() { - let mut engine = GenomePagingEngine::new(200.0); - engine.active.insert( - "loaded".into(), - make_adapter("loaded", "code", 50.0, 0.5, true, 1000), - ); - engine.available.insert( - "disk".into(), - make_adapter("disk", "chat", 40.0, 0.5, false, 0), - ); - engine.memory_used_mb = 50.0; - - let state = engine.state(); - - assert!((state.memory_budget_mb - 200.0).abs() < 0.001); - assert!((state.memory_used_mb - 50.0).abs() < 0.001); - assert!((state.memory_pressure - 0.25).abs() < 0.001); - assert_eq!(state.active_adapters.len(), 1); - assert_eq!(state.available_adapters.len(), 1); - } - - // ── Engine: Decision Time ───────────────────────────────────────── - - #[test] - fn test_decision_time_is_fast() { - let mut engine = GenomePagingEngine::new(200.0); - engine.available.insert( - "test".into(), - make_adapter("test", "code", 50.0, 0.5, false, 0), - ); - - let result = engine.activate_skill("test", 1000); - - assert!( - result.decision_time_us < 100, - "Decision should be <100μs, was {}μs", - result.decision_time_us - ); - } - - // ── Domain Activity Tracking ───────────────────────────────────── - - #[test] - fn test_record_activity_creates_entry() { - let mut engine = GenomePagingEngine::new(200.0); - engine.record_activity("code", true); - engine.record_activity("code", true); - engine.record_activity("code", false); - - let report = engine.coverage_report(); - assert_eq!(report.total_interactions, 3); - assert_eq!(report.gaps.len(), 1, "Code domain with no adapter = gap"); - assert_eq!(report.gaps[0].domain, "code"); - assert_eq!(report.gaps[0].interaction_count, 3); - assert_eq!(report.gaps[0].success_count, 2); - assert_eq!(report.gaps[0].failure_count, 1); - } - - #[test] - fn test_coverage_report_with_adapter() { - let mut engine = GenomePagingEngine::new(200.0); - engine.available.insert( - "ts-expert".into(), - make_adapter("ts-expert", "code", 50.0, 0.5, false, 0), - ); - - engine.record_activity("code", true); - engine.record_activity("code", true); - engine.record_activity("chat", true); - - let report = engine.coverage_report(); - assert_eq!(report.covered.len(), 1, "Code domain has adapter → covered"); - assert_eq!(report.gaps.len(), 1, "Chat domain has no adapter → gap"); - assert_eq!(report.total_interactions, 3); - assert!((report.coverage_ratio - 2.0 / 3.0).abs() < 0.01); - } - - #[test] - fn test_coverage_report_empty() { - let engine = GenomePagingEngine::new(200.0); - let report = engine.coverage_report(); - assert!(report.covered.is_empty()); - assert!(report.gaps.is_empty()); - assert_eq!(report.total_interactions, 0); - assert!( - (report.coverage_ratio - 1.0).abs() < 0.01, - "No activity = fully covered" - ); - } - - #[test] - fn test_gaps_sorted_by_interaction_count() { - let mut engine = GenomePagingEngine::new(200.0); - for _ in 0..5 { - engine.record_activity("chat", true); - } - for _ in 0..15 { - engine.record_activity("creative", true); - } - for _ in 0..2 { - engine.record_activity("analysis", true); - } - - let report = engine.coverage_report(); - assert_eq!(report.gaps.len(), 3); - assert_eq!(report.gaps[0].domain, "creative", "Most active gap first"); - assert_eq!(report.gaps[1].domain, "chat"); - assert_eq!(report.gaps[2].domain, "analysis"); - } - - // ── Compacted Adapters ───────────────────────────────────────────── - - #[test] - fn test_compacted_adapter_smaller_size() { - let mut engine = GenomePagingEngine::new(200.0); - - // Compacted adapter is smaller — more fit in budget - let mut compacted = make_adapter("compacted", "code", 35.0, 0.5, false, 0); - compacted.compaction = Some(CompactionMetadata { - parameter_reduction: 0.30, - topology_path: "head_topology.json".to_string(), - has_compacted_weights: true, - original_size_mb: 50.0, - compacted_size_mb: 35.0, - }); - engine.available.insert("compacted".into(), compacted); - - let normal = make_adapter("normal", "chat", 50.0, 0.5, false, 0); - engine.available.insert("normal".into(), normal); - - // Load both — compacted takes 35MB, normal 50MB = 85MB (fits in 200MB) - engine.activate_skill("compacted", 1000); - engine.activate_skill("normal", 2000); - - assert!((engine.memory_used_mb - 85.0).abs() < 0.001); - assert!( - engine.memory_pressure() < 0.5, - "Should be well under budget" - ); - } - - #[test] - fn test_compacted_adapter_metadata_preserved() { - let mut engine = GenomePagingEngine::new(200.0); - let mut adapter = make_adapter("compacted", "code", 35.0, 0.5, false, 0); - adapter.compaction = Some(CompactionMetadata { - parameter_reduction: 0.25, - topology_path: "head_topology.json".to_string(), - has_compacted_weights: true, - original_size_mb: 50.0, - compacted_size_mb: 35.0, - }); - engine.available.insert("compacted".into(), adapter); - - engine.activate_skill("compacted", 1000); - - let active = engine.active.get("compacted").unwrap(); - assert!(active.compaction.is_some()); - let meta = active.compaction.as_ref().unwrap(); - assert!((meta.parameter_reduction - 0.25).abs() < 0.001); - assert!(meta.has_compacted_weights); - } - - // ── ts-rs binding tests ─────────────────────────────────────────── - - #[test] - fn export_bindings_compactionmetadata() { - let cfg = ts_rs::Config::default(); - CompactionMetadata::export_all(&cfg).unwrap(); - } - - #[test] - fn export_bindings_genomeadapterinfo() { - let cfg = ts_rs::Config::default(); - GenomeAdapterInfo::export_all(&cfg).unwrap(); - } - - #[test] - fn export_bindings_genomepagingstate() { - let cfg = ts_rs::Config::default(); - GenomePagingState::export_all(&cfg).unwrap(); - } - - #[test] - fn export_bindings_activateskillresult() { - let cfg = ts_rs::Config::default(); - ActivateSkillResult::export_all(&cfg).unwrap(); - } - - #[test] - fn export_bindings_domainactivity() { - let cfg = ts_rs::Config::default(); - DomainActivity::export_all(&cfg).unwrap(); - } - - #[test] - fn export_bindings_coveragereport() { - let cfg = ts_rs::Config::default(); - CoverageReport::export_all(&cfg).unwrap(); - } diff --git a/core/continuum-mind/src/persona/mod.rs b/core/continuum-mind/src/persona/mod.rs index a4802f94cf..1c17b39c07 100644 --- a/core/continuum-mind/src/persona/mod.rs +++ b/core/continuum-mind/src/persona/mod.rs @@ -51,7 +51,6 @@ pub mod domain_classifier; pub mod durable_history; pub mod engram_source; pub mod evaluator; -pub mod genome_paging; pub mod host; pub mod hw_tier_descriptor; pub mod identity_provider; @@ -134,10 +133,6 @@ pub use evaluator::{ analyze_burst, AdequacyResult, BurstEvaluateResult, BurstRespondContext, FullEvaluateRequest, FullEvaluateResult, GateDetails, RateLimiterState, RecentResponse, SleepMode, SleepState, }; -pub use genome_paging::{ - ActivateSkillResult, CoverageReport, DomainActivity, GenomeAdapterInfo, GenomePagingEngine, - GenomePagingState, -}; pub use inbox::{PersonaInbox, PersonaInboxFrame, PersonaInboxFrameMetrics}; pub use message_cache::{ CachedMessage, ContentDedupResult, ContentDeduplicator, EchoChamberResult, RecentMessageCache, diff --git a/core/continuum-mind/src/persona/model_selection.rs b/core/continuum-mind/src/persona/model_selection.rs index 8964beef27..dd3ffa76b3 100644 --- a/core/continuum-mind/src/persona/model_selection.rs +++ b/core/continuum-mind/src/persona/model_selection.rs @@ -5,20 +5,12 @@ //! the caller receives a typed error instead of silently using a base model. //! //! Priority chain: -//! 0. Signature distance (the need's embedding vs each gene's MINTED signature — -//! [[gene-routing-is-distance-not-keywords]]; gated by a significance floor -//! because the recall space is anisotropic) //! 1. Trait-specific adapter (domain -> trait mapping, e.g. "code" -> reasoning_style) //! 2. Current active adapter (most recently used) //! 3. Any available trained adapter //! -//! Rung 0 exists because `domain_to_trait` is a hardcoded keyword match — exactly -//! the routing the genome doctrine replaces with proximity: an FP gene should lift -//! a Scheme task no keyword table anticipated. The rung fires only when the caller -//! pre-computed the need's embedding (this fn stays PURE + sync — the async embed -//! happens upstream, mirroring `memory/recall`'s `query_embedding` pattern) AND a -//! signed adapter clears the floor; otherwise every existing tier behaves exactly -//! as before (pinned by the pre-rung tests, which pass unchanged). +//! Which genes shape a persona's TURN (several at once, by signature distance) is +//! `genome::selection`, not this chain. use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -43,13 +35,6 @@ pub struct ModelSelectionRequest { /// "support", "help", "social", "facts", "knowledge", "expertise" #[ts(optional)] pub task_domain: Option, - /// Optional free-text NEED ("refactor rust async code") — embedded by the - /// command layer and matched by DISTANCE against each gene's minted - /// signature (rung 0). Falls back to `task_domain`'s text when absent; when - /// neither is present rung 0 is skipped and the keyword tiers answer. - #[serde(default)] - #[ts(optional)] - pub need: Option, } /// Result of model selection — which model to use and why. @@ -69,38 +54,10 @@ pub struct ModelSelectionResult { /// Trait that matched (if tier 1). #[ts(optional)] pub trait_used: Option, - /// Signature similarity that carried the pick (rung 0 only) — observability - /// for the distance rung, absent on every other tier. - #[ts(optional)] - pub similarity: Option, /// How long the selection took (microseconds). pub decision_time_us: f64, } -/// The need's embedding, pre-computed by the (async) caller so selection stays -/// pure + sync — the same split `memory/recall` uses (`query_embedding` on the -/// query, layers never embed inline). -#[derive(Debug, Clone)] -pub struct NeedEmbedding { - /// Embedding-space identity (`EmbeddingProvider::id()`); signatures from a - /// different space answer `None` and simply don't compete. - pub embedder_id: String, - pub vector: Vec, - /// The space's MEASURED unrelated-cosine null (mean, std) when the provider - /// knows it — the significance floor derives from it (never an absolute - /// cosine threshold in an anisotropic space). - pub unrelated_null: Option<(f32, f32)>, -} - -/// Significance floor when the space's null is unmeasured: the recall space's -/// unrelated band sits ≈0.25–0.30 (recall_faculty's war story), so clearing it -/// by a wide margin is required before distance may outrank a declared trait. -const SIGNATURE_FLOOR_WITHOUT_NULL: f32 = 0.45; - -/// How many stds above the unrelated null a signature match must clear when the -/// null IS measured — same 2σ discipline recall uses. -const SIGNATURE_NULL_SIGMAS: f32 = 2.0; - /// Hard failure when no adapter-backed model satisfies a persona turn. #[derive(Debug, Clone, Serialize, Deserialize, TS, thiserror::Error)] #[ts( @@ -181,59 +138,9 @@ pub fn domain_to_trait(domain: &str) -> &'static str { pub fn select_model( request: &ModelSelectionRequest, registry: &AdapterRegistry, -) -> Result { - select_model_with_signatures(request, registry, None, &std::collections::HashMap::new()) -} - -/// [`select_model`] plus rung 0: when the caller pre-computed the need's -/// embedding AND adapters carry minted signatures (keyed by adapter NAME — -/// the alias the whole adoption chain speaks), the nearest signed adapter -/// above the significance floor wins with `source: "signature_distance"`. -/// No embedding / no signatures / nothing above the floor → identical -/// behavior to the keyword tiers. -pub fn select_model_with_signatures( - request: &ModelSelectionRequest, - registry: &AdapterRegistry, - need: Option<&NeedEmbedding>, - signatures: &std::collections::HashMap, ) -> Result { let start = Instant::now(); - // RUNG 0: signature distance — proximity beats keyword guessing, but only - // significantly ([[gene-routing-is-distance-not-keywords]]). - if let Some(need) = need { - let floor = match need.unrelated_null { - Some((mean, std)) => mean + SIGNATURE_NULL_SIGMAS * std, - None => SIGNATURE_FLOOR_WITHOUT_NULL, - }; - let best = registry - .adapters - .values() - .filter(|a| a.trained_model_name.is_some()) - .filter_map(|a| { - signatures - .get(&a.name) - .and_then(|sig| sig.similarity_in(&need.embedder_id, &need.vector)) - .map(|sim| (a, sim)) - }) - .filter(|(_, sim)| *sim > floor) - .max_by(|(a, sa), (b, sb)| { - sa.partial_cmp(sb) - .unwrap_or(std::cmp::Ordering::Equal) // NaN can't arise from cosine over finite vectors; Equal keeps the max total - .then((a.is_loaded as u8).cmp(&(b.is_loaded as u8))) - }); - if let Some((adapter, sim)) = best { - return Ok(ModelSelectionResult { - model: adapter.trained_model_name.clone().unwrap(), // filtered on is_some() four lines up, same as every tier below - source: "signature_distance".into(), - adapter_name: Some(adapter.name.clone()), - trait_used: None, - similarity: Some(sim), - decision_time_us: start.elapsed().as_secs_f64() * 1_000_000.0, - }); - } - } - // TIER 1: Trait-specific adapter if let Some(ref domain) = request.task_domain { let target_trait = domain_to_trait(domain); @@ -254,7 +161,6 @@ pub fn select_model_with_signatures( source: "trait_adapter".into(), adapter_name: Some(adapter.name.clone()), trait_used: Some(target_trait.to_string()), - similarity: None, decision_time_us: start.elapsed().as_secs_f64() * 1_000_000.0, }); } @@ -272,7 +178,6 @@ pub fn select_model_with_signatures( source: "current_adapter".into(), adapter_name: Some(adapter.name.clone()), trait_used: None, - similarity: None, decision_time_us: start.elapsed().as_secs_f64() * 1_000_000.0, }); } @@ -293,7 +198,6 @@ pub fn select_model_with_signatures( source: "any_adapter".into(), adapter_name: Some(adapter.name.clone()), trait_used: None, - similarity: None, decision_time_us: start.elapsed().as_secs_f64() * 1_000_000.0, }); } @@ -323,7 +227,6 @@ mod tests { ModelSelectionRequest { persona_id: Uuid::new_v4(), task_domain: domain.map(String::from), - need: None, } } @@ -533,79 +436,6 @@ mod tests { } } - // what this catches: rung 0's whole contract, the distance-routing claim made - // mechanical ([[gene-routing-is-distance-not-keywords]]): (a) a SIGNED adapter - // near the need outranks the keyword tier even when the keyword table would - // pick another adapter; (b) below the significance floor the rung stays SILENT - // and every legacy tier behaves exactly as before (no-embedding calls are - // pinned by the untouched pre-rung tests); (c) wrong-space signatures don't - // compete (honest absence, never a lying 0). - #[tokio::test] - async fn rung0_distance_beats_keywords_only_when_significant_and_same_space() { - use crate::ai::embedding::{EmbeddingProvider, LexicalEmbedder}; - use std::sync::Arc; - let embedder: Arc = Arc::new(LexicalEmbedder::default()); - let corpus: Vec = - vec!["fold the list recursively".into(), "map over the vector".into()]; - let corpus_ref = crate::genome::corpus_ref::CorpusRef { - name: "fp-corpus".into(), - content_hash: "sha256:00".into(), - size_bytes: 1, - source_url: None, - }; - let sig = crate::genome::signature::GeneSignature::mint(&corpus, corpus_ref, &embedder, 0) - .await - .expect("mint"); - - let mut registry = AdapterRegistry::default(); - // The keyword tier's darling: matches domain_to_trait("code") directly. - registry.adapters.insert( - "keyword-pick".into(), - make_adapter("keyword-pick", "reasoning_style", Some("keyword-model"), true, false), - ); - // The signed FP gene: its DOMAIN is unrelated junk (keywords would never - // pick it) — only its minted signature can carry it. - registry.adapters.insert( - "fp-gene".into(), - make_adapter("fp-gene", "cooking_recipes", Some("fp-model"), false, false), - ); - let mut signatures = std::collections::HashMap::new(); - signatures.insert("fp-gene".to_string(), sig.clone()); - - let need_text = "fold the list recursively"; - let need = NeedEmbedding { - embedder_id: embedder.id().to_string(), - vector: embedder.embed(need_text).await, - unrelated_null: embedder.unrelated_null(), - }; - let req = make_request(Some("code")); - - // (a) near + significant → the distance rung wins over the keyword tier. - let picked = select_model_with_signatures(&req, ®istry, Some(&need), &signatures) - .expect("select"); - assert_eq!(picked.source, "signature_distance"); - assert_eq!(picked.adapter_name.as_deref(), Some("fp-gene")); - assert!(picked.similarity.expect("carried") > 0.0); - - // (b) far below the floor → silent rung, keyword tier answers as before. - let far = NeedEmbedding { - embedder_id: embedder.id().to_string(), - vector: embedder.embed("quarterly tax accounting spreadsheet").await, - unrelated_null: embedder.unrelated_null(), - }; - let fell = select_model_with_signatures(&req, ®istry, Some(&far), &signatures) - .expect("select"); - assert_eq!(fell.source, "trait_adapter"); - assert_eq!(fell.adapter_name.as_deref(), Some("keyword-pick")); - - // (c) wrong-space signature never competes. - let mut alien = signatures.clone(); - alien.get_mut("fp-gene").expect("present").embedder = "some-other-space".into(); - let unswayed = select_model_with_signatures(&req, ®istry, Some(&need), &alien) - .expect("select"); - assert_eq!(unswayed.source, "trait_adapter"); - } - #[test] fn test_decision_time_is_fast() { let registry = AdapterRegistry::default(); diff --git a/core/continuum-mind/src/persona/self_task_generator.rs b/core/continuum-mind/src/persona/self_task_generator.rs index 1df14b91ab..4821bd3bd0 100644 --- a/core/continuum-mind/src/persona/self_task_generator.rs +++ b/core/continuum-mind/src/persona/self_task_generator.rs @@ -15,7 +15,6 @@ use std::collections::HashMap; use std::time::Instant; use uuid::Uuid; -use super::genome_paging::GenomePagingEngine; /// Configuration for self-task generation intervals. pub struct SelfTaskGeneratorConfig { @@ -119,7 +118,6 @@ impl SelfTaskGenerator { } // 4. Learning opportunities (failed tasks) - // Note: enrollment detection happens separately via detect_enrollment_opportunities() // which is called from the tick handler with access to the genome engine. match self.detect_learning_opportunities(db_path, executor).await { Ok(tasks) => { @@ -248,67 +246,6 @@ impl SelfTaskGenerator { Ok(resume_tasks) } - /// Detect domains with activity but no adapter → create enrollment tasks. - /// Policy: minimum 10 interactions before suggesting enrollment. - /// Returns task JSON values ready for persistence. - pub fn detect_enrollment_opportunities(&self, genome: &GenomePagingEngine) -> Vec { - let report = genome.coverage_report(); - let mut tasks = Vec::new(); - - for gap in &report.gaps { - // Policy: minimum 10 interactions before suggesting enrollment - if gap.interaction_count < 10 { - continue; - } - - let failure_rate = if gap.interaction_count > 0 { - gap.failure_count as f64 / gap.interaction_count as f64 - } else { - 0.0 - }; - - // Determine academy mode based on domain characteristics - let suggested_mode = if gap.domain == "code" - || gap.domain.contains("code") - || gap.domain.contains("typescript") - || gap.domain.contains("rust") - { - "coding" - } else if gap.domain == "creative" - || gap.domain.contains("writ") - || gap.domain.contains("art") - || gap.domain.contains("design") - { - "project" - } else { - "knowledge" - }; - - if let Some(mut task) = self.create_task( - "enroll-academy", - &format!( - "[Self-Task] Skill gap detected: {} ({} interactions, {:.0}% failure rate, no adapter). Recommend academy enrollment.", - gap.domain, gap.interaction_count, failure_rate * 100.0 - ), - 0.6, - ) { - // Enrich with metadata for the enrollment executor - if let Some(obj) = task.as_object_mut() { - obj.insert("domain".to_string(), serde_json::json!(gap.domain)); - obj.insert("metadata".to_string(), serde_json::json!({ - "domain": gap.domain, - "interaction_count": gap.interaction_count, - "failure_rate": failure_rate, - "suggested_mode": suggested_mode, - })); - } - tasks.push(task); - } - } - - tasks - } - /// Detect failed tasks and create learning opportunities grouped by domain. async fn detect_learning_opportunities( &self, @@ -461,87 +398,4 @@ mod tests { assert_eq!(task["priority"], 0.5); assert_eq!(task["domain"], "self"); } - - #[test] - fn test_detect_enrollment_below_threshold() { - let gen = SelfTaskGenerator::new(Uuid::new_v4()); - let mut genome = GenomePagingEngine::new(200.0); - - // Only 5 interactions — below the 10-interaction threshold - for _ in 0..5 { - genome.record_activity("web-api", true); - } - - let tasks = gen.detect_enrollment_opportunities(&genome); - assert!( - tasks.is_empty(), - "Should not suggest enrollment with <10 interactions" - ); - } - - #[test] - fn test_detect_enrollment_above_threshold() { - let gen = SelfTaskGenerator::new(Uuid::new_v4()); - let mut genome = GenomePagingEngine::new(200.0); - - // 15 interactions with no adapter - for _ in 0..15 { - genome.record_activity("web-api", true); - } - - let tasks = gen.detect_enrollment_opportunities(&genome); - assert_eq!( - tasks.len(), - 1, - "Should suggest enrollment for gap with 15 interactions" - ); - assert_eq!(tasks[0]["taskType"], "enroll-academy"); - assert_eq!(tasks[0]["metadata"]["domain"], "web-api"); - assert_eq!(tasks[0]["metadata"]["interaction_count"], 15); - } - - #[test] - fn test_detect_enrollment_ignores_covered_domains() { - use crate::persona::genome_paging::GenomeAdapterInfo; - - let gen = SelfTaskGenerator::new(Uuid::new_v4()); - let mut genome = GenomePagingEngine::new(200.0); - - // Register an adapter for the "code" domain - genome.sync_state(vec![GenomeAdapterInfo { - name: "ts-expert".to_string(), - domain: "code".to_string(), - size_mb: 50.0, - priority: 0.5, - is_loaded: false, - last_used_ms: 0, - trained_model_name: None, - compaction: None, - }]); - - // Record lots of activity in the covered domain - for _ in 0..20 { - genome.record_activity("code", true); - } - - let tasks = gen.detect_enrollment_opportunities(&genome); - assert!( - tasks.is_empty(), - "Covered domain should not trigger enrollment" - ); - } - - #[test] - fn test_detect_enrollment_code_domain_suggests_coding_mode() { - let gen = SelfTaskGenerator::new(Uuid::new_v4()); - let mut genome = GenomePagingEngine::new(200.0); - - for _ in 0..12 { - genome.record_activity("code", true); - } - - let tasks = gen.detect_enrollment_opportunities(&genome); - assert_eq!(tasks.len(), 1); - assert_eq!(tasks[0]["metadata"]["suggested_mode"], "coding"); - } } diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index a2823bac08..79c0b95869 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -52,29 +52,23 @@ pub(super) async fn run_turn_cycle( .cycle_for_room(&ctx.identity.peer_id.as_uuid(), turn_room) { Some(cycle) => { - // HER GENES ARE IN HER HEAD ON EVERY TURN (Joel, 2026-10-10: a gene is hers - // once trained and follows her mind, never her workload; GENE-REUSE-FORK-MINT - // §3d). Pinned before the turn and put back after it, as the work turn does, - // so the genome never changes beneath a request. Unreadable: the genome she - // has. The receipt names the genes that ran (GenerationReceipt::genes). - let _genome_pin = { - let pin = crate::cognition::workspace::GenomeRestore::snapshot( - std::sync::Arc::clone(&cycle), + // HER GENES ARE IN HER HEAD ON EVERY TURN, chosen by what her mind is on + // (GENE-REUSE-FORK-MINT §3d): every gene whose region the turn's focused line is + // inside, weighted by depth (`genome::composer`). They stay on her cycle until + // the next turn selects, so nothing between turns flips her slot's adapters (each + // flip clears her KV). Unreadable: the genome she has. The receipt names the + // genes that ran (GenerationReceipt::genes). + let need = crate::cognition::recall_faculty::focused_query(&workspace_burst.rendered); + if let Some(phenotype) = crate::genome::composer::compose(ctx.identity.peer_id.as_uuid(), need).await { + continuum_base::probe!( + class = "persona.genome.turn_genes", + persona = %ctx.identity.agent_name, + genes = phenotype.genes.len() as u64, + phenotype = %crate::genome::composer::render(&phenotype), + "the phenotype this turn runs with: each gene and its scale" ); - if let Some(genes) = - crate::genome::gene_trial::live_genes(ctx.identity.peer_id.as_uuid()) - { - continuum_base::probe!( - class = "persona.genome.turn_genes", - persona = %ctx.identity.agent_name, - room = %turn_room, - genes = genes.len() as u64, - "the genome this turn runs with: every gene she trained that is not retired" - ); - cycle.page_in(genes); - } - pin - }; + cycle.page_in(phenotype.genes); + } // Run the mind over the metadata-rich burst built above // (WHO/WHEN/WHAT per inbox item, own posts attributed, room as the // WHERE). Recall (the persona's own memories) is injected by the diff --git a/core/continuum-mind/src/persona/training_producer.rs b/core/continuum-mind/src/persona/training_producer.rs index 82becdf8d3..1d04e9184e 100644 --- a/core/continuum-mind/src/persona/training_producer.rs +++ b/core/continuum-mind/src/persona/training_producer.rs @@ -89,6 +89,7 @@ pub mod test_support { }, capture: None, genes: Vec::new(), + gene_scales: Vec::new(), } } diff --git a/core/continuum-mind/src/persona/training_producer/tests/part_2.rs b/core/continuum-mind/src/persona/training_producer/tests/part_2.rs index 2edd6c13cb..ce30461459 100644 --- a/core/continuum-mind/src/persona/training_producer/tests/part_2.rs +++ b/core/continuum-mind/src/persona/training_producer/tests/part_2.rs @@ -283,6 +283,7 @@ use super::*; }, capture: None, genes: Vec::new(), + gene_scales: Vec::new(), }); receipts.push(receipt("failed-after-serving")); let homogeneous = served_provenance(&receipts).unwrap(); @@ -297,6 +298,7 @@ use super::*; }, capture: None, genes: Vec::new(), + gene_scales: Vec::new(), }); assert!(served_provenance(&receipts).is_none()); let last = receipts.last_mut().unwrap(); diff --git a/core/continuum-mind/src/persona/unified.rs b/core/continuum-mind/src/persona/unified.rs index 5b99126a35..d228c19f99 100644 --- a/core/continuum-mind/src/persona/unified.rs +++ b/core/continuum-mind/src/persona/unified.rs @@ -13,7 +13,6 @@ use crate::persona::cognition::PersonaCognitionEngine; use crate::persona::domain_classifier::DomainClassifier; use crate::persona::engram_source::EngramSource; use crate::persona::evaluator::{RateLimiterState, SleepState}; -use crate::persona::genome_paging::GenomePagingEngine; use crate::persona::inbox::PersonaInbox; use crate::persona::inference_profile::PersonaInferenceProfile; use crate::persona::message_cache::{ContentDeduplicator, RecentMessageCache}; @@ -37,7 +36,6 @@ pub struct PersonaCognition { pub rate_limiter: RateLimiterState, pub sleep_state: SleepState, pub adapter_registry: AdapterRegistry, - pub genome_engine: GenomePagingEngine, pub domain_classifier: DomainClassifier, /// Per-room recent message cache — echo chamber detection & post-inference adequacy pub message_cache: RecentMessageCache, @@ -139,19 +137,8 @@ impl PersonaCognition { /// Engine and inbox require persona_id; everything else uses defaults. /// Capture sink defaults to `NoopRagCaptureSink` (zero overhead). pub fn new(persona_id: Uuid, persona_name: String, rag_engine: Arc) -> Self { - Self::with_budget(persona_id, persona_name, rag_engine, 200.0) - } - - /// Create with a specific genome memory budget (from GPU manager). - /// Capture sink defaults to `NoopRagCaptureSink`. - pub fn with_budget( - persona_id: Uuid, - persona_name: String, - rag_engine: Arc, - genome_budget_mb: f32, - ) -> Self { let sink: Arc = Arc::new(NoopRagCaptureSink); - Self::with_capture_sink(persona_id, persona_name, rag_engine, genome_budget_mb, sink) + Self::with_capture_sink(persona_id, persona_name, rag_engine, sink) } /// Create with a custom capture sink — production callers swap @@ -163,7 +150,6 @@ impl PersonaCognition { persona_id: Uuid, persona_name: String, rag_engine: Arc, - genome_budget_mb: f32, capture_sink: Arc, ) -> Self { let (_, shutdown_rx) = tokio::sync::watch::channel(false); @@ -179,7 +165,6 @@ impl PersonaCognition { rate_limiter: RateLimiterState::default(), sleep_state: SleepState::default(), adapter_registry: AdapterRegistry::default(), - genome_engine: GenomePagingEngine::new(genome_budget_mb), domain_classifier: DomainClassifier::new(), message_cache: RecentMessageCache::new(), content_dedup: ContentDeduplicator::new(), @@ -486,7 +471,6 @@ mod tests { crate::persona::evaluator::SleepMode::Active ); assert!(pc.adapter_registry.adapters.is_empty()); - assert!((pc.genome_engine.memory_pressure() - 0.0).abs() < 0.001); } // ---- Slice 10.5: RAG stack wiring (TDD) ---- @@ -572,7 +556,7 @@ mod tests { let rag = Arc::new(RagEngine::new()); let sink = Arc::new(InMemoryRagCaptureSink::new()); let sink_dyn: Arc = sink.clone(); - let pc = PersonaCognition::with_capture_sink(id, "TestBot".into(), rag, 200.0, sink_dyn); + let pc = PersonaCognition::with_capture_sink(id, "TestBot".into(), rag, sink_dyn); // Admit + register one engram. let now = 1_000_000_000u64; @@ -812,7 +796,7 @@ mod tests { let sink = Arc::new(InMemoryRagCaptureSink::new()); let sink_dyn: Arc = sink.clone(); let mut pc = - PersonaCognition::with_capture_sink(id, "Kimi".into(), Arc::new(RagEngine::new()), 200.0, sink_dyn); + PersonaCognition::with_capture_sink(id, "Kimi".into(), Arc::new(RagEngine::new()), sink_dyn); pc.set_airc_source(Arc::new(CannedSource { id: "airc", tokens_per_item: 50, items_offered: 2, share: None })); let mind = crate::cognition::mind_room::mind_room_id(id); let _ = pc.compose_for_turn(&lcd_profile(), 1_000_000, Some(mind)).await; @@ -832,7 +816,7 @@ mod tests { let sink = Arc::new(InMemoryRagCaptureSink::new()); let sink_dyn: Arc = sink.clone(); let mut pc = - PersonaCognition::with_capture_sink(id, "TestBot".into(), rag, 200.0, sink_dyn); + PersonaCognition::with_capture_sink(id, "TestBot".into(), rag, sink_dyn); let airc = Arc::new(CannedSource { id: "airc", diff --git a/docs/architecture/GENE-REUSE-FORK-MINT.md b/docs/architecture/GENE-REUSE-FORK-MINT.md index a1724b1fcf..1bdeba61c3 100644 --- a/docs/architecture/GENE-REUSE-FORK-MINT.md +++ b/docs/architecture/GENE-REUSE-FORK-MINT.md @@ -187,7 +187,7 @@ Status: `genome::recall` already walks local-then-grid (`RecallScope::LocalThenG | Signatures by distance, subspaces | exists (`genome::signature`) | | Fitness with harm → 0 | exists (`genome::fitness`) | | Trials judged on her cards | exists (`genome::gene_trial`); **retired by §3d**: per-card 50/50 arm and card-settled promotion | -| **Per-turn selection by signature distance, automatic floor, several at once (§3d)** | new: `genome_paging` is the dormant pager; signatures and their spread exist | +| **Per-turn selection by signature distance, automatic floor, several at once (§3d)** | coded (`genome::composer::compose -> Phenotype`, probes `genome.select`, `persona.genome.turn_genes`): every gene whose region the turn's focused line is inside, depth `a = clamp((sim - f)/(1 - f))` from its floor `f`, the `capacity` deepest kept, engine scale `a / max(1, Σa)`, enter at the floor and leave at `1.5×` its distance, scales held bit-identical while the set holds (the engine clears a slot's KV on any scale change); `f` is filed at mint (`GeneSignature::region`, the 10th-percentile similarity of its own corpus), floored at the space's null + 2σ; the receipt carries the phenotype (`genes` + `gene_scales`); `Phenotype::without(g)` is the examiner's P∖g. The LOADED tier (paging across GPU / RAM / disk) is the working-set owner's | | **Fitness from the world's surprise + offline gene-off replay (§3d)** | new: `persona::recorder` + `vdd::turn_replay` exist | | Settlement by the room's review | #4765 | | Recall local → grid | exists (`genome::recall`) | diff --git a/docs/architecture/PERSONA-COGNITION-PIPELINE.md b/docs/architecture/PERSONA-COGNITION-PIPELINE.md index bb92a3346e..32b401bdec 100644 --- a/docs/architecture/PERSONA-COGNITION-PIPELINE.md +++ b/docs/architecture/PERSONA-COGNITION-PIPELINE.md @@ -58,7 +58,7 @@ path — reuse it when the capability returns, do not write a parallel one. | 2 | `full_evaluate(...)` | `persona/evaluator/mod.rs` | dormant (command `cognition/full-evaluate` only) | Fast-path gates: sleep mode, undirected-persona chatter, self-message dedup, fast-path priority. Sub-1ms. Silence = first-class outcome. | | 3 | `cognition::analyze(AnalysisInput)` | `cognition/shared_analysis/mod.rs` | dormant (respond path only) | ONE inference per chat message via single-flight DashMap cache. N personas analyzing the same message coalesce into one inference. | | 4 | `score_persona(slot, analysis)` | `cognition/response_orchestrator.rs` | dormant (respond path only) | Per-persona relevance via specialty match. Returns `ResponderDecision`. | -| 5 | `genome_engine.activate_skill(domain, now_ms)` | `persona/genome_paging.rs` | dormant (command `cognition/genome-activate-skill` only) | L1-L5 LoRA paging — page in the adapter for this domain. LRU evicts under pressure. | +| 5 | `genome::composer::compose(persona, perception)` | `continuum-genome/src/genome/composer.rs` (residency: `gene_residency.rs`) | live (both turn sites) | Her phenotype by distance: every gene whose region the turn is inside, weighted by depth, held while the set holds; the node's residency owner keeps her genes on the device and pages cold ones to host RAM under the one device budget. | | 6 | `PersonaCognition::compose_for_turn(profile, now_ms)` | `persona/unified.rs` | **live** (WorkspaceCycle RAG) | Brain RAG composition: `engram_source + airc_source + roster/doctrine/bench sources` via `FlexboxRagBudgetAdapter`. | | 7 | `cognition::generate_response::evaluate_response(...)` | `cognition/generate_response.rs` | dormant (command wrapper + respond path; the live turn infers via `llm_deliberation_faculty`) | Agent inference through the provider registry. Typed errors (no silent fallback). | | 8 | `cognition::clean_and_validate(...)` | `cognition/response_validator.rs` | dormant (test-only today) | Output cleaning + validation. `ValidationOutcome`. | diff --git a/docs/genome/K3-EXPERT-PAGING-SEAMS.md b/docs/genome/K3-EXPERT-PAGING-SEAMS.md index b4bd994618..e0cdc41852 100644 --- a/docs/genome/K3-EXPERT-PAGING-SEAMS.md +++ b/docs/genome/K3-EXPERT-PAGING-SEAMS.md @@ -27,6 +27,8 @@ as a content-addressed artifact on the **Frozen/Cold** tier (D:). Real types it builds on: - `working_set::ArtifactId` — sha256-derived UUID, content-addressed. One per expert `(layer, expert_id)` tile. +> **2026-10-24:** `genome::{blob, store, local_manager, manager, bus, working_set}` were deleted unwired (no caller outside their own tests). Expert paging lives in the engine's `capacity::expert_*` (container, ecache, reconcile, pager) and the expert layout in `inference_capability::expert_layout`; gene residency is `genome::gene_residency`. The seam proposals below are history. + - `blob::ArtifactBlob { id, bytes }` + `blob::Provenance::minimal(id, created_at_ms)`. - `tier::TierStore::write(blob, provenance, role)` — the sink. - `working_set::{PageKind::MoEExpert, PageOffset, PageRef}` — `PageOffset` addresses one diff --git a/protocol/typescript/cognition/GenomeActivateSkillParams.ts b/protocol/typescript/cognition/GenomeActivateSkillParams.ts deleted file mode 100644 index ceaaaee07f..0000000000 --- a/protocol/typescript/cognition/GenomeActivateSkillParams.ts +++ /dev/null @@ -1,15 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeActivateSkillParams = { -/** - * Persona whose genome pages in the skill. - */ -personaId: string, -/** - * Skill/domain to activate (e.g. "typescript-expertise"). - */ -skillName: string, -/** - * Memory budget in MB; 0 or omitted uses the GPU-detected per-persona budget. - */ -memoryBudgetMb: number, }; diff --git a/protocol/typescript/cognition/GenomeCoverageReportParams.ts b/protocol/typescript/cognition/GenomeCoverageReportParams.ts deleted file mode 100644 index 7ebb9bda9d..0000000000 --- a/protocol/typescript/cognition/GenomeCoverageReportParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeCoverageReportParams = { -/** - * Persona whose coverage ledger is read. - */ -personaId: string, }; diff --git a/protocol/typescript/cognition/GenomeEvictUnderPressureParams.ts b/protocol/typescript/cognition/GenomeEvictUnderPressureParams.ts deleted file mode 100644 index b2eb3b1107..0000000000 --- a/protocol/typescript/cognition/GenomeEvictUnderPressureParams.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeEvictUnderPressureParams = { -/** - * Persona whose genome is evicted. - */ -personaId: string, -/** - * Target memory-pressure ratio to evict down to (default 0.75). - */ -targetPressure: number, }; diff --git a/protocol/typescript/cognition/GenomeEvictUnderPressureResult.ts b/protocol/typescript/cognition/GenomeEvictUnderPressureResult.ts deleted file mode 100644 index 9e0f8ecc90..0000000000 --- a/protocol/typescript/cognition/GenomeEvictUnderPressureResult.ts +++ /dev/null @@ -1,3 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeEvictUnderPressureResult = { personaId: string, targetPressure: number, pressureBefore: number, pressureAfter: number, bytesFreed: number, }; diff --git a/protocol/typescript/cognition/GenomeRecordActivityParams.ts b/protocol/typescript/cognition/GenomeRecordActivityParams.ts deleted file mode 100644 index 3901a164ef..0000000000 --- a/protocol/typescript/cognition/GenomeRecordActivityParams.ts +++ /dev/null @@ -1,15 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeRecordActivityParams = { -/** - * Persona whose coverage ledger records the activity. - */ -personaId: string, -/** - * Skill domain the persona acted in (e.g. "code", "chat"). - */ -domain: string, -/** - * Whether the interaction succeeded (default true). - */ -success: boolean, }; diff --git a/protocol/typescript/cognition/GenomeRecordActivityResult.ts b/protocol/typescript/cognition/GenomeRecordActivityResult.ts deleted file mode 100644 index f3c2b71a9f..0000000000 --- a/protocol/typescript/cognition/GenomeRecordActivityResult.ts +++ /dev/null @@ -1,3 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeRecordActivityResult = { recorded: boolean, domain: string, success: boolean, }; diff --git a/protocol/typescript/cognition/GenomeStateParams.ts b/protocol/typescript/cognition/GenomeStateParams.ts deleted file mode 100644 index 5c55e9b240..0000000000 --- a/protocol/typescript/cognition/GenomeStateParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeStateParams = { -/** - * Persona whose genome state is read. - */ -personaId: string, }; diff --git a/protocol/typescript/cognition/GenomeSyncParams.ts b/protocol/typescript/cognition/GenomeSyncParams.ts deleted file mode 100644 index 3f830449ad..0000000000 --- a/protocol/typescript/cognition/GenomeSyncParams.ts +++ /dev/null @@ -1,16 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { GenomeAdapterInfo } from "../persona/GenomeAdapterInfo"; - -export type GenomeSyncParams = { -/** - * Persona whose genome is reconciled. - */ -personaId: string, -/** - * The full adapter inventory to sync into the paging engine. - */ -adapters: Array, -/** - * Memory budget in MB; 0 or omitted uses the GPU-detected per-persona budget. - */ -memoryBudgetMb: number, }; diff --git a/protocol/typescript/cognition/GenomeSyncResult.ts b/protocol/typescript/cognition/GenomeSyncResult.ts deleted file mode 100644 index 41e82d726a..0000000000 --- a/protocol/typescript/cognition/GenomeSyncResult.ts +++ /dev/null @@ -1,3 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GenomeSyncResult = { synced: boolean, adapterCount: number, activeCount: number, memoryUsedMb: number, memoryPressure: number, }; diff --git a/protocol/typescript/cognition/GetStateResult.ts b/protocol/typescript/cognition/GetStateResult.ts index 30014eca7b..f8336d8d10 100644 --- a/protocol/typescript/cognition/GetStateResult.ts +++ b/protocol/typescript/cognition/GetStateResult.ts @@ -3,7 +3,7 @@ import type { Mood } from "../persona/Mood"; /** * The persona's live cognitive state — a camelCase projection of - * [`PersonaState`](crate::persona::PersonaState) plus the derived service cadence. + * [`PersonaState`](crate::cognition::conversation::types::PersonaState) plus the derived service cadence. */ export type GetStateResult = { /** diff --git a/protocol/typescript/cognition/SyncDomainClassifierParams.ts b/protocol/typescript/cognition/SyncDomainClassifierParams.ts deleted file mode 100644 index a5f348fbdf..0000000000 --- a/protocol/typescript/cognition/SyncDomainClassifierParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SyncDomainClassifierParams = { -/** - * Persona whose domain classifier is reconciled. - */ -personaId: string, }; diff --git a/protocol/typescript/cognition/SyncDomainClassifierResult.ts b/protocol/typescript/cognition/SyncDomainClassifierResult.ts deleted file mode 100644 index ffa3bdd82e..0000000000 --- a/protocol/typescript/cognition/SyncDomainClassifierResult.ts +++ /dev/null @@ -1,3 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SyncDomainClassifierResult = { synced: boolean, totalDomains: number, coveredDomains: number, }; diff --git a/protocol/typescript/cognition/index.ts b/protocol/typescript/cognition/index.ts index a9c1f56503..cd966c376e 100644 --- a/protocol/typescript/cognition/index.ts +++ b/protocol/typescript/cognition/index.ts @@ -62,15 +62,6 @@ export type { GenerateRecipeOrchestratorParams } from './GenerateRecipeOrchestra export type { GenerateResponseAdmissionPolicy } from './GenerateResponseAdmissionPolicy'; export type { GenerateResponseRequest } from './GenerateResponseRequest'; export type { GenerateResponseResult } from './GenerateResponseResult'; -export type { GenomeActivateSkillParams } from './GenomeActivateSkillParams'; -export type { GenomeCoverageReportParams } from './GenomeCoverageReportParams'; -export type { GenomeEvictUnderPressureParams } from './GenomeEvictUnderPressureParams'; -export type { GenomeEvictUnderPressureResult } from './GenomeEvictUnderPressureResult'; -export type { GenomeRecordActivityParams } from './GenomeRecordActivityParams'; -export type { GenomeRecordActivityResult } from './GenomeRecordActivityResult'; -export type { GenomeStateParams } from './GenomeStateParams'; -export type { GenomeSyncParams } from './GenomeSyncParams'; -export type { GenomeSyncResult } from './GenomeSyncResult'; export type { GetStateParams } from './GetStateParams'; export type { GetStateResult } from './GetStateResult'; export type { GpuBudgetInfo } from './GpuBudgetInfo'; @@ -150,8 +141,6 @@ export type { ShouldRespondRequest } from './ShouldRespondRequest'; export type { SiliconResidencyRequirement } from './SiliconResidencyRequirement'; export type { SyncAdaptersRequest } from './SyncAdaptersRequest'; export type { SyncAdaptersResult } from './SyncAdaptersResult'; -export type { SyncDomainClassifierParams } from './SyncDomainClassifierParams'; -export type { SyncDomainClassifierResult } from './SyncDomainClassifierResult'; export type { TargetSilicon } from './TargetSilicon'; export type { ThreatDetectionReport } from './ThreatDetectionReport'; export type { ThreatEvidence } from './ThreatEvidence'; diff --git a/protocol/typescript/genome/AccessDenied.ts b/protocol/typescript/genome/AccessDenied.ts deleted file mode 100644 index f248ea8d6f..0000000000 --- a/protocol/typescript/genome/AccessDenied.ts +++ /dev/null @@ -1,35 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { PageRef } from "./PageRef"; - -/** - * Typed refusal from the MMU-style permission check. Per - * GENOME-FOUNDRY-SENTINEL Part 4: "AccessDenied is loud. Audit log - * captures it. This is how the substrate makes per-persona privacy - * structural rather than policy." - * - * PR-1 ships the wire shape. PR-2 / PR-3 add the - * `WorkingSetManager::audit_access` enforcement that produces it, - * and audit-recorder (#1344, codex's PR) subscribes to it as one of - * its `AccessDenied` audit-log inputs. - */ -export type AccessDenied = { -/** - * Which persona attempted the access. - */ -actor: string, -/** - * Which page was attempted. - */ -page: PageRef, -/** - * Which persona OWNS that page (whose private region was it - * reaching into). `None` means "no owner — the region is - * substrate-controlled (e.g. foundry-imported)" and the denial - * is for a different reason (license, policy, etc.). - */ -owner?: string, -/** - * Human-readable reason. Per Joel's "never swallow errors" rule: - * loud, specific, debuggable. - */ -reason: string, }; diff --git a/protocol/typescript/genome/EvictionPolicy.ts b/protocol/typescript/genome/EvictionPolicy.ts deleted file mode 100644 index aaa5e94dcd..0000000000 --- a/protocol/typescript/genome/EvictionPolicy.ts +++ /dev/null @@ -1,15 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Per-tier eviction policy. The variants are dimensioned by the - * per-role table in GENOME-FOUNDRY-SENTINEL Part 2: - * - * | Role | Policy | When eviction fires | - * |------|--------|---------------------| - * | Fast | `LruWithinTurn` | sub-step needs a page not resident | - * | Warm | `LruAcrossTurns { window }` (discrete-GPU only) | Fast spill | - * | Bench | `LfuPlusRecency` | Warm spill (discrete) / Fast spill (UMA) | - * | Cold | `DemandAlignedWithRefinedPreference` | Bench spill | - * | Frozen | `AppendOnlyGcOnSleep` | never in hot path | - */ -export type EvictionPolicy = { "kind": "lruWithinTurn" } | { "kind": "lruAcrossTurns", windowTurns: number, } | { "kind": "lfuPlusRecency" } | { "kind": "demandAlignedWithRefinedPreference" } | { "kind": "appendOnlyGcOnSleep" }; diff --git a/protocol/typescript/genome/EvictionRecord.ts b/protocol/typescript/genome/EvictionRecord.ts deleted file mode 100644 index 43bd5d6b40..0000000000 --- a/protocol/typescript/genome/EvictionRecord.ts +++ /dev/null @@ -1,41 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { EvictionPolicy } from "./EvictionPolicy"; -import type { PageRef } from "./PageRef"; -import type { TierRole } from "./TierRole"; - -/** - * Typed record emitted to the trace bus every time a page is evicted - * from some tier. The reason carries the policy that fired (LRU, - * LFU, etc.). Recurring evictions of the same page across turns are - * the signal sentinel uses to upgrade the page's tier policy. - * - * Per GENOME-FOUNDRY-SENTINEL Part 2: "every evicted page emits an - * EvictionRecord to the trace bus." PR-3 wires this through my just- - * shipped artifact dispatch (#1339 + #1343); PR-1 ships the shape. - */ -export type EvictionRecord = { -/** - * The page that was evicted. - */ -page: PageRef, -/** - * Which tier evicted it. - */ -fromRole: TierRole, -/** - * Where the page went (Some) or whether it was dropped entirely - * (None — only valid for Cold/Frozen during GC). - */ -toRole?: TierRole, -/** - * The policy that fired this eviction. Lets the trace bus - * reconstruct *why* without re-running the policy. - */ -policyFired: EvictionPolicy, -/** - * Time spent on the eviction itself (selection + tier-write + - * metadata update). Doesn't include the time the calling - * page_in/page_out spent blocked on it — that's a separate - * signal on the caller side. - */ -elapsedUs: number, }; diff --git a/protocol/typescript/genome/PageFault.ts b/protocol/typescript/genome/PageFault.ts deleted file mode 100644 index f898c1c577..0000000000 --- a/protocol/typescript/genome/PageFault.ts +++ /dev/null @@ -1,39 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { EvictionRecord } from "./EvictionRecord"; -import type { PageRef } from "./PageRef"; -import type { TierRole } from "./TierRole"; - -/** - * Typed event emitted when a persona's composition needs a page that - * isn't already in its working set. Sentinel observes these to detect - * patterns: a persona that page-faults on the same page across many - * turns is a signal to either pre-fetch it or pin it higher. - * - * `from_role: None` means "true cold miss" — the page does not exist - * in any tier yet (typically a fresh KV-cache entry or a never-loaded - * MoE expert). `from_role: Some(role)` means "tier promotion" — the - * page existed in `role` and got moved up. - */ -export type PageFault = { page: PageRef, -/** - * Where the page was before the fault. `None` for true cold - * miss (page didn't exist yet). - */ -fromRole?: TierRole, -/** - * Where the page lives after the fault is serviced. - */ -toRole: TierRole, persona: string, -/** - * Time spent servicing the fault (tier lookup + transfer + - * eviction-if-any). Drives sentinel's "is this page worth - * pre-fetching" calculus. - */ -elapsedUs: number, -/** - * If servicing the fault required evicting another page, the - * record of that eviction. Lets sentinel correlate cause + - * effect across the trace bus in one record instead of joining - * two separate event streams. - */ -evictionCost?: EvictionRecord, }; diff --git a/protocol/typescript/genome/PageHandle.ts b/protocol/typescript/genome/PageHandle.ts deleted file mode 100644 index e5477ac96b..0000000000 --- a/protocol/typescript/genome/PageHandle.ts +++ /dev/null @@ -1,18 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { PageRef } from "./PageRef"; -import type { TierRole } from "./TierRole"; - -/** - * Opaque handle returned by `page_in`. Carries enough context for the - * caller to use the page without exposing the tier-internal storage. - * PR-1 ships the wire shape; PR-2 (trait + impl) gives the type - * behaviors. The `tier_role` field lets the caller decide whether to - * pin the handle (Fast / Warm) or stream-read it (Cold / Frozen). - */ -export type PageHandle = { page: PageRef, tierRole: TierRole, -/** - * Byte size of the page as resident in `tier_role`. For Cold / - * Frozen this is the size at-rest; for Fast / Warm it's the - * size in accelerator-addressable memory. - */ -sizeBytes: number, }; diff --git a/protocol/typescript/genome/Provenance.ts b/protocol/typescript/genome/Provenance.ts deleted file mode 100644 index 11983e32e1..0000000000 --- a/protocol/typescript/genome/Provenance.ts +++ /dev/null @@ -1,24 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ArtifactId } from "./ArtifactId"; - -/** - * PR-2 stub for `Provenance`. The full shape (GENOME-FOUNDRY- - * SENTINEL Part 1) carries creator, source_trace, source_artifact, - * supersedes, adaptation_method, outcome_metrics, trust_score, and - * license fields. PR-2 ships a typed minimum so the `TierStore::write` - * signature compiles; the full shape is a separate Lane H PR that - * replaces this stub. - * - * PR-2's stub carries: - * - `artifact_id` — the content hash of the artifact this provenance - * describes. Required for the typed contract; matches the - * `ArtifactBlob.id` value passed alongside. - * - `created_at_ms` — Unix-ms timestamp the provenance was attached. - * Required for ordering claims about the artifact across federation. - * - * When the full shape lands, downstream callers will be able to add - * the remaining fields without changing the trait surface — this - * type can grow fields without breaking callers that only set the - * minimum. - */ -export type Provenance = { artifactId: ArtifactId, createdAtMs: number, }; diff --git a/protocol/typescript/genome/ResidentPage.ts b/protocol/typescript/genome/ResidentPage.ts deleted file mode 100644 index 85c4e46704..0000000000 --- a/protocol/typescript/genome/ResidentPage.ts +++ /dev/null @@ -1,23 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { PageRef } from "./PageRef"; -import type { TierRole } from "./TierRole"; - -/** - * A page currently in some persona's working set. Tracks the - * per-turn metadata the eviction policy needs (last_access, - * access_count_window) and the pinning flag the composition layer - * sets to prevent mid-turn evictions of in-use pages. - * - * `last_access_ms` is `u64` (unix-ms) instead of `std::time::Instant` - * because (a) ts-rs needs a wire-stable representation and (b) the - * trace bus can replay records across processes where `Instant` is - * meaningless. Sub-millisecond timing for hot-path decisions stays - * in caller-side `Instant`s. - */ -export type ResidentPage = { page: PageRef, role: TierRole, lastAccessMs: number, accessCountWindow: number, -/** - * When true the eviction policy must skip this page until the - * composition layer unpins it. Composition-pinned pages cannot - * evict mid-turn. - */ -pinned: boolean, }; diff --git a/protocol/typescript/genome/TierCapacity.ts b/protocol/typescript/genome/TierCapacity.ts deleted file mode 100644 index a475b31e02..0000000000 --- a/protocol/typescript/genome/TierCapacity.ts +++ /dev/null @@ -1,19 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Current vs configured byte capacity of a tier. The governor sets - * `configured_limit` from the policy file (Part 11). The tier itself - * reports `current_used` from its backing store. The delta is the - * available headroom; when `current_used` approaches `configured_limit`, - * the tier triggers eviction. - */ -export type TierCapacity = { -/** - * Bytes currently in use by this tier's backing store. - */ -currentUsed: number, -/** - * Bytes the tier is configured to hold (policy limit, NOT a - * hardware ceiling). The governor enforces; the tier respects. - */ -configuredLimit: number, }; diff --git a/protocol/typescript/genome/TierConfig.ts b/protocol/typescript/genome/TierConfig.ts deleted file mode 100644 index a88f2e852b..0000000000 --- a/protocol/typescript/genome/TierConfig.ts +++ /dev/null @@ -1,57 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { EvictionPolicy } from "./EvictionPolicy"; -import type { TierCapacity } from "./TierCapacity"; -import type { TierRole } from "./TierRole"; - -/** - * One typed entry in the governor's `Vec`. Per - * GENOME-FOUNDRY-SENTINEL Part 2: the cache hierarchy is a SEQUENCE - * of tier roles parameterized by hardware class, NOT a fixed L1..L5 - * enum. Discrete-GPU hardware emits five entries (Fast/Warm/Bench/ - * Cold/Frozen). UMA hardware emits four — `Warm` is structurally - * omitted because Fast and Warm would share the same physical bytes - * and an `Fast→Warm` eviction would be a no-op. - * - * Subsystems address tiers by `role`, never by index. That's what - * makes the "L1→L2 eviction on UMA" failure mode structurally - * impossible: there is no `Warm` entry in the vec on UMA, so no - * caller can name one. - * - * `backing` is intentionally absent at this slice. The realization - * ladder is: - * 1. (THIS SLICE) shape + structural-absence invariant — every - * subsystem can address tiers by role, the type system - * guarantees UMA-omits-Warm. - * 2. NEXT SLICE: TierStore handle threading — `backing` becomes - * `Arc` populated by the genome subsystem at boot. - * 3. LATER: policy_file TOML loading writes real `configured_limit` - * bytes from the per-hardware-anchor numbers in the doc - * (M2 Air: Fast 2 LoRA layers + 2k KV tokens; 5090: Fast 8 + 16k; - * etc.). Today's `tier_configs_for` returns `configured_limit = 0` - * across the board — the shape is right, the numbers come later. - * - * The compression principle: a TierConfig is the singular substrate - * description of "one tier on this hardware." Capacity + eviction - * policy + (eventually) backing store live together because they're - * the same logical decision. - */ -export type TierConfig = { -/** - * Which named role this entry fills. Address by this, never by - * vec index. - */ -role: TierRole, -/** - * Current/configured byte capacity. Today's - * `tier_configs_for` returns zeros — TOML loading fills real - * numbers in a follow-up slice. Subsystems should never assume - * `configured_limit > 0` until the governor has loaded a policy. - */ -capacity: TierCapacity, -/** - * Per-role canonical eviction policy from - * `EvictionPolicy::canonical_for(role)`. A future slice may let - * the policy file override this per-installation; today the - * canonical mapping is the single source. - */ -eviction: EvictionPolicy, }; diff --git a/protocol/typescript/genome/TierError.ts b/protocol/typescript/genome/TierError.ts deleted file mode 100644 index ad062c87e7..0000000000 --- a/protocol/typescript/genome/TierError.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { PageRef } from "./PageRef"; -import type { TierRole } from "./TierRole"; - -/** - * Errors a tier's read/write operations can surface. PR-1 ships - * the shape; PR-2's `TierStore` trait returns it. - */ -export type TierError = { "kind": "pageNotFound", page: PageRef, } | { "kind": "noEvictionCandidate", from_role: TierRole, bytes_needed: number, } | { "kind": "backingStoreIo", reason: string, } | { "kind": "roleNotConfigured", role: TierRole, }; diff --git a/protocol/typescript/genome/WorkingSet.ts b/protocol/typescript/genome/WorkingSet.ts deleted file mode 100644 index bd48856d6e..0000000000 --- a/protocol/typescript/genome/WorkingSet.ts +++ /dev/null @@ -1,21 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ResidentPage } from "./ResidentPage"; -import type { WorkingSetCapacity } from "./WorkingSetCapacity"; - -/** - * A persona's currently-resident pages plus its policy budget. - * PR-1 ships the data shape with no traits / no impl — PR-2 adds - * the `WorkingSetManager` trait that produces and consumes these. - * - * `pages` is keyed by `PageRef` because that's the lookup the hot - * path needs (composition asks "is this page resident?"). HashMap - * instead of BTreeMap because access is by exact match, not range. - */ -export type WorkingSet = { persona: string, -/** - * All resident pages for this persona, keyed by a stringified - * `PageRef`. On the wire this serializes as a JSON object with - * string keys (serde's HashMap → object behavior). The TS side - * sees a record keyed by string with `ResidentPage` values. - */ -pages: { [key in string]: ResidentPage }, capacity: WorkingSetCapacity, }; diff --git a/protocol/typescript/genome/WorkingSetCapacity.ts b/protocol/typescript/genome/WorkingSetCapacity.ts deleted file mode 100644 index 4911631b95..0000000000 --- a/protocol/typescript/genome/WorkingSetCapacity.ts +++ /dev/null @@ -1,25 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Per-persona working-set budget the governor publishes. Bytes - * (not page counts) because pages vary in size by kind. The governor - * re-publishes when policy changes (hardware probe shifts class, - * pressure event drops the cap, etc.). - */ -export type WorkingSetCapacity = { -/** - * Maximum bytes the persona's Fast tier is allowed to hold. - */ -fastBytes: number, -/** - * Maximum bytes in Warm. Set to 0 on UMA hardware (where Warm - * is structurally absent) — code that addresses Warm on UMA - * hits `TierError::RoleNotConfigured`. - */ -warmBytes: number, -/** - * Maximum bytes pinned per-turn (composition lock). Smaller - * than fast_bytes because pinning starves the eviction policy; - * the governor caps to prevent runaway pinning. - */ -maxPinnedBytes: number, }; diff --git a/protocol/typescript/genome/index.ts b/protocol/typescript/genome/index.ts index 00e06adc8d..4cf119a99b 100644 --- a/protocol/typescript/genome/index.ts +++ b/protocol/typescript/genome/index.ts @@ -2,7 +2,6 @@ // Source: generator/generate-rust-bindings.ts // Re-generate: npx tsx generator/generate-rust-bindings.ts -export type { AccessDenied } from './AccessDenied'; export type { AcquireSource } from './AcquireSource'; export type { ArtifactId } from './ArtifactId'; export type { ArtifactRef } from './ArtifactRef'; @@ -12,20 +11,15 @@ export type { CompositionHint } from './CompositionHint'; export type { CompositionRef } from './CompositionRef'; export type { DomainHint } from './DomainHint'; export type { EngramRef } from './EngramRef'; -export type { EvictionPolicy } from './EvictionPolicy'; -export type { EvictionRecord } from './EvictionRecord'; export type { FreshnessTarget } from './FreshnessTarget'; export type { LoRALayerRef } from './LoRALayerRef'; export type { MoEExpertRef } from './MoEExpertRef'; export type { OutcomeWindow } from './OutcomeWindow'; -export type { PageFault } from './PageFault'; -export type { PageHandle } from './PageHandle'; export type { PageKind } from './PageKind'; export type { PageOffset } from './PageOffset'; export type { PageRef } from './PageRef'; export type { PeerId } from './PeerId'; export type { PersonaId } from './PersonaId'; -export type { Provenance } from './Provenance'; export type { RankedPool } from './RankedPool'; export type { RecallBudget } from './RecallBudget'; export type { RecallContext } from './RecallContext'; @@ -35,12 +29,7 @@ export type { RecallScore } from './RecallScore'; export type { RecallScoreWeights } from './RecallScoreWeights'; export type { RecallTrace } from './RecallTrace'; export type { ResidencyHint } from './ResidencyHint'; -export type { ResidentPage } from './ResidentPage'; export type { TaskKind } from './TaskKind'; -export type { TierCapacity } from './TierCapacity'; -export type { TierError } from './TierError'; export type { TierRole } from './TierRole'; export type { TrajectoryHint } from './TrajectoryHint'; export type { TrustClass } from './TrustClass'; -export type { WorkingSet } from './WorkingSet'; -export type { WorkingSetCapacity } from './WorkingSetCapacity'; diff --git a/protocol/typescript/index.ts b/protocol/typescript/index.ts index 216e99526b..85f0a94a9b 100644 --- a/protocol/typescript/index.ts +++ b/protocol/typescript/index.ts @@ -144,7 +144,6 @@ export type { HardwareProfile } from './forge'; export type { PriorBaseline } from './forge'; export type { QuantTier } from './forge'; // genome: explicit exports (has duplicate types) -export type { AccessDenied } from './genome'; export type { AcquireSource } from './genome'; export type { ArtifactId } from './genome'; export type { ArtifactRef } from './genome'; @@ -154,20 +153,15 @@ export type { CompositionHint } from './genome'; export type { CompositionRef } from './genome'; export type { DomainHint } from './genome'; export type { EngramRef } from './genome'; -export type { EvictionPolicy } from './genome'; -export type { EvictionRecord } from './genome'; export type { FreshnessTarget } from './genome'; export type { LoRALayerRef } from './genome'; export type { MoEExpertRef } from './genome'; export type { OutcomeWindow } from './genome'; -export type { PageFault } from './genome'; -export type { PageHandle } from './genome'; export type { PageKind } from './genome'; export type { PageOffset } from './genome'; export type { PageRef } from './genome'; export type { PeerId } from './genome'; export type { PersonaId } from './genome'; -export type { Provenance } from './genome'; export type { RankedPool } from './genome'; export type { RecallBudget } from './genome'; export type { RecallContext } from './genome'; @@ -177,15 +171,10 @@ export type { RecallScore } from './genome'; export type { RecallScoreWeights } from './genome'; export type { RecallTrace } from './genome'; export type { ResidencyHint } from './genome'; -export type { ResidentPage } from './genome'; export type { TaskKind } from './genome'; -export type { TierCapacity } from './genome'; -export type { TierError } from './genome'; export type { TierRole } from './genome'; export type { TrajectoryHint } from './genome'; export type { TrustClass } from './genome'; -export type { WorkingSet } from './genome'; -export type { WorkingSetCapacity } from './genome'; // governor: explicit exports (has duplicate types) export type { CadenceMultipliers } from './governor'; export type { CascadeAction } from './governor'; diff --git a/protocol/typescript/persona/ActivateSkillResult.ts b/protocol/typescript/persona/ActivateSkillResult.ts deleted file mode 100644 index ebcb02e58c..0000000000 --- a/protocol/typescript/persona/ActivateSkillResult.ts +++ /dev/null @@ -1,27 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Result of a skill activation decision. - * Tells TypeScript what to load/unload — Rust decides, TS executes. - */ -export type ActivateSkillResult = { -/** - * Whether activation is proceeding - */ -activated: boolean, -/** - * Name of the adapter being activated - */ -adapter_name: string, -/** - * Adapters that must be unloaded first (in order) - */ -evicted: Array, -/** - * Adapter to load (None if already loaded / cache hit) - */ -to_load?: string, -/** - * How long the decision took (microseconds) - */ -decision_time_us: number, }; diff --git a/protocol/typescript/persona/CompactionMetadata.ts b/protocol/typescript/persona/CompactionMetadata.ts deleted file mode 100644 index 2a9dd2cf1c..0000000000 --- a/protocol/typescript/persona/CompactionMetadata.ts +++ /dev/null @@ -1,27 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Compaction metadata for plasticity-optimized adapters. - * When present, the adapter targets a compacted base model with fewer attention heads. - */ -export type CompactionMetadata = { -/** - * Fraction of parameters removed (e.g., 0.30 = 30% smaller base model) - */ -parameter_reduction: number, -/** - * Path to head_topology.json relative to adapter directory - */ -topology_path: string, -/** - * Whether the compacted base model weights exist alongside the adapter - */ -has_compacted_weights: boolean, -/** - * Original base model size in MB (before compaction) - */ -original_size_mb: number, -/** - * Compacted base model size in MB - */ -compacted_size_mb: number, }; diff --git a/protocol/typescript/persona/CoverageReport.ts b/protocol/typescript/persona/CoverageReport.ts deleted file mode 100644 index e8b915324a..0000000000 --- a/protocol/typescript/persona/CoverageReport.ts +++ /dev/null @@ -1,23 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { DomainActivity } from "./DomainActivity"; - -/** - * Coverage report: what's covered, what's missing. - */ -export type CoverageReport = { -/** - * Domains with trained adapters - */ -covered: Array, -/** - * Domains with activity but no adapter - */ -gaps: Array, -/** - * Total interactions across all domains - */ -total_interactions: number, -/** - * Ratio: covered_interactions / total_interactions - */ -coverage_ratio: number, }; diff --git a/protocol/typescript/persona/DomainActivity.ts b/protocol/typescript/persona/DomainActivity.ts deleted file mode 100644 index 1bd9f080d4..0000000000 --- a/protocol/typescript/persona/DomainActivity.ts +++ /dev/null @@ -1,34 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Activity tracking for a single domain. - */ -export type DomainActivity = { -/** - * Domain name - */ -domain: string, -/** - * Total interaction count - */ -interaction_count: number, -/** - * Successful interaction count - */ -success_count: number, -/** - * Failed interaction count - */ -failure_count: number, -/** - * Epoch ms of last activity - */ -last_activity_ms: number, -/** - * Whether this domain has a trained adapter - */ -has_adapter: boolean, -/** - * Adapter name if one exists - */ -adapter_name?: string, }; diff --git a/protocol/typescript/persona/GenomeAdapterInfo.ts b/protocol/typescript/persona/GenomeAdapterInfo.ts deleted file mode 100644 index bb3d89f042..0000000000 --- a/protocol/typescript/persona/GenomeAdapterInfo.ts +++ /dev/null @@ -1,40 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CompactionMetadata } from "./CompactionMetadata"; - -/** - * Per-adapter state for genome paging decisions. - * Extended from AdapterInfo with size_mb and last_used_ms for LRU. - */ -export type GenomeAdapterInfo = { -/** - * Adapter name (e.g. "typescript-expertise") - */ -name: string, -/** - * Skill domain (e.g. "code", "chat", "creative") - */ -domain: string, -/** - * Size in MB when loaded - */ -size_mb: number, -/** - * LRU priority (0.0-1.0, default 0.5). >0.9 = never evict. - */ -priority: number, -/** - * Whether this adapter is currently loaded in GPU memory - */ -is_loaded: boolean, -/** - * Epoch ms when last used (for LRU age calculation) - */ -last_used_ms: number, -/** - * Trained model name for inference (if available after LoRA fine-tuning) - */ -trained_model_name?: string, -/** - * Plasticity compaction metadata (present if adapter uses a compacted base model) - */ -compaction?: CompactionMetadata, }; diff --git a/protocol/typescript/persona/GenomePagingState.ts b/protocol/typescript/persona/GenomePagingState.ts deleted file mode 100644 index 473f4dbcba..0000000000 --- a/protocol/typescript/persona/GenomePagingState.ts +++ /dev/null @@ -1,27 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { GenomeAdapterInfo } from "./GenomeAdapterInfo"; - -/** - * Full genome paging state for a single persona. - */ -export type GenomePagingState = { -/** - * Soft memory budget in MB - */ -memory_budget_mb: number, -/** - * Current memory usage in MB - */ -memory_used_mb: number, -/** - * Memory pressure: used/budget (0.0-1.0) - */ -memory_pressure: number, -/** - * Adapters currently loaded in GPU - */ -active_adapters: Array, -/** - * Adapters available on disk but not loaded - */ -available_adapters: Array, }; diff --git a/protocol/typescript/persona/ModelSelectionRequest.ts b/protocol/typescript/persona/ModelSelectionRequest.ts index 70f09d8004..bc4554914b 100644 --- a/protocol/typescript/persona/ModelSelectionRequest.ts +++ b/protocol/typescript/persona/ModelSelectionRequest.ts @@ -9,11 +9,4 @@ export type ModelSelectionRequest = { persona_id: string, * Values: "code", "debug", "analysis", "creative", "art", "writing", * "support", "help", "social", "facts", "knowledge", "expertise" */ -task_domain?: string, -/** - * Optional free-text NEED ("refactor rust async code") — embedded by the - * command layer and matched by DISTANCE against each gene's minted - * signature (rung 0). Falls back to `task_domain`'s text when absent; when - * neither is present rung 0 is skipped and the keyword tiers answer. - */ -need?: string, }; +task_domain?: string, }; diff --git a/protocol/typescript/persona/ModelSelectionResult.ts b/protocol/typescript/persona/ModelSelectionResult.ts index e0853f7dac..6d0238e04e 100644 --- a/protocol/typescript/persona/ModelSelectionResult.ts +++ b/protocol/typescript/persona/ModelSelectionResult.ts @@ -20,11 +20,6 @@ adapter_name?: string, * Trait that matched (if tier 1). */ trait_used?: string, -/** - * Signature similarity that carried the pick (rung 0 only) — observability - * for the distance rung, absent on every other tier. - */ -similarity?: number, /** * How long the selection took (microseconds). */ diff --git a/protocol/typescript/persona/index.ts b/protocol/typescript/persona/index.ts index 980e1bebec..8d0b9953ed 100644 --- a/protocol/typescript/persona/index.ts +++ b/protocol/typescript/persona/index.ts @@ -2,7 +2,6 @@ // Source: generator/generate-rust-bindings.ts // Re-generate: npx tsx generator/generate-rust-bindings.ts -export type { ActivateSkillResult } from './ActivateSkillResult'; export type { ActivityDomain } from './ActivityDomain'; export type { AdapterInfo } from './AdapterInfo'; export type { AdequacyResult } from './AdequacyResult'; @@ -21,14 +20,11 @@ export type { ChannelStatus } from './ChannelStatus'; export type { ChatMessageRef } from './ChatMessageRef'; export type { CleanedResponse } from './CleanedResponse'; export type { CognitionDecision } from './CognitionDecision'; -export type { CompactionMetadata } from './CompactionMetadata'; export type { ConsolidatedContext } from './ConsolidatedContext'; export type { ConsolidatedInboxChunk } from './ConsolidatedInboxChunk'; export type { ConsolidatedInboxMessage } from './ConsolidatedInboxMessage'; export type { ConversationMessage } from './ConversationMessage'; -export type { CoverageReport } from './CoverageReport'; export type { DespawnReport } from './DespawnReport'; -export type { DomainActivity } from './DomainActivity'; export type { DomainClassification } from './DomainClassification'; export type { DrainTurnFrameParams } from './DrainTurnFrameParams'; export type { EdgeKind } from './EdgeKind'; @@ -41,8 +37,6 @@ export type { FullEvaluateResult } from './FullEvaluateResult'; export type { GarbageCheckResult } from './GarbageCheckResult'; export type { GarbageReason } from './GarbageReason'; export type { GateDetails } from './GateDetails'; -export type { GenomeAdapterInfo } from './GenomeAdapterInfo'; -export type { GenomePagingState } from './GenomePagingState'; export type { InboxMessage } from './InboxMessage'; export type { InboxTask } from './InboxTask'; export type { MediaItemRequest } from './MediaItemRequest';