use std::collections::BTreeMap;
use crate::live_index::knowledge_bridge::{DerivedLimitKind, LimitBreach};
pub use crate::lifecycle_identity::{
AuthorityIdentity, EvaluationIdentity, GenerationAuthority, GenerationIdentity,
InvalidationSequence, ObservationTime, ObserverEpoch, OperationIdentity,
ProducingRuntimeIdentity, ProvenanceIdentity, WorktreeScanId,
};
pub use crate::protocol::read_gate::{
GenerationResolution, observe_disk_beneath, resolve_generation_bytes,
};
pub use crate::lifecycle_identity::{
CanonicalArgumentHash, OperationKind, OperationReceipt, RetryAdvice, SourceRefusal,
SourceRefusalKind,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhysicalRootLease {
root: String,
}
impl PhysicalRootLease {
pub fn for_test_root(root: &str) -> Self {
Self {
root: root.to_string(),
}
}
pub fn root(&self) -> &str {
&self.root
}
}
#[derive(Debug, Clone)]
pub struct ObservationLease {
root: PhysicalRootLease,
observer_epoch: ObserverEpoch,
}
impl ObservationLease {
pub fn for_test_root(root: PhysicalRootLease) -> Self {
Self {
root,
observer_epoch: ObserverEpoch::initial(),
}
}
pub fn root(&self) -> &PhysicalRootLease {
&self.root
}
pub fn observe_missing_path(
&self,
path: &str,
observed_at: ObservationTime,
) -> Result<DiskObservationReceipt, SourceRefusal> {
Ok(DiskObservationReceipt::PathMissing {
identity: AuthorityIdentity::fresh(),
physical_root: self.root.root().to_string(),
path: path.to_string(),
observed_at,
})
}
pub fn complete_scope_scan(
&self,
scope: WorktreeObservationScope,
) -> Result<WorktreeScopeObservationReceipt, SourceRefusal> {
let start = InvalidationSequence::initial();
Ok(WorktreeScopeObservationReceipt {
identity: AuthorityIdentity::fresh(),
physical_root: self.root.root().to_string(),
scope,
scan_id: WorktreeScanId::fresh(),
observation_cut: WorktreeObservationCut {
observer_epoch: self.observer_epoch,
start_seq: start,
end_seq: start.advanced(),
},
coverage: WorktreeScopeCoverage::Complete,
})
}
pub fn admit_generation(&self) -> Result<GenerationAuthority, SourceRefusal> {
Ok(GenerationAuthority::captured(
AuthorityIdentity::fresh(),
GenerationIdentity::fresh(),
self.root.root().to_string(),
))
}
pub fn selection_receipt(&self, project_source: &str) -> SourceSelectionReceipt {
SourceSelectionReceipt {
project_source: project_source.to_string(),
physical_root: self.root.root().to_string(),
}
}
pub fn refuse(
&self,
operation: OperationReceipt,
kind: SourceRefusalKind,
retry: RetryAdvice,
evidence: Option<AuthorityIdentity>,
) -> SourceRefusal {
SourceRefusal::new(kind, operation, retry, evidence)
}
pub fn current_query_lease(&self) -> Result<CurrentQueryLease, SourceRefusal> {
Ok(CurrentQueryLease {
generation: GenerationIdentity::fresh(),
})
}
pub fn context_input(
&self,
project_source: &str,
repository_id: &str,
current: Option<CurrentQueryLease>,
) -> ClaimContextInput {
ClaimContextInput {
project_source: project_source.to_string(),
repository_id: repository_id.to_string(),
root: self.root.root().to_string(),
current,
}
}
pub fn completed_render_authority(&self) -> Result<CompletedRenderAuthority, SourceRefusal> {
Ok(CompletedRenderAuthority { _sealed: () })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiskObservationReceipt {
Bytes {
identity: AuthorityIdentity,
physical_root: String,
path: String,
observed_at: ObservationTime,
byte_digest: u64,
},
Metadata {
identity: AuthorityIdentity,
physical_root: String,
path: String,
observed_at: ObservationTime,
size: u64,
},
PathMissing {
identity: AuthorityIdentity,
physical_root: String,
path: String,
observed_at: ObservationTime,
},
}
impl DiskObservationReceipt {
pub fn identity(&self) -> AuthorityIdentity {
match self {
Self::Bytes { identity, .. }
| Self::Metadata { identity, .. }
| Self::PathMissing { identity, .. } => *identity,
}
}
pub fn path(&self) -> &str {
match self {
Self::Bytes { path, .. }
| Self::Metadata { path, .. }
| Self::PathMissing { path, .. } => path,
}
}
pub fn observed_at(&self) -> ObservationTime {
match self {
Self::Bytes { observed_at, .. }
| Self::Metadata { observed_at, .. }
| Self::PathMissing { observed_at, .. } => *observed_at,
}
}
pub fn physical_root(&self) -> &str {
match self {
Self::Bytes { physical_root, .. }
| Self::Metadata { physical_root, .. }
| Self::PathMissing { physical_root, .. } => physical_root,
}
}
pub fn proves_path_local_absence(&self) -> bool {
matches!(self, Self::PathMissing { .. })
}
pub fn proves_generation_absence(&self) -> bool {
false
}
pub fn proves_repository_absence(&self) -> bool {
false
}
pub fn into_failed_read(self, operation: OperationReceipt) -> Result<Self, SourceRefusal> {
Err(SourceRefusal::new(
SourceRefusalKind::SourceUnavailable,
operation,
RetryAdvice::OnEvent,
Some(self.identity()),
))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeObservationScope {
prefix: String,
}
impl WorktreeObservationScope {
pub fn beneath(prefix: &str) -> Self {
Self {
prefix: prefix.to_string(),
}
}
pub fn contains(&self, path: &str) -> bool {
path.starts_with(&self.prefix)
}
pub fn prefix(&self) -> &str {
&self.prefix
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WorktreeObservationCut {
observer_epoch: ObserverEpoch,
start_seq: InvalidationSequence,
end_seq: InvalidationSequence,
}
impl WorktreeObservationCut {
pub fn observer_epoch(&self) -> ObserverEpoch {
self.observer_epoch
}
pub fn start_seq(&self) -> InvalidationSequence {
self.start_seq
}
pub fn end_seq(&self) -> InvalidationSequence {
self.end_seq
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorktreeScopeCoverage {
Complete,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeScopeObservationReceipt {
identity: AuthorityIdentity,
physical_root: String,
scope: WorktreeObservationScope,
scan_id: WorktreeScanId,
observation_cut: WorktreeObservationCut,
coverage: WorktreeScopeCoverage,
}
impl WorktreeScopeObservationReceipt {
pub fn identity(&self) -> AuthorityIdentity {
self.identity
}
pub fn scope(&self) -> &WorktreeObservationScope {
&self.scope
}
pub fn scan_id(&self) -> WorktreeScanId {
self.scan_id
}
pub fn observation_cut(&self) -> WorktreeObservationCut {
self.observation_cut
}
pub fn coverage(&self) -> WorktreeScopeCoverage {
self.coverage
}
pub fn physical_root(&self) -> &str {
&self.physical_root
}
pub fn proves_absence_within_scope(&self, path: &str) -> bool {
matches!(self.coverage, WorktreeScopeCoverage::Complete) && self.scope.contains(path)
}
pub fn proves_absence_after(&self, sequence: InvalidationSequence) -> bool {
sequence < self.observation_cut.end_seq
}
pub fn proves_absence_before(&self, sequence: InvalidationSequence) -> bool {
sequence > self.observation_cut.start_seq
}
pub fn proves_generation_absence(&self) -> bool {
false
}
pub fn proves_repository_absence(&self) -> bool {
false
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GitObservationReceipt {
Present {
identity: AuthorityIdentity,
object_id: String,
path: String,
},
NotInTree {
identity: AuthorityIdentity,
tree_id: String,
path: String,
},
}
impl GitObservationReceipt {
pub fn not_in_tree(tree_id: &str, path: &str) -> Self {
Self::NotInTree {
identity: AuthorityIdentity::fresh(),
tree_id: tree_id.to_string(),
path: path.to_string(),
}
}
pub fn present(object_id: &str, path: &str) -> Self {
Self::Present {
identity: AuthorityIdentity::fresh(),
object_id: object_id.to_string(),
path: path.to_string(),
}
}
pub fn identity(&self) -> AuthorityIdentity {
match self {
Self::Present { identity, .. } | Self::NotInTree { identity, .. } => *identity,
}
}
pub fn proves_absence_in_tree(&self, tree_id: &str) -> bool {
matches!(self, Self::NotInTree { tree_id: named, .. } if named == tree_id)
}
pub fn proves_generation_absence(&self) -> bool {
false
}
pub fn proves_repository_absence(&self) -> bool {
false
}
}
impl GenerationAuthority {
pub fn into_selected_aggregate(self) -> SelectedAggregateAuthority {
SelectedAggregateAuthority {
_generation: self.generation(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectedAggregateAuthority {
_generation: GenerationIdentity,
}
impl SelectedAggregateAuthority {
pub fn proves_repository_absence(&self) -> bool {
true
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceSelectionReceipt {
project_source: String,
physical_root: String,
}
impl SourceSelectionReceipt {
pub fn project_source(&self) -> &str {
&self.project_source
}
pub fn physical_root(&self) -> &str {
&self.physical_root
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentQueryLease {
generation: GenerationIdentity,
}
impl CurrentQueryLease {
pub fn generation(&self) -> GenerationIdentity {
self.generation
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaimContextInput {
project_source: String,
repository_id: String,
root: String,
current: Option<CurrentQueryLease>,
}
impl ClaimContextInput {
pub fn project_source(&self) -> &str {
&self.project_source
}
pub fn repository_id(&self) -> &str {
&self.repository_id
}
pub fn root(&self) -> &str {
&self.root
}
pub fn current(&self) -> Option<&CurrentQueryLease> {
self.current.as_ref()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperationRelationshipContract {
cross_source_permitted: bool,
requires_current: bool,
}
impl OperationRelationshipContract {
pub fn for_operation(kind: OperationKind) -> Self {
let search = matches!(
kind,
OperationKind::SearchSymbols | OperationKind::SearchText
);
Self {
cross_source_permitted: search,
requires_current: search,
}
}
pub fn cross_source_permitted(&self) -> bool {
self.cross_source_permitted
}
pub fn requires_current(&self) -> bool {
self.requires_current
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaimContext {
operation: OperationReceipt,
inputs: Vec<ClaimContextInput>,
permitted_relationships: OperationRelationshipContract,
}
impl ClaimContext {
pub fn operation(&self) -> OperationReceipt {
self.operation
}
pub fn inputs(&self) -> &[ClaimContextInput] {
&self.inputs
}
pub fn permitted_relationships(&self) -> OperationRelationshipContract {
self.permitted_relationships
}
}
pub fn acquire_claim_context(
operation: OperationReceipt,
inputs: Vec<ClaimContextInput>,
) -> Result<ClaimContext, SourceRefusal> {
if inputs.is_empty() {
return Err(SourceRefusal::new(
SourceRefusalKind::InvalidSelection,
operation,
RetryAdvice::Never,
None,
));
}
let contract = OperationRelationshipContract::for_operation(operation.operation_kind());
if !contract.cross_source_permitted() {
let first_root = inputs[0].root();
if inputs.iter().any(|input| input.root() != first_root) {
return Err(SourceRefusal::new(
SourceRefusalKind::SourceUnavailable,
operation,
RetryAdvice::Operator,
None,
));
}
}
if contract.requires_current() && inputs.iter().any(|input| input.current().is_none()) {
return Err(SourceRefusal::new(
SourceRefusalKind::AdmissionUnavailable,
operation,
RetryAdvice::OnEvent,
None,
));
}
Ok(ClaimContext {
operation,
inputs,
permitted_relationships: contract,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AtomicAuthority {
Generation(GenerationAuthority),
DiskObservation(DiskObservationReceipt),
WorktreeScopeObservation(WorktreeScopeObservationReceipt),
GitObservation(GitObservationReceipt),
}
impl AtomicAuthority {
pub fn identity(&self) -> AuthorityIdentity {
match self {
Self::Generation(authority) => authority.identity(),
Self::DiskObservation(receipt) => receipt.identity(),
Self::WorktreeScopeObservation(receipt) => receipt.identity(),
Self::GitObservation(receipt) => receipt.identity(),
}
}
pub fn kind_name(&self) -> &'static str {
match self {
Self::Generation(_) => "Generation",
Self::DiskObservation(_) => "DiskObservation",
Self::WorktreeScopeObservation(_) => "WorktreeScopeObservation",
Self::GitObservation(_) => "GitObservation",
}
}
pub fn physical_root(&self) -> Option<&str> {
match self {
Self::Generation(authority) => Some(authority.physical_root()),
Self::DiskObservation(receipt) => Some(receipt.physical_root()),
Self::WorktreeScopeObservation(receipt) => Some(receipt.physical_root()),
Self::GitObservation(_) => None,
}
}
pub fn proves_generation_absence(&self) -> bool {
match self {
Self::Generation(authority) => authority.proves_generation_absence(),
Self::DiskObservation(receipt) => receipt.proves_generation_absence(),
Self::WorktreeScopeObservation(receipt) => receipt.proves_generation_absence(),
Self::GitObservation(receipt) => receipt.proves_generation_absence(),
}
}
pub fn proves_repository_absence(&self) -> bool {
false
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClaimInput {
Authority(AtomicAuthority),
Selection(SourceSelectionReceipt),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComparisonRelation {
SameContent,
DifferentContent,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClaimProvenance {
Single {
identity: ProvenanceIdentity,
authority: AtomicAuthority,
},
Comparison {
identity: ProvenanceIdentity,
operation: OperationReceipt,
relation: ComparisonRelation,
left: AtomicAuthority,
right: AtomicAuthority,
},
Derivation {
identity: ProvenanceIdentity,
operation: OperationReceipt,
nonempty_inputs: Vec<ClaimInput>,
},
SelectedAggregate {
identity: ProvenanceIdentity,
operation: OperationReceipt,
selections: Vec<SourceSelectionReceipt>,
generations: BTreeMap<String, AtomicAuthority>,
additional_authorities: Vec<AtomicAuthority>,
},
}
impl ClaimProvenance {
pub fn single(authority: AtomicAuthority) -> Self {
Self::Single {
identity: ProvenanceIdentity::fresh(),
authority,
}
}
pub fn comparison(
operation: OperationReceipt,
relation: ComparisonRelation,
left: AtomicAuthority,
right: AtomicAuthority,
) -> Result<Self, SourceRefusal> {
if !roots_are_compatible(&left, &right) {
return Err(SourceRefusal::new(
SourceRefusalKind::SourceUnavailable,
operation,
RetryAdvice::Operator,
Some(left.identity()),
));
}
Ok(Self::Comparison {
identity: ProvenanceIdentity::fresh(),
operation,
relation,
left,
right,
})
}
pub fn derivation(
operation: OperationReceipt,
inputs: Vec<ClaimInput>,
) -> Result<Self, SourceRefusal> {
if inputs.is_empty() {
return Err(SourceRefusal::new(
SourceRefusalKind::InvalidSelection,
operation,
RetryAdvice::Never,
None,
));
}
let authorities: Vec<&AtomicAuthority> = inputs
.iter()
.filter_map(|input| match input {
ClaimInput::Authority(authority) => Some(authority),
ClaimInput::Selection(_) => None,
})
.collect();
if let Some(first) = authorities.first() {
for other in &authorities[1..] {
if !roots_are_compatible(first, other) {
return Err(SourceRefusal::new(
SourceRefusalKind::SourceUnavailable,
operation,
RetryAdvice::Operator,
Some(first.identity()),
));
}
}
}
Ok(Self::Derivation {
identity: ProvenanceIdentity::fresh(),
operation,
nonempty_inputs: inputs,
})
}
pub fn selected_aggregate(
operation: OperationReceipt,
selections: Vec<SourceSelectionReceipt>,
generations: Vec<(String, GenerationAuthority)>,
additional_authorities: Vec<AtomicAuthority>,
) -> Result<Self, SourceRefusal> {
if selections.is_empty() {
return Err(SourceRefusal::new(
SourceRefusalKind::InvalidSelection,
operation,
RetryAdvice::Never,
None,
));
}
let supplied = generations.len();
let captured: BTreeMap<String, AtomicAuthority> = generations
.into_iter()
.map(|(key, generation)| (key, AtomicAuthority::Generation(generation)))
.collect();
if captured.len() != supplied {
return Err(SourceRefusal::new(
SourceRefusalKind::InvalidSelection,
operation,
RetryAdvice::Never,
None,
));
}
if captured.len() != selections.len()
|| !selections
.iter()
.all(|selection| captured.contains_key(selection.project_source()))
{
return Err(SourceRefusal::new(
SourceRefusalKind::SelectionUnavailable,
operation,
RetryAdvice::OnEvent,
None,
));
}
let all: Vec<&AtomicAuthority> = captured
.values()
.chain(additional_authorities.iter())
.collect();
if let Some(first) = all.first() {
for other in &all[1..] {
if !roots_are_compatible(first, other) {
return Err(SourceRefusal::new(
SourceRefusalKind::SourceUnavailable,
operation,
RetryAdvice::Operator,
Some(other.identity()),
));
}
}
}
Ok(Self::SelectedAggregate {
identity: ProvenanceIdentity::fresh(),
operation,
selections,
generations: captured,
additional_authorities,
})
}
pub fn identity(&self) -> ProvenanceIdentity {
match self {
Self::Single { identity, .. }
| Self::Comparison { identity, .. }
| Self::Derivation { identity, .. }
| Self::SelectedAggregate { identity, .. } => *identity,
}
}
pub fn kind_name(&self) -> &'static str {
match self {
Self::Single { .. } => "Single",
Self::Comparison { .. } => "Comparison",
Self::Derivation { .. } => "Derivation",
Self::SelectedAggregate { .. } => "SelectedAggregate",
}
}
pub fn authorities(&self) -> impl Iterator<Item = &AtomicAuthority> + '_ {
let items: Vec<&AtomicAuthority> = match self {
Self::Single { authority, .. } => vec![authority],
Self::Comparison { left, right, .. } => vec![left, right],
Self::Derivation {
nonempty_inputs, ..
} => nonempty_inputs
.iter()
.filter_map(|input| match input {
ClaimInput::Authority(authority) => Some(authority),
ClaimInput::Selection(_) => None,
})
.collect(),
Self::SelectedAggregate {
generations,
additional_authorities,
..
} => generations
.values()
.chain(additional_authorities.iter())
.collect(),
};
items.into_iter()
}
pub fn authority_count(&self) -> usize {
self.authorities().count()
}
}
fn roots_are_compatible(left: &AtomicAuthority, right: &AtomicAuthority) -> bool {
match (left.physical_root(), right.physical_root()) {
(Some(left_root), Some(right_root)) => left_root == right_root,
_ => true,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EvaluationProvenance {
identity: EvaluationIdentity,
}
impl EvaluationProvenance {
pub fn fresh() -> Self {
Self {
identity: EvaluationIdentity::fresh(),
}
}
pub fn for_test() -> Self {
Self::fresh()
}
pub fn identity(&self) -> EvaluationIdentity {
self.identity
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutputCoverage {
Complete,
Truncated(TruncationBreaches),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TruncationBreaches {
breaches: Vec<LimitBreach>,
}
impl TruncationBreaches {
pub fn breaches(&self) -> &[LimitBreach] {
&self.breaches
}
}
#[derive(Debug)]
pub struct CompletedRenderAuthority {
_sealed: (),
}
impl CompletedRenderAuthority {
pub fn truncate(&self, breaches: Vec<(DerivedLimitKind, u64)>) -> OutputCoverage {
if breaches.is_empty() {
return OutputCoverage::Complete;
}
OutputCoverage::Truncated(TruncationBreaches {
breaches: breaches
.into_iter()
.map(|(kind, omitted)| LimitBreach { kind, omitted })
.collect(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Claim<T> {
value: T,
operation: OperationReceipt,
provenance: ClaimProvenance,
evaluation: Option<EvaluationProvenance>,
producing_runtime_identity: ProducingRuntimeIdentity,
rendered_coverage: Option<OutputCoverage>,
}
impl<T> Claim<T> {
pub fn single(operation: OperationReceipt, authority: AtomicAuthority, value: T) -> Self {
Self {
value,
operation,
provenance: ClaimProvenance::single(authority),
evaluation: None,
producing_runtime_identity: ProducingRuntimeIdentity::fresh(),
rendered_coverage: None,
}
}
pub fn single_ranked(
operation: OperationReceipt,
authority: AtomicAuthority,
value: T,
evaluation: EvaluationProvenance,
) -> Self {
Self {
value,
operation,
provenance: ClaimProvenance::single(authority),
evaluation: Some(evaluation),
producing_runtime_identity: ProducingRuntimeIdentity::fresh(),
rendered_coverage: None,
}
}
pub fn derive(
operation: OperationReceipt,
inputs: impl IntoIterator<Item = ClaimInput>,
value: T,
) -> Result<Self, SourceRefusal> {
let provenance = ClaimProvenance::derivation(operation, inputs.into_iter().collect())?;
Ok(Self {
value,
operation,
provenance,
evaluation: None,
producing_runtime_identity: ProducingRuntimeIdentity::fresh(),
rendered_coverage: None,
})
}
pub fn value(&self) -> &T {
&self.value
}
pub fn operation(&self) -> OperationReceipt {
self.operation
}
pub fn provenance(&self) -> &ClaimProvenance {
&self.provenance
}
pub fn evaluation(&self) -> Option<EvaluationProvenance> {
self.evaluation
}
pub fn producing_runtime_identity(&self) -> ProducingRuntimeIdentity {
self.producing_runtime_identity
}
pub fn rendered_coverage(&self) -> Option<&OutputCoverage> {
self.rendered_coverage.as_ref()
}
pub fn render_bounded(mut self, coverage: OutputCoverage) -> Self {
self.rendered_coverage = Some(coverage);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KnowledgeVoice {
Current,
Intent,
NeedsReview,
Unknown,
HistoryOnly,
Suppressed,
}
#[derive(Debug)]
pub struct KnowledgeVoiceFilter;
impl KnowledgeVoiceFilter {
pub fn selectable_voices() -> Vec<KnowledgeVoice> {
vec![
KnowledgeVoice::Current,
KnowledgeVoice::Intent,
KnowledgeVoice::NeedsReview,
KnowledgeVoice::Unknown,
]
}
}