polyc-query 2026.9.0

Read layer over the event log: a DataFusion engine for SQL over replayed partitions, and a per-conversation Parquet projection for participation-scoped search.
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Production-only capabilities for projected `conversation-core/v1` reads.
//!
//! The types here remain crate-private until the service and atomic cutover
//! slices compose them. They close two authority gaps before that point:
//!
//! - metadata planning has complete direct-State and State-Connect adapters;
//! - artifacts arrive through a GCS client whose type and OAuth scope are both
//!   read-only, then immediately disappear behind realm-typed sealed readers.
//!
//! No constructor accepts [`polyc_storage_gcs::GcsClient`]. A Query deployment
//! therefore cannot gain create, mutable-name read, list, or delete authority
//! through this module.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use connectrpc::client::ClientTransport;
use polyc_projection_artifact::{
    ArtifactReadError, ArtifactReadFuture, ExactArtifactBackend, ExactObjectMetadata,
    ExactObjectRange, FleetArtifactAccess, FleetArtifactReader, RealmTopology,
    VisibleArtifactAccess, VisibleArtifactReader,
};
use polyc_state::immutable::AtRestProtection;
use polyc_state::journal::{
    CreateJournalDirectorySnapshot, GetJournalSource, JournalDirectoryPage,
    JournalDirectorySnapshot, JournalSourceHead, ListJournalDirectorySnapshot,
    ReleaseJournalDirectorySnapshot,
};
// Reached only by the in-process adapter below, which the tests compose.
#[cfg(test)]
use polyc_state::journal::JournalRead;
#[cfg(test)]
use polyc_state::projection::ProjectionCatalog;
use polyc_state::projection::artifact::{ExactObjectRef, ManifestTrust, ObjectNamespace};
use polyc_state::projection::{ProjectionResolution, ResolveManifest};
#[cfg(test)]
use polyc_state::query_audit::{AuditPhase, QueryAuditRead, QueryAuditWrite, ReadQueryAudit};
use polyc_state::query_audit::{BeginOutcome, BeginQueryAudit};
use polyc_state::receipt::Receipt;
use polyc_state_connect::journal::client::JournalClient;
use polyc_state_connect::projection::client::ProjectionCatalogClient;
use polyc_state_connect::query_audit::client::QueryAuditClient;
use polyc_storage_gcs::{GcsError, GcsReadClient};

use crate::core_execution::{
    CoreArtifactAuthority, CoreExecutionAdmission, CoreExecutionError, CurrentCredentialAuthority,
};
use crate::core_resolution::{
    CoreCompletionCommand, CoreCompletionContext, CoreExecutionPermit, CoreMetadataAuthority,
    CoreOperationContext, CoreResolutionError,
};

/// Names the in-process State audit capability Query composes directly.
///
/// The transported composition reaches the same two capabilities through
/// `polyc_state_connect`. This alias exists so the direct composition states
/// which pair it needs, in one place, without naming a transport type.
#[cfg(test)]
pub(crate) trait DirectQueryAudit: QueryAuditRead + QueryAuditWrite {}

#[cfg(test)]
impl<T> DirectQueryAudit for T where T: QueryAuditRead + QueryAuditWrite + ?Sized {}

/// Direct in-process access to the three State capabilities planning and
/// terminal settlement need. The journal, catalog, and audit implementations
/// may be backed by different modules; no umbrella State authority is accepted.
#[cfg(test)]
pub(crate) struct DirectCoreMetadata {
    journal: Arc<dyn JournalRead>,
    projections: Arc<dyn ProjectionCatalog>,
    audit: Arc<dyn DirectQueryAudit>,
}

#[cfg(test)]
impl DirectCoreMetadata {
    pub(crate) const fn new(
        journal: Arc<dyn JournalRead>,
        projections: Arc<dyn ProjectionCatalog>,
        audit: Arc<dyn DirectQueryAudit>,
    ) -> Self {
        Self {
            journal,
            projections,
            audit,
        }
    }
}

#[async_trait]
#[cfg(test)]
impl CoreMetadataAuthority for DirectCoreMetadata {
    async fn create_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
    ) -> Result<JournalDirectorySnapshot, CoreResolutionError> {
        Ok(self.journal.create_directory_snapshot(
            CreateJournalDirectorySnapshot,
            operation.local_context()?,
        )?)
    }

    async fn directory_page(
        &self,
        operation: &CoreOperationContext,
        request: ListJournalDirectorySnapshot,
    ) -> Result<JournalDirectoryPage, CoreResolutionError> {
        Ok(self
            .journal
            .directory_page(request, operation.local_context()?)?)
    }

    async fn release_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
        request: ReleaseJournalDirectorySnapshot,
    ) -> Result<(), CoreResolutionError> {
        Ok(self
            .journal
            .release_directory_snapshot(request, operation.local_context()?)?)
    }

    async fn source_head(
        &self,
        operation: &CoreOperationContext,
        request: GetJournalSource,
    ) -> Result<Option<JournalSourceHead>, CoreResolutionError> {
        Ok(self
            .journal
            .source_head(request, operation.local_context()?)?)
    }

    async fn resolve_manifest(
        &self,
        operation: &CoreOperationContext,
        request: ResolveManifest,
    ) -> Result<ProjectionResolution, CoreResolutionError> {
        Ok(self
            .projections
            .resolve(request, operation.local_context()?)?)
    }

    async fn begin_audit(
        &self,
        operation: &CoreOperationContext,
        command: BeginQueryAudit,
    ) -> Result<BeginOutcome<CoreExecutionPermit>, CoreResolutionError> {
        Ok(map_begin_outcome(
            self.audit.begin(command, operation.local_context()?)?,
        ))
    }

    async fn complete_audit(
        &self,
        operation: &CoreCompletionContext,
        command: &CoreCompletionCommand,
    ) -> Result<Receipt, CoreResolutionError> {
        let CoreCompletionCommand::Local(command) = command else {
            return Err(CoreResolutionError::InvalidComposition);
        };
        Ok(self
            .audit
            .complete(command.clone(), operation.local_context()?)?)
    }

    async fn completion_receipt(
        &self,
        operation: &CoreCompletionContext,
        command: &CoreCompletionCommand,
    ) -> Result<Option<Receipt>, CoreResolutionError> {
        let CoreCompletionCommand::Local(command) = command else {
            return Err(CoreResolutionError::InvalidComposition);
        };
        let context = operation.local_context()?;
        let Some(receipt) = self.audit.recorded_receipt(
            command.query(),
            command.namespace(),
            AuditPhase::Completion,
        )?
        else {
            return Ok(None);
        };
        if !receipt.is_deduplicated() || !receipt.answers(command.metadata()) {
            return Err(CoreResolutionError::CompletionReceiptMismatch);
        }
        let audit = self
            .audit
            .audit(
                ReadQueryAudit::new(command.query().clone(), command.namespace().clone()),
                context,
            )?
            .ok_or(CoreResolutionError::CompletionReceiptMismatch)?;
        if audit.intent().source() != command.intent_source()
            || audit.completion() != Some(command.completion())
        {
            return Err(CoreResolutionError::CompletionReceiptMismatch);
        }
        Ok(Some(receipt))
    }
}

/// State-Connect access to the same closed metadata capability set.
pub(crate) struct ConnectCoreMetadata<T> {
    journal: JournalClient<T>,
    projections: ProjectionCatalogClient<T>,
    audit: QueryAuditClient<T>,
}

impl<T> ConnectCoreMetadata<T> {
    pub(crate) const fn new(
        journal: JournalClient<T>,
        projections: ProjectionCatalogClient<T>,
        audit: QueryAuditClient<T>,
    ) -> Self {
        Self {
            journal,
            projections,
            audit,
        }
    }
}

#[async_trait]
impl<T> CoreMetadataAuthority for ConnectCoreMetadata<T>
where
    T: ClientTransport + Send + Sync,
    <T::ResponseBody as connectrpc::http_body::Body>::Error: fmt::Display,
{
    async fn create_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
    ) -> Result<JournalDirectorySnapshot, CoreResolutionError> {
        Ok(self
            .journal
            .create_directory_snapshot(&operation.declared()?, &CreateJournalDirectorySnapshot)
            .await?)
    }

    async fn directory_page(
        &self,
        operation: &CoreOperationContext,
        request: ListJournalDirectorySnapshot,
    ) -> Result<JournalDirectoryPage, CoreResolutionError> {
        Ok(self
            .journal
            .directory_page(&operation.declared()?, &request)
            .await?)
    }

    async fn release_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
        request: ReleaseJournalDirectorySnapshot,
    ) -> Result<(), CoreResolutionError> {
        Ok(self
            .journal
            .release_directory_snapshot(&operation.declared()?, &request)
            .await?)
    }

    async fn source_head(
        &self,
        operation: &CoreOperationContext,
        request: GetJournalSource,
    ) -> Result<Option<JournalSourceHead>, CoreResolutionError> {
        Ok(self
            .journal
            .source_head(&operation.declared()?, &request)
            .await?)
    }

    async fn resolve_manifest(
        &self,
        operation: &CoreOperationContext,
        request: ResolveManifest,
    ) -> Result<ProjectionResolution, CoreResolutionError> {
        Ok(self
            .projections
            .resolve(&operation.declared()?, &request)
            .await?)
    }

    async fn begin_audit(
        &self,
        operation: &CoreOperationContext,
        command: BeginQueryAudit,
    ) -> Result<BeginOutcome<CoreExecutionPermit>, CoreResolutionError> {
        Ok(map_begin_outcome(
            self.audit.begin(&operation.declared()?, &command).await?,
        ))
    }

    async fn complete_audit(
        &self,
        operation: &CoreCompletionContext,
        command: &CoreCompletionCommand,
    ) -> Result<Receipt, CoreResolutionError> {
        let CoreCompletionCommand::Remote(command) = command else {
            return Err(CoreResolutionError::InvalidComposition);
        };
        let receipt = self
            .audit
            .complete(&operation.declared()?, command)
            .await
            .map_err(settlement_answer)?;
        // Defence in depth. The client already refuses a receipt that does
        // not answer this command; checking again here means one broken or
        // hostile State is classified the same way whichever code path
        // noticed it first.
        if !receipt.answers(command.metadata()) {
            return Err(CoreResolutionError::CompletionReceiptMismatch);
        }
        Ok(receipt)
    }

    async fn completion_receipt(
        &self,
        operation: &CoreCompletionContext,
        command: &CoreCompletionCommand,
    ) -> Result<Option<Receipt>, CoreResolutionError> {
        let CoreCompletionCommand::Remote(command) = command else {
            return Err(CoreResolutionError::InvalidComposition);
        };
        let Some(receipt) = self
            .audit
            .completion_receipt(&operation.declared()?, command)
            .await
            .map_err(settlement_answer)?
        else {
            return Ok(None);
        };
        if !receipt.is_deduplicated() || !receipt.answers(command.metadata()) {
            return Err(CoreResolutionError::CompletionReceiptMismatch);
        }
        Ok(Some(receipt))
    }
}

/// Classifies a settlement answer that does not match the presented command.
///
/// The Connect client refuses a response whose receipt or audit trail
/// disagrees with the command it sent, and names the exact field. Those are
/// not State declining the operation: they are a remote answering about
/// something else, which is what a broken or compromised listener looks like
/// from here.
///
/// The direct adapter calls that `CompletionReceiptMismatch`. This adapter
/// agrees, so one dishonest answer is classified identically whichever
/// transport carried it, and never as a retryable State outage.
fn settlement_answer(error: polyc_state::query_audit::QueryAuditError) -> CoreResolutionError {
    if let polyc_state::query_audit::QueryAuditError::State(
        polyc_state::error::StateError::Malformed { field, .. },
    ) = &error
        && (field.starts_with("receipt") || field.starts_with("audit"))
    {
        return CoreResolutionError::CompletionReceiptMismatch;
    }
    error.into()
}

fn map_begin_outcome<P: Into<CoreExecutionPermit>>(
    outcome: BeginOutcome<P>,
) -> BeginOutcome<CoreExecutionPermit> {
    match outcome {
        BeginOutcome::Granted(permit) => BeginOutcome::Granted(permit.into()),
        BeginOutcome::AlreadyRecorded(receipt) => BeginOutcome::AlreadyRecorded(receipt),
    }
}

/// `Debug` reports the protection only. A namespace names where tenant bytes
/// live, so it never reaches a log line through this type.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct GcsReadNamespace {
    namespace: ObjectNamespace,
    protection: AtRestProtection,
}

impl std::fmt::Debug for GcsReadNamespace {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("GcsReadNamespace")
            .field("protection", &self.protection)
            .finish_non_exhaustive()
    }
}

impl GcsReadNamespace {
    pub(crate) const fn new(namespace: ObjectNamespace, protection: AtRestProtection) -> Self {
        Self {
            namespace,
            protection,
        }
    }
}

#[derive(Clone)]
struct GcsExactBackend {
    client: GcsReadClient,
    protection: BTreeMap<ObjectNamespace, AtRestProtection>,
}

impl GcsExactBackend {
    fn try_new(
        client: GcsReadClient,
        profiles: &[GcsReadNamespace],
    ) -> Result<Self, CoreExecutionError> {
        let protection = profiles
            .iter()
            .map(|profile| (profile.namespace.clone(), profile.protection))
            .collect::<BTreeMap<_, _>>();
        if profiles.is_empty() || protection.len() != profiles.len() {
            return Err(CoreExecutionError::InvalidComposition(
                "an artifact realm has empty or duplicate namespace protection",
            ));
        }
        Ok(Self { client, protection })
    }

    fn object_name(reference: &ExactObjectRef) -> String {
        format!(
            "{}/{}",
            reference.namespace().as_str(),
            reference.key().as_str()
        )
    }
}

impl ExactArtifactBackend for GcsExactBackend {
    fn declared_protection(&self, namespace: &ObjectNamespace) -> AtRestProtection {
        self.protection
            .get(namespace)
            .copied()
            .unwrap_or(AtRestProtection::None)
    }

    fn head_exact(
        &self,
        reference: &ExactObjectRef,
    ) -> ArtifactReadFuture<'_, ExactObjectMetadata> {
        let name = Self::object_name(reference);
        let generation = reference.generation();
        Box::pin(async move {
            let address = i64::try_from(generation).map_err(|_| ArtifactReadError::Refused {
                reason: format!("{name} names a generation GCS cannot address"),
            })?;
            match self.client.head_exact(&name, address).await {
                Ok(metadata) => {
                    let observed = u64::try_from(metadata.generation).map_err(|_| {
                        ArtifactReadError::Refused {
                            reason: format!("{name} returned an invalid generation"),
                        }
                    })?;
                    Ok(ExactObjectMetadata::new(observed, metadata.size))
                }
                Err(error) => Err(classify_gcs_read(&name, generation, None, error)),
            }
        })
    }

    fn read_exact_range(
        &self,
        reference: &ExactObjectRef,
        offset: u64,
        len: u64,
    ) -> ArtifactReadFuture<'_, ExactObjectRange> {
        let name = Self::object_name(reference);
        let generation = reference.generation();
        Box::pin(async move {
            let address = i64::try_from(generation).map_err(|_| ArtifactReadError::Refused {
                reason: format!("{name} names a generation GCS cannot address"),
            })?;
            let served = self
                .client
                .read_exact_range(&name, address, offset, len)
                .await
                .map_err(|error| classify_gcs_read(&name, generation, Some(offset), error))?;
            // This adapter translates the transport's served range into the
            // shared one. It does not decide. `accept_served_range` in the
            // shared realm reader owns the comparison, so one reader makes it
            // for every backend rather than each adapter making its own.
            let observed =
                u64::try_from(served.generation()).map_err(|_| ArtifactReadError::Refused {
                    reason: format!("{name} served a generation this reader cannot represent"),
                })?;
            Ok(ExactObjectRange::new(observed, served.into_bytes()))
        })
    }
}

fn classify_gcs_read(
    name: &str,
    generation: u64,
    offset: Option<u64>,
    error: GcsError,
) -> ArtifactReadError {
    match error {
        GcsError::NotFound { .. } => ArtifactReadError::NotFound {
            key: name.to_owned(),
            generation,
        },
        GcsError::GenerationMismatch {
            expected, observed, ..
        } => match (u64::try_from(expected), u64::try_from(observed)) {
            (Ok(expected), Ok(observed)) => ArtifactReadError::GenerationMismatch {
                expected,
                observed,
                key: name.to_owned(),
            },
            _ => ArtifactReadError::Refused {
                reason: format!("{name} returned an invalid generation mismatch"),
            },
        },
        GcsError::ShortRead {
            offset,
            expected,
            observed,
            ..
        } => ArtifactReadError::RangeLengthMismatch {
            key: name.to_owned(),
            offset,
            expected,
            observed,
        },
        GcsError::OverlongRead {
            offset,
            expected,
            observed_at_least,
            ..
        } => ArtifactReadError::RangeLengthMismatch {
            key: name.to_owned(),
            offset,
            expected,
            observed: observed_at_least,
        },
        GcsError::Http(inner) => ArtifactReadError::Unavailable {
            reason: format!("{name}: {inner}"),
        },
        GcsError::Status { status, message }
            if status == 408 || status == 429 || (500..600).contains(&status) =>
        {
            ArtifactReadError::Unavailable {
                reason: format!("{name}: {status} {message}"),
            }
        }
        GcsError::RangeTooLarge { len, .. } => ArtifactReadError::Refused {
            reason: format!("{name}: exact range of {len} bytes cannot be represented"),
        },
        other => ArtifactReadError::Refused {
            reason: format!(
                "{name}{}: {other}",
                offset.map_or_else(String::new, |value| format!(" at offset {value}"))
            ),
        },
    }
}

pub(crate) struct VisibleGcsSource {
    client: GcsReadClient,
    profiles: Vec<GcsReadNamespace>,
}

impl VisibleGcsSource {
    pub(crate) const fn new(client: GcsReadClient, profiles: Vec<GcsReadNamespace>) -> Self {
        Self { client, profiles }
    }
}

pub(crate) struct FleetGcsSource {
    client: GcsReadClient,
    profiles: Vec<GcsReadNamespace>,
}

impl FleetGcsSource {
    pub(crate) const fn new(client: GcsReadClient, profiles: Vec<GcsReadNamespace>) -> Self {
        Self { client, profiles }
    }
}

fn namespace_set(profiles: &[GcsReadNamespace]) -> BTreeSet<ObjectNamespace> {
    profiles
        .iter()
        .map(|profile| profile.namespace.clone())
        .collect()
}

/// Composes a visible-only artifact authority. Fleet namespace names are
/// topology data only; this path receives no Fleet credential or reader.
#[allow(clippy::too_many_arguments)]
pub(crate) fn visible_gcs_artifacts(
    visible: VisibleGcsSource,
    fleet_namespaces: impl IntoIterator<Item = ObjectNamespace>,
    trust: Arc<dyn ManifestTrust>,
    scope: Arc<dyn CurrentCredentialAuthority>,
    revalidation_interval: Duration,
    admission: Arc<CoreExecutionAdmission>,
) -> Result<CoreArtifactAuthority, CoreExecutionError> {
    let visible_namespaces = namespace_set(&visible.profiles);
    let topology = RealmTopology::try_new(visible_namespaces.clone(), fleet_namespaces)?;
    let backend = GcsExactBackend::try_new(visible.client, &visible.profiles)?;
    let reader: Arc<dyn VisibleArtifactAccess> =
        Arc::new(VisibleArtifactReader::try_new(backend, visible_namespaces)?);
    CoreArtifactAuthority::visible(
        reader,
        trust,
        topology,
        scope,
        revalidation_interval,
        admission,
    )
}

/// Composes Fleet execution with separately typed visible and Fleet-only
/// clients. The visible reader still serves visible artifacts; the Fleet
/// reader cannot mint visible tokens.
#[allow(clippy::too_many_arguments)]
pub(crate) fn fleet_gcs_artifacts(
    visible: VisibleGcsSource,
    fleet: FleetGcsSource,
    trust: Arc<dyn ManifestTrust>,
    scope: Arc<dyn CurrentCredentialAuthority>,
    revalidation_interval: Duration,
    admission: Arc<CoreExecutionAdmission>,
) -> Result<CoreArtifactAuthority, CoreExecutionError> {
    let visible_namespaces = namespace_set(&visible.profiles);
    let fleet_namespaces = namespace_set(&fleet.profiles);
    let topology = RealmTopology::try_new(visible_namespaces.clone(), fleet_namespaces.clone())?;
    let visible_backend = GcsExactBackend::try_new(visible.client, &visible.profiles)?;
    let fleet_backend = GcsExactBackend::try_new(fleet.client, &fleet.profiles)?;
    let visible_reader: Arc<dyn VisibleArtifactAccess> = Arc::new(VisibleArtifactReader::try_new(
        visible_backend,
        visible_namespaces,
    )?);
    let fleet_reader: Arc<dyn FleetArtifactAccess> = Arc::new(FleetArtifactReader::try_new(
        fleet_backend,
        fleet_namespaces,
    )?);
    CoreArtifactAuthority::fleet(
        visible_reader,
        fleet_reader,
        trust,
        topology,
        scope,
        revalidation_interval,
        admission,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_status_classification_is_retry_safe_and_content_free() {
        let throttled = classify_gcs_read(
            "visible/object",
            7,
            None,
            GcsError::Status {
                status: 429,
                message: "response body withheld".to_owned(),
            },
        );
        assert!(throttled.is_retryable());

        let denied = classify_gcs_read(
            "visible/object",
            7,
            None,
            GcsError::Status {
                status: 403,
                message: "response body withheld".to_owned(),
            },
        );
        assert!(!denied.is_retryable());
        assert!(!denied.to_string().contains("provider-secret"));
    }

    #[test]
    fn crossed_generation_remains_typed() {
        let error = classify_gcs_read(
            "visible/object",
            7,
            None,
            GcsError::GenerationMismatch {
                name: "visible/object".to_owned(),
                expected: 7,
                observed: 8,
            },
        );
        assert!(matches!(
            error,
            ArtifactReadError::GenerationMismatch {
                expected: 7,
                observed: 8,
                ..
            }
        ));
    }
}

/// The two production metadata adapters, proved against real State.
#[cfg(test)]
mod adapter_conformance;