From 551c704eada62e1a18334cd58e18b0f48b0439e2 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Wed, 9 Sep 2026 01:38:26 +0000 Subject: [PATCH] refactor(code-index): call production rerank execute directly Delete the private SemanticRerankExecutorV1 pass-through so semantic query runtime invokes ProductionCodeRerankAuthorityV1::execute with the existing generation, query, and control. Preserve unavailable, fallback, budget, and cancellation semantics. --- .../semantic_query_runtime.rs | 187 ++++++++++++----- .../src/code_index_scheduler/tests.rs | 96 ++++++++- .../src/retrieval/semantic.rs | 2 +- .../retrieval/semantic/execution_authority.rs | 192 +++++++++--------- .../tracedecay-semantic/src/rerank_adapter.rs | 8 + 5 files changed, 333 insertions(+), 152 deletions(-) diff --git a/crates/tracedecay-code-index-runtime/src/code_index_scheduler/semantic_query_runtime.rs b/crates/tracedecay-code-index-runtime/src/code_index_scheduler/semantic_query_runtime.rs index 72b609e40f..0a95d3b79f 100644 --- a/crates/tracedecay-code-index-runtime/src/code_index_scheduler/semantic_query_runtime.rs +++ b/crates/tracedecay-code-index-runtime/src/code_index_scheduler/semantic_query_runtime.rs @@ -37,8 +37,7 @@ use tracedecay_query::retrieval::rerank::RerankExecutionControlV1; use tracedecay_query::retrieval::semantic::{ SemanticAbstentionDispositionV1, SemanticAbstentionV1, SemanticCompositionExecutionAuthorityV1, SemanticCompositionExecutionOutcomeV1, SemanticExecutionControl, SemanticQueryModeV1, - SemanticQueryServiceError, SemanticRerankExecutionPortV1, SemanticRerankReadinessV1, - SemanticRetrievalRequestV1, + SemanticQueryServiceError, SemanticRetrievalRequestV1, apply_bounded_rerank_outcome, }; #[derive(Clone)] @@ -582,38 +581,11 @@ impl CodeIndexSchedulerRegistryV1 { label = "daemon.query.semantic.vector_and_lane" ) .await?; - let mut rerank_executor = authority - .rerank - .as_ref() - .and_then(|configured| { - configured - .mounted - .as_ref() - .filter(|rerank| rerank.compatibility() == &configured.pins) - }) - .map(|rerank| SemanticRerankExecutorV1 { - rerank, - code_generation, - query_view, - control, - }); - let rerank_readiness = if authority.execution.rerank_policy().is_none() { - None - } else { - Some(match rerank_executor.as_mut() { - Some(executor) => SemanticRerankReadinessV1::Ready(executor), - None => SemanticRerankReadinessV1::Unavailable( - tracedecay_domain::SanitizedStageFailure::AuthorityUnavailable, - ), - }) - }; let outcome = hotpath::measure_block!("daemon.query.semantic.compose", { authority.execution.execute( - base, authorized_query, outcome, semantic_abstention_disposition(mode), - rerank_readiness, ) })?; match outcome { @@ -624,7 +596,22 @@ impl CodeIndexSchedulerRegistryV1 { abstention, fallback, }), - SemanticCompositionExecutionOutcomeV1::Augmented(executed) => { + SemanticCompositionExecutionOutcomeV1::Augmented(mut executed) => { + if authorized_query + .request_cursor + .as_ref() + .and_then(|cursor| cursor.semantic.as_ref()) + .is_none() + { + executed.rerank = apply_configured_semantic_rerank( + &authority, + code_generation, + query_view, + base, + &mut executed.composition, + control, + ); + } let mut composition = executed.composition; let Some(query_authority) = hotpath::future!( self.query_authority_for_scope(scope), @@ -704,33 +691,45 @@ where } } -struct SemanticRerankExecutorV1<'a, C: ?Sized> { - rerank: &'a ProductionCodeRerankAuthorityV1, - code_generation: &'a CodeIndexPublishedGenerationV1, - query_view: &'a EphemeralSanitizedQueryViewV1, - control: &'a C, +fn mounted_compatible_rerank( + configured: Option<&ConfiguredRerankAuthorityV1>, +) -> Option<&ProductionCodeRerankAuthorityV1> { + configured.and_then(|configured| { + configured + .mounted + .as_ref() + .filter(|rerank| rerank.compatibility() == &configured.pins) + }) } -impl SemanticRerankExecutionPortV1 for SemanticRerankExecutorV1<'_, C> +fn apply_configured_semantic_rerank( + authority: &SemanticQueryAuthorityV1, + code_generation: &CodeIndexPublishedGenerationV1, + query_view: &EphemeralSanitizedQueryViewV1, + request: &RetrievalRequest, + composition: &mut CompositionOutputV1, + control: &C, +) -> OptionalStagePublicStatus where C: SemanticExecutionControl + ?Sized, { - fn execute_rerank( - &mut self, - request: &RetrievalRequest, - policy: &tracedecay_domain::RerankPolicy, - pre_rerank: &[tracedecay_domain::RankedCandidate], - ) -> tracedecay_query::retrieval::rerank::BoundedRerankOutcomeV1 { - let rerank_control = SemanticRerankControlV1(self.control); - self.rerank.execute( - self.code_generation, - self.query_view, - request, - policy, - pre_rerank, - &rerank_control, - ) - } + let Some(policy) = authority.execution.rerank_policy() else { + return OptionalStagePublicStatus::NotRequested; + }; + let Some(rerank) = mounted_compatible_rerank(authority.rerank.as_ref()) else { + return OptionalStagePublicStatus::Unavailable( + tracedecay_domain::SanitizedStageFailure::AuthorityUnavailable, + ); + }; + let outcome = rerank.execute( + code_generation, + query_view, + request, + policy, + &composition.ranked_candidates, + &SemanticRerankControlV1(control), + ); + apply_bounded_rerank_outcome(composition, outcome) } fn paginate_semantic_composition( @@ -900,6 +899,11 @@ mod tests { use super::*; use tracedecay_query::retrieval::fusion::RetrievalCursorKeyringV1; + use tracedecay_query::retrieval::rerank::{ + AdmittedNativeRerankExecutorV1, DeterministicLocalRerankExecutorV1, LocalRerankFailureV1, + LocalRerankInputV1, LocalRerankPermitV1, + }; + use tracedecay_semantic_contracts::RerankCompatibilityPinsV1; fn id(value: &str) -> T where @@ -1772,4 +1776,83 @@ mod tests { } if selected == generation )); } + + struct IdentityRerankExecutorV1 { + digest: ManifestDigest, + } + + impl DeterministicLocalRerankExecutorV1 for IdentityRerankExecutorV1 { + fn planned_model_invocations( + &self, + _candidate_count: u32, + ) -> Result { + Ok(1) + } + + fn rerank( + &self, + _policy: &tracedecay_domain::RerankPolicy, + inputs: &[LocalRerankInputV1<'_>], + _permit: LocalRerankPermitV1, + ) -> Result, LocalRerankFailureV1> { + Ok(inputs + .iter() + .map(|input| input.candidate.candidate.anchor_id.clone()) + .collect()) + } + } + + impl AdmittedNativeRerankExecutorV1 for IdentityRerankExecutorV1 { + fn artifact_manifest_digest(&self) -> &ManifestDigest { + &self.digest + } + } + + fn rerank_pins(byte: char) -> RerankCompatibilityPinsV1 { + RerankCompatibilityPinsV1 { + implementation_revision: id("rerank.fastembed.production.v1"), + artifact_manifest_digest: digest(byte), + runtime_compatibility_digest: digest(byte), + } + } + + #[test] + fn configured_rerank_is_unavailable_when_unmounted_or_pins_diverge() { + let pins = rerank_pins('a'); + let unmounted = ConfiguredRerankAuthorityV1 { + pins: pins.clone(), + mounted: None, + }; + assert!(mounted_compatible_rerank(Some(&unmounted)).is_none()); + assert!(mounted_compatible_rerank(None).is_none()); + + let mounted = ProductionCodeRerankAuthorityV1::from_executor_for_test( + rerank_pins('b'), + Arc::new(IdentityRerankExecutorV1 { + digest: digest('b'), + }), + ); + let mismatched = ConfiguredRerankAuthorityV1 { + pins, + mounted: Some(mounted), + }; + assert!(mounted_compatible_rerank(Some(&mismatched)).is_none()); + } + + #[test] + fn configured_rerank_selects_the_mounted_authority_with_exact_pins() { + let pins = rerank_pins('c'); + let mounted = ProductionCodeRerankAuthorityV1::from_executor_for_test( + pins.clone(), + Arc::new(IdentityRerankExecutorV1 { + digest: digest('c'), + }), + ); + let configured = ConfiguredRerankAuthorityV1 { + pins: pins.clone(), + mounted: Some(mounted), + }; + let selected = mounted_compatible_rerank(Some(&configured)).expect("compatible mount"); + assert_eq!(selected.compatibility(), &pins); + } } diff --git a/crates/tracedecay-code-index-runtime/src/code_index_scheduler/tests.rs b/crates/tracedecay-code-index-runtime/src/code_index_scheduler/tests.rs index 4f29aa94f2..a3d0c07123 100644 --- a/crates/tracedecay-code-index-runtime/src/code_index_scheduler/tests.rs +++ b/crates/tracedecay-code-index-runtime/src/code_index_scheduler/tests.rs @@ -46,9 +46,9 @@ use tracedecay_application::semantic_runtime::{ use tracedecay_graph_db::NeverCancelled; #[cfg(feature = "semantic-fastembed")] use tracedecay_runtime_core::db::{Database, DatabaseAuthority, TestDatabaseRuntimeMode}; -use tracedecay_semantic_contracts::SemanticFallbackReasonV1; #[cfg(feature = "semantic-fastembed")] use tracedecay_semantic_contracts::{DEFAULT_FASTEMBED_MODEL_ID, SemanticResourceCeilings}; +use tracedecay_semantic_contracts::{RerankCompatibilityPinsV1, SemanticFallbackReasonV1}; use super::registry::{ ColdMountOpenEventV1, ServingGenerationInstallationOutcomeV1, @@ -65,7 +65,9 @@ use crate::code_index::production::{ CodeIndexProductionErrorV1, CodeIndexPublicationStoreErrorV1, UninterruptibleCodeIndexControlV1, VerifiedSealedLexicalPageReadV1, }; -use crate::semantic_code::rerank_adapter::GenerationBoundCodeRerankViewsV1; +use crate::semantic_code::rerank_adapter::{ + GenerationBoundCodeRerankViewsV1, ProductionCodeRerankAuthorityV1, +}; use tracedecay_query::retrieval::QueryAuthorityV1; use tracedecay_query::retrieval::exact::{ CentralExactAdmissionAuthorityV1, ExactAdmissionAuthority, ExactLaneRequest, @@ -77,9 +79,10 @@ use tracedecay_query::retrieval::lexical::{ LexicalRouteKindV1, LexicalRoutingV1, }; use tracedecay_query::retrieval::rerank::{ - BoundedRerankRuntimeV1, DeterministicLocalRerankExecutorV1, LocalRerankFailureV1, - LocalRerankInputV1, LocalRerankPermitV1, RerankExecutionControlV1, + AdmittedNativeRerankExecutorV1, BoundedRerankRuntimeV1, DeterministicLocalRerankExecutorV1, + LocalRerankFailureV1, LocalRerankInputV1, LocalRerankPermitV1, RerankExecutionControlV1, }; +use tracedecay_query::retrieval::semantic::apply_bounded_rerank_outcome; use tracedecay_query::retrieval::semantic::{ SemanticAbstentionV1, SemanticExecutionControl, SemanticQueryModeV1, }; @@ -2496,6 +2499,15 @@ fn oversized_generations_still_produce_a_complete_retention_finding() { struct MixedAnchorReverseRerankExecutorV1; +impl AdmittedNativeRerankExecutorV1 for MixedAnchorReverseRerankExecutorV1 { + fn artifact_manifest_digest(&self) -> &ManifestDigest { + static DIGEST: OnceLock = OnceLock::new(); + DIGEST.get_or_init(|| { + ManifestDigest::new(format!("sha256:{}", "a".repeat(64))).expect("artifact digest") + }) + } +} + impl DeterministicLocalRerankExecutorV1 for MixedAnchorReverseRerankExecutorV1 { fn planned_model_invocations( &self, @@ -2530,6 +2542,18 @@ impl RerankExecutionControlV1 for ReadyRerankControlV1 { } } +struct CancelledRerankControlV1; + +impl RerankExecutionControlV1 for CancelledRerankControlV1 { + fn elapsed_micros(&self) -> u64 { + 0 + } + + fn is_cancelled(&self) -> bool { + true + } +} + struct ReadySemanticControlV1; impl SemanticExecutionControl for ReadySemanticControlV1 { @@ -3803,18 +3827,74 @@ fn generation_bound_rerank_authorizes_mixed_symbol_and_chunk_anchors() { deadline_micros: None, }; let mut views = GenerationBoundCodeRerankViewsV1::new(&latest.generation, &query); - let outcome = BoundedRerankRuntimeV1::new(&mut views, &MixedAnchorReverseRerankExecutorV1) - .rerank(&request, &policy, &candidates, &ReadyRerankControlV1); + let runtime_outcome = BoundedRerankRuntimeV1::new( + &mut views, + &MixedAnchorReverseRerankExecutorV1, + ) + .rerank(&request, &policy, &candidates, &ReadyRerankControlV1); + let pins = RerankCompatibilityPinsV1 { + implementation_revision: ComponentRevision::new("rerank.fastembed.production.v1") + .expect("implementation revision"), + artifact_manifest_digest: MixedAnchorReverseRerankExecutorV1 + .artifact_manifest_digest() + .clone(), + runtime_compatibility_digest: ManifestDigest::new(format!("sha256:{}", "b".repeat(64))) + .expect("runtime digest"), + }; + let authority = ProductionCodeRerankAuthorityV1::from_executor_for_test( + pins, + Arc::new(MixedAnchorReverseRerankExecutorV1), + ); + let execute_outcome = authority.execute( + &latest.generation, + &query, + &request, + &policy, + &candidates, + &ReadyRerankControlV1, + ); - assert_eq!(outcome.public_status, OptionalStagePublicStatus::Complete); + assert_eq!(execute_outcome, runtime_outcome); + assert_eq!( + execute_outcome.public_status, + OptionalStagePublicStatus::Complete + ); assert_eq!( - outcome + execute_outcome .ordered_candidates .iter() .map(|candidate| candidate.candidate.anchor_id.clone()) .collect::>(), anchors.into_iter().rev().collect::>() ); + + let cancelled = authority.execute( + &latest.generation, + &query, + &request, + &policy, + &candidates, + &CancelledRerankControlV1, + ); + assert_eq!( + cancelled.public_status, + OptionalStagePublicStatus::Cancelled + ); + assert_eq!(cancelled.ordered_candidates, candidates); + let mut composition = tracedecay_query::retrieval::fusion::CompositionOutputV1 { + profile_id: request.profile_id.clone(), + ranked_candidates: candidates.clone(), + comparator_records: Vec::new(), + internal_lane_outcomes: BTreeMap::new(), + public_lane_statuses: BTreeMap::new(), + freshness: Vec::new(), + lane_checkpoints: Vec::new(), + dedupe_decisions: Vec::new(), + diversity_decisions: Vec::new(), + }; + let status = apply_bounded_rerank_outcome(&mut composition, cancelled); + assert_eq!(status, OptionalStagePublicStatus::Cancelled); + assert_eq!(composition.ranked_candidates, candidates); } #[test] diff --git a/crates/tracedecay-query/src/retrieval/semantic.rs b/crates/tracedecay-query/src/retrieval/semantic.rs index 19c74c407d..75a607411e 100644 --- a/crates/tracedecay-query/src/retrieval/semantic.rs +++ b/crates/tracedecay-query/src/retrieval/semantic.rs @@ -46,7 +46,7 @@ mod service; pub use execution_authority::{ ExecutedSemanticCompositionV1, SemanticCompositionAuthorityErrorV1, SemanticCompositionExecutionAuthorityV1, SemanticCompositionExecutionOutcomeV1, - SemanticRerankExecutionPortV1, SemanticRerankReadinessV1, restore_frozen_semantic_order, + apply_bounded_rerank_outcome, restore_frozen_semantic_order, }; pub use service::{ CalibratedSemanticQueryService, CompleteSemanticGenerationV1, SemanticAbstentionDispositionV1, diff --git a/crates/tracedecay-query/src/retrieval/semantic/execution_authority.rs b/crates/tracedecay-query/src/retrieval/semantic/execution_authority.rs index 31842145a6..bcd2f8401b 100644 --- a/crates/tracedecay-query/src/retrieval/semantic/execution_authority.rs +++ b/crates/tracedecay-query/src/retrieval/semantic/execution_authority.rs @@ -10,8 +10,8 @@ use std::sync::Arc; use thiserror::Error; use tracedecay_domain::{ ComponentRevision, DiversityPolicy, FusionProfile, OptionalStagePublicStatus, - QueryFallbackSubpayload, RankedCandidate, RerankPolicy, RetrievalRequest, RetrieverKind, - SanitizedStageFailure, SemanticRetrievalContinuationV1, + QueryFallbackSubpayload, RankedCandidate, RerankPolicy, RetrieverKind, SanitizedStageFailure, + SemanticRetrievalContinuationV1, }; use super::{ @@ -29,25 +29,6 @@ pub enum SemanticCompositionAuthorityErrorV1 { InvalidAuthority(String), } -/// Query-layer port for one already-mounted deterministic local reranker. -/// -/// Daemon adapters may capture generation-bound view authority and execution -/// control, but the query authority depends only on the bounded rerank -/// contract and transport-independent retrieval values. -pub trait SemanticRerankExecutionPortV1 { - fn execute_rerank( - &mut self, - request: &RetrievalRequest, - policy: &RerankPolicy, - pre_rerank: &[RankedCandidate], - ) -> BoundedRerankOutcomeV1; -} - -pub enum SemanticRerankReadinessV1<'a> { - Ready(&'a mut dyn SemanticRerankExecutionPortV1), - Unavailable(SanitizedStageFailure), -} - /// Successful semantic composition before paging and hydration. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExecutedSemanticCompositionV1 { @@ -122,15 +103,14 @@ impl SemanticCompositionExecutionAuthorityV1 { /// Typed semantic abstentions pass through unchanged. Composition failure /// becomes a typed lane abstention, while strict mode remains unavailable. /// An authenticated continuation restores its frozen order and never - /// invokes the current reranker. + /// invokes the current reranker. Live optional rerank is the caller's + /// responsibility after this returns. #[hotpath::measure(label = "query.fusion.semantic")] pub fn execute( &self, - request: &RetrievalRequest, authorized_query: &AuthorizedQueryFallbackV1, semantic: SemanticQueryServiceOutcomeV1, on_abstention: SemanticAbstentionDispositionV1, - rerank: Option>, ) -> Result { if authorized_query.fallback.validate().is_err() || !Arc::ptr_eq(semantic.fallback(), &authorized_query.fallback) @@ -182,7 +162,7 @@ impl SemanticCompositionExecutionAuthorityV1 { restore_frozen_semantic_order(continuation, &mut composition)?; continuation.rerank.clone() } - None => self.execute_optional_rerank(request, rerank, &mut composition), + None => OptionalStagePublicStatus::NotRequested, }; Ok(SemanticCompositionExecutionOutcomeV1::Augmented(Box::new( @@ -194,33 +174,18 @@ impl SemanticCompositionExecutionAuthorityV1 { }, ))) } +} - #[hotpath::measure(label = "query.rerank.semantic")] - fn execute_optional_rerank( - &self, - request: &RetrievalRequest, - readiness: Option>, - composition: &mut CompositionOutputV1, - ) -> OptionalStagePublicStatus { - let Some(policy) = self.rerank_policy.as_ref() else { - return OptionalStagePublicStatus::NotRequested; - }; - let Some(readiness) = readiness else { - return OptionalStagePublicStatus::Unavailable( - SanitizedStageFailure::AuthorityUnavailable, - ); - }; - let executor = match readiness { - SemanticRerankReadinessV1::Ready(executor) => executor, - SemanticRerankReadinessV1::Unavailable(reason) => { - return OptionalStagePublicStatus::Unavailable(reason); - } - }; - - let original = composition.ranked_candidates.clone(); - let outcome = executor.execute_rerank(request, policy, &original); - apply_rerank_outcome(original, outcome, composition) - } +/// Apply one bounded rerank outcome to the exact post-composition candidates. +/// +/// Complete permutations replace the ranked list. Every other public status +/// restores the pre-rerank value. +pub fn apply_bounded_rerank_outcome( + composition: &mut CompositionOutputV1, + outcome: BoundedRerankOutcomeV1, +) -> OptionalStagePublicStatus { + let original = composition.ranked_candidates.clone(); + apply_rerank_outcome(original, outcome, composition) } /// Restore the authenticated rerank order without rerunning an optional stage. @@ -389,13 +354,11 @@ mod tests { use std::collections::BTreeMap; use tracedecay_domain::{ - AuthorizationRevision, CalibrationProfileId, CandidateSetDigest, ExactClass, - FreshnessVectorDigest, FusedCandidate, LogicalEvidenceId, ManifestDigest, PrincipalId, - ProjectionKeyV1, ProjectionKindV1, PublicRetrieverStatus, QueryDigest, QueryMac, - RankingRevision, RetrievalAnchorId, RetrievalBudget, RetrievalScope, RetrievalSnapshot, - RetrieverBatch, RetrieverCoverage, RetrieverOutcome, SanitizedBudgetUsage, - SemanticSearchIndexProfileV1, SingleRootScopeV1, SourceFreshness, TemporalModeV1, - UtcMicros, VectorGenerationIdV1, VectorWatermark, + CalibrationProfileId, CandidateSetDigest, ExactClass, FusedCandidate, LogicalEvidenceId, + ManifestDigest, ProjectionKeyV1, ProjectionKindV1, PublicRetrieverStatus, QueryDigest, + QueryMac, RankingRevision, RetrievalAnchorId, RetrievalBudget, RetrieverBatch, + RetrieverCoverage, RetrieverOutcome, SanitizedBudgetUsage, SemanticSearchIndexProfileV1, + SourceFreshness, VectorGenerationIdV1, }; use super::*; @@ -473,31 +436,6 @@ mod tests { } } - fn request() -> RetrievalRequest { - RetrievalRequest { - principal: id::("principal.semantic-execution"), - scope: RetrievalScope { - privacy_domain: id("privacy.semantic-execution"), - root: SingleRootScopeV1 { - repository: id("repository.semantic-execution"), - worktree: None, - reference: None, - }, - }, - temporal_mode: TemporalModeV1::Current, - snapshot: RetrievalSnapshot { - watermarks: VectorWatermark::default(), - freshness_digest: digest::('a'), - authorization_revision: id::( - "authorization.semantic-execution.v1", - ), - captured_at: UtcMicros(1), - }, - profile_id: id("profile.semantic-execution.v1"), - budget: budget(), - } - } - fn fallback() -> Arc { Arc::new( QueryFallbackSubpayload::new( @@ -584,14 +522,12 @@ mod tests { ] { let outcome = authority() .execute( - &request(), &authorized, SemanticQueryServiceOutcomeV1::Fallback { abstention: abstention.clone(), fallback: Arc::clone(&fallback), }, SemanticAbstentionDispositionV1::UseFallback, - None, ) .expect("typed fallback"); assert!(matches!( @@ -612,7 +548,6 @@ mod tests { let authorized = authorized(Arc::clone(&fallback)); let outcome = authority() .execute( - &request(), &authorized, SemanticQueryServiceOutcomeV1::Augmented { semantic_lane: empty_lane(RetrieverKind::Semantic), @@ -625,7 +560,6 @@ mod tests { fallback: Arc::clone(&fallback), }, SemanticAbstentionDispositionV1::UseFallback, - None, ) .expect("semantic composition"); let SemanticCompositionExecutionOutcomeV1::Augmented(executed) = outcome else { @@ -658,14 +592,12 @@ mod tests { assert!(matches!( authority().execute( - &request(), &authorized, SemanticQueryServiceOutcomeV1::Fallback { abstention: SemanticAbstentionV1::Denied, fallback: duplicate, }, SemanticAbstentionDispositionV1::UseFallback, - None, ), Err(SemanticQueryServiceError::InvalidFallback) )); @@ -764,6 +696,86 @@ mod tests { ); } + fn rerank_policy() -> tracedecay_domain::RerankPolicy { + tracedecay_domain::RerankPolicy { + policy_id: id("rerank.semantic-execution.v1"), + evaluation_result_anchor: id("evaluation.semantic-execution.v1"), + max_candidates: 8, + max_input_bytes: u64::MAX, + max_input_tokens: u64::MAX, + max_work_units: 8, + max_model_invocations: 1, + deadline_micros: None, + } + } + + #[test] + fn first_page_with_rerank_policy_leaves_not_requested_for_the_caller() { + let fallback = fallback(); + let policy = rerank_policy(); + let authority = SemanticCompositionExecutionAuthorityV1::new( + profile(Some(policy.policy_id.clone())), + diversity(), + Some(policy), + id("ranking.semantic-execution.v1"), + ) + .expect("valid semantic composition authority with rerank"); + let outcome = authority + .execute( + &authorized(Arc::clone(&fallback)), + SemanticQueryServiceOutcomeV1::Augmented { + semantic_lane: empty_lane(RetrieverKind::Semantic), + calibration: SemanticCalibrationEvidenceV1 { + calibration_profile_id: id("calibration.semantic-execution.v1"), + cohort_digest: digest('8'), + best_distance: super::super::CanonicalSemanticDistanceV1(0), + next_best_margin_micros: u64::MAX, + }, + fallback, + }, + SemanticAbstentionDispositionV1::UseFallback, + ) + .expect("semantic composition"); + let SemanticCompositionExecutionOutcomeV1::Augmented(executed) = outcome else { + panic!("complete semantic lane must augment"); + }; + assert_eq!(executed.rerank, OptionalStagePublicStatus::NotRequested); + } + + #[test] + fn apply_bounded_rerank_keeps_a_complete_permutation() { + let reranked = vec![ranked("anchor.two", 0), ranked("anchor.one", 1)]; + let mut composition = empty_composition(id("profile.semantic-execution.v1")); + composition.ranked_candidates = vec![ranked("anchor.one", 0), ranked("anchor.two", 1)]; + let status = apply_bounded_rerank_outcome( + &mut composition, + BoundedRerankOutcomeV1 { + ordered_candidates: reranked.clone(), + public_status: OptionalStagePublicStatus::Complete, + usage: RerankUsageV1::default(), + }, + ); + assert_eq!(status, OptionalStagePublicStatus::Complete); + assert_eq!(composition.ranked_candidates, reranked); + } + + #[test] + fn apply_bounded_rerank_cancelled_restores_the_exact_post_composition_value() { + let original = vec![ranked("anchor.one", 0), ranked("anchor.two", 1)]; + let mut composition = empty_composition(id("profile.semantic-execution.v1")); + composition.ranked_candidates = original.clone(); + let status = apply_bounded_rerank_outcome( + &mut composition, + BoundedRerankOutcomeV1 { + ordered_candidates: vec![ranked("anchor.two", 0), ranked("anchor.one", 1)], + public_status: OptionalStagePublicStatus::Cancelled, + usage: RerankUsageV1::default(), + }, + ); + assert_eq!(status, OptionalStagePublicStatus::Cancelled); + assert_eq!(composition.ranked_candidates, original); + } + #[test] fn malformed_complete_rerank_is_rejected_and_restored() { let original = vec![ranked("anchor.one", 0), ranked("anchor.two", 1)]; @@ -792,7 +804,6 @@ mod tests { let mut authorized = authorized(Arc::clone(&fallback)); authorized.fallback_lanes.clear(); let result = authority().execute( - &request(), &authorized, SemanticQueryServiceOutcomeV1::Augmented { semantic_lane: empty_lane(RetrieverKind::Semantic), @@ -805,7 +816,6 @@ mod tests { fallback, }, SemanticAbstentionDispositionV1::RejectUnavailable, - None, ); assert!(matches!( diff --git a/crates/tracedecay-semantic/src/rerank_adapter.rs b/crates/tracedecay-semantic/src/rerank_adapter.rs index 90691311b6..7b7acd9a67 100644 --- a/crates/tracedecay-semantic/src/rerank_adapter.rs +++ b/crates/tracedecay-semantic/src/rerank_adapter.rs @@ -551,4 +551,12 @@ impl ProductionCodeRerankAuthorityV1 { BoundedRerankRuntimeV1::new(&mut views, self.executor.as_ref()) .rerank(request, policy, pre_rerank, control) } + + #[cfg(any(test, feature = "test-helpers"))] + pub fn from_executor_for_test( + pins: RerankCompatibilityPinsV1, + executor: Arc, + ) -> Self { + Self { pins, executor } + } }