diff --git a/crates/tracedecay-application/src/primitives/runtime.rs b/crates/tracedecay-application/src/primitives/runtime.rs index 55ed5f7351..b78e36c1e3 100644 --- a/crates/tracedecay-application/src/primitives/runtime.rs +++ b/crates/tracedecay-application/src/primitives/runtime.rs @@ -342,12 +342,6 @@ impl PrimitiveProjectRuntime { pub fn database(&self) -> &Database { &self.database } - - /// Releases the project database, dispatch, and all Arc-backed - /// primitive authorities as one teardown unit. - pub fn teardown(self) { - drop(self); - } } impl PrimitiveDispatch for OwnedPrimitiveRuntime { diff --git a/crates/tracedecay-automation-runtime/src/automation/session_reflector.rs b/crates/tracedecay-automation-runtime/src/automation/session_reflector.rs index 735f5fa528..b3cf56a682 100644 --- a/crates/tracedecay-automation-runtime/src/automation/session_reflector.rs +++ b/crates/tracedecay-automation-runtime/src/automation/session_reflector.rs @@ -446,8 +446,8 @@ fn session_fact_category(category: &str) -> Option { /// Accepts numeric trust in `[0, 1]` plus the `low`/`medium`/`high` bucket /// labels models frequently emit despite the numeric prompt instruction. -/// Buckets map to the representative scores defined next to -/// [`tracedecay_session_memory::memory::trust::trust_bucket`], so they cannot drift out of their +/// Buckets map to the representative scores in +/// [`tracedecay_session_memory::memory::trust`], so they cannot drift out of their /// documented ranges. /// /// Deliberate decision: the prompt forbids string labels, but they are diff --git a/crates/tracedecay-code-index/src/chunks.rs b/crates/tracedecay-code-index/src/chunks.rs index 15fd1f44b0..200d8572c7 100644 --- a/crates/tracedecay-code-index/src/chunks.rs +++ b/crates/tracedecay-code-index/src/chunks.rs @@ -585,13 +585,6 @@ impl DeterministicCodeChunker { } } - /// Pin the sensitivity level recorded on every chunk of this generation. - #[must_use] - pub fn with_sensitivity_level(mut self, level: SensitivityLevelV1) -> Self { - self.sensitivity_level = level; - self - } - /// The generation this chunker is bound to. pub fn generation_id(&self) -> &CodeGenerationId { &self.generation_id diff --git a/crates/tracedecay-contracts/src/external_source.rs b/crates/tracedecay-contracts/src/external_source.rs index 3565860310..874600b9a9 100644 --- a/crates/tracedecay-contracts/src/external_source.rs +++ b/crates/tracedecay-contracts/src/external_source.rs @@ -274,14 +274,6 @@ impl SourceCanonicalRefetchAuthorityV1 { self.binding == *refresh.binding() && self.original_refresh_digest == *refresh.receipt_digest() } - - /// Reports whether this opaque capability names the exact refresh. - /// - /// The capability still exposes no binding fields or constructor, so a - /// provider or transport cannot mint or retarget it. - pub fn authorizes(&self, refresh: &SourceRefreshReceiptV1) -> bool { - self.matches(refresh) - } } #[derive(Clone, Debug)] diff --git a/crates/tracedecay-domain/src/configuration/topology.rs b/crates/tracedecay-domain/src/configuration/topology.rs index ace8747122..2084581a8f 100644 --- a/crates/tracedecay-domain/src/configuration/topology.rs +++ b/crates/tracedecay-domain/src/configuration/topology.rs @@ -348,16 +348,6 @@ pub enum BranchNameSeparatorV1 { Slash, } -impl BranchNameSeparatorV1 { - pub const fn as_char(self) -> char { - match self { - Self::Hyphen => '-', - Self::Underscore => '_', - Self::Slash => '/', - } - } -} - #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case", tag = "kind")] pub enum BranchCollisionPolicyV1 { diff --git a/crates/tracedecay-domain/src/feedback/proximity.rs b/crates/tracedecay-domain/src/feedback/proximity.rs index b6077d04d3..b93d341cf9 100644 --- a/crates/tracedecay-domain/src/feedback/proximity.rs +++ b/crates/tracedecay-domain/src/feedback/proximity.rs @@ -191,20 +191,6 @@ impl ProximityContributionV1 { observed_at.0 >= self.expires_at.0 } - /// Records presentation suppression without discarding the evidence, - /// threshold provenance, or expiry that produced the duplicate warning. - pub fn suppressed_duplicate(mut self) -> Result { - self.validate()?; - if self.inclusion != ProximityInclusionV1::Included { - return Err(DomainError::NonCanonical { - field: "proximity duplicate suppression input", - }); - } - self.inclusion = ProximityInclusionV1::SuppressedDuplicate; - self.validate()?; - Ok(self) - } - pub fn validate(&self) -> Result<(), DomainError> { self.contribution_id.validate()?; self.warning_id.validate()?; diff --git a/crates/tracedecay-domain/src/git/read_model.rs b/crates/tracedecay-domain/src/git/read_model.rs index 726f9c168c..600cf0bba9 100644 --- a/crates/tracedecay-domain/src/git/read_model.rs +++ b/crates/tracedecay-domain/src/git/read_model.rs @@ -65,15 +65,6 @@ pub enum GitObjectFormatV1 { Sha256, } -impl GitObjectFormatV1 { - pub const fn oid_hex_len(self) -> usize { - match self { - Self::Sha1 => 40, - Self::Sha256 => 64, - } - } -} - fn validate_git_oid(value: &str, field: &'static str) -> Result<(), DomainError> { if value.is_empty() { return Err(DomainError::Empty { field }); diff --git a/crates/tracedecay-domain/src/research/watermark.rs b/crates/tracedecay-domain/src/research/watermark.rs index 2bcb1b50a7..14cf5a2e0f 100644 --- a/crates/tracedecay-domain/src/research/watermark.rs +++ b/crates/tracedecay-domain/src/research/watermark.rs @@ -29,17 +29,6 @@ impl VectorWatermark { (false, false) => None, } } - - pub fn merge_max(&self, other: &Self) -> Self { - let mut components = self.components.clone(); - for (shard, sequence) in &other.components { - components - .entry(shard.clone()) - .and_modify(|current| *current = (*current).max(*sequence)) - .or_insert(*sequence); - } - Self { components } - } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/crates/tracedecay-global-db/src/profile_registry_maintenance.rs b/crates/tracedecay-global-db/src/profile_registry_maintenance.rs index 1d7a4cf163..fcf85b277b 100644 --- a/crates/tracedecay-global-db/src/profile_registry_maintenance.rs +++ b/crates/tracedecay-global-db/src/profile_registry_maintenance.rs @@ -10,8 +10,6 @@ use std::path::{Component, Path, PathBuf}; use crate::{ ProjectRegistryContext, RegisteredGlobalDb, RegisteredGlobalDbLeaseV1, registry_maintenance::ForgetRegistryProjectRows, registry_maintenance::RegistryGcReport, - registry_maintenance::RegistryOrphanRelinkApplyReport, - registry_maintenance::RegistryOrphanRelinkReport, registry_maintenance::forget_registry_project, }; @@ -246,18 +244,6 @@ impl ProfileRegistryMaintenanceRuntime { }) } - #[hotpath::measure(label = "daemon.profile_registry.apply_orphan_relink", future = true)] - pub async fn apply_orphan_relink( - &self, - report: &RegistryOrphanRelinkReport, - ) -> std::result::Result> { - crate::registry_maintenance::apply_registry_orphan_relink_report( - self.profile_database.as_ref(), - report, - ) - .await - } - #[hotpath::measure(label = "daemon.profile_registry.gc", future = true)] pub async fn registry_gc( &self, diff --git a/crates/tracedecay-global-db/src/registered_lcm.rs b/crates/tracedecay-global-db/src/registered_lcm.rs index d19382697a..982d5484cf 100644 --- a/crates/tracedecay-global-db/src/registered_lcm.rs +++ b/crates/tracedecay-global-db/src/registered_lcm.rs @@ -497,35 +497,6 @@ impl RegisteredGlobalDb { Ok((work, has_more)) } - #[hotpath::skip] - pub async fn lcm_payload_health_detail( - &self, - storage_root: &Path, - provider: &str, - session_id: Option<&str>, - deep: bool, - sample_limit: usize, - cfg: &LcmGcConfig, - ) -> Result { - SessionStoreAccess::new(self) - .lcm_payload_health_detail(storage_root, provider, session_id, deep, sample_limit, cfg) - .await - } - - #[hotpath::skip] - pub async fn lcm_preview_payload_gc( - &self, - storage_root: &Path, - provider: &str, - session_id: Option<&str>, - cfg: &LcmGcConfig, - now: i64, - ) -> Result { - SessionStoreAccess::new(self) - .lcm_preview_payload_gc(storage_root, provider, session_id, cfg, now) - .await - } - #[hotpath::skip] pub async fn lcm_run_payload_gc_apply( &self, diff --git a/crates/tracedecay-global-db/src/registry_maintenance.rs b/crates/tracedecay-global-db/src/registry_maintenance.rs index 360e007303..a0665d2685 100644 --- a/crates/tracedecay-global-db/src/registry_maintenance.rs +++ b/crates/tracedecay-global-db/src/registry_maintenance.rs @@ -1,4 +1,4 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use std::fs; use std::path::{Component, Path, PathBuf}; @@ -9,7 +9,6 @@ use crate::{ RegisteredGlobalDbWriteTransaction, StoreArtifactUpsert, StoreInstanceUpsert, }; use tracedecay_runtime_core::branch_meta; -use tracedecay_runtime_core::db::engine::{Executor, IntoParams, QueryExecutor, params}; use tracedecay_runtime_core::storage::{ STORE_MANIFEST_FILENAME, STORE_MANIFEST_SCHEMA_VERSION, StorageMode, StoreKind, read_legacy_enrollment_marker, read_repository_identity_marker, read_store_manifest, @@ -56,15 +55,6 @@ pub struct RegistryOrphanRelinkReport { pub issues: Vec, } -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] -pub struct RegistryOrphanRelinkApplyReport { - pub projects: usize, - pub aliases: usize, - pub stores: usize, - pub graph_scopes: usize, - pub artifacts: usize, -} - /// Canonical read-only plan returned by the daemon and consumed by the /// `registry-gc` CLI. Apply fills only the deletion counters after executing /// the same plan under the active database mutation authority. @@ -95,320 +85,11 @@ impl RegistryGcReport { } } -fn encode_registry_identity( - value: &T, - label: impl std::fmt::Display, -) -> std::result::Result { - serde_json::to_string(value).map_err(|error| format!("could not encode {label}: {error}")) -} - -#[hotpath::measure(future = true, label = "global_db.registry_maintenance.persist")] -pub async fn apply_registry_orphan_relink_report( - db: &RegisteredGlobalDb, - report: &RegistryOrphanRelinkReport, -) -> std::result::Result> { - let transaction = db.begin_write_transaction().await.map_err(|error| { - vec![format!( - "could not start atomic registry orphan relink: {error}" - )] - })?; - let issues = preflight_registry_orphan_relink(&transaction, report).await; - if !issues.is_empty() { - return Err(issues); - } - let applied = apply_registry_orphan_relink_rows(&transaction, report) - .await - .map_err(|issue| vec![issue])?; - transaction.commit().await.map_err(|error| { - vec![format!( - "could not commit atomic registry orphan relink: {error}" - )] - })?; - Ok(applied) -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests; -pub async fn apply_single_registry_orphan_relink_report( - db: &RegisteredGlobalDb, - report: &RegistryOrphanRelinkReport, -) -> std::result::Result> { - let [plan] = report.plans.as_slice() else { - return Err(vec![format!( - "migration cutover requires exactly one registry orphan relink plan, found {}", - report.plans.len() - )]); - }; - if plan.status != RegistryOrphanRelinkStatus::Eligible { - return Err(vec![format!( - "migration cutover registry orphan relink plan for '{}' is {:?}: {}", - plan.project.project_id, - plan.status, - plan.status_reason.as_deref().unwrap_or("not eligible") - )]); - } - apply_registry_orphan_relink_report(db, report).await -} - -async fn preflight_registry_orphan_relink( - conn: &Q, - report: &RegistryOrphanRelinkReport, -) -> Vec -where - Q: QueryExecutor + ?Sized, -{ - let mut issues = report.issues.clone(); - let mut project_roots = BTreeMap::::new(); - let mut aliases = BTreeMap::::new(); - let mut stores = BTreeMap::::new(); - let mut store_paths = BTreeMap::::new(); - let mut scopes = BTreeMap::::new(); - let mut scope_paths = BTreeMap::::new(); - - for plan in &report.plans { - match plan.status { - RegistryOrphanRelinkStatus::Eligible => {} - RegistryOrphanRelinkStatus::Stale | RegistryOrphanRelinkStatus::Retired => { - continue; - } - RegistryOrphanRelinkStatus::Blocked => { - issues.push(format!( - "{} reconstruction plan for '{}' is blocked: {}", - plan.manifest_path.display(), - plan.project.project_id, - plan.status_reason.as_deref().unwrap_or("not eligible") - )); - continue; - } - } - let project = &plan.project; - let root = RegisteredGlobalDb::canonical_project_key(&project.project_root); - let root_alias = RegisteredGlobalDb::project_path_alias_key(&project.project_root); - record_batch_owner( - &mut project_roots, - &root_alias, - &project.project_id, - "canonical project root", - &mut issues, - ); - match query_optional_text( - conn, - "SELECT canonical_root FROM code_projects WHERE project_id=?1", - params![project.project_id.as_str()], - ) - .await - { - Ok(Some(existing)) if existing != root => issues.push(format!( - "project '{}' already owns canonical root '{}' instead of '{}'", - project.project_id, existing, root - )), - Err(error) => issues.push(error), - _ => {} - } - match query_all_text( - conn, - "SELECT project_id FROM project_aliases WHERE alias_path=?1", - params![root_alias.as_str()], - ) - .await - { - Ok(owners) => { - for owner in owners { - if owner != project.project_id { - issues.push(format!( - "canonical root '{root}' is already owned by project '{owner}'" - )); - } - } - } - Err(error) => issues.push(error), - } - for alias in &project.aliases { - let alias = RegisteredGlobalDb::project_path_alias_key(alias); - record_batch_owner( - &mut aliases, - &alias, - &project.project_id, - "project alias", - &mut issues, - ); - match query_optional_text( - conn, - "SELECT project_id FROM project_aliases WHERE alias_path=?1", - params![alias.as_str()], - ) - .await - { - Ok(Some(owner)) if owner != project.project_id => issues.push(format!( - "alias '{alias}' is already owned by project '{owner}'" - )), - Err(error) => issues.push(error), - _ => {} - } - } - - let store_identity = match encode_registry_identity( - &( - &plan.store.project_id, - &plan.store.store_kind, - &plan.store.storage_mode, - &plan.store.store_relpath, - &plan.store.manifest_relpath, - ), - format!("store '{}'", plan.store.store_id), - ) { - Ok(identity) => identity, - Err(error) => { - issues.push(error); - continue; - } - }; - record_batch_owner( - &mut stores, - &plan.store.store_id, - &store_identity, - "store id", - &mut issues, - ); - match query_optional_text( - conn, - "SELECT json_array(project_id, store_kind, storage_mode, store_relpath, manifest_relpath) - FROM store_instances WHERE store_id=?1", - params![plan.store.store_id.as_str()], - ) - .await - { - Ok(Some(existing)) if existing != store_identity => issues.push(format!( - "store '{}' already has conflicting ownership or location", - plan.store.store_id - )), - Err(error) => issues.push(error), - _ => {} - } - for physical_path in std::iter::once(plan.store.store_relpath.as_str()) - .chain(plan.store.manifest_relpath.as_deref()) - { - record_batch_owner( - &mut store_paths, - physical_path, - &plan.store.store_id, - "physical store path", - &mut issues, - ); - match query_all_text( - conn, - "SELECT store_id FROM store_instances - WHERE store_relpath=?1 OR manifest_relpath=?1", - params![physical_path], - ) - .await - { - Ok(owners) => { - for owner in owners { - if owner != plan.store.store_id { - issues.push(format!( - "physical store path '{physical_path}' is already owned by store '{owner}'" - )); - } - } - } - Err(error) => issues.push(error), - } - } - - for scope in &plan.graph_scopes { - let scope_identity = match encode_registry_identity( - &( - &scope.project_id, - &scope.store_id, - &scope.branch_name, - &scope.db_relpath, - &scope.parent_scope_id, - ), - format!("graph scope '{}'", scope.graph_scope_id), - ) { - Ok(identity) => identity, - Err(error) => { - issues.push(error); - continue; - } - }; - record_batch_owner( - &mut scopes, - &scope.graph_scope_id, - &scope_identity, - "graph scope id", - &mut issues, - ); - match query_optional_text( - conn, - "SELECT json_array(project_id, store_id, branch_name, db_relpath, parent_scope_id) - FROM graph_scopes WHERE graph_scope_id=?1", - params![scope.graph_scope_id.as_str()], - ) - .await - { - Ok(Some(existing)) - if existing != scope_identity - && !graph_scope_location_drift_is_repairable(&existing, scope) => - { - issues.push(format!( - "graph scope '{}' already has conflicting ownership", - scope.graph_scope_id - )); - } - Err(error) => issues.push(error), - _ => {} - } - record_batch_owner( - &mut scope_paths, - &scope.db_relpath, - &scope.graph_scope_id, - "physical graph database path", - &mut issues, - ); - match query_all_text( - conn, - "SELECT graph_scope_id FROM graph_scopes WHERE db_relpath=?1", - params![scope.db_relpath.as_str()], - ) - .await - { - Ok(owners) => { - for owner in owners { - if owner != scope.graph_scope_id { - issues.push(format!( - "physical graph database path '{}' is already owned by scope '{}'", - scope.db_relpath, owner - )); - } - } - } - Err(error) => issues.push(error), - } - } - } - issues -} - -fn record_batch_owner( - owners: &mut BTreeMap, - key: &str, - owner: &str, - label: &str, - issues: &mut Vec, -) { - if let Some(existing) = owners.insert(key.to_string(), owner.to_string()) - && existing != owner - { - issues.push(format!( - "{label} '{key}' has conflicting batch owners '{existing}' and '{owner}'" - )); - } -} - +#[cfg(test)] fn graph_scope_location_drift_is_repairable(existing: &str, expected: &GraphScopeUpsert) -> bool { serde_json::from_str::<(String, String, String, String, Option)>(existing).is_ok_and( |(project_id, store_id, branch_name, _, _)| { @@ -418,180 +99,3 @@ fn graph_scope_location_drift_is_repairable(existing: &str, expected: &GraphScop }, ) } - -async fn query_optional_text( - conn: &Q, - sql: &str, - params: P, -) -> std::result::Result, String> -where - Q: QueryExecutor + ?Sized, - P: IntoParams, -{ - let mut rows = conn - .query(sql, params) - .await - .map_err(|error| format!("registry orphan relink preflight query failed: {error}"))?; - rows.next() - .await - .map_err(|error| format!("registry orphan relink preflight row failed: {error}"))? - .map(|row| { - row.get::(0) - .map_err(|error| format!("registry orphan relink preflight value failed: {error}")) - }) - .transpose() -} - -async fn query_all_text( - conn: &Q, - sql: &str, - params: P, -) -> std::result::Result, String> -where - Q: QueryExecutor + ?Sized, - P: IntoParams, -{ - let mut rows = conn - .query(sql, params) - .await - .map_err(|error| format!("registry orphan relink preflight query failed: {error}"))?; - let mut values = Vec::new(); - while let Some(row) = rows - .next() - .await - .map_err(|error| format!("registry orphan relink preflight row failed: {error}"))? - { - values.push( - row.get::(0).map_err(|error| { - format!("registry orphan relink preflight value failed: {error}") - })?, - ); - } - Ok(values) -} - -async fn apply_registry_orphan_relink_rows( - conn: &E, - report: &RegistryOrphanRelinkReport, -) -> std::result::Result -where - E: Executor + ?Sized, -{ - let mut applied = RegistryOrphanRelinkApplyReport::default(); - let now = tracedecay_runtime_core::tracedecay::current_timestamp(); - for plan in &report.plans { - if plan.status != RegistryOrphanRelinkStatus::Eligible { - continue; - } - let project = &plan.project; - let canonical_root = RegisteredGlobalDb::canonical_project_key(&project.project_root); - applied.projects += usize::try_from( - conn.execute( - "INSERT OR IGNORE INTO code_projects( - project_id, canonical_root, display_root, git_common_dir, git_remote_url, - default_branch, created_at, last_seen_at - ) VALUES(?1, ?2, ?3, NULL, NULL, ?4, ?5, ?5)", - params![ - project.project_id.as_str(), - canonical_root, - project.project_root.to_string_lossy().to_string(), - project.default_branch.as_deref(), - now, - ], - ) - .await - .map_err(|error| format!("failed to insert code project: {error}"))?, - ) - .unwrap_or(usize::MAX); - for alias in &project.aliases { - applied.aliases += usize::try_from( - conn.execute( - "INSERT OR IGNORE INTO project_aliases(alias_path, project_id, last_seen_at) - VALUES(?1, ?2, ?3)", - params![ - RegisteredGlobalDb::project_path_alias_key(alias), - project.project_id.as_str(), - now, - ], - ) - .await - .map_err(|error| format!("failed to insert project alias: {error}"))?, - ) - .unwrap_or(usize::MAX); - } - applied.stores += usize::try_from( - conn.execute( - "INSERT OR IGNORE INTO store_instances( - store_id, project_id, store_kind, storage_mode, store_relpath, - manifest_relpath, created_at, last_verified_at, last_write_at - ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", - params![ - plan.store.store_id.as_str(), - plan.store.project_id.as_str(), - plan.store.store_kind.as_str(), - plan.store.storage_mode.as_str(), - plan.store.store_relpath.as_str(), - plan.store.manifest_relpath.as_deref(), - now, - plan.store.last_verified_at, - plan.store.last_write_at, - ], - ) - .await - .map_err(|error| format!("failed to insert store instance: {error}"))?, - ) - .unwrap_or(usize::MAX); - for scope in &plan.graph_scopes { - applied.graph_scopes += usize::try_from( - conn.execute( - "INSERT INTO graph_scopes( - graph_scope_id, project_id, store_id, branch_name, db_relpath, - parent_scope_id, last_synced_at, writable - ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) - ON CONFLICT(graph_scope_id) DO UPDATE SET - project_id = excluded.project_id, - store_id = excluded.store_id, - branch_name = excluded.branch_name, - db_relpath = excluded.db_relpath, - parent_scope_id = excluded.parent_scope_id, - last_synced_at = excluded.last_synced_at, - writable = excluded.writable", - params![ - scope.graph_scope_id.as_str(), - scope.project_id.as_str(), - scope.store_id.as_str(), - scope.branch_name.as_str(), - scope.db_relpath.as_str(), - scope.parent_scope_id.as_deref(), - scope.last_synced_at, - i64::from(scope.writable), - ], - ) - .await - .map_err(|error| format!("failed to insert graph scope: {error}"))?, - ) - .unwrap_or(usize::MAX); - } - for artifact in &plan.artifacts { - applied.artifacts += usize::try_from( - conn.execute( - "INSERT OR IGNORE INTO store_artifacts( - store_id, artifact_kind, relpath, size_bytes, schema_version, updated_at - ) VALUES(?1, ?2, ?3, ?4, ?5, ?6)", - params![ - artifact.store_id.as_str(), - artifact.artifact_kind.as_str(), - artifact.relpath.as_str(), - artifact.size_bytes, - artifact.schema_version.as_deref(), - artifact.updated_at, - ], - ) - .await - .map_err(|error| format!("failed to insert store artifact: {error}"))?, - ) - .unwrap_or(usize::MAX); - } - } - Ok(applied) -} diff --git a/crates/tracedecay-global-db/src/stack_delivery.rs b/crates/tracedecay-global-db/src/stack_delivery.rs index ffedfbeb15..1e0df42ad0 100644 --- a/crates/tracedecay-global-db/src/stack_delivery.rs +++ b/crates/tracedecay-global-db/src/stack_delivery.rs @@ -118,11 +118,6 @@ pub enum GitHubStackSignalAppendOutcomeV1 { } impl GitHubStackSignalAppendOutcomeV1 { - #[hotpath::skip] - pub const fn is_saturated(&self) -> bool { - matches!(self, Self::Saturated { .. }) - } - #[hotpath::skip] pub const fn pending_count(&self) -> usize { match self { diff --git a/crates/tracedecay-global-db/src/transcript.rs b/crates/tracedecay-global-db/src/transcript.rs index 811eb42268..53e1b6f633 100644 --- a/crates/tracedecay-global-db/src/transcript.rs +++ b/crates/tracedecay-global-db/src/transcript.rs @@ -1,4 +1,4 @@ -use super::{ParseOffset, RegisteredGlobalDb, TranscriptBatch}; +use super::{ParseOffset, RegisteredGlobalDb}; use tracedecay_sessions::runtime::{ SessionMessageRecord, SessionRecord, SessionStoreAccess, TranscriptGitEvidence, TranscriptPersistenceError, @@ -102,21 +102,6 @@ impl RegisteredGlobalDb { .await } - #[hotpath::measure( - future = true, - label = "global_db.transcript.upsert_projection_batches" - )] - pub async fn upsert_transcript_projection_batches( - &self, - batches: &[TranscriptBatch], - parse_offset_path: &str, - parse_offset: ParseOffset, - ) -> Result<(), String> { - SessionStoreAccess::new(self) - .upsert_transcript_projection_batches(batches, parse_offset_path, parse_offset) - .await - } - #[hotpath::measure(future = true, label = "global_db.transcript.get_parse_offset")] pub async fn get_parse_offset(&self, path: &str) -> Option { SessionStoreAccess::new(self).get_parse_offset(path).await diff --git a/crates/tracedecay-graph-query/src/lib.rs b/crates/tracedecay-graph-query/src/lib.rs index 589e76be45..b92432a60b 100644 --- a/crates/tracedecay-graph-query/src/lib.rs +++ b/crates/tracedecay-graph-query/src/lib.rs @@ -32,7 +32,7 @@ pub use projection::{ request_graph_cancellation, }; pub use queries::{ - FileAdjacencyScan, GraphQueryManager, NodeMetrics, VerifiedHealthFileAggregateV1, + FileAdjacencyScan, GraphQueryManager, VerifiedHealthFileAggregateV1, }; #[cfg(any(test, feature = "test-helpers"))] pub use verified_query::admitted_verified_graph_query_port; diff --git a/crates/tracedecay-graph-query/src/queries.rs b/crates/tracedecay-graph-query/src/queries.rs index 4addc3d0f3..854403dbe7 100644 --- a/crates/tracedecay-graph-query/src/queries.rs +++ b/crates/tracedecay-graph-query/src/queries.rs @@ -28,16 +28,6 @@ const HEALTH_EDGE_KINDS: [RelationEdgeKindV1; 8] = [ RelationEdgeKindV1::Annotates, ]; -#[derive(Debug, Clone)] -pub struct NodeMetrics { - pub incoming_edge_count: usize, - pub outgoing_edge_count: usize, - pub call_count: usize, - pub caller_count: usize, - pub child_count: usize, - pub depth: usize, -} - #[derive(Debug)] pub struct FileAdjacencyScan { pub adjacency: HashMap>, @@ -287,59 +277,6 @@ impl<'a> GraphQueryManager<'a> { Ok(dead) } - #[hotpath::measure(label = "usecases.graph.node_metrics", future = true)] - pub async fn get_node_metrics(&self, node_id: &str) -> Result { - let occurrence = SymbolOccurrenceId::new(node_id.to_owned()).map_err(|error| { - TraceDecayError::Config { - message: error.to_string(), - } - })?; - let counts = self - .reader - .edge_kind_counts(&occurrence, Arc::clone(&self.cancellation)) - .map_err(|error| { - super::map_code_graph_read_runtime_error(map_projection_error(error)) - })?; - let incoming_edge_count = - usize::try_from(counts.incoming.values().sum::()).unwrap_or(usize::MAX); - let outgoing_edge_count = - usize::try_from(counts.outgoing.values().sum::()).unwrap_or(usize::MAX); - Ok(NodeMetrics { - incoming_edge_count, - outgoing_edge_count, - call_count: usize::try_from( - counts - .outgoing - .get(&RelationEdgeKindV1::Calls) - .copied() - .unwrap_or(0), - ) - .unwrap_or(usize::MAX), - caller_count: usize::try_from( - counts - .incoming - .get(&RelationEdgeKindV1::Calls) - .copied() - .unwrap_or(0), - ) - .unwrap_or(usize::MAX), - child_count: usize::try_from( - counts - .outgoing - .get(&RelationEdgeKindV1::Contains) - .copied() - .unwrap_or(0), - ) - .unwrap_or(usize::MAX), - depth: 0, - }) - } - - #[hotpath::measure(label = "usecases.graph.file_dependencies", future = true)] - pub async fn get_file_dependencies(&self, file_path: &str) -> Result> { - self.file_neighbors(file_path, false) - } - #[hotpath::measure(label = "usecases.graph.file_dependents", future = true)] pub async fn get_file_dependents(&self, file_path: &str) -> Result> { self.file_neighbors(file_path, true) @@ -578,36 +515,6 @@ impl<'a> GraphQueryManager<'a> { }) } - #[hotpath::measure(label = "usecases.graph.health_file_aggregates", future = true)] - pub async fn health_file_aggregates( - &self, - path_prefix: Option<&str>, - ) -> Result> { - let logical_paths = match path_prefix { - Some(prefix) => Some( - self.reader - .files(MAX_ANALYTICAL_SYMBOLS, Arc::clone(&self.cancellation)) - .map_err(|error| { - super::map_code_graph_read_runtime_error(map_projection_error(error)) - })? - .into_iter() - .map(|file| file.logical_path) - .filter(|path| path_is_within(path, prefix)) - .collect::>(), - ), - None => None, - }; - let (symbols, edges, external_test_markers) = - self.health_evidence(logical_paths.as_ref())?; - let metadata = health_symbol_metadata(&symbols)?; - Ok(fold_health_aggregates( - metadata, - &edges, - external_test_markers, - path_prefix, - )) - } - /// Health symbols, the induced edge set, and the test markers only the /// scoped `callers` walk can see: its far endpoints legitimately sit /// outside the scoped symbol census, so their marker metadata cannot be diff --git a/crates/tracedecay-graph-query/src/verified_query.rs b/crates/tracedecay-graph-query/src/verified_query.rs index 1978b8144d..774e84fc2d 100644 --- a/crates/tracedecay-graph-query/src/verified_query.rs +++ b/crates/tracedecay-graph-query/src/verified_query.rs @@ -23,7 +23,7 @@ use tracedecay_domain::{ }; use tracedecay_graph_db::GraphCancellation; -use super::queries::{GraphQueryManager, NodeMetrics, VerifiedHealthFileAggregateV1}; +use super::queries::GraphQueryManager; use super::source_authority::{ AdmittedSourceAuthority, graph_source_scope_mismatch, graph_source_unbound, }; @@ -298,27 +298,6 @@ impl VerifiedGraphQuery { .await } - #[hotpath::measure(label = "usecases.graph.verified.file_dependencies", future = true)] - pub async fn get_file_dependencies(&self, file_path: &str) -> Result> { - self.await_bound(self.manager().get_file_dependencies(file_path)) - .await - } - - #[hotpath::measure(label = "usecases.graph.verified.node_metrics", future = true)] - pub async fn get_node_metrics(&self, node_id: &str) -> Result { - self.await_bound(self.manager().get_node_metrics(node_id)) - .await - } - - #[hotpath::measure(label = "usecases.graph.verified.health_aggregates", future = true)] - pub async fn health_file_aggregates( - &self, - path_prefix: Option<&str>, - ) -> Result> { - self.await_bound(self.manager().health_file_aggregates(path_prefix)) - .await - } - #[hotpath::measure(label = "usecases.graph.verified.health_snapshot", future = true)] pub async fn verified_health_snapshot( &self, diff --git a/crates/tracedecay-lsp/src/compile_diagnostics/cache.rs b/crates/tracedecay-lsp/src/compile_diagnostics/cache.rs index 4963339652..ec53e0b99d 100644 --- a/crates/tracedecay-lsp/src/compile_diagnostics/cache.rs +++ b/crates/tracedecay-lsp/src/compile_diagnostics/cache.rs @@ -31,6 +31,7 @@ struct CachedDiagnostics { #[derive(Debug, Clone, PartialEq, Eq)] enum DiagnosticsCacheRevision { + #[cfg(test)] WorkspaceChange(u64), Recovery(DiagnosticsFingerprint), } @@ -100,25 +101,6 @@ impl DiagnosticsCache { .await } - /// Run diagnostics under the code index's worktree-change authority. - /// - /// A generation is exactly as fresh as the index used by search: hook - /// hints and Git metadata changes are observed immediately, while other - /// out-of-band edits are observed by the 30-second stat-signature ladder. - /// Until that ladder runs, diagnostics intentionally reuse the preceding - /// generation rather than deriving a second workspace-change authority. - pub async fn run_for_generation( - &self, - project_root: &Path, - scope: &Scope, - generation: u64, - ) -> Result> { - self.run_with_generation(project_root, scope, generation, || { - run_all(project_root, scope) - }) - .await - } - #[hotpath::measure(label = "compile_diagnostics.cache.run", future = true)] pub(crate) async fn run_with( &self, @@ -157,6 +139,7 @@ impl DiagnosticsCache { .await } + #[cfg(test)] pub(crate) async fn run_with_generation( &self, project_root: &Path, diff --git a/crates/tracedecay-maintenance/src/retention/orphan_stores.rs b/crates/tracedecay-maintenance/src/retention/orphan_stores.rs index 817a26cdb2..e374c02427 100644 --- a/crates/tracedecay-maintenance/src/retention/orphan_stores.rs +++ b/crates/tracedecay-maintenance/src/retention/orphan_stores.rs @@ -240,15 +240,6 @@ pub struct CollectionPlan { pub unverifiable: Vec, } -impl CollectionPlan { - /// Total bytes that collecting [`Self::collect`] would reclaim. - pub fn collectable_bytes(&self) -> u64 { - self.collect - .iter() - .fold(0u64, |acc, f| acc.saturating_add(f.size_bytes)) - } -} - /// Partition findings under a retention window. Live stores are dropped from /// the plan entirely, they are never a retention concern. Pure. pub fn plan_collection(findings: Vec, retention_secs: i64) -> CollectionPlan { diff --git a/crates/tracedecay-maintenance/src/retention/orphan_stores/pages.rs b/crates/tracedecay-maintenance/src/retention/orphan_stores/pages.rs index e6b2b1fa04..328395e94b 100644 --- a/crates/tracedecay-maintenance/src/retention/orphan_stores/pages.rs +++ b/crates/tracedecay-maintenance/src/retention/orphan_stores/pages.rs @@ -586,15 +586,6 @@ pub struct UnregisteredCollectionPlan { pub retained_immature: Vec, } -impl UnregisteredCollectionPlan { - /// Total bytes that collecting [`Self::collect`] would reclaim. - pub fn collectable_bytes(&self) -> u64 { - self.collect - .iter() - .fold(0u64, |acc, f| acc.saturating_add(f.size_bytes)) - } -} - /// Partition findings under a retention window. Pure. pub fn plan_unregistered_collection( findings: Vec, diff --git a/crates/tracedecay-project/Cargo.toml b/crates/tracedecay-project/Cargo.toml index 6fccb31a3c..93915b47fb 100644 --- a/crates/tracedecay-project/Cargo.toml +++ b/crates/tracedecay-project/Cargo.toml @@ -40,7 +40,7 @@ test-helpers = [ ] # Mirrors the composition root's `test-transport`: the standalone -# `TraceDecay::init` / `open` / `open_read_only` entry points route through +# `TraceDecay::init` / `open` / `open_read_only_with_options` entry points route through # the registered test runtime instead of the exclusive maintenance lease. test-transport = [ "test-helpers", diff --git a/crates/tracedecay-project/src/project/lifecycle/mod.rs b/crates/tracedecay-project/src/project/lifecycle/mod.rs index 5812e816f5..b89dae280b 100644 --- a/crates/tracedecay-project/src/project/lifecycle/mod.rs +++ b/crates/tracedecay-project/src/project/lifecycle/mod.rs @@ -713,11 +713,6 @@ impl TraceDecay { /// sentinels, clear markers, or rewrite corrupted DBs. It is intended for /// status/verification commands that must be able to inspect read-only /// stores without mutating them. - #[hotpath::skip] - pub async fn open_read_only(project_root: &Path) -> Result { - Self::open_read_only_with_options(project_root, TraceDecayOpenOptions::default()).await - } - #[hotpath::skip] pub async fn open_read_only_with_options( project_root: &Path, diff --git a/crates/tracedecay-project/src/test_support/host_admission/profile_registry_test_support.rs b/crates/tracedecay-project/src/test_support/host_admission/profile_registry_test_support.rs index 688dedc544..8fed6e5cc8 100644 --- a/crates/tracedecay-project/src/test_support/host_admission/profile_registry_test_support.rs +++ b/crates/tracedecay-project/src/test_support/host_admission/profile_registry_test_support.rs @@ -217,36 +217,6 @@ impl HostAdmissionTestRuntimeV1 { self.profile_database.apply_registry_reap(&plan).await } - #[doc(hidden)] - pub async fn apply_registry_orphan_relink_report( - &self, - report: &tracedecay_global_db::registry_maintenance::RegistryOrphanRelinkReport, - ) -> std::result::Result< - tracedecay_global_db::registry_maintenance::RegistryOrphanRelinkApplyReport, - Vec, - > { - tracedecay_global_db::registry_maintenance::apply_registry_orphan_relink_report( - self.profile_database.as_ref(), - report, - ) - .await - } - - #[doc(hidden)] - pub async fn apply_single_registry_orphan_relink_report( - &self, - report: &tracedecay_global_db::registry_maintenance::RegistryOrphanRelinkReport, - ) -> std::result::Result< - tracedecay_global_db::registry_maintenance::RegistryOrphanRelinkApplyReport, - Vec, - > { - tracedecay_global_db::registry_maintenance::apply_single_registry_orphan_relink_report( - self.profile_database.as_ref(), - report, - ) - .await - } - #[doc(hidden)] pub async fn upsert_graph_scope( &self, diff --git a/crates/tracedecay-runtime-core/src/db/access.rs b/crates/tracedecay-runtime-core/src/db/access.rs index 88f8614a94..56c8e826aa 100644 --- a/crates/tracedecay-runtime-core/src/db/access.rs +++ b/crates/tracedecay-runtime-core/src/db/access.rs @@ -582,14 +582,6 @@ impl ExactSqlWriteAuthority for DatabaseAuthority { ExactSqlWriteIntent::ExecuteBatch => { "execute registered global database statement batch" } - ExactSqlWriteIntent::Vacuum => { - if self.role() != DatabaseAuthorityRole::Maintenance { - return Err(ExactSqlError::AuthorityDenied( - "whole-database vacuum requires exclusive maintenance authority".to_owned(), - )); - } - "vacuum registered global database under exclusive maintenance" - } ExactSqlWriteIntent::BeginTransaction => "begin registered global database transaction", ExactSqlWriteIntent::Commit => "commit registered global database transaction", }; diff --git a/crates/tracedecay-runtime-core/src/db/engine/connection.rs b/crates/tracedecay-runtime-core/src/db/engine/connection.rs index c4ee65e924..8114d9f355 100644 --- a/crates/tracedecay-runtime-core/src/db/engine/connection.rs +++ b/crates/tracedecay-runtime-core/src/db/engine/connection.rs @@ -212,15 +212,6 @@ impl Connection { .map_err(Into::into) } - #[hotpath::skip] - pub async fn repair_incremental_auto_vacuum(&self) -> Result<()> { - let runtime = Arc::clone(&self.runtime); - runtime - .repair_incremental_auto_vacuum_async() - .await - .map_err(Into::into) - } - #[cfg(any(test, feature = "test-helpers"))] #[hotpath::skip] pub async fn prepare(&self, sql: &str) -> Result> { diff --git a/crates/tracedecay-runtime-core/src/db/migrations/tests.rs b/crates/tracedecay-runtime-core/src/db/migrations/tests.rs index 2e4bc6570b..4f24404cbf 100644 --- a/crates/tracedecay-runtime-core/src/db/migrations/tests.rs +++ b/crates/tracedecay-runtime-core/src/db/migrations/tests.rs @@ -23,14 +23,8 @@ mod fts; struct AllowSchemaWrites; impl ExactSqlWriteAuthority for AllowSchemaWrites { - fn verify(&self, intent: ExactSqlWriteIntent) -> Result<(), ExactSqlError> { - if intent == ExactSqlWriteIntent::Vacuum { - Err(ExactSqlError::AuthorityDenied( - "ordinary schema fixture cannot vacuum".to_owned(), - )) - } else { - Ok(()) - } + fn verify(&self, _intent: ExactSqlWriteIntent) -> Result<(), ExactSqlError> { + Ok(()) } } diff --git a/crates/tracedecay-runtime-core/src/shard_runtime/registry.rs b/crates/tracedecay-runtime-core/src/shard_runtime/registry.rs index 0bdfd1abc3..b218d83607 100644 --- a/crates/tracedecay-runtime-core/src/shard_runtime/registry.rs +++ b/crates/tracedecay-runtime-core/src/shard_runtime/registry.rs @@ -823,17 +823,6 @@ impl tracedecay_rusqlite_runtime::exact_sql::ExactSqlWriteAuthority tracedecay_rusqlite_runtime::exact_sql::ExactSqlWriteIntent::ExecuteBatch => { "execute registered exact SQL statement batch" } - tracedecay_rusqlite_runtime::exact_sql::ExactSqlWriteIntent::Vacuum => { - if self.authority.role() != crate::db::DatabaseAuthorityRole::Maintenance { - return Err( - tracedecay_rusqlite_runtime::exact_sql::ExactSqlError::AuthorityDenied( - "whole-database vacuum requires exclusive maintenance authority" - .to_owned(), - ), - ); - } - "vacuum registered database under exclusive maintenance" - } tracedecay_rusqlite_runtime::exact_sql::ExactSqlWriteIntent::BeginTransaction => { "begin registered exact SQL transaction" } diff --git a/crates/tracedecay-rusqlite-runtime/src/exact_sql/command.rs b/crates/tracedecay-rusqlite-runtime/src/exact_sql/command.rs index b1b09dde95..3d3c9b9020 100644 --- a/crates/tracedecay-rusqlite-runtime/src/exact_sql/command.rs +++ b/crates/tracedecay-rusqlite-runtime/src/exact_sql/command.rs @@ -15,12 +15,12 @@ use std::{ use rusqlite::{Connection, DropBehavior, ErrorCode, Transaction, TransactionBehavior}; -use super::guard::{AuthorizedDatabaseOperation, with_exact_sql_guard}; +use super::guard::with_exact_sql_guard; use super::{ EXACT_SQL_TRANSACTION_IDLE_LIMIT, EXACT_SQL_TRANSACTION_LIMIT, ExactSqlAttachment, ExactSqlCommitReceipt, ExactSqlError, ExactSqlRollbackReceipt, ExactSqlRows, ExactSqlStatement, ExactSqlWriteAuthority, ExactSqlWriteIntent, ExecutionPolicy, MAX_EXACT_SQL_ATTACHMENTS, - SqlRequest, SqlResult, TransactionPolicy, attach_database, detach_database, execute_batch, + SqlRequest, SqlResult, TransactionPolicy, attach_database, detach_database, execute_query_unchecked, execute_request, publish_last_insert_rowid, sqlite_error, verify_write_authority, }; @@ -46,10 +46,6 @@ pub(crate) enum WriterCommand { reply: async_channel::Sender>, authority: Option>, }, - Vacuum { - reply: async_channel::Sender>, - authority: Option>, - }, } /// Pause between busy-begin attempts so the acquire deadline is the real bound. @@ -362,62 +358,6 @@ pub(crate) fn run_writer_command( }); let _ = reply.try_send(result); } - WriterCommand::Vacuum { reply, authority } => { - let Some(authority) = authority else { - let _ = reply.try_send(Err(ExactSqlError::AuthorityDenied( - "exclusive-maintenance vacuum requires attached write authority".to_owned(), - ))); - return; - }; - if let Err(error) = - verify_write_authority(Some(authority.as_ref()), ExactSqlWriteIntent::Vacuum) - { - let _ = reply.try_send(Err(error)); - return; - } - let previous_attachment_limit = - match connection.set_limit(Limit::SQLITE_LIMIT_ATTACHED, 1) { - Ok(previous) => previous, - Err(error) => { - let _ = reply.try_send(Err(sqlite_error( - "open exclusive-maintenance vacuum attachment slot", - error, - ))); - return; - } - }; - let mut result = hotpath::measure_block!("rusqlite.exact_sql.vacuum", { - with_exact_sql_guard( - connection, - false, - true, - Some(Arc::clone(shutdown_requested)), - None, - true, - Some((Arc::clone(&authority), ExactSqlWriteIntent::Vacuum)), - crate::connection::authorize_writer, - true, - Some(AuthorizedDatabaseOperation::Vacuum), - None, - || { - execute_batch(connection, "PRAGMA auto_vacuum = INCREMENTAL; VACUUM") - .map(|_| ()) - }, - ) - }); - if let Err(error) = - connection.set_limit(Limit::SQLITE_LIMIT_ATTACHED, previous_attachment_limit) - { - shutdown_requested.store(true, Ordering::Release); - if result.is_ok() { - result = Err(sqlite_error( - "restore exclusive-maintenance vacuum attachment limit", - error, - )); - } - } - let _ = reply.try_send(result); - } } } @@ -432,9 +372,6 @@ pub(crate) fn reject_writer_command(command: WriterCommand) { WriterCommand::CheckpointWalTruncate { reply, .. } => { let _ = reply.try_send(Err(ExactSqlError::WriterUnavailable)); } - WriterCommand::Vacuum { reply, .. } => { - let _ = reply.try_send(Err(ExactSqlError::WriterUnavailable)); - } } } diff --git a/crates/tracedecay-rusqlite-runtime/src/exact_sql/guard.rs b/crates/tracedecay-rusqlite-runtime/src/exact_sql/guard.rs index 925ff8ed7e..0bfcc54e96 100644 --- a/crates/tracedecay-rusqlite-runtime/src/exact_sql/guard.rs +++ b/crates/tracedecay-rusqlite-runtime/src/exact_sql/guard.rs @@ -34,7 +34,6 @@ pub(super) struct InsertTracker { pub(super) enum AuthorizedDatabaseOperation { Attach, Detach(String), - Vacuum, } #[allow(clippy::too_many_arguments)] @@ -202,7 +201,7 @@ fn authorize_exact_sql_writer( AuthAction::Attach { .. } if matches!( database_operation, - Some(AuthorizedDatabaseOperation::Attach | AuthorizedDatabaseOperation::Vacuum) + Some(AuthorizedDatabaseOperation::Attach) ) => { return Authorization::Allow; @@ -216,7 +215,7 @@ fn authorize_exact_sql_writer( } if code == rusqlite::ffi::SQLITE_ATTACH && matches!( database_operation, - Some(AuthorizedDatabaseOperation::Attach | AuthorizedDatabaseOperation::Vacuum) + Some(AuthorizedDatabaseOperation::Attach) ) => { return Authorization::Allow; @@ -226,9 +225,6 @@ fn authorize_exact_sql_writer( database_operation, Some(AuthorizedDatabaseOperation::Detach(expected)) if database_name.eq_ignore_ascii_case(expected) - ) || matches!( - database_operation, - Some(AuthorizedDatabaseOperation::Vacuum) ) => { return Authorization::Allow; diff --git a/crates/tracedecay-rusqlite-runtime/src/exact_sql/mod.rs b/crates/tracedecay-rusqlite-runtime/src/exact_sql/mod.rs index 8f8cd4ab5c..5c05e3522b 100644 --- a/crates/tracedecay-rusqlite-runtime/src/exact_sql/mod.rs +++ b/crates/tracedecay-rusqlite-runtime/src/exact_sql/mod.rs @@ -486,34 +486,6 @@ impl ExactSqlHandle { Ok(merge_memory_release(readers, writer)) } - /// Enables incremental auto-vacuum through its fixed maintenance rebuild. - fn enqueue_repair_incremental_auto_vacuum( - &self, - ) -> Result>, ExactSqlError> { - let (reply, response) = async_channel::bounded(1); - self.writer - .as_ref() - .ok_or(ExactSqlError::WriterUnavailable)? - .try_send(WriterCommand::Vacuum { - reply, - authority: self.write_authority.clone(), - }) - .map_err(map_writer_send_error)?; - Ok(response) - } - - pub fn repair_incremental_auto_vacuum(&self) -> Result<(), ExactSqlError> { - recv_writer_reply(self.enqueue_repair_incremental_auto_vacuum()?) - .map_err(|_| ExactSqlError::WriterUnavailable)? - } - - pub async fn repair_incremental_auto_vacuum_async(&self) -> Result<(), ExactSqlError> { - self.enqueue_repair_incremental_auto_vacuum()? - .recv() - .await - .map_err(|_| ExactSqlError::WriterUnavailable)? - } - /// Interactive read snapshot. Admits against the whole general lane. pub fn begin_read_snapshot( &self, diff --git a/crates/tracedecay-rusqlite-runtime/src/exact_sql/types.rs b/crates/tracedecay-rusqlite-runtime/src/exact_sql/types.rs index eb74bee2a6..0e571abed0 100644 --- a/crates/tracedecay-rusqlite-runtime/src/exact_sql/types.rs +++ b/crates/tracedecay-rusqlite-runtime/src/exact_sql/types.rs @@ -210,7 +210,6 @@ pub enum ExactSqlWriteIntent { Execute, Query, ExecuteBatch, - Vacuum, BeginTransaction, Commit, } diff --git a/crates/tracedecay-session-memory/src/memory/trust.rs b/crates/tracedecay-session-memory/src/memory/trust.rs index 0930dc15ee..110b5dc47f 100644 --- a/crates/tracedecay-session-memory/src/memory/trust.rs +++ b/crates/tracedecay-session-memory/src/memory/trust.rs @@ -4,26 +4,8 @@ pub const TRUST_MIN: f64 = 0.0; pub const TRUST_MAX: f64 = 1.0; pub const DEFAULT_TRUST: f64 = 0.5; pub const DEFAULT_MIN_TRUST: f64 = 0.3; -/// Lower bound of the "high" bucket in [`trust_bucket`]; scores in -/// `[DEFAULT_MIN_TRUST, HIGH_TRUST_THRESHOLD)` are "medium". -pub(crate) const HIGH_TRUST_THRESHOLD: f64 = 0.75; /// Representative score for a "low" trust label, inside the low bucket. pub const LOW_TRUST_REPRESENTATIVE: f64 = 0.15; /// Representative score for a "high" trust label, inside the high bucket. /// `DEFAULT_TRUST` is the representative for "medium". pub const HIGH_TRUST_REPRESENTATIVE: f64 = 0.85; - -pub fn clamp_trust(score: f64) -> f64 { - score.clamp(TRUST_MIN, TRUST_MAX) -} - -pub fn trust_bucket(score: f64) -> &'static str { - let clamped = clamp_trust(score); - if clamped < DEFAULT_MIN_TRUST { - "low" - } else if clamped < HIGH_TRUST_THRESHOLD { - "medium" - } else { - "high" - } -} diff --git a/crates/tracedecay-sessions/src/runtime/hosts/cursor_composer.rs b/crates/tracedecay-sessions/src/runtime/hosts/cursor_composer.rs index f1585afec6..f683ebfa08 100644 --- a/crates/tracedecay-sessions/src/runtime/hosts/cursor_composer.rs +++ b/crates/tracedecay-sessions/src/runtime/hosts/cursor_composer.rs @@ -111,23 +111,7 @@ impl CursorComposerSource { .await } - #[hotpath::skip] - pub async fn ingest_user( - &self, - admission: &dyn crate::admission::HostAdmission, - registered_roots: &[std::path::PathBuf], - envelope_cap: usize, - ) -> CursorComposerSweepResult { - self.ingest_user_capped( - admission, - registered_roots, - envelope_cap, - Some(sqlite::DEFAULT_COMPOSER_SWEEP_BYTES), - ) - .await - } - - /// [`Self::ingest_user`] with an aggregate serialized-payload byte budget. + /// User-scope ingest with an aggregate serialized-payload byte budget. #[hotpath::skip] pub async fn ingest_user_capped( &self, diff --git a/crates/tracedecay-sessions/src/runtime/store_access/lcm.rs b/crates/tracedecay-sessions/src/runtime/store_access/lcm.rs index 0890e5275f..9abf793d50 100644 --- a/crates/tracedecay-sessions/src/runtime/store_access/lcm.rs +++ b/crates/tracedecay-sessions/src/runtime/store_access/lcm.rs @@ -320,42 +320,6 @@ impl<'a, D: SessionRegisteredDb + Sync> SessionStoreAccess<'a, D> { compression::preflight(&snapshot, request).await } - #[hotpath::skip] - pub async fn lcm_payload_health_detail( - &self, - storage_root: &Path, - provider: &str, - session_id: Option<&str>, - deep: bool, - sample_limit: usize, - cfg: &LcmGcConfig, - ) -> Result { - let snapshot = self.lcm_read_snapshot().await?; - query::payload_health_detail( - &snapshot, - storage_root, - provider, - session_id, - deep, - sample_limit, - cfg, - ) - .await - } - - #[hotpath::skip] - pub async fn lcm_preview_payload_gc( - &self, - storage_root: &Path, - provider: &str, - session_id: Option<&str>, - cfg: &LcmGcConfig, - now: i64, - ) -> Result { - let snapshot = self.lcm_read_snapshot().await?; - gc::run_payload_gc(&snapshot, storage_root, provider, session_id, cfg, now).await - } - #[hotpath::skip] pub async fn lcm_run_payload_gc_apply( &self, diff --git a/crates/tracedecay-sessions/src/runtime/store_access/transcript.rs b/crates/tracedecay-sessions/src/runtime/store_access/transcript.rs index ec37288060..b4c1c7c9fa 100644 --- a/crates/tracedecay-sessions/src/runtime/store_access/transcript.rs +++ b/crates/tracedecay-sessions/src/runtime/store_access/transcript.rs @@ -3,7 +3,6 @@ use tracedecay_store::{ParseOffset, SessionMessageRecord, SessionRecord, StoreSh use tracedecay_lcm::payload::PayloadFileRollback; use tracedecay_lcm::raw; -use tracedecay_lcm::retrieval_content::derived_text_for_index; use super::super::git_correlation::{ CommitSessionRecord, SpanObservation, enqueue_git_evidence_publication, @@ -13,12 +12,6 @@ use super::super::shared::{durable_project_path_key, path_identity_key}; use super::codex_goal_reconciliation::find_preceding_codex_goal_response; use super::types::{TranscriptBatch, TranscriptPersistenceError}; -#[derive(Debug, Clone, Copy)] -enum TranscriptWritePolicy { - Full { expected_offset: ParseOffset }, - ProjectionOnly, -} - /// Exact Git evidence staged atomically with one transcript write. #[derive(Debug, Clone, Copy)] pub struct TranscriptGitEvidence<'a> { @@ -533,7 +526,7 @@ impl SessionStoreAccess<'_, D> { std::slice::from_ref(&batch), parse_offset_path, parse_offset, - TranscriptWritePolicy::Full { expected_offset }, + expected_offset, None, ) .await @@ -573,7 +566,7 @@ impl SessionStoreAccess<'_, D> { std::slice::from_ref(&batch), parse_offset_path, parse_offset, - TranscriptWritePolicy::Full { expected_offset }, + expected_offset, Some(git_evidence), ) .await @@ -595,34 +588,13 @@ impl SessionStoreAccess<'_, D> { .map_err(|error| TranscriptPersistenceError::storage("commit transcript batch", error)) } - /// Atomically upserts several transcript sessions (and their messages), - /// writing only the searchable `session_messages` projection, never - /// `lcm_raw_messages`, and then advances one shared parse cursor. - #[hotpath::skip] - pub async fn upsert_transcript_projection_batches( - &self, - batches: &[TranscriptBatch], - parse_offset_path: &str, - parse_offset: ParseOffset, - ) -> Result<(), String> { - self.upsert_transcript_batches_inner( - batches, - parse_offset_path, - parse_offset, - TranscriptWritePolicy::ProjectionOnly, - None, - ) - .await - .map_err(|error| error.to_string()) - } - #[hotpath::measure(label = "sessions.store.transcript.write_batches", future = true)] async fn upsert_transcript_batches_inner( &self, batches: &[TranscriptBatch], parse_offset_path: &str, parse_offset: ParseOffset, - policy: TranscriptWritePolicy, + expected_offset: ParseOffset, git_evidence: Option>, ) -> Result<(), TranscriptPersistenceError> { let storage_root = self @@ -630,25 +602,19 @@ impl SessionStoreAccess<'_, D> { .parent() .unwrap_or_else(|| std::path::Path::new(".")); let mut payload_rollback = PayloadFileRollback::begin_cancellation_safe(storage_root); - let staged_messages = match policy { - TranscriptWritePolicy::Full { .. } => { - stage_full_transcript_messages(storage_root, batches, &mut payload_rollback)? - } - TranscriptWritePolicy::ProjectionOnly => Vec::new(), - }; + let staged_messages = + stage_full_transcript_messages(storage_root, batches, &mut payload_rollback)?; let mut staged_messages = staged_messages.into_iter(); let transaction = self.begin_transcript_transaction().await?; let write_result: Result<(), TranscriptPersistenceError> = async { let mut projection_statements = Vec::with_capacity(TRANSCRIPT_STATEMENT_WINDOW); - if let TranscriptWritePolicy::Full { expected_offset } = policy { - // Full batches are one-winner compare-and-swap on the durable - // parse cursor. `actual == next_offset` is not a retry grant: - // a competing writer can share that destination while carrying - // different parse products. Post-commit publication retries - // must not re-enter this CAS with a stale expected cursor. - require_expected_offset(&transaction, parse_offset_path, expected_offset).await?; - } + // Full batches are one-winner compare-and-swap on the durable + // parse cursor. `actual == next_offset` is not a retry grant: + // a competing writer can share that destination while carrying + // different parse products. Post-commit publication retries + // must not re-enter this CAS with a stale expected cursor. + require_expected_offset(&transaction, parse_offset_path, expected_offset).await?; for batch in batches { if !Self::upsert_session_in_existing_tx(&transaction, &batch.session).await { return Err(TranscriptPersistenceError::message( @@ -671,32 +637,16 @@ impl SessionStoreAccess<'_, D> { .await?; reconcile_codex_goal_response(&transaction, message).await?; } - match policy { - TranscriptWritePolicy::Full { .. } => { - let staged = staged_messages.next().ok_or_else(|| { - TranscriptPersistenceError::message( - "upsert LCM raw message", - "staged transcript message count did not match the write batch", - ) - })?; - projection_statements.push( - self.upsert_session_message_in_existing_tx( - &transaction, - message, - staged, - ) - .await?, - ); - } - TranscriptWritePolicy::ProjectionOnly => { - let text = derived_text_for_index(&message.text); - projection_statements.push(Self::session_message_projection_statement( - message, - &text, - message.metadata_json.as_deref(), - )?); - } - } + let staged = staged_messages.next().ok_or_else(|| { + TranscriptPersistenceError::message( + "upsert LCM raw message", + "staged transcript message count did not match the write batch", + ) + })?; + projection_statements.push( + self.upsert_session_message_in_existing_tx(&transaction, message, staged) + .await?, + ); if projection_statements.len() >= TRANSCRIPT_STATEMENT_WINDOW { flush_transcript_statement_window(&transaction, &mut projection_statements) .await?; @@ -704,9 +654,7 @@ impl SessionStoreAccess<'_, D> { } } flush_transcript_statement_window(&transaction, &mut projection_statements).await?; - if matches!(policy, TranscriptWritePolicy::Full { .. }) - && staged_messages.next().is_some() - { + if staged_messages.next().is_some() { return Err(TranscriptPersistenceError::message( "upsert LCM raw message", "staged transcript message count exceeded the write batch", @@ -724,19 +672,7 @@ impl SessionStoreAccess<'_, D> { TranscriptPersistenceError::storage("stage transcript git evidence", error) })?; } - if matches!(policy, TranscriptWritePolicy::Full { .. }) { - set_parse_offset(&transaction, parse_offset_path, parse_offset).await?; - } else { - Self::set_parse_offset_monotonic_in_existing_tx( - &transaction, - parse_offset_path, - parse_offset, - ) - .await - .map_err(|message| { - TranscriptPersistenceError::message("advance projection parse offset", message) - })?; - } + set_parse_offset(&transaction, parse_offset_path, parse_offset).await?; Ok(()) } .await; diff --git a/crates/tracedecay-temporal-query/src/resolution.rs b/crates/tracedecay-temporal-query/src/resolution.rs index a35d685c4e..87b4c18ec1 100644 --- a/crates/tracedecay-temporal-query/src/resolution.rs +++ b/crates/tracedecay-temporal-query/src/resolution.rs @@ -12,7 +12,7 @@ pub use self::summary::{ evaluate_summary_lineage_eligibility, evaluate_summary_lineage_eligibility_controlled, }; pub use self::types::{ - ResolutionAssertion, ResolutionCertainty, ResolutionCheckpoint, ResolutionEvidence, - ResolutionInputError, ResolutionLineageEdge, ResolutionLineageEdgeKind, ResolutionOccurrence, - ResolvedOccurrence, TemporalResolution, ValidatedAuthorization, + ResolutionAssertion, ResolutionCheckpoint, ResolutionEvidence, ResolutionInputError, + ResolutionLineageEdge, ResolutionLineageEdgeKind, ResolutionOccurrence, ResolvedOccurrence, + TemporalResolution, ValidatedAuthorization, }; diff --git a/crates/tracedecay-temporal-query/src/resolution/types.rs b/crates/tracedecay-temporal-query/src/resolution/types.rs index 46de986132..3135cdad76 100644 --- a/crates/tracedecay-temporal-query/src/resolution/types.rs +++ b/crates/tracedecay-temporal-query/src/resolution/types.rs @@ -100,23 +100,6 @@ pub struct ResolvedOccurrence { pub supporting_anchor_ids: BTreeSet, } -impl ResolvedOccurrence { - #[hotpath::skip] - pub const fn certainty(&self) -> ResolutionCertainty { - if self.uncertain { - ResolutionCertainty::AuthorizedUnknown - } else { - ResolutionCertainty::Known - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ResolutionCertainty { - Known, - AuthorizedUnknown, -} - #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum ResolutionLineageEdgeKind { Correction,