interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-kv-store / src / host_fs.rs

3868 lines · 133894 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16// The publication protocol (temp write, file fsync, atomic rename, directory
17// fsync, index insert) and the startup walk are written from ADR 0003 sections
18// 2.4, 3.4, 4.1 and 7.4. LMCache fs_l2_adapter.py (4d69cdc4, Apache-2.0,
19// Copyright LMCache contributors) informed two ideas only: a completed object
20// is published by writing a temporary file and renaming it, and a store of a
21// key that already exists on disk is skipped. No code was copied. See
22// THIRD_PARTY.md and ADR 0003 context item 24.
23
24//! Host filesystem `KvStore` adapter (cut C4, `sovereign-core#484`).
25//!
26//! Layout under `<root>` (ADR 0003 section 2.4), plus `seal-usage/` for the
27//! per-key seal budget (#811):
28//!
29//! ```text
30//! <root>/
31//! STORE_ID
32//! objects/00/ .. objects/ff/
33//! tmp/
34//! seal-usage/
35//! ```
36//!
37//! All 256 shard directories, `tmp/` and `seal-usage/` are created at
38//! [`HostFsStore::open`] with a parent-directory `fsync`; the hot path never
39//! creates a directory. The per-key count file inside `seal-usage/` is written
40//! when an object is sealed.
41
42use crate::identity::{BackendFormat, ChunkKey, LayoutStrides, NamespaceFields, NamespaceId};
43use crate::index::{Index, IndexEntry, FLAG_FOREIGN, FLAG_INDETERMINATE};
44use crate::pin::{HolderGuard, PinnedDest, PinnedSource};
45use crate::record::{
46 payload_root, ChunkHeader, RecordHeader, FLAG_PARTIAL_TAIL, HEADER_REGION_LEN, MAX_SEGMENTS,
47 PAYLOAD_DOMAIN, SEGMENT_TABLE_OFFSET,
48};
49use crate::store::{
50 CancelOutcome, Capacity, Completion, DrainReport, Incarnation, JobId, JobStage, KvStore,
51 PinToken, PublishOutcome, RecoveryProgress, StoreState, Terminal, UnfinishedJob,
52};
53use crate::validate::validate_record;
54use aien_platform::{ObjectId, PlatformError};
55use sha2::{Digest, Sha256};
56use std::collections::{BTreeMap, VecDeque};
57use std::fs::{File, OpenOptions};
58use std::io::{Read, Write};
59use std::os::unix::fs::{FileExt, MetadataExt};
60use std::path::{Path, PathBuf};
61use std::sync::atomic::{AtomicU64, Ordering};
62use std::sync::{Arc, Condvar, Mutex, MutexGuard};
63use std::thread::JoinHandle;
64use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
65
66/// Raw `ENOSPC` for [`FaultAction::Fail`].
67pub const ENOSPC: i32 = 28;
68/// Raw `EIO` for [`FaultAction::Fail`].
69pub const EIO: i32 = 5;
70
71const DEFAULT_QUOTA_BYTES: u64 = 8 << 30;
72const DEFAULT_MAX_OBJECTS: u64 = 65_536;
73const DEFAULT_MAX_RESTORE_OPS: u32 = 48;
74const DEFAULT_MAX_PARK_OPS: u32 = 64;
75const DEFAULT_MAX_INFLIGHT_BYTES: u64 = 256 << 20;
76const DEFAULT_MAX_WAITERS_PER_JOB: u32 = 16;
77const DEFAULT_MAX_WAITERS_TOTAL: u32 = 1024;
78const DEFAULT_RECOVERY_SLICE_MS: u64 = 50;
79
80/// Who runs the worker steps.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum WorkerMode {
83 Manual,
84 Thread,
85}
86
87/// Where a fault can be injected (ADR 2.4 P1 to P5, plus the other I/O).
88#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
89pub enum Boundary {
90 P1Write,
91 P2FsyncFile,
92 P3Rename,
93 P4FsyncDir,
94 P5IndexInsert,
95 Unlink,
96 LoadRead,
97 FlushSync,
98 /// Once per directory entry of the recovery walk, before its stat, with
99 /// the index lock NOT held. `Fail(errno)` stands for a stat I/O error.
100 RecoverEntry,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum FaultAction {
105 Fail(i32),
106 TornWrite { after_bytes: u64, crash: bool },
107 Crash,
108 Stall(Duration),
109}
110
111pub trait FaultHook: Send + Sync {
112 fn at(&self, boundary: Boundary, key: &ChunkKey) -> Option<FaultAction>;
113}
114
115#[derive(Default)]
116struct Script {
117 armed: BTreeMap<Boundary, Vec<FaultAction>>,
118 fired: BTreeMap<Boundary, u64>,
119 seen: Vec<Boundary>,
120}
121
122/// One-shot faults per boundary, consumed in the order they were armed.
123#[derive(Default)]
124pub struct ScriptedFaults {
125 inner: Mutex<Script>,
126}
127
128impl ScriptedFaults {
129 pub fn new() -> Arc<Self> {
130 Arc::new(Self::default())
131 }
132
133 pub fn arm(&self, boundary: Boundary, action: FaultAction) {
134 let mut s = self.inner.lock().unwrap_or_else(|e| e.into_inner());
135 s.armed.entry(boundary).or_default().push(action);
136 }
137
138 pub fn fired(&self, boundary: Boundary) -> u64 {
139 self.inner
140 .lock()
141 .unwrap_or_else(|e| e.into_inner())
142 .fired
143 .get(&boundary)
144 .copied()
145 .unwrap_or(0)
146 }
147
148 /// Every boundary the adapter consulted, in order.
149 pub fn seen(&self) -> Vec<Boundary> {
150 self.inner
151 .lock()
152 .unwrap_or_else(|e| e.into_inner())
153 .seen
154 .clone()
155 }
156
157 pub fn armed(&self, boundary: Boundary) -> usize {
158 self.inner
159 .lock()
160 .unwrap_or_else(|e| e.into_inner())
161 .armed
162 .get(&boundary)
163 .map_or(0, Vec::len)
164 }
165}
166
167impl FaultHook for ScriptedFaults {
168 fn at(&self, boundary: Boundary, _key: &ChunkKey) -> Option<FaultAction> {
169 let mut s = self.inner.lock().unwrap_or_else(|e| e.into_inner());
170 s.seen.push(boundary);
171 let list = s.armed.get_mut(&boundary)?;
172 if list.is_empty() {
173 return None;
174 }
175 let a = list.remove(0);
176 *s.fired.entry(boundary).or_insert(0) += 1;
177 Some(a)
178 }
179}
180
181#[derive(Clone)]
182pub struct HostFsConfig {
183 pub root: PathBuf,
184 pub namespace: NamespaceId,
185 pub model_sha256: [u8; 32],
186 pub layout: LayoutStrides,
187 pub num_layers: u32,
188 pub num_kv_heads: u32,
189 pub head_dim: u32,
190 pub block_size: u32,
191 pub chunk_tokens: u32,
192 pub dtype: u8,
193 pub backend_format: u8,
194 pub quota_bytes: u64,
195 pub max_objects: u64,
196 pub max_restore_ops: u32,
197 pub max_park_ops: u32,
198 pub max_inflight_bytes: u64,
199 pub max_waiters_per_job: u32,
200 pub max_waiters_total: u32,
201 pub recovery_slice_ms: u64,
202 pub purge_after_recovery: bool,
203 pub worker: WorkerMode,
204 pub faults: Option<Arc<dyn FaultHook>>,
205 /// The key every object is sealed with (ADR 0003 section 20). `None`:
206 /// `open` refuses (fail closed); there is no plaintext mode.
207 pub seal_key: Option<Arc<crate::seal::SealKey>>,
208}
209
210impl std::fmt::Debug for HostFsConfig {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 f.debug_struct("HostFsConfig")
213 .field("root", &self.root)
214 .field("namespace", &self.namespace)
215 .field("quota_bytes", &self.quota_bytes)
216 .field("max_objects", &self.max_objects)
217 .field("worker", &self.worker)
218 .finish()
219 }
220}
221
222impl HostFsConfig {
223 pub fn from_fields(root: PathBuf, f: &NamespaceFields<'_>) -> Result<Self, PlatformError> {
224 if f.backend_format != BackendFormat::HostPagedPoolV1 {
225 return Err(PlatformError::InvalidLayout);
226 }
227 let namespace = f.namespace_id().map_err(|_| PlatformError::InvalidLayout)?;
228 let cfg = Self {
229 root,
230 namespace,
231 model_sha256: f.model_sha256,
232 layout: f.layout,
233 num_layers: f.num_layers,
234 num_kv_heads: f.num_kv_heads,
235 head_dim: f.head_dim,
236 block_size: f.block_size,
237 chunk_tokens: f.chunk_tokens,
238 dtype: f.dtype as u8,
239 backend_format: f.backend_format as u8,
240 quota_bytes: DEFAULT_QUOTA_BYTES,
241 max_objects: DEFAULT_MAX_OBJECTS,
242 max_restore_ops: DEFAULT_MAX_RESTORE_OPS,
243 max_park_ops: DEFAULT_MAX_PARK_OPS,
244 max_inflight_bytes: DEFAULT_MAX_INFLIGHT_BYTES,
245 max_waiters_per_job: DEFAULT_MAX_WAITERS_PER_JOB,
246 max_waiters_total: DEFAULT_MAX_WAITERS_TOTAL,
247 recovery_slice_ms: DEFAULT_RECOVERY_SLICE_MS,
248 purge_after_recovery: true,
249 worker: WorkerMode::Thread,
250 faults: None,
251 seal_key: None,
252 };
253 validate_config(&cfg)?;
254 Ok(cfg)
255 }
256
257 pub fn apply_env(&mut self, get: impl Fn(&str) -> Option<String>) -> Result<(), PlatformError> {
258 fn parse_pos(val: Option<String>) -> Result<Option<u64>, PlatformError> {
259 let Some(s) = val else {
260 return Ok(None);
261 };
262 let v: u64 = s.parse().map_err(|_| PlatformError::InvalidLayout)?;
263 if v == 0 {
264 return Err(PlatformError::InvalidLayout);
265 }
266 Ok(Some(v))
267 }
268
269 let q = parse_pos(get("AIEN_KV_STORE_QUOTA_BYTES"))?;
270 let m = parse_pos(get("AIEN_KV_STORE_MAX_OBJECTS"))?;
271 let sl = parse_pos(get("AIEN_KV_STORE_RECOVERY_SLICE_MS"))?;
272
273 if let Some(v) = q {
274 self.quota_bytes = v;
275 }
276 if let Some(v) = m {
277 self.max_objects = v;
278 }
279 if let Some(v) = sl {
280 self.recovery_slice_ms = v;
281 }
282 Ok(())
283 }
284}
285
286fn validate_config(c: &HostFsConfig) -> Result<(), PlatformError> {
287 if c.quota_bytes == 0
288 || c.max_objects == 0
289 || c.max_restore_ops == 0
290 || c.max_park_ops == 0
291 || c.max_inflight_bytes == 0
292 || c.max_waiters_per_job == 0
293 || c.max_waiters_total == 0
294 || c.block_size == 0
295 || c.chunk_tokens == 0
296 || !c.chunk_tokens.is_multiple_of(c.block_size)
297 || (c.chunk_tokens / c.block_size) as usize > MAX_SEGMENTS
298 || c.num_layers == 0
299 || c.num_kv_heads == 0
300 || c.head_dim == 0
301 || c.layout.block_stride == 0
302 || c.layout.element_bytes == 0
303 {
304 return Err(PlatformError::InvalidLayout);
305 }
306
307 let head_bytes = (c.head_dim as u64)
308 .checked_mul(c.layout.element_bytes)
309 .ok_or(PlatformError::InvalidLayout)?;
310 if head_bytes > c.layout.head_stride {
311 return Err(PlatformError::InvalidLayout);
312 }
313 let row_span = (c.num_kv_heads as u64 - 1)
314 .checked_mul(c.layout.head_stride)
315 .and_then(|x| x.checked_add(head_bytes))
316 .ok_or(PlatformError::InvalidLayout)?;
317 if row_span > c.layout.token_stride {
318 return Err(PlatformError::InvalidLayout);
319 }
320 let plane_span = (c.block_size as u64 - 1)
321 .checked_mul(c.layout.token_stride)
322 .and_then(|x| x.checked_add(row_span))
323 .ok_or(PlatformError::InvalidLayout)?;
324 if plane_span > c.layout.kv_plane_stride {
325 return Err(PlatformError::InvalidLayout);
326 }
327 let two_planes = c
328 .layout
329 .kv_plane_stride
330 .checked_add(plane_span)
331 .ok_or(PlatformError::InvalidLayout)?;
332 if two_planes > c.layout.layer_stride {
333 return Err(PlatformError::InvalidLayout);
334 }
335 let total_span = (c.num_layers as u64 - 1)
336 .checked_mul(c.layout.layer_stride)
337 .and_then(|x| x.checked_add(two_planes))
338 .ok_or(PlatformError::InvalidLayout)?;
339 if total_span > c.layout.block_stride {
340 return Err(PlatformError::InvalidLayout);
341 }
342 Ok(())
343}
344
345#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
346pub struct HostFsStats {
347 pub io_ops: u64,
348 pub reads: u64,
349 pub read_bytes: u64,
350 pub writes: u64,
351 pub write_bytes: u64,
352 pub file_fsyncs: u64,
353 pub dir_fsyncs: u64,
354 pub renames: u64,
355 pub unlinks: u64,
356 pub metadata_calls: u64,
357 pub mkdirs: u64,
358 pub dir_entries: u64,
359 pub queue_full_total: u64,
360 pub disk_full_total: u64,
361 pub cancelled_total: u64,
362 pub evicted_bytes_total: u64,
363 pub dedup_total: u64,
364 pub indeterminate_total: u64,
365 pub published_total: u64,
366 pub terminal_done: u64,
367 pub terminal_failed: u64,
368 pub terminal_cancelled: u64,
369 pub peak_completion_queue: u64,
370 pub completion_overflow_total: u64,
371 pub released_source_violations: u64,
372 pub corrupt_deleted_total: u64,
373 pub foreign_files: u64,
374 pub foreign_file_bytes: u64,
375 pub tmp_bytes_deleted: u64,
376 pub corrupt_bytes_deleted: u64,
377 pub purge_unlinked: u64,
378 pub tail_scratch_bytes: u64,
379 pub over_cap: bool,
380 pub shutdown_unfinished_jobs: u64,
381 pub shutdown_unfinished_bytes: u64,
382 /// Most directory entries the recovery or purge walk held in memory at
383 /// once. The walk streams one entry at a time (ADR 4.1), so this is 0 or 1.
384 pub walk_peak_buffered: u64,
385 /// Recovery unlinks (temp or corrupt files) that failed; the file's bytes
386 /// stay counted and recovery ends `Degraded`.
387 pub recovery_unlink_failures: u64,
388 /// Purge unlinks that failed; the purge stopped with its accounting intact.
389 pub purge_unlink_failures: u64,
390}
391
392#[derive(Clone, Copy, PartialEq, Eq)]
393enum Kind {
394 Store,
395 Load,
396 Flush,
397 Noop,
398}
399
400#[derive(Clone, Copy, PartialEq, Eq)]
401enum Phase {
402 Queued,
403 Writing,
404 Syncing,
405 Publishing,
406 Reading,
407 Flushing,
408}
409
410struct Job {
411 id: u64,
412 kind: Kind,
413 inc: Incarnation,
414 key: ChunkKey,
415 park: bool,
416 bytes: u64,
417 payload_len: u64,
418 reserved: u64,
419 submitted_at: Instant,
420 stage: JobStage,
421 phase: Phase,
422 in_step: bool,
423 cancelling: bool,
424 crashed: bool,
425 header: Option<ChunkHeader>,
426 src: Option<PinnedSource>,
427 dst: Option<PinnedDest>,
428 attached: u32,
429 busy_held: bool,
430 /// Objects this store marked evicting to make room. They stay on disk and
431 /// in the index until the new object is durable (P5); then their unlinks
432 /// are queued. Any other ending clears the marks (Grok C4 P1-1).
433 victims: Vec<[u8; 32]>,
434}
435
436#[derive(Clone)]
437struct Unlink {
438 key: [u8; 32],
439 evict: bool,
440}
441
442/// Which directory a walk is listing.
443#[derive(Clone, Copy, PartialEq, Eq, Debug)]
444enum WalkStage {
445 Tmp,
446 Shard(u16),
447 Done,
448}
449
450/// A streaming directory walk: one open `ReadDir` and the stage it lists.
451/// Holds no listing, so memory is constant however many files exist (ADR
452/// 4.1, Grok C4 P1-2). Lives behind its own mutex, never the index lock.
453struct Walk {
454 stage: WalkStage,
455 dir: Option<std::fs::ReadDir>,
456}
457
458impl Walk {
459 fn new(stage: WalkStage) -> Self {
460 Self { stage, dir: None }
461 }
462
463 fn advance(&mut self) {
464 self.dir = None;
465 self.stage = match self.stage {
466 WalkStage::Tmp => WalkStage::Shard(0),
467 WalkStage::Shard(s) if s < 255 => WalkStage::Shard(s + 1),
468 _ => WalkStage::Done,
469 };
470 }
471
472 fn dir_path(&self, root: &Path) -> Option<PathBuf> {
473 match self.stage {
474 WalkStage::Tmp => Some(root.join("tmp")),
475 WalkStage::Shard(s) => Some(root.join("objects").join(format!("{s:02x}"))),
476 WalkStage::Done => None,
477 }
478 }
479
480 /// The next entry, or `None` when every directory has been listed. A
481 /// directory that does not exist is empty; any other listing error is
482 /// returned (never read as an empty directory, Grok C4 P1-3).
483 fn next(&mut self, root: &Path) -> std::io::Result<Option<(WalkStage, PathBuf)>> {
484 loop {
485 let Some(path) = self.dir_path(root) else {
486 return Ok(None);
487 };
488 if self.dir.is_none() {
489 match std::fs::read_dir(&path) {
490 Ok(rd) => self.dir = Some(rd),
491 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
492 self.advance();
493 continue;
494 }
495 Err(e) => return Err(e),
496 }
497 }
498 match self.dir.as_mut().and_then(Iterator::next) {
499 None => self.advance(),
500 Some(Err(e)) => return Err(e),
501 Some(Ok(entry)) => return Ok(Some((self.stage, entry.path()))),
502 }
503 }
504 }
505}
506
507struct Inner {
508 cfg: HostFsConfig,
509 store_id: Option<[u8; 16]>,
510 state: StoreState,
511 closed: bool,
512 stop_worker: bool,
513 next_job: u64,
514 next_pin: u64,
515 last_clock_ns: u64,
516 index: Index,
517 unindexed_bytes: u64,
518 unindexed_objects: u64,
519 /// Bytes of temp files recovery could not unlink: still on disk, so
520 /// counted in `used_bytes` until a restart removes them.
521 stuck_bytes: u64,
522 /// A recovery unlink failed: recovery ends `Degraded`, not `Open`.
523 recovery_stuck: bool,
524 /// The purge is walking the shards for unindexed files.
525 purge_walking: bool,
526 /// The one key the purge is unlinking right now: stores of it are refused
527 /// until the unlink returns, so the purge never deletes a fresh object.
528 purging: Option<[u8; 32]>,
529 reserved: u64,
530 jobs: BTreeMap<u64, Job>,
531 inflight_store: BTreeMap<[u8; 32], u64>,
532 unlinks: VecDeque<Unlink>,
533 pins: BTreeMap<u64, Vec<[u8; 32]>>,
534 restore_ops: u32,
535 park_ops: u32,
536 restore_bytes: u64,
537 park_bytes: u64,
538 restore_streak: u32,
539 attached_total: u32,
540 queue: VecDeque<Completion>,
541 stats: HostFsStats,
542 recovery: RecoveryProgress,
543 purge_pending: bool,
544 purge_evict_quota: bool,
545 /// Reservations are rounded up to this many bytes (the objects
546 /// directory's `st_blksize`, at least 512), so a reservation is not
547 /// smaller than what publication later charges from `st_blocks`
548 /// (Codex re-review 2, partial 8).
549 alloc_unit: u64,
550 graveyard: Vec<HolderGuard>,
551}
552
553struct Shared {
554 root: PathBuf,
555 inner: Mutex<Inner>,
556 cv: Condvar,
557 tail_scratch: Mutex<Vec<u8>>,
558 /// The recovery walk. Taken before (never while holding) `inner`.
559 walk: Mutex<Walk>,
560 /// The purge walk over the shards. Taken before (never while holding) `inner`.
561 purge_walk: Mutex<Walk>,
562 /// SEAL SEAM (#506): the key every object is sealed and opened with.
563 seal_key: Arc<crate::seal::SealKey>,
564 /// The root's `LOCK`, held for the store's lifetime (#521).
565 _dir_lock: File,
566}
567
568/// Host filesystem `KvStore` implementation.
569pub struct HostFsStore {
570 shared: Arc<Shared>,
571 worker: Mutex<Option<JoinHandle<()>>>,
572}
573
574static STORE_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
575
576fn generate_store_id() -> [u8; 16] {
577 let mut buf = [0u8; 16];
578 if let Ok(mut f) = File::open("/dev/urandom") {
579 if f.read_exact(&mut buf).is_ok() && buf != [0u8; 16] {
580 return buf;
581 }
582 }
583 let mut h = Sha256::new();
584 let now = SystemTime::now()
585 .duration_since(UNIX_EPOCH)
586 .unwrap_or_default()
587 .as_nanos();
588 h.update(now.to_le_bytes());
589 h.update(std::process::id().to_le_bytes());
590 h.update(
591 STORE_ID_COUNTER
592 .fetch_add(1, Ordering::Relaxed)
593 .to_le_bytes(),
594 );
595 let digest = h.finalize();
596 buf.copy_from_slice(&digest[..16]);
597 buf
598}
599
600fn fsync_dir(path: &Path) -> std::io::Result<()> {
601 use std::os::unix::fs::OpenOptionsExt;
602 let f = OpenOptions::new()
603 .read(true)
604 .custom_flags(OPEN_FLAGS | libc::O_DIRECTORY)
605 .open(path)?;
606 f.sync_all()
607}
608
609// ---- at-rest privacy (ADR 0003 section 19) -------------------------------
610//
611// The objects hold K/V derived from user prompts. Every directory of the store
612// is 0700 and every file 0600, owned by the effective uid; existing
613// directories are checked (never silently chmodded) and refused with
614// `AccessDenied` when others could reach them. Once the root is a verified
615// private directory under a trusted parent, only our own uid (or root) can
616// change anything inside it, so per-operation dirfd/openat is not needed
617// (same-uid attackers are out of scope, section 19.1).
618
619const PRIVATE_DIR_MODE: u32 = 0o700;
620const PRIVATE_FILE_MODE: u32 = 0o600;
621/// Every open of a store file: never follow a symlink in the last component,
622/// never leak the descriptor into a child process.
623const OPEN_FLAGS: i32 = libc::O_NOFOLLOW | libc::O_CLOEXEC;
624
625fn euid() -> u32 {
626 // SAFETY: geteuid has no preconditions and cannot fail.
627 unsafe { libc::geteuid() }
628}
629
630/// `Ok(true)`: a private directory of ours. `Ok(false)`: nothing there.
631/// `AccessDenied`: a symlink, not a directory, another owner, or any group or
632/// other permission bit.
633fn check_private_dir(path: &Path) -> Result<bool, PlatformError> {
634 let meta = match std::fs::symlink_metadata(path) {
635 Ok(m) => m,
636 Err(e) if is_not_found(&e) => return Ok(false),
637 Err(e) => return Err(io_to_error(&e, "stat store directory")),
638 };
639 if !meta.file_type().is_dir() || meta.uid() != euid() || meta.mode() & 0o077 != 0 {
640 return Err(PlatformError::AccessDenied);
641 }
642 Ok(true)
643}
644
645/// The directory that will hold the root (the root's parent, or the nearest
646/// existing ancestor when the root is still to be created) must be owned by
647/// us or by root and, if group or others can write it, carry the sticky bit
648/// (like /tmp): otherwise another user could rename the root away and put
649/// their own directory in its place.
650fn check_trusted_parent(root: &Path) -> Result<(), PlatformError> {
651 let mut cur = root.parent();
652 while let Some(dir) = cur {
653 let dir = if dir.as_os_str().is_empty() {
654 Path::new(".")
655 } else {
656 dir
657 };
658 match std::fs::metadata(dir) {
659 Ok(m) => {
660 let shared_write = m.mode() & 0o022 != 0;
661 let sticky = m.mode() & 0o1000 != 0;
662 let owner_ok = m.uid() == euid() || m.uid() == 0;
663 if !m.is_dir() || !owner_ok || (shared_write && !sticky) {
664 return Err(PlatformError::AccessDenied);
665 }
666 return Ok(());
667 }
668 Err(e) if is_not_found(&e) => cur = dir.parent(),
669 Err(e) => return Err(io_to_error(&e, "stat store parent")),
670 }
671 }
672 Ok(())
673}
674
675/// Create one store directory 0700 (the explicit chmod undoes a umask that
676/// narrowed it), or verify an existing one. Returns true when it was created.
677fn make_private_dir(path: &Path, recursive: bool) -> Result<bool, PlatformError> {
678 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
679 // An existing directory is verified, never chmodded (a recursive
680 // DirBuilder would report success for it).
681 if check_private_dir(path)? {
682 return Ok(false);
683 }
684 match std::fs::DirBuilder::new()
685 .recursive(recursive)
686 .mode(PRIVATE_DIR_MODE)
687 .create(path)
688 {
689 Ok(()) => {}
690 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
691 check_private_dir(path)?;
692 return Ok(false);
693 }
694 Err(e) => return Err(io_to_error(&e, "create store directory")),
695 }
696 std::fs::set_permissions(path, std::fs::Permissions::from_mode(PRIVATE_DIR_MODE))
697 .map_err(|e| io_to_error(&e, "chmod store directory"))?;
698 check_private_dir(path)?;
699 Ok(true)
700}
701
702/// The one way the adapter creates a file: 0600, no symlink followed, no
703/// descriptor leaked. Truncates a leftover of ours (a crash temp in the
704/// verified tmp/ directory) instead of failing on it, so a crash never blocks
705/// the next attempt; the mode is forced to 0600 through the descriptor so a
706/// leftover with an old mode, or a narrowing umask, cannot survive.
707fn create_private_file(path: &Path) -> std::io::Result<File> {
708 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
709 let f = OpenOptions::new()
710 .write(true)
711 .create(true)
712 .truncate(true)
713 .mode(PRIVATE_FILE_MODE)
714 .custom_flags(OPEN_FLAGS)
715 .open(path)?;
716 let meta = f.metadata()?;
717 if !meta.is_file() || meta.uid() != euid() {
718 return Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
719 }
720 if meta.mode() & 0o777 != PRIVATE_FILE_MODE {
721 f.set_permissions(std::fs::Permissions::from_mode(PRIVATE_FILE_MODE))?;
722 }
723 Ok(f)
724}
725
726/// One open store per store directory (#521; ADR 0003 supports one runtime
727/// per store directory). An exclusive `flock` on `LOCK` in the root, taken at
728/// open before anything else in the root is touched and released when the
729/// store drops. A second opener, in this process or another, is refused:
730/// otherwise its recovery would delete the first store's in-flight temps and
731/// the two in-memory indexes would drift apart. A planted `LOCK` (a symlink,
732/// another owner) is `AccessDenied` like every other planted name.
733fn lock_store_dir(root: &Path) -> Result<File, PlatformError> {
734 use std::os::unix::io::AsRawFd;
735 let path = root.join("LOCK");
736 let f = create_private_file(&path).map_err(|e| {
737 if e.raw_os_error() == Some(libc::ELOOP) || e.kind() == std::io::ErrorKind::PermissionDenied
738 {
739 PlatformError::AccessDenied
740 } else {
741 io_to_error(&e, "create LOCK")
742 }
743 })?;
744 // SAFETY: flock only takes an advisory lock on a descriptor we own; the
745 // lock lives as long as `f`.
746 if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
747 let e = std::io::Error::last_os_error();
748 if e.raw_os_error() == Some(libc::EWOULDBLOCK) {
749 return Err(PlatformError::TaskRejected(format!(
750 "store directory {} is in use by another open store ({} is held)",
751 root.display(),
752 path.display()
753 )));
754 }
755 return Err(io_to_error(&e, "lock LOCK"));
756 }
757 Ok(f)
758}
759
760/// `create_private_file` plus the bytes (fault injection, temps).
761fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
762 create_private_file(path)?.write_all(bytes)
763}
764
765/// What a no-follow open of a store file found.
766enum PrivateOpen {
767 /// A regular file of ours, with its descriptor's metadata.
768 Ours(File, std::fs::Metadata),
769 /// A symlink, a non-regular file, or another owner's file: not ours,
770 /// never read or served, left alone (ADR 0003 section 4.1 `foreign_file`).
771 NotOurs(u64),
772}
773
774/// Open a store file for reading without following a symlink and check it
775/// through the descriptor (no window between check and use). A file of ours
776/// that group or others can read (written before section 19) is tightened to
777/// 0600 with fchmod.
778fn open_private_read(path: &Path) -> std::io::Result<PrivateOpen> {
779 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
780 let f = match OpenOptions::new()
781 .read(true)
782 // O_NONBLOCK: a planted FIFO must not hang the worker; no effect on
783 // regular files.
784 .custom_flags(OPEN_FLAGS | libc::O_NONBLOCK)
785 .open(path)
786 {
787 Ok(f) => f,
788 Err(e) if e.raw_os_error() == Some(libc::ELOOP) => {
789 let len = std::fs::symlink_metadata(path).map_or(0, |m| m.len());
790 return Ok(PrivateOpen::NotOurs(len));
791 }
792 Err(e) => return Err(e),
793 };
794 let meta = f.metadata()?;
795 if !meta.is_file() || meta.uid() != euid() {
796 return Ok(PrivateOpen::NotOurs(meta.len()));
797 }
798 if meta.mode() & 0o077 != 0 {
799 f.set_permissions(std::fs::Permissions::from_mode(PRIVATE_FILE_MODE))?;
800 }
801 Ok(PrivateOpen::Ours(f, meta))
802}
803
804fn phys_bytes_of(meta: &std::fs::Metadata) -> u64 {
805 meta.len().max(meta.blocks().saturating_mul(512))
806}
807
808fn meta_mtime_ns(meta: &std::fs::Metadata) -> u64 {
809 meta.modified()
810 .ok()
811 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
812 .map_or(0, |d| d.as_nanos().min(u64::MAX as u128) as u64)
813}
814
815fn system_now_ns() -> u64 {
816 SystemTime::now()
817 .duration_since(UNIX_EPOCH)
818 .map_or(0, |d| d.as_nanos().min(u64::MAX as u128) as u64)
819}
820
821fn hex_encode(bytes: &[u8; 32]) -> String {
822 let mut s = String::with_capacity(64);
823 for b in bytes {
824 use std::fmt::Write;
825 let _ = write!(&mut s, "{b:02x}");
826 }
827 s
828}
829
830fn object_path_for(root: &Path, key: &[u8; 32]) -> PathBuf {
831 let hex = hex_encode(key);
832 root.join("objects")
833 .join(&hex[..2])
834 .join(format!("{hex}.kvc"))
835}
836
837fn tmp_path_for(root: &Path, key: &[u8; 32], job_id: u64, inc: Incarnation) -> PathBuf {
838 let hex = hex_encode(key);
839 root.join("tmp")
840 .join(format!("{hex}.{job_id}.{}.{}.part", inc.seq_id, inc.epoch))
841}
842
843fn parse_kvc_filename(name: &str, expected_shard: u8) -> Option<[u8; 32]> {
844 let hex = name.strip_suffix(".kvc")?;
845 if hex.len() != 64 {
846 return None;
847 }
848 if !hex
849 .bytes()
850 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
851 {
852 return None;
853 }
854 let mut out = [0u8; 32];
855 for (i, chunk) in hex.as_bytes().as_chunks::<2>().0.iter().enumerate() {
856 let hi = match chunk[0] {
857 b'0'..=b'9' => chunk[0] - b'0',
858 b'a'..=b'f' => chunk[0] - b'a' + 10,
859 _ => return None,
860 };
861 let lo = match chunk[1] {
862 b'0'..=b'9' => chunk[1] - b'0',
863 b'a'..=b'f' => chunk[1] - b'a' + 10,
864 _ => return None,
865 };
866 out[i] = (hi << 4) | lo;
867 }
868 if out[0] != expected_shard {
869 return None;
870 }
871 Some(out)
872}
873
874fn errno_to_error(errno: i32, context: &str) -> PlatformError {
875 if errno == ENOSPC {
876 PlatformError::OutOfMemory
877 } else {
878 PlatformError::HardwareFault(format!("{context}: errno {errno}"))
879 }
880}
881
882fn io_to_error(err: &std::io::Error, context: &str) -> PlatformError {
883 if err.raw_os_error() == Some(ENOSPC) {
884 PlatformError::OutOfMemory
885 } else {
886 PlatformError::HardwareFault(format!("{context}: {err}"))
887 }
888}
889
890#[allow(clippy::too_many_arguments)]
891fn zero_tail_block(
892 scratch: &mut [u8],
893 src_block: &[u8],
894 layout: &LayoutStrides,
895 num_layers: u32,
896 num_kv_heads: u32,
897 head_dim: u32,
898 block_size: u32,
899 valid_tokens: u32,
900) {
901 scratch.copy_from_slice(src_block);
902 let head_bytes = (head_dim as usize) * (layout.element_bytes as usize);
903 let row_bytes = (num_kv_heads as usize - 1) * (layout.head_stride as usize) + head_bytes;
904 for layer in 0..(num_layers as usize) {
905 for plane in 0..2usize {
906 for tok in (valid_tokens as usize)..(block_size as usize) {
907 let off = layer * (layout.layer_stride as usize)
908 + plane * (layout.kv_plane_stride as usize)
909 + tok * (layout.token_stride as usize);
910 scratch[off..off + row_bytes].fill(0);
911 }
912 }
913 }
914}
915
916enum RecoveredHeader {
917 Ours { payload_len: u64 },
918 Foreign { payload_len: u64 },
919 Corrupt,
920}
921
922fn classify_recovered_header(
923 buf: &[u8],
924 file_size: u64,
925 file_key: &[u8; 32],
926 cfg: &HostFsConfig,
927) -> RecoveredHeader {
928 // SEAL SEAM (#506): an object without the sealed-format marker (an old
929 // plaintext file) is discarded, never read.
930 if !crate::seal::is_sealed_region(buf) {
931 return RecoveredHeader::Corrupt;
932 }
933 let Ok(rec) = RecordHeader::decode(buf) else {
934 return RecoveredHeader::Corrupt;
935 };
936 let h = &rec.chunk;
937 if &h.chunk_key.0 .0 != file_key {
938 return RecoveredHeader::Corrupt;
939 }
940 if h.namespace_id == cfg.namespace {
941 if h.model_sha256 != cfg.model_sha256
942 || h.chunk_tokens != cfg.chunk_tokens
943 || h.block_size != cfg.block_size
944 || h.num_layers != cfg.num_layers
945 || h.num_kv_heads != cfg.num_kv_heads
946 || h.head_dim != cfg.head_dim
947 || h.dtype != cfg.dtype
948 || h.backend_format != cfg.backend_format
949 || !h.first_position.is_multiple_of(cfg.chunk_tokens)
950 || h.token_count == 0
951 || h.token_count > cfg.chunk_tokens
952 {
953 return RecoveredHeader::Corrupt;
954 }
955 let want_flags = if h.token_count < cfg.chunk_tokens {
956 FLAG_PARTIAL_TAIL
957 } else {
958 0
959 };
960 if h.flags != want_flags {
961 return RecoveredHeader::Corrupt;
962 }
963 let expected_blocks = h.token_count.div_ceil(cfg.block_size) as u64;
964 if h.payload_len != expected_blocks.saturating_mul(cfg.layout.block_stride) {
965 return RecoveredHeader::Corrupt;
966 }
967 if validate_record(buf, file_size, h, cfg.layout.block_stride).is_err() {
968 return RecoveredHeader::Corrupt;
969 }
970 RecoveredHeader::Ours {
971 payload_len: h.payload_len,
972 }
973 } else {
974 if h.payload_len == 0
975 || (HEADER_REGION_LEN as u64).checked_add(h.payload_len) != Some(file_size)
976 || !foreign_region_is_clean(buf, &rec)
977 {
978 return RecoveredHeader::Corrupt;
979 }
980 RecoveredHeader::Foreign {
981 payload_len: h.payload_len,
982 }
983 }
984}
985
986/// Padding and segment-root check for an object of another namespace (Grok
987/// C4 P2-4). Its segment size is not ours to know (the file does not store
988/// it, ADR 2.1 item 3), but the region does: the digest table ends at the
989/// last nonzero byte after the 256-byte header, everything after it must be
990/// zero, and the root over exactly that table must match. A table whose last
991/// digest is 32 zero bytes is the only false negative (probability 2^-256).
992fn foreign_region_is_clean(buf: &[u8], rec: &RecordHeader) -> bool {
993 let region = &buf[..HEADER_REGION_LEN];
994 // SEAL SEAM (#506): the table and padding end where the seal slot starts.
995 let Some(last) = region[SEGMENT_TABLE_OFFSET..crate::record::SEAL_SLOT_OFFSET]
996 .iter()
997 .rposition(|b| *b != 0)
998 else {
999 return false;
1000 };
1001 let n_seg = (last + 1).div_ceil(32);
1002 if n_seg == 0 || n_seg > MAX_SEGMENTS || n_seg as u64 > rec.chunk.payload_len {
1003 return false;
1004 }
1005 let table_end = SEGMENT_TABLE_OFFSET + 32 * n_seg;
1006 let mut root = Sha256::new();
1007 root.update(PAYLOAD_DOMAIN);
1008 root.update(&region[SEGMENT_TABLE_OFFSET..table_end]);
1009 root.finalize().as_slice() == rec.payload_sha256
1010}
1011
1012impl Inner {
1013 fn used_bytes(&self) -> u64 {
1014 self.index.total_bytes() + self.unindexed_bytes + self.stuck_bytes
1015 }
1016
1017 fn evicting_bytes(&self) -> u64 {
1018 self.index.evicting().0
1019 }
1020
1021 fn store_reservations(&self) -> u64 {
1022 self.jobs
1023 .values()
1024 .filter(|j| j.kind == Kind::Store && j.reserved > 0 && !j.crashed)
1025 .count() as u64
1026 }
1027
1028 fn bytes_after(&self) -> u64 {
1029 self.used_bytes()
1030 .saturating_sub(self.evicting_bytes())
1031 .saturating_add(self.reserved)
1032 }
1033
1034 fn count_after(&self) -> u64 {
1035 let (_, evicting_count) = self.index.evicting();
1036 let live = (self.index.len() as u64).saturating_sub(evicting_count);
1037 live + self.store_reservations()
1038 }
1039
1040 fn completion_capacity(&self) -> usize {
1041 3 * (self.cfg.max_restore_ops as usize + self.cfg.max_park_ops as usize)
1042 }
1043
1044 fn park_byte_limit(&self) -> u64 {
1045 self.cfg.max_inflight_bytes / 4
1046 }
1047
1048 fn restore_byte_limit(&self) -> u64 {
1049 self.cfg.max_inflight_bytes - self.park_byte_limit()
1050 }
1051
1052 fn capacity(&self) -> Capacity {
1053 Capacity {
1054 state: self.state,
1055 quota_bytes: self.cfg.quota_bytes,
1056 used_bytes: self.used_bytes(),
1057 reserved_bytes: self.reserved,
1058 evicting_bytes: self.evicting_bytes(),
1059 unindexed_bytes: self.unindexed_bytes,
1060 unindexed_objects: self.unindexed_objects,
1061 objects: self.index.len() as u64,
1062 max_objects: self.cfg.max_objects,
1063 restore_ops: self.restore_ops,
1064 max_restore_ops: self.cfg.max_restore_ops,
1065 park_ops: self.park_ops,
1066 max_park_ops: self.cfg.max_park_ops,
1067 inflight_bytes: self.restore_bytes + self.park_bytes,
1068 max_inflight_bytes: self.cfg.max_inflight_bytes,
1069 max_waiters_per_job: self.cfg.max_waiters_per_job,
1070 }
1071 }
1072
1073 fn set_degraded(&mut self) {
1074 if self.state == StoreState::Open {
1075 self.state = StoreState::Degraded;
1076 }
1077 }
1078
1079 fn next_timestamp_ns(&mut self, floor_ns: u64) -> u64 {
1080 let now = system_now_ns()
1081 .max(floor_ns)
1082 .max(self.last_clock_ns.saturating_add(1));
1083 self.last_clock_ns = now;
1084 now
1085 }
1086
1087 fn queue_full(&mut self) -> PlatformError {
1088 self.stats.queue_full_total += 1;
1089 PlatformError::QueueFull
1090 }
1091
1092 fn gate(&mut self, needs_open: bool) -> Result<(), PlatformError> {
1093 if self.state == StoreState::Recovering {
1094 return Err(self.queue_full());
1095 }
1096 if self.closed
1097 || self.state == StoreState::Failed
1098 || (needs_open && self.state == StoreState::Degraded)
1099 {
1100 return Err(PlatformError::DeviceUnavailable);
1101 }
1102 Ok(())
1103 }
1104
1105 fn active_job_count(&self) -> usize {
1106 self.jobs.values().filter(|j| !j.crashed).count()
1107 }
1108
1109 fn credit_check(&mut self, park: bool, bytes: u64) -> Result<(), PlatformError> {
1110 let (ops, max_ops, used_bytes, limit) = if park {
1111 (
1112 self.park_ops,
1113 self.cfg.max_park_ops,
1114 self.park_bytes,
1115 self.park_byte_limit(),
1116 )
1117 } else {
1118 (
1119 self.restore_ops,
1120 self.cfg.max_restore_ops,
1121 self.restore_bytes,
1122 self.restore_byte_limit(),
1123 )
1124 };
1125 let slots = self.queue.len() + 3 * self.active_job_count() + 3;
1126 if ops >= max_ops || used_bytes + bytes > limit || slots > self.completion_capacity() {
1127 return Err(self.queue_full());
1128 }
1129 Ok(())
1130 }
1131
1132 fn push_completion(&mut self, c: Completion) {
1133 self.queue.push_back(c);
1134 self.stats.peak_completion_queue = self
1135 .stats
1136 .peak_completion_queue
1137 .max(self.queue.len() as u64);
1138 }
1139
1140 /// Settle a store's victims: queue their unlinks only when the new object
1141 /// is durable; otherwise (failure, cancel, crash, indeterminate publish)
1142 /// return them to service. The store therefore never loses an old object
1143 /// unless the new one is known to survive (ADR 3.4, Grok C4 P1-1).
1144 fn settle_victims(&mut self, job: &mut Job, durable: bool) {
1145 for v in std::mem::take(&mut job.victims) {
1146 if durable {
1147 self.unlinks.push_back(Unlink {
1148 key: v,
1149 evict: true,
1150 });
1151 } else {
1152 self.index.clear_evicting(&v);
1153 }
1154 }
1155 }
1156
1157 fn finish(
1158 &mut self,
1159 mut job: Job,
1160 terminal: Terminal,
1161 stage: JobStage,
1162 publish: PublishOutcome,
1163 ) {
1164 if job.park {
1165 self.park_ops = self.park_ops.saturating_sub(1);
1166 self.park_bytes = self.park_bytes.saturating_sub(job.bytes);
1167 } else {
1168 self.restore_ops = self.restore_ops.saturating_sub(1);
1169 self.restore_bytes = self.restore_bytes.saturating_sub(job.bytes);
1170 }
1171 self.reserved = self.reserved.saturating_sub(job.reserved);
1172 job.reserved = 0;
1173 if job.kind == Kind::Store {
1174 let durable =
1175 publish == PublishOutcome::Durable && matches!(terminal, Terminal::Done(_));
1176 self.settle_victims(&mut job, durable);
1177 if self.inflight_store.get(&job.key.0 .0) == Some(&job.id) {
1178 self.inflight_store.remove(&job.key.0 .0);
1179 }
1180 }
1181 if job.busy_held {
1182 self.index.busy_dec(&job.key.0 .0);
1183 job.busy_held = false;
1184 }
1185 self.attached_total = self.attached_total.saturating_sub(job.attached);
1186 match &terminal {
1187 Terminal::Done(_) => self.stats.terminal_done += 1,
1188 Terminal::Failed(_) => self.stats.terminal_failed += 1,
1189 Terminal::Cancelled => {
1190 self.stats.terminal_cancelled += 1;
1191 self.stats.cancelled_total += 1;
1192 }
1193 }
1194 let c = Completion {
1195 job: JobId(job.id),
1196 incarnation: job.inc,
1197 key: job.key,
1198 stage,
1199 terminal: Some(terminal),
1200 publish,
1201 bytes: job.payload_len,
1202 elapsed_us: job.submitted_at.elapsed().as_micros() as u64,
1203 holder: None,
1204 };
1205 self.push_completion(c);
1206 if let Some(s) = job.src.take() {
1207 self.graveyard.push(s.into_guard());
1208 }
1209 if let Some(d) = job.dst.take() {
1210 self.graveyard.push(d.into_guard());
1211 }
1212 }
1213
1214 fn fail_job(&mut self, job: Job, e: PlatformError) {
1215 let stage = job.stage;
1216 self.finish(
1217 job,
1218 Terminal::Failed(e),
1219 stage,
1220 PublishOutcome::NotApplicable,
1221 );
1222 }
1223
1224 fn mark_crashed(&mut self, mut job: Job) {
1225 if job.park {
1226 self.park_ops = self.park_ops.saturating_sub(1);
1227 self.park_bytes = self.park_bytes.saturating_sub(job.bytes);
1228 } else {
1229 self.restore_ops = self.restore_ops.saturating_sub(1);
1230 self.restore_bytes = self.restore_bytes.saturating_sub(job.bytes);
1231 }
1232 self.reserved = self.reserved.saturating_sub(job.reserved);
1233 job.reserved = 0;
1234 if job.kind == Kind::Store {
1235 self.settle_victims(&mut job, false);
1236 if self.inflight_store.get(&job.key.0 .0) == Some(&job.id) {
1237 self.inflight_store.remove(&job.key.0 .0);
1238 }
1239 }
1240 if job.busy_held {
1241 self.index.busy_dec(&job.key.0 .0);
1242 job.busy_held = false;
1243 }
1244 self.attached_total = self.attached_total.saturating_sub(job.attached);
1245 if let Some(s) = job.src.take() {
1246 self.graveyard.push(s.into_guard());
1247 }
1248 if let Some(d) = job.dst.take() {
1249 self.graveyard.push(d.into_guard());
1250 }
1251 job.crashed = true;
1252 job.in_step = false;
1253 }
1254
1255 fn validate_chunk_header_against_config(&self, h: &ChunkHeader) -> Result<(), PlatformError> {
1256 if h.namespace_id != self.cfg.namespace
1257 || h.model_sha256 != self.cfg.model_sha256
1258 || h.chunk_tokens != self.cfg.chunk_tokens
1259 || h.block_size != self.cfg.block_size
1260 || h.num_layers != self.cfg.num_layers
1261 || h.num_kv_heads != self.cfg.num_kv_heads
1262 || h.head_dim != self.cfg.head_dim
1263 || h.dtype != self.cfg.dtype
1264 || h.backend_format != self.cfg.backend_format
1265 || !h.first_position.is_multiple_of(self.cfg.chunk_tokens)
1266 || h.token_count == 0
1267 || h.token_count > self.cfg.chunk_tokens
1268 || h.payload_len == 0
1269 {
1270 return Err(PlatformError::InvalidLayout);
1271 }
1272 let want_flags = if h.token_count < self.cfg.chunk_tokens {
1273 FLAG_PARTIAL_TAIL
1274 } else {
1275 0
1276 };
1277 if h.flags != want_flags {
1278 return Err(PlatformError::InvalidLayout);
1279 }
1280 let expected_blocks = h.token_count.div_ceil(self.cfg.block_size) as u64;
1281 if expected_blocks as usize > MAX_SEGMENTS
1282 || h.payload_len != expected_blocks.saturating_mul(self.cfg.layout.block_stride)
1283 {
1284 return Err(PlatformError::InvalidLayout);
1285 }
1286 Ok(())
1287 }
1288
1289 fn submit_store(
1290 &mut self,
1291 header: ChunkHeader,
1292 slot: &mut Option<PinnedSource>,
1293 inc: Incarnation,
1294 ) -> Result<JobId, PlatformError> {
1295 self.gate(true)?;
1296 let src = slot.as_ref().ok_or(PlatformError::InvalidLayout)?;
1297 self.validate_chunk_header_against_config(&header)?;
1298 if src.total_bytes() != Some(header.payload_len)
1299 || src.block_count() == 0
1300 || src.block_count() > MAX_SEGMENTS
1301 || src.block_bytes() as u64 != self.cfg.layout.block_stride
1302 {
1303 return Err(PlatformError::InvalidLayout);
1304 }
1305 let full = (src.block_count() as u64 - 1) * header.block_size as u64;
1306 let tail = (header.token_count as u64).checked_sub(full);
1307 match tail {
1308 Some(t)
1309 if t >= 1
1310 && t <= header.block_size as u64
1311 && t == src.tail_valid_tokens() as u64 => {}
1312 _ => return Err(PlatformError::InvalidLayout),
1313 }
1314
1315 let key = header.chunk_key;
1316 let k = key.0 .0;
1317 if let Some(&jid) = self.inflight_store.get(&k).filter(|jid| {
1318 self.jobs
1319 .get(jid)
1320 .is_some_and(|j| !j.cancelling && !j.crashed)
1321 }) {
1322 self.stats.dedup_total += 1;
1323 return Ok(JobId(jid));
1324 }
1325 // A key whose file is being unlinked (a victim, a delete, a purge) is
1326 // refused until the unlink returns: publishing it now would let that
1327 // unlink delete the new object.
1328 if self.purging == Some(k) || self.index.get(&k).is_some_and(|e| e.is_evicting()) {
1329 return Err(self.queue_full());
1330 }
1331 if let Some(e) = self
1332 .index
1333 .get(&k)
1334 .filter(|e| !e.is_evicting() && !e.is_foreign())
1335 {
1336 let _ = e;
1337 self.credit_check(true, 0)?;
1338 let id = self.next_job;
1339 self.next_job += 1;
1340 self.park_ops += 1;
1341 let job = Job {
1342 id,
1343 kind: Kind::Noop,
1344 inc,
1345 key,
1346 park: true,
1347 bytes: 0,
1348 payload_len: 0,
1349 reserved: 0,
1350 submitted_at: Instant::now(),
1351 stage: JobStage::Submitted,
1352 phase: Phase::Queued,
1353 in_step: false,
1354 cancelling: false,
1355 crashed: false,
1356 header: None,
1357 src: None,
1358 dst: None,
1359 attached: 0,
1360 busy_held: false,
1361 victims: Vec::new(),
1362 };
1363 self.stats.dedup_total += 1;
1364 self.jobs.insert(id, job);
1365 return Ok(JobId(id));
1366 }
1367
1368 let bytes =
1369 (header.payload_len + HEADER_REGION_LEN as u64).next_multiple_of(self.alloc_unit);
1370 self.credit_check(true, bytes)?;
1371 // While a purge is pending only free headroom admits a store: evicting
1372 // a good object for bytes the purge is about to free would lose data
1373 // for nothing (ADR 4.1, Grok C4 P2-5).
1374 let (eb, en) = if self.purge_pending {
1375 (0, 0)
1376 } else {
1377 self.index.evictable()
1378 };
1379 if self.bytes_after() + bytes > self.cfg.quota_bytes + eb
1380 || self.count_after() + 1 > self.cfg.max_objects + en
1381 {
1382 self.stats.disk_full_total += 1;
1383 return Err(PlatformError::OutOfMemory);
1384 }
1385
1386 let id = self.next_job;
1387 self.next_job += 1;
1388 self.park_ops += 1;
1389 self.park_bytes += bytes;
1390 self.reserved += bytes;
1391 let job = Job {
1392 id,
1393 kind: Kind::Store,
1394 inc,
1395 key,
1396 park: true,
1397 bytes,
1398 payload_len: header.payload_len,
1399 reserved: bytes,
1400 submitted_at: Instant::now(),
1401 stage: JobStage::Submitted,
1402 phase: Phase::Queued,
1403 in_step: false,
1404 cancelling: false,
1405 crashed: false,
1406 header: Some(header),
1407 src: slot.take(),
1408 dst: None,
1409 attached: 0,
1410 busy_held: false,
1411 victims: Vec::new(),
1412 };
1413 self.inflight_store.insert(k, id);
1414 self.jobs.insert(id, job);
1415 Ok(JobId(id))
1416 }
1417
1418 fn submit_load(
1419 &mut self,
1420 key: ChunkKey,
1421 expect: &ChunkHeader,
1422 slot: &mut Option<PinnedDest>,
1423 inc: Incarnation,
1424 ) -> Result<JobId, PlatformError> {
1425 self.gate(false)?;
1426 let dst = slot.as_ref().ok_or(PlatformError::InvalidLayout)?;
1427 let k = key.0 .0;
1428 let entry = self
1429 .index
1430 .get(&k)
1431 .filter(|e| !e.is_evicting() && !e.is_foreign())
1432 .ok_or(PlatformError::ObjectNotFound(key.0))?;
1433 if expect.chunk_key != key {
1434 return Err(PlatformError::InvalidLayout);
1435 }
1436 self.validate_chunk_header_against_config(expect)?;
1437 if entry.payload_len != expect.payload_len
1438 || dst.total_bytes() != Some(expect.payload_len)
1439 || dst.block_bytes() as u64 != self.cfg.layout.block_stride
1440 {
1441 return Err(PlatformError::InvalidLayout);
1442 }
1443 let bytes = entry.phys_bytes;
1444 let payload_len = expect.payload_len;
1445 self.credit_check(false, bytes)?;
1446 let ok = self.index.busy_inc(&k);
1447 debug_assert!(ok);
1448 let id = self.next_job;
1449 self.next_job += 1;
1450 self.restore_ops += 1;
1451 self.restore_bytes += bytes;
1452 let job = Job {
1453 id,
1454 kind: Kind::Load,
1455 inc,
1456 key,
1457 park: false,
1458 bytes,
1459 payload_len,
1460 reserved: 0,
1461 submitted_at: Instant::now(),
1462 stage: JobStage::Submitted,
1463 phase: Phase::Queued,
1464 in_step: false,
1465 cancelling: false,
1466 crashed: false,
1467 header: Some(*expect),
1468 src: None,
1469 dst: slot.take(),
1470 attached: 0,
1471 busy_held: true,
1472 victims: Vec::new(),
1473 };
1474 self.jobs.insert(id, job);
1475 Ok(JobId(id))
1476 }
1477
1478 fn submit_flush(&mut self, inc: Incarnation) -> Result<JobId, PlatformError> {
1479 self.gate(false)?;
1480 self.credit_check(true, 0)?;
1481 let id = self.next_job;
1482 self.next_job += 1;
1483 self.park_ops += 1;
1484 let job = Job {
1485 id,
1486 kind: Kind::Flush,
1487 inc,
1488 key: ChunkKey(ObjectId([0; 32])),
1489 park: true,
1490 bytes: 0,
1491 payload_len: 0,
1492 reserved: 0,
1493 submitted_at: Instant::now(),
1494 stage: JobStage::Submitted,
1495 phase: Phase::Queued,
1496 in_step: false,
1497 cancelling: false,
1498 crashed: false,
1499 header: None,
1500 src: None,
1501 dst: None,
1502 attached: 0,
1503 busy_held: false,
1504 victims: Vec::new(),
1505 };
1506 self.jobs.insert(id, job);
1507 Ok(JobId(id))
1508 }
1509
1510 fn reap_cancels(&mut self) -> bool {
1511 let ids: Vec<u64> = self
1512 .jobs
1513 .iter()
1514 .filter(|(_, j)| j.cancelling && !j.in_step && !j.crashed)
1515 .map(|(id, _)| *id)
1516 .collect();
1517 let any = !ids.is_empty();
1518 for id in ids {
1519 let job = self.jobs.remove(&id).expect("cancelling job");
1520 let stage = job.stage;
1521 self.finish(
1522 job,
1523 Terminal::Cancelled,
1524 stage,
1525 PublishOutcome::NotApplicable,
1526 );
1527 }
1528 any
1529 }
1530}
1531
1532fn check_fault(
1533 hook: &Option<Arc<dyn FaultHook>>,
1534 boundary: Boundary,
1535 key: &ChunkKey,
1536) -> Option<FaultAction> {
1537 hook.as_ref().and_then(|h| h.at(boundary, key))
1538}
1539
1540/// What one recovery entry came to, applied under a short index lock.
1541enum EntryOutcome {
1542 Skip,
1543 TmpDeleted(u64),
1544 TmpStuck(u64),
1545 Foreign(u64),
1546 Unindexed(u64),
1547 CorruptDeleted(u64),
1548 CorruptStuck(u64),
1549 Unreadable(u64),
1550 Index(IndexEntry, bool),
1551}
1552
1553fn is_not_found(e: &std::io::Error) -> bool {
1554 e.kind() == std::io::ErrorKind::NotFound
1555}
1556
1557/// Unlink with the outcome recovery and purge need: `Ok(true)` removed,
1558/// `Ok(false)` already gone, `Err` still there.
1559fn unlink_counted(path: &Path) -> std::io::Result<bool> {
1560 match std::fs::remove_file(path) {
1561 Ok(()) => Ok(true),
1562 Err(e) if is_not_found(&e) => Ok(false),
1563 Err(e) => Err(e),
1564 }
1565}
1566
1567/// Examine one directory entry of the recovery walk. Runs with the index lock
1568/// NOT held (stat, header read, unlink); only the cap check takes it briefly.
1569fn recover_entry(
1570 shared: &Shared,
1571 cfg: &HostFsConfig,
1572 stage: WalkStage,
1573 path: &Path,
1574) -> std::io::Result<EntryOutcome> {
1575 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1576 let parsed = match stage {
1577 WalkStage::Shard(s) => parse_kvc_filename(name, s as u8),
1578 _ => None,
1579 };
1580 let hook_key = ChunkKey(ObjectId(parsed.unwrap_or([0; 32])));
1581 match check_fault(&cfg.faults, Boundary::RecoverEntry, &hook_key) {
1582 Some(FaultAction::Stall(d)) => std::thread::sleep(d),
1583 Some(FaultAction::Fail(errno)) => return Err(std::io::Error::from_raw_os_error(errno)),
1584 _ => {}
1585 }
1586 let meta = match std::fs::symlink_metadata(path) {
1587 Ok(m) => m,
1588 Err(e) if is_not_found(&e) => return Ok(EntryOutcome::Skip),
1589 Err(e) => return Err(e),
1590 };
1591 let phys = phys_bytes_of(&meta);
1592 if stage == WalkStage::Tmp {
1593 if !(meta.is_file() && name.ends_with(".part")) {
1594 return Ok(EntryOutcome::Foreign(meta.len()));
1595 }
1596 return Ok(match unlink_counted(path) {
1597 Ok(_) => EntryOutcome::TmpDeleted(meta.len()),
1598 Err(_) => EntryOutcome::TmpStuck(phys),
1599 });
1600 }
1601 // A symlink, a non-regular file or another owner's file is not ours:
1602 // `foreign_file`, left alone, never read (ADR 0003 sections 4.1 and 19).
1603 let Some(file_key) = parsed.filter(|_| meta.is_file() && meta.uid() == euid()) else {
1604 return Ok(EntryOutcome::Foreign(meta.len()));
1605 };
1606 let full = {
1607 let g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1608 (g.index.len() as u64) >= g.cfg.max_objects
1609 };
1610 if full {
1611 return Ok(EntryOutcome::Unindexed(phys));
1612 }
1613 // Re-check through the descriptor: what is read is what was checked.
1614 let (file, meta) = match open_private_read(path) {
1615 Ok(PrivateOpen::Ours(f, m)) => (f, m),
1616 Ok(PrivateOpen::NotOurs(len)) => return Ok(EntryOutcome::Foreign(len)),
1617 Err(e) if is_not_found(&e) => return Ok(EntryOutcome::Skip),
1618 // Cannot open or tighten it: do not delete what might be good data;
1619 // count it.
1620 Err(_) => return Ok(EntryOutcome::Unreadable(phys)),
1621 };
1622 let phys = phys_bytes_of(&meta);
1623 let file_size = meta.len();
1624 let kind = if file_size < HEADER_REGION_LEN as u64 {
1625 RecoveredHeader::Corrupt
1626 } else {
1627 let mut buf = [0u8; HEADER_REGION_LEN];
1628 match file.read_exact_at(&mut buf, 0) {
1629 Ok(()) => classify_recovered_header(&buf, file_size, &file_key, cfg),
1630 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => RecoveredHeader::Corrupt,
1631 // Cannot read it: do not delete what might be good data; count it.
1632 Err(_) => return Ok(EntryOutcome::Unreadable(phys)),
1633 }
1634 };
1635 drop(file);
1636 let mtime_ns = meta_mtime_ns(&meta);
1637 Ok(match kind {
1638 RecoveredHeader::Ours { payload_len } => EntryOutcome::Index(
1639 IndexEntry {
1640 key: file_key,
1641 phys_bytes: phys,
1642 mtime_ns,
1643 payload_len,
1644 flags: 0,
1645 },
1646 false,
1647 ),
1648 RecoveredHeader::Foreign { payload_len } => EntryOutcome::Index(
1649 IndexEntry {
1650 key: file_key,
1651 phys_bytes: phys,
1652 mtime_ns,
1653 payload_len,
1654 flags: FLAG_FOREIGN,
1655 },
1656 true,
1657 ),
1658 RecoveredHeader::Corrupt => match unlink_counted(path) {
1659 Ok(_) => EntryOutcome::CorruptDeleted(phys),
1660 Err(_) => EntryOutcome::CorruptStuck(phys),
1661 },
1662 })
1663}
1664
1665impl Inner {
1666 fn apply_recovered(&mut self, out: EntryOutcome) {
1667 self.stats.dir_entries += 1;
1668 self.stats.metadata_calls += 1;
1669 self.stats.io_ops += 1;
1670 self.stats.walk_peak_buffered = self.stats.walk_peak_buffered.max(1);
1671 let unindexed = |g: &mut Inner, phys: u64| {
1672 g.unindexed_objects += 1;
1673 g.unindexed_bytes += phys;
1674 g.recovery.unindexed_objects += 1;
1675 g.recovery.unindexed_bytes += phys;
1676 g.recovery.bytes += phys;
1677 };
1678 match out {
1679 EntryOutcome::Skip => {}
1680 EntryOutcome::TmpDeleted(len) => {
1681 self.stats.unlinks += 1;
1682 self.stats.io_ops += 1;
1683 self.recovery.tmp_deleted += 1;
1684 self.stats.tmp_bytes_deleted += len;
1685 }
1686 EntryOutcome::TmpStuck(phys) => {
1687 self.stats.recovery_unlink_failures += 1;
1688 self.stuck_bytes += phys;
1689 self.recovery_stuck = true;
1690 }
1691 EntryOutcome::Foreign(len) => {
1692 self.stats.foreign_files += 1;
1693 self.stats.foreign_file_bytes += len;
1694 }
1695 EntryOutcome::Unindexed(phys) => {
1696 unindexed(self, phys);
1697 self.stats.over_cap = true;
1698 }
1699 EntryOutcome::CorruptDeleted(phys) => {
1700 self.stats.unlinks += 1;
1701 self.stats.io_ops += 1;
1702 self.recovery.corrupt_deleted += 1;
1703 self.stats.corrupt_deleted_total += 1;
1704 self.stats.corrupt_bytes_deleted += phys;
1705 }
1706 EntryOutcome::CorruptStuck(phys) | EntryOutcome::Unreadable(phys) => {
1707 if matches!(out, EntryOutcome::CorruptStuck(_)) {
1708 self.stats.recovery_unlink_failures += 1;
1709 }
1710 unindexed(self, phys);
1711 self.recovery_stuck = true;
1712 }
1713 EntryOutcome::Index(e, foreign) => {
1714 self.stats.reads += 1;
1715 self.stats.read_bytes += HEADER_REGION_LEN as u64;
1716 self.stats.io_ops += 1;
1717 self.last_clock_ns = self.last_clock_ns.max(e.mtime_ns);
1718 self.index.insert(e);
1719 if foreign {
1720 self.recovery.foreign_namespace += 1;
1721 } else {
1722 self.recovery.indexed += 1;
1723 }
1724 self.recovery.bytes += e.phys_bytes;
1725 }
1726 }
1727 if matches!(
1728 out,
1729 EntryOutcome::CorruptDeleted(_) | EntryOutcome::CorruptStuck(_)
1730 ) {
1731 self.stats.reads += 1;
1732 self.stats.read_bytes += HEADER_REGION_LEN as u64;
1733 }
1734 }
1735
1736 fn fail_recovery(&mut self) {
1737 self.state = StoreState::Failed;
1738 self.recovery.failed = true;
1739 self.recovery.done = false;
1740 }
1741
1742 fn progress(&self) -> RecoveryProgress {
1743 let mut p = self.recovery;
1744 if self.state == StoreState::Failed {
1745 p.failed = true;
1746 p.done = false;
1747 }
1748 p
1749 }
1750}
1751
1752/// One slice of the resumable recovery walk (ADR 4.1). The walk streams one
1753/// directory entry at a time from a `ReadDir` held under its own mutex; the
1754/// index lock is taken only to apply each entry's outcome, never across a
1755/// listing, stat, header read or unlink. A listing or stat error fails the
1756/// store (`Failed`, never done, admission never opens on a partial walk);
1757/// an unlink that fails leaves the file's bytes counted and the store
1758/// `Degraded` when the walk ends (Grok C4 P1-2, P1-3, P2-6).
1759fn recover_step_on(shared: &Shared, slice_ms: u64) -> RecoveryProgress {
1760 let start = Instant::now();
1761 let budget = Duration::from_millis(slice_ms);
1762 let mut walk = shared.walk.lock().unwrap_or_else(|e| e.into_inner());
1763 let (root, cfg) = {
1764 let g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1765 if g.state == StoreState::Failed || g.recovery.done {
1766 return g.progress();
1767 }
1768 (g.cfg.root.clone(), g.cfg.clone())
1769 };
1770 let mut processed = 0usize;
1771 loop {
1772 if processed >= 1 && start.elapsed() >= budget {
1773 break;
1774 }
1775 let next = walk.next(&root);
1776 let outcome = match next {
1777 Ok(Some((stage, path))) => {
1778 processed += 1;
1779 recover_entry(shared, &cfg, stage, &path).map(Some)
1780 }
1781 Ok(None) => Ok(None),
1782 Err(e) => Err(e),
1783 };
1784 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1785 match outcome {
1786 Err(_) => {
1787 g.fail_recovery();
1788 break;
1789 }
1790 Ok(Some(out)) => g.apply_recovered(out),
1791 Ok(None) => {
1792 g.recovery.done = true;
1793 if g.state == StoreState::Recovering {
1794 g.state = if g.recovery_stuck {
1795 StoreState::Degraded
1796 } else {
1797 StoreState::Open
1798 };
1799 }
1800 if g.cfg.purge_after_recovery
1801 && (g.unindexed_objects > 0 || g.used_bytes() > g.cfg.quota_bytes)
1802 {
1803 g.purge_pending = true;
1804 g.purge_walking = g.unindexed_objects > 0;
1805 g.purge_evict_quota = g.used_bytes() > g.cfg.quota_bytes;
1806 }
1807 break;
1808 }
1809 }
1810 }
1811 drop(walk);
1812 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1813 g.recovery.elapsed_us += start.elapsed().as_micros() as u64;
1814 let res = g.progress();
1815 let garbage = std::mem::take(&mut g.graveyard);
1816 drop(g);
1817 drop(garbage);
1818 shared.cv.notify_all();
1819 res
1820}
1821
1822fn run_one_unlink(shared: &Shared, u: Unlink) {
1823 let (root, hook) = {
1824 let g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1825 (g.cfg.root.clone(), g.cfg.faults.clone())
1826 };
1827 let k = ChunkKey(ObjectId(u.key));
1828 let action = check_fault(&hook, Boundary::Unlink, &k);
1829 if let Some(FaultAction::Stall(d)) = action {
1830 std::thread::sleep(d);
1831 }
1832 let path = object_path_for(&root, &u.key);
1833 let outcome: std::io::Result<bool> = match action {
1834 Some(FaultAction::Fail(errno)) => Err(std::io::Error::from_raw_os_error(errno)),
1835 Some(FaultAction::Crash) => return,
1836 _ => unlink_counted(&path),
1837 };
1838
1839 let garbage = {
1840 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1841 g.stats.io_ops += 1;
1842 match outcome {
1843 // Still on disk: back in service, still counted. No job waits on
1844 // an unlink, so nothing else changes (the store that chose this
1845 // victim already published; quota is over until a later eviction).
1846 Err(_) => g.index.clear_evicting(&u.key),
1847 Ok(_) => {
1848 if let Some(removed) = g.index.remove(&u.key) {
1849 g.stats.unlinks += 1;
1850 if u.evict {
1851 g.stats.evicted_bytes_total += removed.phys_bytes;
1852 }
1853 }
1854 }
1855 }
1856 std::mem::take(&mut g.graveyard)
1857 };
1858 drop(garbage);
1859 shared.cv.notify_all();
1860}
1861
1862impl Inner {
1863 fn end_purge_walk(&mut self) {
1864 self.purge_walking = false;
1865 if !self.purge_evict_quota {
1866 self.purge_pending = false;
1867 }
1868 }
1869}
1870
1871/// One step of the unindexed-file purge: stream the shards, unlink one `.kvc`
1872/// file that is not indexed and not being stored. Accounting is subtracted
1873/// only after the unlink succeeds; a failed unlink stops the purge with the
1874/// counts intact (Grok C4 P1-3). A clean pass leaves nothing unindexed.
1875fn purge_walk_step(shared: &Shared, root: &Path) -> bool {
1876 let mut walk = shared.purge_walk.lock().unwrap_or_else(|e| e.into_inner());
1877 let next = walk.next(root);
1878 let (stage, path) = match next {
1879 Ok(Some(x)) => x,
1880 Ok(None) => {
1881 *walk = Walk::new(WalkStage::Shard(0));
1882 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1883 g.unindexed_objects = 0;
1884 g.unindexed_bytes = 0;
1885 g.stats.over_cap = false;
1886 g.end_purge_walk();
1887 return true;
1888 }
1889 Err(_) => {
1890 *walk = Walk::new(WalkStage::Shard(0));
1891 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1892 g.purge_pending = false;
1893 g.purge_walking = false;
1894 g.purge_evict_quota = false;
1895 return true;
1896 }
1897 };
1898 let WalkStage::Shard(s) = stage else {
1899 return true;
1900 };
1901 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1902 let Some(key) = parse_kvc_filename(name, s as u8) else {
1903 return true;
1904 };
1905 {
1906 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1907 g.stats.dir_entries += 1;
1908 g.stats.walk_peak_buffered = g.stats.walk_peak_buffered.max(1);
1909 if g.index.get(&key).is_some() || g.inflight_store.contains_key(&key) {
1910 return true;
1911 }
1912 g.purging = Some(key);
1913 }
1914 let (phys, res) = match std::fs::symlink_metadata(&path) {
1915 Ok(m) => (phys_bytes_of(&m), unlink_counted(&path)),
1916 Err(e) if is_not_found(&e) => (0, Ok(false)),
1917 Err(e) => (0, Err(e)),
1918 };
1919 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1920 g.purging = None;
1921 g.stats.io_ops += 2;
1922 g.stats.metadata_calls += 1;
1923 match res {
1924 Ok(true) => {
1925 g.unindexed_objects = g.unindexed_objects.saturating_sub(1);
1926 g.unindexed_bytes = g.unindexed_bytes.saturating_sub(phys);
1927 g.stats.unlinks += 1;
1928 g.stats.purge_unlinked += 1;
1929 }
1930 Ok(false) => {}
1931 Err(_) => {
1932 g.stats.purge_unlink_failures += 1;
1933 g.purge_pending = false;
1934 g.purge_walking = false;
1935 g.purge_evict_quota = false;
1936 drop(g);
1937 *walk = Walk::new(WalkStage::Shard(0));
1938 }
1939 }
1940 true
1941}
1942
1943fn run_one_purge_step(shared: &Shared) -> bool {
1944 let (root, walking) = {
1945 let g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1946 if !g.purge_pending || !g.recovery.done || g.state == StoreState::Failed {
1947 return false;
1948 }
1949 (g.cfg.root.clone(), g.purge_walking)
1950 };
1951 if walking {
1952 let did = purge_walk_step(shared, &root);
1953 shared.cv.notify_all();
1954 return did;
1955 }
1956
1957 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1958 if g.purge_evict_quota && (g.used_bytes() as u128) * 10 > (g.cfg.quota_bytes as u128) * 9 {
1959 if let Some(victim) = g.index.pick_victim() {
1960 g.index.mark_evicting(&victim);
1961 let path = object_path_for(&root, &victim);
1962 drop(g);
1963 let ok = unlink_counted(&path).is_ok();
1964 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1965 g.stats.io_ops += 1;
1966 if ok {
1967 if let Some(removed) = g.index.remove(&victim) {
1968 g.stats.unlinks += 1;
1969 g.stats.evicted_bytes_total += removed.phys_bytes;
1970 }
1971 } else {
1972 g.index.clear_evicting(&victim);
1973 g.purge_pending = false;
1974 g.purge_evict_quota = false;
1975 }
1976 if (g.used_bytes() as u128) * 10 <= (g.cfg.quota_bytes as u128) * 9 {
1977 g.purge_pending = false;
1978 g.purge_evict_quota = false;
1979 }
1980 drop(g);
1981 shared.cv.notify_all();
1982 return true;
1983 }
1984 }
1985
1986 g.purge_pending = false;
1987 g.purge_evict_quota = false;
1988 drop(g);
1989 shared.cv.notify_all();
1990 false
1991}
1992
1993fn execute_store_job(shared: &Shared, job_id: u64) {
1994 let (root, hook, key, inc, mut file_bytes) = {
1995 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
1996 let Some(job) = g.jobs.get(&job_id) else {
1997 return;
1998 };
1999 if job.cancelling {
2000 let job = g.jobs.remove(&job_id).unwrap();
2001 let stage = job.stage;
2002 g.finish(
2003 job,
2004 Terminal::Cancelled,
2005 stage,
2006 PublishOutcome::NotApplicable,
2007 );
2008 let garbage = std::mem::take(&mut g.graveyard);
2009 drop(g);
2010 drop(garbage);
2011 shared.cv.notify_all();
2012 return;
2013 }
2014
2015 // Make room by marking victims. They are NOT unlinked yet: the write
2016 // goes ahead at once, and `finish` queues their unlinks only when the
2017 // new object is durable (or returns them to service on any other
2018 // ending). While a purge is pending nothing is evicted for room.
2019 while g.bytes_after() > g.cfg.quota_bytes || g.count_after() > g.cfg.max_objects {
2020 let victim = if g.purge_pending {
2021 None
2022 } else {
2023 g.index.pick_victim()
2024 };
2025 let Some(victim) = victim else {
2026 let job = g.jobs.remove(&job_id).unwrap();
2027 g.stats.disk_full_total += 1;
2028 g.fail_job(job, PlatformError::OutOfMemory);
2029 let garbage = std::mem::take(&mut g.graveyard);
2030 drop(g);
2031 drop(garbage);
2032 shared.cv.notify_all();
2033 return;
2034 };
2035 g.index.mark_evicting(&victim);
2036 g.jobs.get_mut(&job_id).unwrap().victims.push(victim);
2037 }
2038
2039 let cfg_layout = g.cfg.layout;
2040 let num_layers = g.cfg.num_layers;
2041 let num_kv_heads = g.cfg.num_kv_heads;
2042 let head_dim = g.cfg.head_dim;
2043 let block_size = g.cfg.block_size;
2044
2045 let job = g.jobs.get(&job_id).unwrap();
2046 let header = job.header.expect("store header");
2047 let key = job.key;
2048 let inc = job.inc;
2049 let src = job.src.as_ref().expect("store source");
2050 let n_blocks = src.block_count();
2051 let tail_valid = src.tail_valid_tokens();
2052 let mut payload = Vec::with_capacity(header.payload_len as usize);
2053 let mut digests = Vec::with_capacity(n_blocks);
2054
2055 for i in 0..n_blocks {
2056 match src.block(i) {
2057 Ok(b) => {
2058 if i + 1 == n_blocks && tail_valid < block_size {
2059 let mut scratch = shared
2060 .tail_scratch
2061 .lock()
2062 .unwrap_or_else(|e| e.into_inner());
2063 zero_tail_block(
2064 &mut scratch,
2065 b,
2066 &cfg_layout,
2067 num_layers,
2068 num_kv_heads,
2069 head_dim,
2070 block_size,
2071 tail_valid,
2072 );
2073 let mut h = Sha256::new();
2074 h.update(&*scratch);
2075 digests.push(h.finalize().into());
2076 payload.extend_from_slice(&scratch);
2077 } else {
2078 let mut h = Sha256::new();
2079 h.update(b);
2080 digests.push(h.finalize().into());
2081 payload.extend_from_slice(b);
2082 }
2083 }
2084 Err(e) => {
2085 g.stats.released_source_violations += 1;
2086 let job = g.jobs.remove(&job_id).unwrap();
2087 g.fail_job(job, e);
2088 let garbage = std::mem::take(&mut g.graveyard);
2089 drop(g);
2090 drop(garbage);
2091 shared.cv.notify_all();
2092 return;
2093 }
2094 }
2095 }
2096
2097 let rec = RecordHeader {
2098 chunk: header,
2099 payload_sha256: payload_root(&digests),
2100 };
2101 let region = match rec.encode_region(&digests) {
2102 Ok(r) => r,
2103 Err(_) => {
2104 let job = g.jobs.remove(&job_id).unwrap();
2105 g.fail_job(job, PlatformError::InvalidLayout);
2106 let garbage = std::mem::take(&mut g.graveyard);
2107 drop(g);
2108 drop(garbage);
2109 shared.cv.notify_all();
2110 return;
2111 }
2112 };
2113 let mut file_bytes = Vec::with_capacity(HEADER_REGION_LEN + payload.len());
2114 file_bytes.extend_from_slice(&region);
2115 file_bytes.extend_from_slice(&payload);
2116
2117 let job = g.jobs.get_mut(&job_id).unwrap();
2118 job.phase = Phase::Writing;
2119 job.in_step = true;
2120 (
2121 g.cfg.root.clone(),
2122 g.cfg.faults.clone(),
2123 key,
2124 inc,
2125 file_bytes,
2126 )
2127 };
2128
2129 // SEAL SEAM (#506, #708, #811): encrypt the payload in place and fill the
2130 // seal slot, off the lock. `SealError::Random`, `Budget` and `UsageStore`
2131 // leave `file_bytes` plaintext, so the error return below is what keeps
2132 // that buffer off disk. The usage count is durable before this returns
2133 // Ok. There is no fallback nonce.
2134 let usage_dir = root.join(crate::seal::USAGE_DIR_NAME);
2135 if let Err(err) = shared.seal_key.seal_file(&usage_dir, &mut file_bytes) {
2136 let why = match err {
2137 crate::seal::SealError::Budget => "seal budget exhausted",
2138 crate::seal::SealError::UsageStore => "seal usage counter failed",
2139 _ => "seal failed",
2140 };
2141 let garbage = {
2142 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2143 if let Some(job) = g.jobs.remove(&job_id) {
2144 g.fail_job(job, PlatformError::HardwareFault(why.into()));
2145 }
2146 std::mem::take(&mut g.graveyard)
2147 };
2148 drop(garbage);
2149 shared.cv.notify_all();
2150 return;
2151 }
2152
2153 let tpath = tmp_path_for(&root, &key.0 .0, job_id, inc);
2154 let opath = object_path_for(&root, &key.0 .0);
2155 let shard_dir = opath.parent().expect("shard dir").to_path_buf();
2156
2157 // P1: Write temporary file.
2158 let p1 = check_fault(&hook, Boundary::P1Write, &key);
2159 if let Some(FaultAction::Stall(d)) = p1 {
2160 std::thread::sleep(d);
2161 }
2162 match p1 {
2163 Some(FaultAction::Crash) => {
2164 let _ = write_private_file(&tpath, &file_bytes);
2165 let garbage = {
2166 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2167 if let Some(job) = g.jobs.remove(&job_id) {
2168 g.mark_crashed(job);
2169 }
2170 std::mem::take(&mut g.graveyard)
2171 };
2172 drop(garbage);
2173 shared.cv.notify_all();
2174 return;
2175 }
2176 Some(FaultAction::TornWrite { after_bytes, crash }) => {
2177 let cut = (after_bytes as usize).min(file_bytes.len());
2178 let wrote = write_private_file(&tpath, &file_bytes[..cut]).is_ok();
2179 if crash {
2180 let garbage = {
2181 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2182 if let Some(job) = g.jobs.remove(&job_id) {
2183 g.mark_crashed(job);
2184 }
2185 std::mem::take(&mut g.graveyard)
2186 };
2187 drop(garbage);
2188 shared.cv.notify_all();
2189 return;
2190 }
2191 if wrote {
2192 let _ = std::fs::remove_file(&tpath);
2193 }
2194 let garbage = {
2195 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2196 g.stats.writes += 1;
2197 g.stats.write_bytes += cut as u64;
2198 g.stats.unlinks += 1;
2199 g.stats.io_ops += 2;
2200 if let Some(job) = g.jobs.remove(&job_id) {
2201 g.fail_job(job, PlatformError::HardwareFault("torn write".into()));
2202 }
2203 std::mem::take(&mut g.graveyard)
2204 };
2205 drop(garbage);
2206 shared.cv.notify_all();
2207 return;
2208 }
2209 Some(FaultAction::Fail(errno)) => {
2210 // Only remove what this call created: a failed create (say, a
2211 // planted symlink) leaves the path alone.
2212 if write_private_file(&tpath, &file_bytes[..HEADER_REGION_LEN]).is_ok() {
2213 let _ = std::fs::remove_file(&tpath);
2214 }
2215 let garbage = {
2216 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2217 g.stats.unlinks += 1;
2218 g.stats.io_ops += 2;
2219 if errno == ENOSPC {
2220 g.stats.disk_full_total += 1;
2221 }
2222 if let Some(job) = g.jobs.remove(&job_id) {
2223 g.fail_job(job, errno_to_error(errno, "write temp failed"));
2224 }
2225 std::mem::take(&mut g.graveyard)
2226 };
2227 drop(garbage);
2228 shared.cv.notify_all();
2229 return;
2230 }
2231 _ => {}
2232 }
2233
2234 // `created`: the open succeeded, so a failed write leaves a temp of ours
2235 // to remove. A failed open (a planted symlink: O_NOFOLLOW gives ELOOP)
2236 // created nothing and the path is left alone.
2237 let mut created = false;
2238 let write_res = create_private_file(&tpath).and_then(|mut f| {
2239 created = true;
2240 f.write_all(&file_bytes)?;
2241 Ok(f)
2242 });
2243 let tmp_file = match write_res {
2244 Ok(f) => f,
2245 Err(e) => {
2246 if created {
2247 let _ = std::fs::remove_file(&tpath);
2248 }
2249 let garbage = {
2250 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2251 g.stats.io_ops += 1;
2252 if e.raw_os_error() == Some(ENOSPC) {
2253 g.stats.disk_full_total += 1;
2254 }
2255 if let Some(job) = g.jobs.remove(&job_id) {
2256 g.fail_job(job, io_to_error(&e, "write temp failed"));
2257 }
2258 std::mem::take(&mut g.graveyard)
2259 };
2260 drop(garbage);
2261 shared.cv.notify_all();
2262 return;
2263 }
2264 };
2265
2266 {
2267 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2268 g.stats.writes += 1;
2269 g.stats.write_bytes += file_bytes.len() as u64;
2270 g.stats.io_ops += 1;
2271 let cancelled = g.jobs.get(&job_id).is_none_or(|j| j.cancelling);
2272 if cancelled {
2273 drop(tmp_file);
2274 let _ = std::fs::remove_file(&tpath);
2275 g.stats.unlinks += 1;
2276 g.stats.io_ops += 1;
2277 if let Some(job) = g.jobs.remove(&job_id) {
2278 let stage = job.stage;
2279 g.finish(
2280 job,
2281 Terminal::Cancelled,
2282 stage,
2283 PublishOutcome::NotApplicable,
2284 );
2285 }
2286 let garbage = std::mem::take(&mut g.graveyard);
2287 drop(g);
2288 drop(garbage);
2289 shared.cv.notify_all();
2290 return;
2291 }
2292 if let Some(job) = g.jobs.get_mut(&job_id) {
2293 job.phase = Phase::Syncing;
2294 }
2295 }
2296
2297 // P2: fsync temporary file.
2298 let p2 = check_fault(&hook, Boundary::P2FsyncFile, &key);
2299 if let Some(FaultAction::Stall(d)) = p2 {
2300 std::thread::sleep(d);
2301 }
2302 match p2 {
2303 Some(FaultAction::Crash) => {
2304 drop(tmp_file);
2305 let garbage = {
2306 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2307 if let Some(job) = g.jobs.remove(&job_id) {
2308 g.mark_crashed(job);
2309 }
2310 std::mem::take(&mut g.graveyard)
2311 };
2312 drop(garbage);
2313 shared.cv.notify_all();
2314 return;
2315 }
2316 Some(FaultAction::Fail(errno)) => {
2317 drop(tmp_file);
2318 let _ = std::fs::remove_file(&tpath);
2319 let garbage = {
2320 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2321 g.stats.file_fsyncs += 1;
2322 g.stats.unlinks += 1;
2323 g.stats.io_ops += 2;
2324 g.set_degraded();
2325 if let Some(job) = g.jobs.remove(&job_id) {
2326 g.fail_job(job, errno_to_error(errno, "fsync(file) failed"));
2327 }
2328 std::mem::take(&mut g.graveyard)
2329 };
2330 drop(garbage);
2331 shared.cv.notify_all();
2332 return;
2333 }
2334 _ => {}
2335 }
2336
2337 if let Err(e) = tmp_file.sync_all() {
2338 drop(tmp_file);
2339 let _ = std::fs::remove_file(&tpath);
2340 let garbage = {
2341 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2342 g.stats.file_fsyncs += 1;
2343 g.stats.unlinks += 1;
2344 g.stats.io_ops += 2;
2345 g.set_degraded();
2346 if let Some(job) = g.jobs.remove(&job_id) {
2347 g.fail_job(job, io_to_error(&e, "fsync(file) failed"));
2348 }
2349 std::mem::take(&mut g.graveyard)
2350 };
2351 drop(garbage);
2352 shared.cv.notify_all();
2353 return;
2354 }
2355 drop(tmp_file);
2356
2357 {
2358 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2359 g.stats.file_fsyncs += 1;
2360 g.stats.io_ops += 1;
2361 if let Some(job) = g.jobs.get_mut(&job_id) {
2362 job.stage = JobStage::Completed;
2363 job.phase = Phase::Publishing;
2364 let snap = Completion {
2365 job: JobId(job.id),
2366 incarnation: job.inc,
2367 key: job.key,
2368 stage: JobStage::Completed,
2369 terminal: None,
2370 publish: PublishOutcome::NotApplicable,
2371 bytes: job.payload_len,
2372 elapsed_us: job.submitted_at.elapsed().as_micros() as u64,
2373 holder: None,
2374 };
2375 g.push_completion(snap);
2376 }
2377 }
2378
2379 // P3: atomic rename of temporary file into shard directory.
2380 let p3 = check_fault(&hook, Boundary::P3Rename, &key);
2381 if let Some(FaultAction::Stall(d)) = p3 {
2382 std::thread::sleep(d);
2383 }
2384 match p3 {
2385 Some(FaultAction::Crash) => {
2386 let garbage = {
2387 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2388 if let Some(job) = g.jobs.remove(&job_id) {
2389 g.mark_crashed(job);
2390 }
2391 std::mem::take(&mut g.graveyard)
2392 };
2393 drop(garbage);
2394 shared.cv.notify_all();
2395 return;
2396 }
2397 Some(FaultAction::Fail(errno)) => {
2398 let _ = std::fs::remove_file(&tpath);
2399 let garbage = {
2400 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2401 g.stats.unlinks += 1;
2402 g.stats.io_ops += 2;
2403 if let Some(job) = g.jobs.remove(&job_id) {
2404 g.fail_job(job, errno_to_error(errno, "rename failed"));
2405 }
2406 std::mem::take(&mut g.graveyard)
2407 };
2408 drop(garbage);
2409 shared.cv.notify_all();
2410 return;
2411 }
2412 _ => {}
2413 }
2414
2415 if let Err(e) = std::fs::rename(&tpath, &opath) {
2416 let _ = std::fs::remove_file(&tpath);
2417 let garbage = {
2418 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2419 g.stats.unlinks += 1;
2420 g.stats.io_ops += 2;
2421 if let Some(job) = g.jobs.remove(&job_id) {
2422 g.fail_job(job, io_to_error(&e, "rename failed"));
2423 }
2424 std::mem::take(&mut g.graveyard)
2425 };
2426 drop(garbage);
2427 shared.cv.notify_all();
2428 return;
2429 }
2430
2431 let (phys_bytes, file_mtime_ns) = match std::fs::symlink_metadata(&opath) {
2432 Ok(m) => (phys_bytes_of(&m), meta_mtime_ns(&m)),
2433 Err(_) => (file_bytes.len() as u64, system_now_ns()),
2434 };
2435
2436 {
2437 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2438 g.stats.renames += 1;
2439 g.stats.metadata_calls += 1;
2440 g.stats.io_ops += 2;
2441 if let Some(job) = g.jobs.get_mut(&job_id) {
2442 job.stage = JobStage::Published;
2443 }
2444 }
2445
2446 // P4: fsync parent shard directory.
2447 let p4 = check_fault(&hook, Boundary::P4FsyncDir, &key);
2448 if let Some(FaultAction::Stall(d)) = p4 {
2449 std::thread::sleep(d);
2450 }
2451 let dir_sync_res: Result<(), PlatformError> = match p4 {
2452 Some(FaultAction::Crash) => {
2453 let garbage = {
2454 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2455 if let Some(job) = g.jobs.remove(&job_id) {
2456 g.mark_crashed(job);
2457 }
2458 std::mem::take(&mut g.graveyard)
2459 };
2460 drop(garbage);
2461 shared.cv.notify_all();
2462 return;
2463 }
2464 Some(FaultAction::Fail(errno)) => Err(errno_to_error(errno, "fsync(dir) failed")),
2465 _ => fsync_dir(&shard_dir).map_err(|e| io_to_error(&e, "fsync(dir) failed")),
2466 };
2467
2468 if let Err(err) = dir_sync_res {
2469 let garbage = {
2470 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2471 g.stats.dir_fsyncs += 1;
2472 g.stats.io_ops += 1;
2473 g.stats.published_total += 1;
2474 g.stats.indeterminate_total += 1;
2475 g.set_degraded();
2476 let mtime_ns = g.next_timestamp_ns(file_mtime_ns);
2477 if let Some(job) = g.jobs.remove(&job_id) {
2478 g.index.insert(IndexEntry {
2479 key: key.0 .0,
2480 phys_bytes,
2481 mtime_ns,
2482 payload_len: job.payload_len,
2483 flags: FLAG_INDETERMINATE,
2484 });
2485 g.finish(
2486 job,
2487 Terminal::Failed(err),
2488 JobStage::Published,
2489 PublishOutcome::Indeterminate,
2490 );
2491 }
2492 std::mem::take(&mut g.graveyard)
2493 };
2494 drop(garbage);
2495 shared.cv.notify_all();
2496 return;
2497 }
2498
2499 {
2500 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2501 g.stats.dir_fsyncs += 1;
2502 g.stats.io_ops += 1;
2503 }
2504
2505 // P5: insert entry into in-memory index.
2506 let p5 = check_fault(&hook, Boundary::P5IndexInsert, &key);
2507 if let Some(FaultAction::Stall(d)) = p5 {
2508 std::thread::sleep(d);
2509 }
2510 if matches!(p5, Some(FaultAction::Crash)) {
2511 let garbage = {
2512 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2513 if let Some(job) = g.jobs.remove(&job_id) {
2514 g.mark_crashed(job);
2515 }
2516 std::mem::take(&mut g.graveyard)
2517 };
2518 drop(garbage);
2519 shared.cv.notify_all();
2520 return;
2521 }
2522
2523 let garbage = {
2524 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2525 let mtime_ns = g.next_timestamp_ns(file_mtime_ns);
2526 g.stats.published_total += 1;
2527 if let Some(mut job) = g.jobs.remove(&job_id) {
2528 g.index.insert(IndexEntry {
2529 key: key.0 .0,
2530 phys_bytes,
2531 mtime_ns,
2532 payload_len: job.payload_len,
2533 flags: 0,
2534 });
2535 job.stage = JobStage::Durable;
2536 g.finish(
2537 job,
2538 Terminal::Done(JobStage::Durable),
2539 JobStage::Durable,
2540 PublishOutcome::Durable,
2541 );
2542 }
2543 std::mem::take(&mut g.graveyard)
2544 };
2545 drop(garbage);
2546 shared.cv.notify_all();
2547}
2548
2549fn execute_load_job(shared: &Shared, job_id: u64) {
2550 let (root, hook, key, expect, block_stride) = {
2551 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2552 let Some(job) = g.jobs.get_mut(&job_id) else {
2553 return;
2554 };
2555 if job.cancelling {
2556 let job = g.jobs.remove(&job_id).unwrap();
2557 let stage = job.stage;
2558 g.finish(
2559 job,
2560 Terminal::Cancelled,
2561 stage,
2562 PublishOutcome::NotApplicable,
2563 );
2564 let garbage = std::mem::take(&mut g.graveyard);
2565 drop(g);
2566 drop(garbage);
2567 shared.cv.notify_all();
2568 return;
2569 }
2570 job.phase = Phase::Reading;
2571 job.in_step = true;
2572 let key = job.key;
2573 let expect = job.header.expect("load expect");
2574 (
2575 g.cfg.root.clone(),
2576 g.cfg.faults.clone(),
2577 key,
2578 expect,
2579 g.cfg.layout.block_stride,
2580 )
2581 };
2582
2583 let lr = check_fault(&hook, Boundary::LoadRead, &key);
2584 if let Some(FaultAction::Stall(d)) = lr {
2585 std::thread::sleep(d);
2586 }
2587 match lr {
2588 Some(FaultAction::Crash) => {
2589 let garbage = {
2590 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2591 if let Some(job) = g.jobs.remove(&job_id) {
2592 g.mark_crashed(job);
2593 }
2594 std::mem::take(&mut g.graveyard)
2595 };
2596 drop(garbage);
2597 shared.cv.notify_all();
2598 return;
2599 }
2600 Some(FaultAction::Fail(errno)) => {
2601 let garbage = {
2602 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2603 g.stats.io_ops += 1;
2604 if let Some(job) = g.jobs.remove(&job_id) {
2605 g.fail_job(job, errno_to_error(errno, "load read failed"));
2606 }
2607 std::mem::take(&mut g.graveyard)
2608 };
2609 drop(garbage);
2610 shared.cv.notify_all();
2611 return;
2612 }
2613 _ => {}
2614 }
2615
2616 let opath = object_path_for(&root, &key.0 .0);
2617 // No symlink followed, checked through the descriptor: a link, a
2618 // non-regular file or another owner's file is never served; it leaves
2619 // the index as not found and the file is left alone (ADR 0003 section 19).
2620 let (file, meta) = match open_private_read(&opath) {
2621 Ok(PrivateOpen::Ours(f, m)) => (f, m),
2622 Err(e) if !is_not_found(&e) => {
2623 let garbage = {
2624 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2625 g.stats.metadata_calls += 1;
2626 g.stats.io_ops += 1;
2627 if let Some(job) = g.jobs.remove(&job_id) {
2628 g.fail_job(job, io_to_error(&e, "open object failed"));
2629 }
2630 std::mem::take(&mut g.graveyard)
2631 };
2632 drop(garbage);
2633 shared.cv.notify_all();
2634 return;
2635 }
2636 Ok(PrivateOpen::NotOurs(_)) | Err(_) => {
2637 let garbage = {
2638 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2639 g.stats.metadata_calls += 1;
2640 g.stats.io_ops += 1;
2641 if let Some(mut job) = g.jobs.remove(&job_id) {
2642 if job.busy_held {
2643 g.index.busy_dec(&key.0 .0);
2644 job.busy_held = false;
2645 }
2646 g.index.remove(&key.0 .0);
2647 g.fail_job(job, PlatformError::ObjectNotFound(key.0));
2648 }
2649 std::mem::take(&mut g.graveyard)
2650 };
2651 drop(garbage);
2652 shared.cv.notify_all();
2653 return;
2654 }
2655 };
2656
2657 let file_size = meta.len();
2658 if file_size < HEADER_REGION_LEN as u64 {
2659 let _ = std::fs::remove_file(&opath);
2660 let garbage = {
2661 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2662 g.stats.metadata_calls += 1;
2663 g.stats.unlinks += 1;
2664 g.stats.io_ops += 2;
2665 g.stats.corrupt_deleted_total += 1;
2666 if let Some(mut job) = g.jobs.remove(&job_id) {
2667 if job.busy_held {
2668 g.index.busy_dec(&key.0 .0);
2669 job.busy_held = false;
2670 }
2671 if let Some(rem) = g.index.remove(&key.0 .0) {
2672 g.stats.corrupt_bytes_deleted += rem.phys_bytes;
2673 }
2674 g.fail_job(job, PlatformError::InvalidLayout);
2675 }
2676 std::mem::take(&mut g.graveyard)
2677 };
2678 drop(garbage);
2679 shared.cv.notify_all();
2680 return;
2681 }
2682
2683 let mut header_buf = [0u8; HEADER_REGION_LEN];
2684 if file.read_exact_at(&mut header_buf, 0).is_err()
2685 || validate_record(&header_buf, file_size, &expect, block_stride).is_err()
2686 {
2687 drop(file);
2688 let _ = std::fs::remove_file(&opath);
2689 let garbage = {
2690 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2691 g.stats.metadata_calls += 1;
2692 g.stats.reads += 1;
2693 g.stats.read_bytes += HEADER_REGION_LEN as u64;
2694 g.stats.unlinks += 1;
2695 g.stats.io_ops += 3;
2696 g.stats.corrupt_deleted_total += 1;
2697 if let Some(mut job) = g.jobs.remove(&job_id) {
2698 if job.busy_held {
2699 g.index.busy_dec(&key.0 .0);
2700 job.busy_held = false;
2701 }
2702 if let Some(rem) = g.index.remove(&key.0 .0) {
2703 g.stats.corrupt_bytes_deleted += rem.phys_bytes;
2704 }
2705 g.fail_job(job, PlatformError::InvalidLayout);
2706 }
2707 std::mem::take(&mut g.graveyard)
2708 };
2709 drop(garbage);
2710 shared.cv.notify_all();
2711 return;
2712 }
2713
2714 let n_seg = (expect.payload_len / block_stride) as usize;
2715 let seg_len = block_stride as usize;
2716 let mut reads_done = 1u64;
2717 let mut bytes_read = HEADER_REGION_LEN as u64;
2718
2719 // SEAL SEAM (#506): read the whole ciphertext, then authenticate and
2720 // decrypt it before any segment reaches the destination. A refusal (wrong
2721 // key, tampered bytes, swapped header, no seal) discards the object like
2722 // any corrupt one; the caller recomputes.
2723 let mut payload = vec![0u8; expect.payload_len as usize];
2724 let read_ok = file
2725 .read_exact_at(&mut payload, crate::record::PAYLOAD_OFFSET as u64)
2726 .is_ok();
2727 if read_ok {
2728 reads_done += 1;
2729 bytes_read += expect.payload_len;
2730 }
2731 if !read_ok
2732 || shared
2733 .seal_key
2734 .open_payload(&header_buf, &mut payload)
2735 .is_err()
2736 {
2737 drop(file);
2738 let _ = std::fs::remove_file(&opath);
2739 let garbage = {
2740 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2741 g.stats.metadata_calls += 1;
2742 g.stats.reads += reads_done;
2743 g.stats.read_bytes += bytes_read;
2744 g.stats.unlinks += 1;
2745 g.stats.io_ops += 2 + reads_done;
2746 g.stats.corrupt_deleted_total += 1;
2747 if let Some(mut job) = g.jobs.remove(&job_id) {
2748 if job.busy_held {
2749 g.index.busy_dec(&key.0 .0);
2750 job.busy_held = false;
2751 }
2752 if let Some(rem) = g.index.remove(&key.0 .0) {
2753 g.stats.corrupt_bytes_deleted += rem.phys_bytes;
2754 }
2755 g.fail_job(job, PlatformError::InvalidLayout);
2756 }
2757 std::mem::take(&mut g.graveyard)
2758 };
2759 drop(garbage);
2760 shared.cv.notify_all();
2761 return;
2762 }
2763
2764 for i in 0..n_seg {
2765 let seg_buf = &payload[i * seg_len..(i + 1) * seg_len];
2766 let mut h = Sha256::new();
2767 h.update(seg_buf);
2768 let digest: [u8; 32] = h.finalize().into();
2769 let want = &header_buf[256 + 32 * i..256 + 32 * (i + 1)];
2770 if digest != want {
2771 drop(file);
2772 let _ = std::fs::remove_file(&opath);
2773 let garbage = {
2774 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2775 g.stats.metadata_calls += 1;
2776 g.stats.reads += reads_done;
2777 g.stats.read_bytes += bytes_read;
2778 g.stats.unlinks += 1;
2779 g.stats.io_ops += 2 + reads_done;
2780 g.stats.corrupt_deleted_total += 1;
2781 if let Some(mut job) = g.jobs.remove(&job_id) {
2782 if job.busy_held {
2783 g.index.busy_dec(&key.0 .0);
2784 job.busy_held = false;
2785 }
2786 if let Some(rem) = g.index.remove(&key.0 .0) {
2787 g.stats.corrupt_bytes_deleted += rem.phys_bytes;
2788 }
2789 g.fail_job(job, PlatformError::InvalidLayout);
2790 }
2791 std::mem::take(&mut g.graveyard)
2792 };
2793 drop(garbage);
2794 shared.cv.notify_all();
2795 return;
2796 }
2797
2798 let write_err = {
2799 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2800 let dst = g
2801 .jobs
2802 .get_mut(&job_id)
2803 .and_then(|j| j.dst.as_mut())
2804 .expect("load dst");
2805 dst.write_block(i, seg_buf).err()
2806 };
2807 if let Some(err) = write_err {
2808 drop(file);
2809 let garbage = {
2810 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2811 g.stats.metadata_calls += 1;
2812 g.stats.reads += reads_done;
2813 g.stats.read_bytes += bytes_read;
2814 g.stats.io_ops += 1 + reads_done;
2815 if let Some(job) = g.jobs.remove(&job_id) {
2816 g.fail_job(job, err);
2817 }
2818 std::mem::take(&mut g.graveyard)
2819 };
2820 drop(garbage);
2821 shared.cv.notify_all();
2822 return;
2823 }
2824 }
2825 drop(file);
2826
2827 let garbage = {
2828 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2829 g.stats.metadata_calls += 1;
2830 g.stats.reads += reads_done;
2831 g.stats.read_bytes += bytes_read;
2832 g.stats.io_ops += 1 + reads_done;
2833 let ts = g.next_timestamp_ns(0);
2834 g.index.touch(&key.0 .0, ts);
2835 if let Some(mut job) = g.jobs.remove(&job_id) {
2836 job.stage = JobStage::Completed;
2837 g.finish(
2838 job,
2839 Terminal::Done(JobStage::Completed),
2840 JobStage::Completed,
2841 PublishOutcome::NotApplicable,
2842 );
2843 }
2844 std::mem::take(&mut g.graveyard)
2845 };
2846 drop(garbage);
2847 shared.cv.notify_all();
2848}
2849
2850fn execute_flush_job(shared: &Shared, job_id: u64) {
2851 let (root, hook, key) = {
2852 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2853 let Some(job) = g.jobs.get_mut(&job_id) else {
2854 return;
2855 };
2856 job.phase = Phase::Flushing;
2857 job.in_step = true;
2858 let key = job.key;
2859 (g.cfg.root.clone(), g.cfg.faults.clone(), key)
2860 };
2861
2862 let fs = check_fault(&hook, Boundary::FlushSync, &key);
2863 if let Some(FaultAction::Stall(d)) = fs {
2864 std::thread::sleep(d);
2865 }
2866 let res: Result<(), PlatformError> = match fs {
2867 Some(FaultAction::Crash) => {
2868 let garbage = {
2869 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2870 if let Some(job) = g.jobs.remove(&job_id) {
2871 g.mark_crashed(job);
2872 }
2873 std::mem::take(&mut g.graveyard)
2874 };
2875 drop(garbage);
2876 shared.cv.notify_all();
2877 return;
2878 }
2879 Some(FaultAction::Fail(errno)) => Err(errno_to_error(errno, "flush failed")),
2880 _ => fsync_dir(&root.join("objects"))
2881 .and_then(|()| fsync_dir(&root))
2882 .map_err(|e| io_to_error(&e, "flush failed")),
2883 };
2884
2885 let garbage = {
2886 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2887 g.stats.dir_fsyncs += 1;
2888 g.stats.io_ops += 1;
2889 match res {
2890 Err(e) => {
2891 g.set_degraded();
2892 if let Some(job) = g.jobs.remove(&job_id) {
2893 g.fail_job(job, e);
2894 }
2895 }
2896 Ok(()) => {
2897 if let Some(mut job) = g.jobs.remove(&job_id) {
2898 job.stage = JobStage::Durable;
2899 g.finish(
2900 job,
2901 Terminal::Done(JobStage::Durable),
2902 JobStage::Durable,
2903 PublishOutcome::Durable,
2904 );
2905 }
2906 }
2907 }
2908 std::mem::take(&mut g.graveyard)
2909 };
2910 drop(garbage);
2911 shared.cv.notify_all();
2912}
2913
2914fn pump_one(shared: &Shared) -> bool {
2915 let reaped = {
2916 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2917 let r = g.reap_cancels();
2918 let garbage = std::mem::take(&mut g.graveyard);
2919 drop(g);
2920 drop(garbage);
2921 r
2922 };
2923 if reaped {
2924 shared.cv.notify_all();
2925 return true;
2926 }
2927
2928 let unlink = {
2929 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2930 g.unlinks.pop_front()
2931 };
2932 if let Some(u) = unlink {
2933 run_one_unlink(shared, u);
2934 return true;
2935 }
2936
2937 if run_one_purge_step(shared) {
2938 return true;
2939 }
2940
2941 let picked: Option<(u64, Kind)> = {
2942 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2943 let next_restore = g
2944 .jobs
2945 .iter()
2946 .find(|(_, j)| {
2947 !j.park && !j.cancelling && !j.in_step && !j.crashed && j.phase == Phase::Queued
2948 })
2949 .map(|(id, j)| (*id, j.kind));
2950 let next_park = g
2951 .jobs
2952 .iter()
2953 .find(|(_, j)| {
2954 j.park && !j.cancelling && !j.in_step && !j.crashed && j.phase == Phase::Queued
2955 })
2956 .map(|(id, j)| (*id, j.kind));
2957 match (next_restore, next_park) {
2958 (Some(r), Some(p)) => {
2959 if g.restore_streak < 3 {
2960 g.restore_streak += 1;
2961 Some(r)
2962 } else {
2963 g.restore_streak = 0;
2964 Some(p)
2965 }
2966 }
2967 (Some(r), None) => {
2968 g.restore_streak = g.restore_streak.saturating_add(1);
2969 Some(r)
2970 }
2971 (None, Some(p)) => {
2972 g.restore_streak = 0;
2973 Some(p)
2974 }
2975 (None, None) => None,
2976 }
2977 };
2978
2979 let Some((job_id, kind)) = picked else {
2980 return false;
2981 };
2982
2983 match kind {
2984 Kind::Noop => {
2985 let garbage = {
2986 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
2987 if let Some(mut job) = g.jobs.remove(&job_id) {
2988 job.stage = JobStage::Durable;
2989 g.finish(
2990 job,
2991 Terminal::Done(JobStage::Durable),
2992 JobStage::Durable,
2993 PublishOutcome::NotApplicable,
2994 );
2995 }
2996 std::mem::take(&mut g.graveyard)
2997 };
2998 drop(garbage);
2999 shared.cv.notify_all();
3000 }
3001 Kind::Store => execute_store_job(shared, job_id),
3002 Kind::Load => execute_load_job(shared, job_id),
3003 Kind::Flush => execute_flush_job(shared, job_id),
3004 }
3005 true
3006}
3007
3008fn worker_loop(shared: Arc<Shared>) {
3009 loop {
3010 let (need_recover, slice_ms, stop) = {
3011 let g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
3012 (
3013 g.state == StoreState::Recovering && !g.recovery.done,
3014 g.cfg.recovery_slice_ms,
3015 g.stop_worker,
3016 )
3017 };
3018 if stop {
3019 break;
3020 }
3021 if need_recover {
3022 recover_step_on(&shared, slice_ms);
3023 continue;
3024 }
3025 if pump_one(&shared) {
3026 continue;
3027 }
3028 let mut g = shared.inner.lock().unwrap_or_else(|e| e.into_inner());
3029 if g.stop_worker {
3030 break;
3031 }
3032 let has_work = (g.state == StoreState::Recovering && !g.recovery.done)
3033 || !g.unlinks.is_empty()
3034 || (g.purge_pending && g.recovery.done)
3035 || g.jobs
3036 .values()
3037 .any(|j| !j.in_step && !j.crashed && (j.cancelling || j.phase == Phase::Queued));
3038 if !has_work {
3039 g = shared.cv.wait(g).unwrap_or_else(|e| e.into_inner());
3040 }
3041 drop(g);
3042 }
3043}
3044
3045impl HostFsStore {
3046 pub fn open(config: HostFsConfig) -> Result<Self, PlatformError> {
3047 validate_config(&config)?;
3048 // SEAL SEAM (#506): no key, no store (fail closed, nothing touched).
3049 let seal_key = config.seal_key.clone().ok_or(PlatformError::AccessDenied)?;
3050 let mut stats = HostFsStats {
3051 tail_scratch_bytes: config.layout.block_stride,
3052 ..HostFsStats::default()
3053 };
3054
3055 let root = &config.root;
3056 let objects_dir = root.join("objects");
3057 let tmp_dir = root.join("tmp");
3058 let usage_dir = root.join(crate::seal::USAGE_DIR_NAME);
3059 let shard_dirs: Vec<PathBuf> = (0..=255u8)
3060 .map(|b| objects_dir.join(format!("{b:02x}")))
3061 .collect();
3062
3063 // Check everything that already exists before creating anything, so
3064 // a refused store is left exactly as it was (ADR 0003 section 19.3).
3065 check_trusted_parent(root)?;
3066 if check_private_dir(root)? {
3067 check_private_dir(&tmp_dir)?;
3068 check_private_dir(&usage_dir)?;
3069 if check_private_dir(&objects_dir)? {
3070 for shard in &shard_dirs {
3071 check_private_dir(shard)?;
3072 }
3073 }
3074 }
3075
3076 if make_private_dir(root, true)? {
3077 stats.mkdirs += 1;
3078 stats.io_ops += 1;
3079 }
3080 let dir_lock = lock_store_dir(root)?;
3081 stats.io_ops += 1;
3082 for dir in [&objects_dir, &tmp_dir] {
3083 if make_private_dir(dir, false)? {
3084 stats.mkdirs += 1;
3085 stats.io_ops += 1;
3086 }
3087 }
3088 if make_private_dir(&usage_dir, false)? {
3089 stats.mkdirs += 1;
3090 stats.io_ops += 1;
3091 // The directory name has to be durable before the first seal.
3092 // Losing `seal-usage/` beside sealed objects fails the next seal
3093 // (`SealError::UsageStore`) and records the key. A key already in
3094 // `key-fingerprints` cannot start over. An empty store still
3095 // starts at zero.
3096 fsync_dir(&usage_dir).map_err(|e| io_to_error(&e, "fsync seal-usage"))?;
3097 fsync_dir(root).map_err(|e| io_to_error(&e, "fsync root for seal-usage"))?;
3098 stats.dir_fsyncs += 2;
3099 stats.io_ops += 2;
3100 }
3101
3102 let alloc_unit = std::fs::metadata(&objects_dir)
3103 .map(|m| m.blksize())
3104 .unwrap_or(4096)
3105 .max(512);
3106
3107 let mut created_shard = false;
3108 for shard in &shard_dirs {
3109 if make_private_dir(shard, false)? {
3110 stats.mkdirs += 1;
3111 stats.io_ops += 1;
3112 created_shard = true;
3113 }
3114 }
3115 if created_shard {
3116 fsync_dir(&objects_dir).map_err(|e| io_to_error(&e, "fsync objects"))?;
3117 stats.dir_fsyncs += 1;
3118 stats.io_ops += 1;
3119 }
3120
3121 let store_id_path = root.join("STORE_ID");
3122 let (store_id, state, recovery_done) = if std::fs::symlink_metadata(&store_id_path).is_ok()
3123 {
3124 stats.reads += 1;
3125 stats.io_ops += 1;
3126 // No symlink followed, a regular file of ours, exactly 16 bytes;
3127 // anything else fails the store (as an unreadable STORE_ID did).
3128 let mut arr = [0u8; 16];
3129 let read = match open_private_read(&store_id_path) {
3130 Ok(PrivateOpen::Ours(mut f, meta)) if meta.len() == 16 => {
3131 f.read_exact(&mut arr).is_ok()
3132 }
3133 _ => false,
3134 };
3135 if read {
3136 stats.read_bytes += 16;
3137 (Some(arr), StoreState::Recovering, false)
3138 } else {
3139 (None, StoreState::Failed, false)
3140 }
3141 } else {
3142 let id = generate_store_id();
3143 let part = tmp_dir.join("STORE_ID.part");
3144 {
3145 // A STORE_ID.part left by a crash is ours (tmp/ is verified
3146 // private) and is truncated, so it never blocks reopening.
3147 let mut f = create_private_file(&part)
3148 .map_err(|e| io_to_error(&e, "create STORE_ID.part"))?;
3149 f.write_all(&id)
3150 .map_err(|e| io_to_error(&e, "write STORE_ID.part"))?;
3151 stats.writes += 1;
3152 stats.write_bytes += 16;
3153 stats.io_ops += 1;
3154 f.sync_all()
3155 .map_err(|e| io_to_error(&e, "fsync STORE_ID.part"))?;
3156 stats.file_fsyncs += 1;
3157 stats.io_ops += 1;
3158 }
3159 std::fs::rename(&part, &store_id_path)
3160 .map_err(|e| io_to_error(&e, "rename STORE_ID"))?;
3161 stats.renames += 1;
3162 stats.io_ops += 1;
3163 fsync_dir(root).map_err(|e| io_to_error(&e, "fsync root"))?;
3164 stats.dir_fsyncs += 1;
3165 stats.io_ops += 1;
3166 (Some(id), StoreState::Recovering, false)
3167 };
3168
3169 let scratch_len = config.layout.block_stride as usize;
3170 let worker_mode = config.worker;
3171 let root_buf = config.root.clone();
3172 let recovery = RecoveryProgress {
3173 done: recovery_done,
3174 failed: state == StoreState::Failed,
3175 ..RecoveryProgress::default()
3176 };
3177 let inner = Inner {
3178 cfg: config,
3179 store_id,
3180 state,
3181 closed: false,
3182 stop_worker: false,
3183 next_job: 1,
3184 next_pin: 1,
3185 last_clock_ns: 0,
3186 index: Index::new(),
3187 unindexed_bytes: 0,
3188 unindexed_objects: 0,
3189 stuck_bytes: 0,
3190 recovery_stuck: false,
3191 purge_walking: false,
3192 purging: None,
3193 reserved: 0,
3194 jobs: BTreeMap::new(),
3195 inflight_store: BTreeMap::new(),
3196 unlinks: VecDeque::new(),
3197 pins: BTreeMap::new(),
3198 restore_ops: 0,
3199 park_ops: 0,
3200 restore_bytes: 0,
3201 park_bytes: 0,
3202 restore_streak: 0,
3203 attached_total: 0,
3204 queue: VecDeque::new(),
3205 stats,
3206 recovery,
3207 purge_pending: false,
3208 purge_evict_quota: false,
3209 alloc_unit,
3210 graveyard: Vec::new(),
3211 };
3212
3213 let shared = Arc::new(Shared {
3214 root: root_buf,
3215 inner: Mutex::new(inner),
3216 cv: Condvar::new(),
3217 tail_scratch: Mutex::new(vec![0u8; scratch_len]),
3218 walk: Mutex::new(Walk::new(WalkStage::Tmp)),
3219 purge_walk: Mutex::new(Walk::new(WalkStage::Shard(0))),
3220 seal_key,
3221 _dir_lock: dir_lock,
3222 });
3223
3224 let handle = if worker_mode == WorkerMode::Thread {
3225 let s2 = Arc::clone(&shared);
3226 Some(std::thread::spawn(move || worker_loop(s2)))
3227 } else {
3228 None
3229 };
3230
3231 Ok(Self {
3232 shared,
3233 worker: Mutex::new(handle),
3234 })
3235 }
3236
3237 fn lock(&self) -> MutexGuard<'_, Inner> {
3238 self.shared.inner.lock().unwrap_or_else(|e| e.into_inner())
3239 }
3240
3241 fn with<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
3242 let (r, garbage) = {
3243 let mut g = self.lock();
3244 let r = f(&mut g);
3245 (r, std::mem::take(&mut g.graveyard))
3246 };
3247 drop(garbage);
3248 r
3249 }
3250
3251 pub fn root(&self) -> &Path {
3252 &self.shared.root
3253 }
3254
3255 pub fn object_path(&self, key: &ChunkKey) -> PathBuf {
3256 object_path_for(&self.shared.root, &key.0 .0)
3257 }
3258
3259 pub fn tmp_dir(&self) -> PathBuf {
3260 self.shared.root.join("tmp")
3261 }
3262
3263 pub fn store_id(&self) -> Option<[u8; 16]> {
3264 self.with(|i| i.store_id)
3265 }
3266
3267 pub fn stats(&self) -> HostFsStats {
3268 self.with(|i| i.stats)
3269 }
3270
3271 pub fn pump(&self) -> bool {
3272 pump_one(&self.shared)
3273 }
3274
3275 pub fn run_until_idle(&self) {
3276 while self.pump() {}
3277 }
3278
3279 pub fn start_purge(&self) {
3280 *self
3281 .shared
3282 .purge_walk
3283 .lock()
3284 .unwrap_or_else(|e| e.into_inner()) = Walk::new(WalkStage::Shard(0));
3285 self.with(|i| {
3286 i.purge_pending = true;
3287 i.purge_walking = i.unindexed_objects > 0;
3288 i.purge_evict_quota = i.used_bytes() > i.cfg.quota_bytes;
3289 });
3290 self.shared.cv.notify_all();
3291 }
3292
3293 pub fn purge_pending(&self) -> bool {
3294 self.with(|i| i.purge_pending)
3295 }
3296
3297 pub fn audit(&self) -> Result<(), String> {
3298 self.with(|i| {
3299 i.index.audit()?;
3300 let expected_res: u64 = i
3301 .jobs
3302 .values()
3303 .filter(|j| !j.crashed)
3304 .map(|j| j.reserved)
3305 .sum();
3306 if i.reserved != expected_res {
3307 return Err(format!(
3308 "reserved_bytes {} != job sum {}",
3309 i.reserved, expected_res
3310 ));
3311 }
3312 Ok(())
3313 })
3314 }
3315}
3316
3317impl Drop for HostFsStore {
3318 fn drop(&mut self) {
3319 {
3320 let mut g = self.lock();
3321 g.stop_worker = true;
3322 }
3323 self.shared.cv.notify_all();
3324 if let Some(h) = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take() {
3325 let _ = h.join();
3326 }
3327 let garbage = {
3328 let mut g = self.lock();
3329 let mut guards = std::mem::take(&mut g.graveyard);
3330 for (_, mut j) in std::mem::take(&mut g.jobs) {
3331 if let Some(s) = j.src.take() {
3332 guards.push(s.into_guard());
3333 }
3334 if let Some(d) = j.dst.take() {
3335 guards.push(d.into_guard());
3336 }
3337 }
3338 guards
3339 };
3340 drop(garbage);
3341 }
3342}
3343
3344impl KvStore for HostFsStore {
3345 fn namespace(&self) -> NamespaceId {
3346 self.with(|i| i.cfg.namespace)
3347 }
3348
3349 fn capacity(&self) -> Capacity {
3350 self.with(|i| i.capacity())
3351 }
3352
3353 fn lookup(&self, keys: &[ChunkKey]) -> Vec<Option<u64>> {
3354 self.with(|i| {
3355 let serving = !matches!(i.state, StoreState::Recovering | StoreState::Failed);
3356 keys.iter()
3357 .map(|k| {
3358 i.index
3359 .get(&k.0 .0)
3360 .filter(|e| serving && !e.is_evicting() && !e.is_foreign())
3361 .map(|e| e.payload_len)
3362 })
3363 .collect()
3364 })
3365 }
3366
3367 fn submit_store(
3368 &self,
3369 header: ChunkHeader,
3370 src: PinnedSource,
3371 inc: Incarnation,
3372 ) -> Result<JobId, PlatformError> {
3373 let mut slot = Some(src);
3374 let res = self.with(|i| i.submit_store(header, &mut slot, inc));
3375 drop(slot);
3376 if res.is_ok() {
3377 self.shared.cv.notify_all();
3378 }
3379 res
3380 }
3381
3382 fn submit_load(
3383 &self,
3384 key: ChunkKey,
3385 expect: &ChunkHeader,
3386 dst: PinnedDest,
3387 inc: Incarnation,
3388 ) -> Result<JobId, PlatformError> {
3389 let mut slot = Some(dst);
3390 let res = self.with(|i| i.submit_load(key, expect, &mut slot, inc));
3391 drop(slot);
3392 if res.is_ok() {
3393 self.shared.cv.notify_all();
3394 }
3395 res
3396 }
3397
3398 fn submit_flush(&self, inc: Incarnation) -> Result<JobId, PlatformError> {
3399 let res = self.with(|i| i.submit_flush(inc));
3400 if res.is_ok() {
3401 self.shared.cv.notify_all();
3402 }
3403 res
3404 }
3405
3406 fn attach_waiter(&self, job: JobId, _inc: Incarnation) -> Result<(), PlatformError> {
3407 self.with(|i| {
3408 let per_job = i.cfg.max_waiters_per_job;
3409 let total = i.cfg.max_waiters_total;
3410 let attached_total = i.attached_total;
3411 let j = match i.jobs.get_mut(&job.0) {
3412 Some(j) if j.kind == Kind::Load && !j.cancelling && !j.crashed => j,
3413 _ => {
3414 return Err(PlatformError::TaskRejected(String::from(
3415 "not an in-flight load",
3416 )))
3417 }
3418 };
3419 if 1 + j.attached >= per_job || attached_total >= total {
3420 i.stats.queue_full_total += 1;
3421 return Err(PlatformError::QueueFull);
3422 }
3423 j.attached += 1;
3424 i.attached_total += 1;
3425 Ok(())
3426 })
3427 }
3428
3429 fn poll(&self, max: usize) -> Vec<Completion> {
3430 self.with(|i| {
3431 let n = max.min(i.queue.len());
3432 i.queue.drain(..n).collect()
3433 })
3434 }
3435
3436 fn cancel(&self, job: JobId) -> CancelOutcome {
3437 let out = self.with(|i| match i.jobs.get_mut(&job.0) {
3438 None => CancelOutcome::TooLate,
3439 Some(j) if j.crashed => CancelOutcome::TooLate,
3440 Some(j) if j.cancelling => CancelOutcome::Cancelled,
3441 Some(j) => {
3442 let cancellable = !matches!(
3443 (j.kind, j.phase),
3444 (Kind::Flush | Kind::Noop, _)
3445 | (Kind::Store, Phase::Syncing | Phase::Publishing)
3446 );
3447 if cancellable {
3448 j.cancelling = true;
3449 CancelOutcome::Cancelled
3450 } else {
3451 CancelOutcome::TooLate
3452 }
3453 }
3454 });
3455 if out == CancelOutcome::Cancelled {
3456 self.shared.cv.notify_all();
3457 }
3458 out
3459 }
3460
3461 fn pin(&self, keys: &[ChunkKey]) -> Result<PinToken, PlatformError> {
3462 self.with(|i| {
3463 if i.state == StoreState::Recovering {
3464 return Err(i.queue_full());
3465 }
3466 if i.state == StoreState::Failed || i.closed {
3467 return Err(PlatformError::DeviceUnavailable);
3468 }
3469 if i.pins.len() as u32 >= i.cfg.max_restore_ops {
3470 return Err(i.queue_full());
3471 }
3472 for k in keys {
3473 if !i
3474 .index
3475 .get(&k.0 .0)
3476 .is_some_and(|e| !e.is_evicting() && !e.is_foreign())
3477 {
3478 return Err(PlatformError::ObjectNotFound(k.0));
3479 }
3480 }
3481 let id = i.next_pin;
3482 i.next_pin += 1;
3483 let list: Vec<[u8; 32]> = keys.iter().map(|k| k.0 .0).collect();
3484 for k in &list {
3485 let ok = i.index.busy_inc(k);
3486 debug_assert!(ok);
3487 }
3488 i.pins.insert(id, list);
3489 Ok(PinToken(id))
3490 })
3491 }
3492
3493 fn unpin(&self, token: PinToken) {
3494 self.with(|i| {
3495 if let Some(list) = i.pins.remove(&token.0) {
3496 for k in list {
3497 i.index.busy_dec(&k);
3498 }
3499 }
3500 });
3501 }
3502
3503 fn delete(&self, keys: &[ChunkKey]) -> u64 {
3504 let marked = self.with(|i| {
3505 if matches!(i.state, StoreState::Recovering | StoreState::Failed) {
3506 return 0;
3507 }
3508 let mut marked = 0;
3509 for k in keys {
3510 let kb = k.0 .0;
3511 if i.index.is_busy(&kb) || i.inflight_store.contains_key(&kb) {
3512 continue;
3513 }
3514 if i.index.mark_evicting(&kb) {
3515 i.unlinks.push_back(Unlink {
3516 key: kb,
3517 evict: false,
3518 });
3519 marked += 1;
3520 }
3521 }
3522 marked
3523 });
3524 if marked > 0 {
3525 self.shared.cv.notify_all();
3526 }
3527 marked
3528 }
3529
3530 fn recover_step(&self, slice_ms: u64) -> RecoveryProgress {
3531 recover_step_on(&self.shared, slice_ms)
3532 }
3533
3534 fn shutdown(&self, intake_deadline_ms: u64) -> DrainReport {
3535 let deadline = Instant::now() + Duration::from_millis(intake_deadline_ms);
3536 let (published_before, cancelled, worker_mode) = self.with(|i| {
3537 i.closed = true;
3538 let published_before = i.stats.published_total;
3539 let mut cancelled = 0;
3540 for j in i.jobs.values_mut() {
3541 if j.crashed {
3542 continue;
3543 }
3544 let cancellable = !matches!(
3545 (j.kind, j.phase),
3546 (Kind::Flush | Kind::Noop, _)
3547 | (Kind::Store, Phase::Syncing | Phase::Publishing)
3548 );
3549 if cancellable {
3550 if !j.cancelling {
3551 j.cancelling = true;
3552 }
3553 cancelled += 1;
3554 }
3555 }
3556 i.reap_cancels();
3557 (published_before, cancelled, i.cfg.worker)
3558 });
3559 self.shared.cv.notify_all();
3560
3561 if worker_mode == WorkerMode::Manual {
3562 while Instant::now() < deadline {
3563 if !self.pump() {
3564 break;
3565 }
3566 }
3567 } else {
3568 let mut g = self.lock();
3569 loop {
3570 g.reap_cancels();
3571 let busy = g.jobs.values().any(|j| !j.crashed) || !g.unlinks.is_empty();
3572 if !busy {
3573 break;
3574 }
3575 let now = Instant::now();
3576 if now >= deadline {
3577 break;
3578 }
3579 let wait = deadline - now;
3580 let (g2, _) = self
3581 .shared
3582 .cv
3583 .wait_timeout(g, wait)
3584 .unwrap_or_else(|e| e.into_inner());
3585 g = g2;
3586 }
3587 let garbage = std::mem::take(&mut g.graveyard);
3588 drop(g);
3589 drop(garbage);
3590 }
3591
3592 self.with(|i| {
3593 i.reap_cancels();
3594 let unfinished: Vec<UnfinishedJob> = i
3595 .jobs
3596 .values()
3597 .filter(|j| !j.crashed)
3598 .map(|j| UnfinishedJob {
3599 job: JobId(j.id),
3600 key: j.key,
3601 bytes: j.bytes,
3602 stage: j.stage,
3603 })
3604 .collect();
3605 i.stats.shutdown_unfinished_jobs = unfinished.len() as u64;
3606 i.stats.shutdown_unfinished_bytes = unfinished.iter().map(|u| u.bytes).sum();
3607 DrainReport {
3608 published: i.stats.published_total - published_before,
3609 cancelled,
3610 unfinished,
3611 }
3612 })
3613 }
3614}
3615
3616#[cfg(test)]
3617mod tests {
3618 use super::*;
3619 use crate::identity::{chunk_chain, ComputeConfig, HiddenAct, KvDtype};
3620 use crate::pin::HolderGuard;
3621
3622 const BS: usize = 8192;
3623
3624 fn test_fields() -> NamespaceFields<'static> {
3625 let compute = ComputeConfig {
3626 num_heads: 32,
3627 hidden_dim: 2048,
3628 intermediate_dim: 8192,
3629 vocab_size: 128_256,
3630 rms_norm_eps: 1e-5,
3631 tie_word_embeddings: true,
3632 hidden_act: HiddenAct::Silu,
3633 arith_id: "ReferenceCpuBackend",
3634 arith_epoch: 1,
3635 };
3636 NamespaceFields {
3637 model_sha256: [0xAB; 32],
3638 model_digest_kind: "sha256-file",
3639 model_id: "llama-3.2-1b-instruct",
3640 num_layers: 2,
3641 num_kv_heads: 4,
3642 head_dim: 64,
3643 block_size: 4,
3644 rope_theta: 500000.0,
3645 rope_scaling: None,
3646 qk_norm: false,
3647 dtype: KvDtype::Bf16,
3648 layout: LayoutStrides {
3649 head_stride: 128,
3650 token_stride: 512,
3651 kv_plane_stride: 2048,
3652 layer_stride: 4096,
3653 block_stride: BS as u64,
3654 element_bytes: 2,
3655 },
3656 backend_format: BackendFormat::HostPagedPoolV1,
3657 chunk_tokens: 8,
3658 sharing_namespace: "default",
3659 compute_config_digest: compute.digest().unwrap(),
3660 }
3661 }
3662
3663 fn make_src(blocks: usize, tail_valid: u32) -> (PinnedSource, Box<[u8]>) {
3664 let mut buf = vec![0x33u8; blocks * BS].into_boxed_slice();
3665 let ptr = buf.as_mut_ptr();
3666 let guard = HolderGuard::detached();
3667 let src = unsafe { PinnedSource::new(ptr, BS, (0..blocks).collect(), tail_valid, guard) };
3668 (src, buf)
3669 }
3670
3671 fn test_key() -> Arc<crate::seal::SealKey> {
3672 Arc::new(crate::seal::SealKey::generate().unwrap())
3673 }
3674
3675 fn temp_root(tag: &str) -> PathBuf {
3676 let nanos = SystemTime::now()
3677 .duration_since(UNIX_EPOCH)
3678 .unwrap()
3679 .as_nanos();
3680 let p = std::env::temp_dir().join(format!(
3681 "aien-kv-hostfs-unit-{tag}-{}-{nanos}",
3682 std::process::id()
3683 ));
3684 // The store refuses a root others can reach (ADR 0003 section 19).
3685 std::os::unix::fs::DirBuilderExt::mode(std::fs::DirBuilder::new().recursive(true), 0o700)
3686 .create(&p)
3687 .unwrap();
3688 p
3689 }
3690
3691 #[test]
3692 fn host_fs_reservation_covers_the_physical_bytes_publication_charges() {
3693 // Codex re-review 2, partial 8: three KV heads give 6144-byte blocks,
3694 // so payload plus header (10240) is not a filesystem-block multiple.
3695 // The reservation taken at submit must not be smaller than what the
3696 // published file is charged (st_blocks).
3697 const BS3: usize = 6144;
3698 let root = temp_root("alloc-round");
3699 let mut f = test_fields();
3700 f.num_kv_heads = 3;
3701 f.layout = LayoutStrides {
3702 head_stride: 128,
3703 token_stride: 384,
3704 kv_plane_stride: 1536,
3705 layer_stride: 3072,
3706 block_stride: BS3 as u64,
3707 element_bytes: 2,
3708 };
3709 let ns = f.namespace_id().unwrap();
3710 let mut cfg = HostFsConfig::from_fields(root.clone(), &f).unwrap();
3711 cfg.seal_key = Some(test_key());
3712 cfg.worker = WorkerMode::Manual;
3713 let s = HostFsStore::open(cfg).unwrap();
3714 while !s.recover_step(50).done {}
3715 let toks: Vec<u32> = (0..4).collect();
3716 let key = chunk_chain(&ns, 8, &toks).unwrap()[0];
3717 let h = f.chunk_header(&ns, key, None, 0, 4, 1).unwrap();
3718 let mut buf = vec![0x33u8; BS3].into_boxed_slice();
3719 let src = unsafe {
3720 PinnedSource::new(buf.as_mut_ptr(), BS3, vec![0], 4, HolderGuard::detached())
3721 };
3722 s.submit_store(h, src, Incarnation::seq(1)).unwrap();
3723 let reserved = s.capacity().reserved_bytes;
3724 s.run_until_idle();
3725 let comps = s.poll(16);
3726 assert!(comps
3727 .iter()
3728 .any(|c| c.terminal == Some(Terminal::Done(JobStage::Durable))));
3729 let used = s.capacity().used_bytes;
3730 assert!(
3731 reserved >= used,
3732 "reserved {reserved} < charged {used} at publication"
3733 );
3734 s.audit().unwrap();
3735 drop(buf);
3736 let _ = std::fs::remove_dir_all(&root);
3737 }
3738
3739 #[test]
3740 fn host_fs_max_objects_includes_starting_job_reservation() {
3741 let root = temp_root("max-obj");
3742 let f = test_fields();
3743 let ns = f.namespace_id().unwrap();
3744 let mut cfg = HostFsConfig::from_fields(root.clone(), &f).unwrap();
3745 cfg.seal_key = Some(test_key());
3746 cfg.max_objects = 2;
3747 cfg.worker = WorkerMode::Manual;
3748 let s = HostFsStore::open(cfg).unwrap();
3749 while !s.recover_step(50).done {}
3750
3751 for n in 1..=3u32 {
3752 let toks: Vec<u32> = (0..8).map(|i| n * 100 + i).collect();
3753 let key = chunk_chain(&ns, 8, &toks).unwrap()[0];
3754 let h = f.chunk_header(&ns, key, None, 0, 8, 1).unwrap();
3755 let (src, _buf) = make_src(2, 4);
3756 s.submit_store(h, src, Incarnation::seq(n as u64)).unwrap();
3757 s.run_until_idle();
3758 let _ = s.poll(16);
3759 }
3760 assert_eq!(s.capacity().objects, 2);
3761 s.audit().unwrap();
3762 let _ = std::fs::remove_dir_all(&root);
3763 }
3764
3765 #[test]
3766 fn host_fs_victims_are_unlinked_after_publish_and_a_failed_unlink_keeps_one() {
3767 let root = temp_root("abort-evict");
3768 let f = test_fields();
3769 let ns = f.namespace_id().unwrap();
3770 let small_phys = HEADER_REGION_LEN as u64 + BS as u64;
3771 let faults = ScriptedFaults::new();
3772 let mut cfg = HostFsConfig::from_fields(root.clone(), &f).unwrap();
3773 cfg.seal_key = Some(test_key());
3774 cfg.quota_bytes = 2 * small_phys;
3775 cfg.worker = WorkerMode::Manual;
3776 cfg.faults = Some(faults.clone());
3777 let s = HostFsStore::open(cfg).unwrap();
3778 while !s.recover_step(50).done {}
3779
3780 // Store two 1-block objects.
3781 let mut small_keys = Vec::new();
3782 for n in 1..=2u32 {
3783 let toks: Vec<u32> = (0..4).map(|i| n * 100 + i).collect();
3784 let key = chunk_chain(&ns, 8, &toks).unwrap()[0];
3785 let h = f.chunk_header(&ns, key, None, 0, 4, 1).unwrap();
3786 let (src, _buf) = make_src(1, 4);
3787 s.submit_store(h, src, Incarnation::seq(n as u64)).unwrap();
3788 s.run_until_idle();
3789 let _ = s.poll(16);
3790 small_keys.push(key);
3791 }
3792
3793 // A 2-block object needs both small ones evicted. The victims are
3794 // unlinked only after it is durable; the first unlink fails, so that
3795 // victim returns to service and stays counted, and the store is Done.
3796 faults.arm(Boundary::Unlink, FaultAction::Fail(EIO));
3797 let toks: Vec<u32> = (0..8).map(|i| 300 + i).collect();
3798 let key3 = chunk_chain(&ns, 8, &toks).unwrap()[0];
3799 let h3 = f.chunk_header(&ns, key3, None, 0, 8, 1).unwrap();
3800 let (src3, _buf3) = make_src(2, 4);
3801 let j3 = s.submit_store(h3, src3, Incarnation::seq(3)).unwrap();
3802 s.run_until_idle();
3803 let comps = s.poll(16);
3804 assert!(comps
3805 .iter()
3806 .any(|c| c.job == j3 && c.terminal == Some(Terminal::Done(JobStage::Durable))));
3807 assert_eq!(s.lookup(&small_keys), vec![Some(BS as u64), None]);
3808 assert_eq!(s.lookup(&[key3]), vec![Some(2 * BS as u64)]);
3809 let cap = s.capacity();
3810 assert_eq!(cap.evicting_bytes, 0);
3811 assert_eq!(
3812 cap.used_bytes,
3813 small_phys + HEADER_REGION_LEN as u64 + 2 * BS as u64
3814 );
3815 s.audit().unwrap();
3816 let _ = std::fs::remove_dir_all(&root);
3817 }
3818
3819 #[test]
3820 fn host_fs_never_dedups_into_cancelling_job_and_checks_segments_and_strides() {
3821 let root = temp_root("dedup-cancel");
3822 let f = test_fields();
3823 let ns = f.namespace_id().unwrap();
3824 let mut cfg = HostFsConfig::from_fields(root.clone(), &f).unwrap();
3825 cfg.seal_key = Some(test_key());
3826 cfg.worker = WorkerMode::Manual;
3827 let s = HostFsStore::open(cfg.clone()).unwrap();
3828 while !s.recover_step(50).done {}
3829
3830 let toks: Vec<u32> = (0..8).collect();
3831 let key = chunk_chain(&ns, 8, &toks).unwrap()[0];
3832 let h = f.chunk_header(&ns, key, None, 0, 8, 1).unwrap();
3833 let (src1, _b1) = make_src(2, 4);
3834 let j1 = s.submit_store(h, src1, Incarnation::seq(1)).unwrap();
3835 assert_eq!(s.cancel(j1), CancelOutcome::Cancelled);
3836 let (src2, _b2) = make_src(2, 4);
3837 let j2 = s.submit_store(h, src2, Incarnation::seq(2)).unwrap();
3838 assert_ne!(j1, j2);
3839 s.run_until_idle();
3840 assert_eq!(s.lookup(&[key]), vec![Some(2 * BS as u64)]);
3841
3842 // Refuse > MAX_SEGMENTS blocks at submit time.
3843 let mut h_many = h;
3844 h_many.payload_len = 121 * BS as u64;
3845 h_many.token_count = 121 * 4;
3846 let (src_many, _bm) = make_src(121, 4);
3847 assert_eq!(
3848 s.submit_store(h_many, src_many, Incarnation::seq(3)),
3849 Err(PlatformError::InvalidLayout)
3850 );
3851
3852 // Refuse zero block_stride and zero element_bytes in config validation.
3853 let mut bad1 = cfg.clone();
3854 bad1.layout.block_stride = 0;
3855 assert!(matches!(
3856 HostFsStore::open(bad1),
3857 Err(PlatformError::InvalidLayout)
3858 ));
3859 let mut bad2 = cfg;
3860 bad2.layout.element_bytes = 0;
3861 assert!(matches!(
3862 HostFsStore::open(bad2),
3863 Err(PlatformError::InvalidLayout)
3864 ));
3865
3866 let _ = std::fs::remove_dir_all(&root);
3867 }
3868}