1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//! Exact source-neutral relationship-selection host-service contracts.
use std::sync::Arc;
use axioval_ir::{Evidence, ObjectId};
use thiserror::Error;
use crate::session::{SnapshotBoundService, SourceSnapshot};
/// Failure to select comparison candidates conclusively.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum RelationshipSelectionError {
/// The requested relationship or candidate universe is malformed.
#[error("relationship selection request is invalid")]
InvalidRequest,
/// The candidate universe or response contains the same object more than once.
#[error("relationship selection contains a duplicate candidate")]
DuplicateCandidate,
/// A response repeats one evidence locator.
#[error("relationship selection contains duplicate evidence")]
DuplicateEvidence,
/// Returned data belongs to another request or escapes its candidate universe.
#[error("relationship selection response does not match its request")]
ResponseRequestMismatch,
/// A conclusive selection lacks exact, reviewable completeness evidence.
#[error("relationship selection evidence is not exact and reviewable")]
InexactEvidence,
/// The source cannot currently provide a conclusive selection.
#[error("relationship selection unavailable: {0}")]
Unavailable(String),
}
/// A host-registered semantic relationship or grouping identity.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SemanticRelationship(String);
impl SemanticRelationship {
/// Creates a non-empty source-neutral relationship identity.
pub fn try_new(value: impl Into<String>) -> Result<Self, RelationshipSelectionError> {
let value = value.into();
if value.trim().is_empty() {
return Err(RelationshipSelectionError::InvalidRequest);
}
Ok(Self(value))
}
/// Returns the declared semantic identity.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
/// Direction used when traversing a directed semantic relationship.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TraversalDirection {
/// Follow edges from source to target.
Forward,
/// Follow edges from target to source.
Backward,
/// Follow edges in either direction.
Either,
}
/// Source-neutral relationship operation used to select candidates.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RelationshipQuery {
/// Select members sharing at least one complete semantic group with the anchor.
SharedGroup {
/// Host-registered grouping identity such as a spatial or assembly context.
relationship: SemanticRelationship,
},
/// Traverse a directed semantic relationship from the anchor.
Related {
/// Host-registered relationship identity.
relationship: SemanticRelationship,
/// Requested traversal direction.
direction: TraversalDirection,
/// Whether traversal continues beyond immediate neighbors.
follow_chain: bool,
},
}
impl RelationshipQuery {
/// The relationship or grouping identity the query names.
#[must_use]
pub fn relationship(&self) -> &SemanticRelationship {
match self {
Self::SharedGroup { relationship } | Self::Related { relationship, .. } => relationship,
}
}
}
/// What a relationship service does with an instance whose required end is absent.
///
/// A source can carry relationship instances that omit an end the schema
/// requires, for example a virtual space boundary with no bounding element.
/// Such an instance contributes no edge through the absent end, so treating it
/// as a complete answer would silently read "not related" into a gap. The
/// default refuses; a rule opts into skipping explicitly, and the service then
/// names every skipped instance it passed over in the selection's evidence.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AbsentEndPolicy {
/// Refuse the whole answer while any instance of the type lacks a required end.
#[default]
Refuse,
/// Answer from the edges that exist and cite each skipped instance.
Skip,
}
/// Request for relationship-selected objects within a caller-bound universe.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct RelationshipSelectionRequest {
anchor: ObjectId,
candidate_universe: Vec<ObjectId>,
query: RelationshipQuery,
absent_ends: AbsentEndPolicy,
}
impl RelationshipSelectionRequest {
/// Creates a request with a canonical, duplicate-free candidate universe.
pub fn try_new(
anchor: ObjectId,
mut candidate_universe: Vec<ObjectId>,
query: RelationshipQuery,
) -> Result<Self, RelationshipSelectionError> {
candidate_universe.sort();
if candidate_universe.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(RelationshipSelectionError::DuplicateCandidate);
}
Ok(Self {
anchor,
candidate_universe,
query,
absent_ends: AbsentEndPolicy::default(),
})
}
/// Sets how instances with an absent required end are treated.
#[must_use]
pub fn with_absent_ends(mut self, policy: AbsentEndPolicy) -> Self {
self.absent_ends = policy;
self
}
/// How instances with an absent required end are treated.
#[must_use]
pub fn absent_ends(&self) -> AbsentEndPolicy {
self.absent_ends
}
/// Anchor whose relationships determine the selection.
#[must_use]
pub fn anchor(&self) -> &ObjectId {
&self.anchor
}
/// Complete caller-approved universe from which candidates may be returned.
#[must_use]
pub fn candidate_universe(&self) -> &[ObjectId] {
&self.candidate_universe
}
/// Requested relationship operation.
#[must_use]
pub fn query(&self) -> &RelationshipQuery {
&self.query
}
fn contains_candidate(&self, candidate: &ObjectId) -> bool {
self.candidate_universe.binary_search(candidate).is_ok()
}
}
/// Complete exact candidate selection bound to the request that produced it.
#[derive(Clone, Debug, PartialEq)]
pub struct CompleteRelationshipSelection {
request: RelationshipSelectionRequest,
candidates: Vec<ObjectId>,
evidence: Vec<Evidence>,
}
impl CompleteRelationshipSelection {
/// Creates a request-bound complete selection with canonical candidate ordering.
pub fn try_new(
request: RelationshipSelectionRequest,
mut candidates: Vec<ObjectId>,
mut evidence: Vec<Evidence>,
) -> Result<Self, RelationshipSelectionError> {
candidates.sort();
if candidates.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(RelationshipSelectionError::DuplicateCandidate);
}
if candidates
.iter()
.any(|candidate| !request.contains_candidate(candidate))
{
return Err(RelationshipSelectionError::ResponseRequestMismatch);
}
if evidence.is_empty() || evidence.iter().any(|item| !reviewable(item)) {
return Err(RelationshipSelectionError::InexactEvidence);
}
evidence.sort_by(|left, right| {
(&left.source, &left.locator).cmp(&(&right.source, &right.locator))
});
if evidence.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(RelationshipSelectionError::DuplicateEvidence);
}
Ok(Self {
request,
candidates,
evidence,
})
}
/// Complete request, including anchor, universe, and query.
#[must_use]
pub fn request(&self) -> &RelationshipSelectionRequest {
&self.request
}
/// Canonically ordered selected candidates.
#[must_use]
pub fn candidates(&self) -> &[ObjectId] {
&self.candidates
}
/// Exact reviewable evidence proving the selection is complete.
#[must_use]
pub fn evidence(&self) -> &[Evidence] {
&self.evidence
}
}
/// Trusted adapter seam for complete relationship-based candidate selection.
pub trait RelationshipSelectionService: Send + Sync {
/// Exact source snapshots used to construct this service.
///
/// The default is intentionally unbound for services used only through a
/// raw [`crate::ServiceRegistry`]; an [`crate::EvidenceSession`] rejects it.
fn source_snapshots(&self) -> &[SourceSnapshot] {
&[]
}
/// Selects candidates or reports why the result is not conclusive.
fn select(
&self,
request: &RelationshipSelectionRequest,
) -> Result<CompleteRelationshipSelection, RelationshipSelectionError>;
}
/// Cloneable, type-erased relationship service registered by the host.
#[derive(Clone)]
pub struct RelationshipSelectionServiceHandle(Arc<dyn RelationshipSelectionService>);
impl RelationshipSelectionServiceHandle {
/// Wraps a trusted relationship-selection service.
#[must_use]
pub fn new(service: Arc<dyn RelationshipSelectionService>) -> Self {
Self(service)
}
/// Selects and validates complete request binding and evidence exactness.
pub fn select(
&self,
request: &RelationshipSelectionRequest,
) -> Result<CompleteRelationshipSelection, RelationshipSelectionError> {
validate_selection(request, self.0.select(request)?)
}
}
/// Checks that `selection` answers exactly `request`, stays inside its
/// universe in canonical order, and carries exact reviewable evidence.
pub(crate) fn validate_selection(
request: &RelationshipSelectionRequest,
selection: CompleteRelationshipSelection,
) -> Result<CompleteRelationshipSelection, RelationshipSelectionError> {
if selection.request() != request
|| selection
.candidates()
.iter()
.any(|candidate| !request.contains_candidate(candidate))
{
return Err(RelationshipSelectionError::ResponseRequestMismatch);
}
if selection
.candidates()
.windows(2)
.any(|pair| pair[0] >= pair[1])
{
return Err(RelationshipSelectionError::DuplicateCandidate);
}
if selection.evidence().is_empty() || selection.evidence().iter().any(|item| !reviewable(item))
{
return Err(RelationshipSelectionError::InexactEvidence);
}
Ok(selection)
}
impl SnapshotBoundService for RelationshipSelectionServiceHandle {
fn source_snapshots(&self) -> &[SourceSnapshot] {
self.0.source_snapshots()
}
}
fn reviewable(evidence: &Evidence) -> bool {
evidence.exact && !evidence.locator.trim().is_empty()
}