hf2q 0.1.7

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
//! Descriptor-relative standalone installation state.
//!
//! This bounded context implements private descriptor-relative extraction,
//! crash-resumable normalization to signed file/directory modes under a private
//! stage root, crash-durable no-replace prepared-version publication, and the
//! first activation of an already authenticated standalone release. Only the
//! sealed current-time TUF/native coordinator can publish; neither publication
//! nor activation establishes generic update or deletion authority.

mod artifact;
mod extraction;
mod file;
mod host;
mod identity;
mod locked;
pub(in crate::distribution) mod metadata;
mod release_floor;
mod unix;
mod verify;

#[cfg(test)]
mod release_floor_tests;
#[cfg(test)]
mod test_fixture;
#[cfg(test)]
mod tests;

use std::fs::File;
use std::path::{Path, PathBuf};

use schema::{
    AbsoluteInstallPath, InstallReceiptError, InstallReceiptV1, OwnerFamily, ReleaseManifestError,
    TransitionKind, UpdateRoute,
};

use self::unix::Directory;
use self::verify::VerifiedPreparedVersion;
use super::schema;

#[cfg(test)]
pub(in crate::distribution) use artifact::create_ephemeral_artifact_stage;
pub(in crate::distribution) use artifact::{
    ArtifactStageError, EphemeralArtifactStage, VerifiedArchiveFile,
};
#[cfg(test)]
pub(in crate::distribution) use extraction::{
    abort_after_prepared_barrier, fail_after_prepared_barrier, observed_prepared_barriers,
    reset_observed_prepared_barriers, run_prepared_crash_worker, set_prepared_precommit_hook,
};
pub(in crate::distribution) use extraction::{
    ExecutableReleaseBinding, ExtractedReleaseTree, ExtractionError,
    NormalizedExtractedReleaseTree, PreparedVersionError, PreparedVersionState,
    PublishedPreparedVersion, ReleaseExtractionStage, VerifiedPublishedPreparedVersion,
};
#[allow(unused_imports)]
pub(in crate::distribution) use identity::{
    bootstrap_installation_identity, open_existing_installation_identity,
    DurableInstallationIdentity, InstallationIdentityBootstrap, LockedInstallationIdentity,
};
pub(in crate::distribution) use release_floor::{
    ActiveInstalledReleaseFloor, LiveInstalledReleaseFloor,
};

#[cfg(test)]
pub(in crate::distribution) use identity::{
    bootstrap_installation_identity_for_test, IdentityFaultPlan,
};

const FIRST_SEQUENCE: u64 = 1;
const FIRST_GENERATION: &str = "00000000000000000001";
const PENDING_ACTIVATION: &str = ".pending-00000000000000000001";
const PENDING_CURRENT: &str = ".current-00000000000000000001";
const CURRENT_TARGET: &str = "activations/00000000000000000001";

#[cfg(test)]
std::thread_local! {
    static FAIL_AFTER_CURRENT_COMMIT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static FAIL_RECOVERY_BARRIER: std::cell::Cell<Option<RecoveryBarrier>> = const { std::cell::Cell::new(None) };
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RecoveryBarrier {
    ActivationDirectory,
    ActivationsParent,
    RootDirectory,
    ReceiptFullSync,
}

#[derive(Debug, thiserror::Error)]
pub(crate) enum InstallStateError {
    #[error("another hf2q installation transition is already running")]
    Busy,
    #[error("invalid explicit installation root: {0}")]
    InvalidRoot(&'static str),
    #[error("invalid standalone installation layout: {0}")]
    InvalidLayout(&'static str),
    #[error("required standalone installation {0} is missing")]
    Missing(&'static str),
    #[error("{operation} failed: {source}")]
    Io {
        operation: &'static str,
        #[source]
        source: std::io::Error,
    },
    #[error(transparent)]
    Receipt(#[from] InstallReceiptError),
    #[error(transparent)]
    Manifest(#[from] ReleaseManifestError),
    #[error(transparent)]
    Identity(#[from] schema::InstallationIdentityError),
    #[error(
        "installation identity {installation_id} was committed, but its final durability is unknown: {source}"
    )]
    IdentityCommittedDurabilityUnknown {
        installation_id: String,
        #[source]
        source: Box<InstallStateError>,
    },
    #[error(
        "activation sequence {sequence} was committed, but its final durability is unknown: {source}"
    )]
    CommittedDurabilityUnknown {
        sequence: u64,
        #[source]
        source: Box<InstallStateError>,
    },
}

impl InstallStateError {
    fn io(operation: &'static str, source: rustix::io::Errno) -> Self {
        Self::Io {
            operation,
            source: std::io::Error::from_raw_os_error(source.raw_os_error()),
        }
    }

    fn std_io(operation: &'static str, source: std::io::Error) -> Self {
        Self::Io { operation, source }
    }

    fn after_commit(self) -> Self {
        Self::CommittedDurabilityUnknown {
            sequence: FIRST_SEQUENCE,
            source: Box::new(self),
        }
    }

    fn after_identity_commit(self, installation_id: &schema::InstallationId) -> Self {
        Self::IdentityCommittedDurabilityUnknown {
            installation_id: installation_id.as_str().to_owned(),
            source: Box::new(self),
        }
    }
}

/// Explicit user authorization for one exact standalone installation root.
#[derive(Debug)]
pub(crate) struct ExplicitRootAuthorization {
    path: PathBuf,
    canonical: AbsoluteInstallPath,
}

impl ExplicitRootAuthorization {
    pub(crate) fn new(path: &Path) -> Result<Self, InstallStateError> {
        let text = path
            .to_str()
            .ok_or(InstallStateError::InvalidRoot("root path must be UTF-8"))?;
        let canonical = AbsoluteInstallPath::parse("installation_root", text.to_owned())?;
        Ok(Self {
            path: path.to_owned(),
            canonical,
        })
    }
}

/// Exact receipt bytes whose release targets were authenticated upstream.
///
/// There is deliberately no public constructor. The dormant signed-update
/// adapter constructs this capability only after authenticating the exact
/// manifest/archive/receipt, durably publishing the prepared version, and
/// consuming a receipt-bound final freshness token. Parsing JSON is
/// insufficient; activation preparation independently re-verifies and
/// re-syncs every byte.
#[derive(Debug)]
pub(crate) struct AuthenticatedPreparedVersion {
    receipt_bytes: Vec<u8>,
}

#[cfg(test)]
impl AuthenticatedPreparedVersion {
    fn for_test_only(receipt_bytes: Vec<u8>) -> Self {
        Self { receipt_bytes }
    }
}

#[derive(Debug)]
pub(crate) enum FirstActivationPreparation {
    Ready(PreparedFirstActivation),
    AlreadyCommitted { sequence: u64 },
}

/// A lock-held, descriptor-backed capability to commit only sequence one.
///
/// The capability is intentionally neither `Clone` nor serializable and does
/// not grant update, overwrite, entry-point, pruning, or deletion authority.
#[derive(Debug)]
pub(crate) struct PreparedFirstActivation {
    locked: LockedInstallationIdentity,
    versions: Directory,
    activations: Directory,
    receipt: InstallReceiptV1,
    receipt_bytes: Vec<u8>,
    version: VerifiedPreparedVersion,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FirstActivationOutcome {
    pub(crate) sequence: u64,
}

pub(in crate::distribution) fn prepare_first_activation(
    identity: DurableInstallationIdentity,
    authenticated: AuthenticatedPreparedVersion,
) -> Result<FirstActivationPreparation, InstallStateError> {
    let receipt =
        verify::validate_first_receipt(&authenticated.receipt_bytes, identity.state_root())?;
    if receipt.installation_id() != identity.installation_id() {
        return Err(InstallStateError::InvalidLayout(
            "prepared version belongs to a different installation identity",
        ));
    }
    let locked = identity.lock()?;
    let live = locked.reopen()?;
    let versions = unix::open_directory_at(&live.root, "versions", Some(0o700), true)?;
    let activations = unix::ensure_private_directory(&live.root, "activations")?;

    if unix::entry_identity(locked.root(), "current")?.is_some() {
        let repair = || -> Result<(), InstallStateError> {
            if unix::entry_identity(locked.root(), PENDING_CURRENT)?.is_some() {
                return Err(InstallStateError::InvalidLayout(
                    "committed activation coexists with a pending current entry",
                ));
            }
            let version = verify::verify_prepared_version(&versions, &receipt)?;
            if unix::read_symlink(locked.root(), "current")? != CURRENT_TARGET {
                return Err(InstallStateError::InvalidLayout(
                    "current does not select the canonical first activation",
                ));
            }
            require_exact_activation_parent(&activations)?;
            let activation = verify::verify_committed_first_activation(
                locked.root(),
                &activations,
                &receipt,
                &authenticated.receipt_bytes,
                &version,
            )?;
            repeat_postcommit_barriers(&activation, &activations, locked.root())?;
            locked.full_sync_endpoint()?;
            Ok(())
        };
        repair().map_err(InstallStateError::after_commit)?;
        return Ok(FirstActivationPreparation::AlreadyCommitted {
            sequence: FIRST_SEQUENCE,
        });
    }

    let version = verify::verify_prepared_version(&versions, &receipt)?;

    Ok(FirstActivationPreparation::Ready(PreparedFirstActivation {
        locked,
        versions,
        activations,
        receipt,
        receipt_bytes: authenticated.receipt_bytes,
        version,
    }))
}

impl PreparedFirstActivation {
    pub(crate) fn commit(self) -> Result<FirstActivationOutcome, InstallStateError> {
        let (activations, version) = self.reopen_verified_namespace()?;
        if unix::entry_identity(self.locked.root(), "current")?.is_some() {
            return Err(InstallStateError::InvalidLayout(
                "current appeared after first-activation preparation",
            ));
        }

        self.publish_or_adopt_activation(&activations, &version)?;
        self.stage_current_link()?;

        // Re-open every root-relative directory and re-verify the complete
        // activation immediately before the sole commit point. This prevents
        // a stale descriptor from authorizing a different named namespace.
        let (live_activations, live_version) = self.reopen_verified_namespace()?;
        require_exact_activation_parent(&live_activations)?;
        verify::verify_activation(
            &live_activations,
            FIRST_GENERATION,
            &self.receipt,
            &self.receipt_bytes,
            &live_version,
        )?;
        if unix::entry_identity(self.locked.root(), "current")?.is_some()
            || unix::read_symlink(self.locked.root(), PENDING_CURRENT)? != CURRENT_TARGET
        {
            return Err(InstallStateError::InvalidLayout(
                "current namespace changed before activation commit",
            ));
        }
        // This no-replace rename is the sole activation commit point.
        unix::rename_noreplace(
            self.locked.root(),
            PENDING_CURRENT,
            self.locked.root(),
            "current",
        )?;

        #[cfg(test)]
        if FAIL_AFTER_CURRENT_COMMIT.replace(false) {
            return Err(InstallStateError::std_io(
                "injected post-commit durability step",
                std::io::Error::other("test-only post-commit failure"),
            )
            .after_commit());
        }

        let finalize = || -> Result<(), InstallStateError> {
            let (fresh_activations, fresh_version) = self.reopen_verified_namespace()?;
            require_exact_activation_parent(&fresh_activations)?;
            let activation = verify::verify_committed_first_activation(
                self.locked.root(),
                &fresh_activations,
                &self.receipt,
                &self.receipt_bytes,
                &fresh_version,
            )?;
            repeat_postcommit_barriers(&activation, &fresh_activations, self.locked.root())?;
            self.locked.full_sync_endpoint()?;
            Ok(())
        };
        finalize().map_err(InstallStateError::after_commit)?;
        Ok(FirstActivationOutcome {
            sequence: FIRST_SEQUENCE,
        })
    }

    fn publish_or_adopt_activation(
        &self,
        activations: &Directory,
        version: &VerifiedPreparedVersion,
    ) -> Result<File, InstallStateError> {
        let names = unix::list_names(activations)?;
        let allowed = std::collections::BTreeSet::from([
            FIRST_GENERATION.to_owned(),
            PENDING_ACTIVATION.to_owned(),
        ]);
        if !names.is_subset(&allowed) {
            return Err(InstallStateError::InvalidLayout(
                "first activation parent contains an unexpected generation",
            ));
        }
        let final_exists = names.contains(FIRST_GENERATION);
        let pending_exists = names.contains(PENDING_ACTIVATION);
        if final_exists && pending_exists {
            return Err(InstallStateError::InvalidLayout(
                "published and pending first activations coexist",
            ));
        }
        if final_exists {
            let activation = verify::verify_activation(
                activations,
                FIRST_GENERATION,
                &self.receipt,
                &self.receipt_bytes,
                version,
            )?;
            // A prior process may have stopped between publishing the
            // activation and syncing its parent. Re-establish both durability
            // barriers before allowing `current` to select it.
            unix::sync_directory(activations)?;
            unix::sync_directory(&activation.directory)?;
            unix::full_sync_file(&activation.receipt_file)?;
            return Ok(activation.receipt_file);
        }

        let pending = unix::ensure_private_directory(activations, PENDING_ACTIVATION)?;
        verify::resume_activation_prefix(&pending, &self.receipt, &self.receipt_bytes, version)?;
        let receipt_file = verify::verify_activation_directory(
            &pending,
            &self.receipt,
            &self.receipt_bytes,
            version,
        )?;
        unix::sync_directory(&pending)?;
        // Preflight the platform's strongest durability primitive before the
        // `current` commit point.
        unix::full_sync_file(&receipt_file)?;
        unix::rename_noreplace(
            activations,
            PENDING_ACTIVATION,
            activations,
            FIRST_GENERATION,
        )?;
        unix::sync_directory(activations)?;
        Ok(receipt_file)
    }

    fn reopen_verified_namespace(
        &self,
    ) -> Result<(Directory, VerifiedPreparedVersion), InstallStateError> {
        let live = self.locked.reopen()?;

        let versions = unix::open_directory_at(&live.root, "versions", Some(0o700), true)?;
        if !versions.same_object(&self.versions) {
            return Err(InstallStateError::InvalidLayout(
                "named versions directory changed after preparation",
            ));
        }
        let version = verify::verify_prepared_version(&versions, &self.receipt)?;
        if !version.directory.same_object(&self.version.directory) {
            return Err(InstallStateError::InvalidLayout(
                "named prepared version changed after preparation",
            ));
        }

        let activations = unix::open_directory_at(&live.root, "activations", Some(0o700), true)?;
        if !activations.same_object(&self.activations) {
            return Err(InstallStateError::InvalidLayout(
                "named activations directory changed after preparation",
            ));
        }
        Ok((activations, version))
    }

    fn stage_current_link(&self) -> Result<(), InstallStateError> {
        match unix::entry_identity(self.locked.root(), PENDING_CURRENT)? {
            None => {
                unix::create_symlink(self.locked.root(), PENDING_CURRENT, CURRENT_TARGET)?;
                unix::sync_directory(self.locked.root())?;
            }
            Some(_)
                if unix::read_symlink(self.locked.root(), PENDING_CURRENT)? == CURRENT_TARGET => {}
            Some(_) => {
                return Err(InstallStateError::InvalidLayout(
                    "pending current link has conflicting contents",
                ))
            }
        }
        Ok(())
    }
}

fn validate_receipt_shape(receipt: &InstallReceiptV1) -> Result<(), InstallStateError> {
    let transition =
        receipt
            .last_successful_transition()
            .ok_or(InstallStateError::InvalidLayout(
                "first activation lacks its transition",
            ))?;
    if receipt.owner_family() != OwnerFamily::Standalone
        || receipt.update_route() != Some(UpdateRoute::Standalone)
        || !receipt.retained().is_empty()
        || transition.sequence() != FIRST_SEQUENCE
        || transition.transition_type() != TransitionKind::Install
    {
        return Err(InstallStateError::InvalidLayout(
            "receipt is not a standalone sequence-one activation",
        ));
    }
    Ok(())
}

fn require_exact_activation_parent(activations: &Directory) -> Result<(), InstallStateError> {
    if unix::list_names(activations)?
        != std::collections::BTreeSet::from([FIRST_GENERATION.to_owned()])
    {
        return Err(InstallStateError::InvalidLayout(
            "first activation parent inventory is not exact",
        ));
    }
    Ok(())
}

fn repeat_postcommit_barriers(
    activation: &verify::VerifiedActivation,
    activations: &Directory,
    root: &Directory,
) -> Result<(), InstallStateError> {
    maybe_fail_recovery_barrier(RecoveryBarrier::ActivationDirectory)?;
    unix::sync_directory(&activation.directory)?;
    maybe_fail_recovery_barrier(RecoveryBarrier::ActivationsParent)?;
    unix::sync_directory(activations)?;
    maybe_fail_recovery_barrier(RecoveryBarrier::RootDirectory)?;
    unix::sync_directory(root)?;
    maybe_fail_recovery_barrier(RecoveryBarrier::ReceiptFullSync)?;
    unix::full_sync_file(&activation.receipt_file)
}

#[cfg(test)]
fn maybe_fail_recovery_barrier(barrier: RecoveryBarrier) -> Result<(), InstallStateError> {
    let should_fail = FAIL_RECOVERY_BARRIER.with(|selected| {
        if selected.get() == Some(barrier) {
            selected.set(None);
            true
        } else {
            false
        }
    });
    if should_fail {
        return Err(InstallStateError::std_io(
            "injected post-commit recovery barrier",
            std::io::Error::other("test-only recovery barrier failure"),
        ));
    }
    Ok(())
}

#[cfg(not(test))]
fn maybe_fail_recovery_barrier(_barrier: RecoveryBarrier) -> Result<(), InstallStateError> {
    Ok(())
}