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 / worker.rs

1654 lines · 59346 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 storage worker (cut C5, ADR 0003 sections 7 and 8).
17//!
18//! Two bounded intake queues (restore and park) and one bounded completion
19//! queue in front of an inner `KvStore`. Caller threads never touch the inner
20//! store on the hot path (`submit_*`, `poll`, `cancel` of queued jobs); a
21//! single background worker thread dispatches by 3:1 credit fairness, advances
22//! the inner store, and reaps completions.
23
24use crate::coalesce::{AttachRefused, CoalesceLimits, CoalesceTable, Detach, Share};
25use crate::identity::{ChunkKey, NamespaceId};
26use crate::pin::{HolderGuard, PinnedDest, PinnedSource};
27use crate::record::{ChunkHeader, HEADER_REGION_LEN, MAX_SEGMENTS};
28use crate::store::{
29 CancelOutcome, Capacity, Completion, DrainReport, Incarnation, JobId, JobStage, KvStore,
30 LandingHolder, PinToken, PublishOutcome, RecoveryProgress, StoreState, Terminal, UnfinishedJob,
31};
32use aien_platform::{ObjectId, PlatformError};
33use std::collections::{BTreeMap, VecDeque};
34use std::panic::{catch_unwind, AssertUnwindSafe};
35use std::string::String;
36use std::sync::atomic::{AtomicBool, Ordering};
37use std::sync::{Arc, Condvar, Mutex, MutexGuard, TryLockError};
38use std::thread;
39use std::time::{Duration, Instant};
40use std::vec::Vec;
41
42const HEADER_REGION: u64 = HEADER_REGION_LEN as u64;
43
44/// A setting that could not be used.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct ConfigError {
47 pub name: String,
48 pub value: String,
49 pub reason: &'static str,
50}
51
52impl std::fmt::Display for ConfigError {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 write!(f, "{}={:?}: {}", self.name, self.value, self.reason)
55 }
56}
57
58impl std::error::Error for ConfigError {}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct WorkerConfig {
62 pub max_restore_ops: u32,
63 pub max_park_ops: u32,
64 pub max_inflight_bytes: u64,
65 pub max_waiters_per_job: u32,
66 pub max_waiters_total: u32,
67 pub dispatch_depth: u32,
68 pub idle_poll: Duration,
69 pub start_paused: bool,
70 pub drain_ms: u64,
71}
72
73impl Default for WorkerConfig {
74 fn default() -> Self {
75 Self {
76 max_restore_ops: 48,
77 max_park_ops: 64,
78 max_inflight_bytes: 256 << 20,
79 max_waiters_per_job: 16,
80 max_waiters_total: 1024,
81 dispatch_depth: 4,
82 idle_poll: Duration::from_micros(500),
83 start_paused: false,
84 drain_ms: 2000,
85 }
86 }
87}
88
89fn parse_pos_u32(
90 get: &impl Fn(&str) -> Option<String>,
91 name: &'static str,
92 default: u32,
93) -> Result<u32, ConfigError> {
94 let Some(raw) = get(name) else {
95 return Ok(default);
96 };
97 let v = raw.parse::<u32>().map_err(|_| ConfigError {
98 name: String::from(name),
99 value: raw.clone(),
100 reason: "must be a positive integer",
101 })?;
102 if v == 0 {
103 return Err(ConfigError {
104 name: String::from(name),
105 value: raw,
106 reason: "must be greater than zero",
107 });
108 }
109 Ok(v)
110}
111
112fn parse_pos_u64(
113 get: &impl Fn(&str) -> Option<String>,
114 name: &'static str,
115 default: u64,
116) -> Result<u64, ConfigError> {
117 let Some(raw) = get(name) else {
118 return Ok(default);
119 };
120 let v = raw.parse::<u64>().map_err(|_| ConfigError {
121 name: String::from(name),
122 value: raw.clone(),
123 reason: "must be a positive integer",
124 })?;
125 if v == 0 {
126 return Err(ConfigError {
127 name: String::from(name),
128 value: raw,
129 reason: "must be greater than zero",
130 });
131 }
132 Ok(v)
133}
134
135fn parse_nonneg_u64(
136 get: &impl Fn(&str) -> Option<String>,
137 name: &'static str,
138 default: u64,
139) -> Result<u64, ConfigError> {
140 let Some(raw) = get(name) else {
141 return Ok(default);
142 };
143 raw.parse::<u64>().map_err(|_| ConfigError {
144 name: String::from(name),
145 value: raw,
146 reason: "must be a non-negative integer",
147 })
148}
149
150impl WorkerConfig {
151 pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
152 let mut c = Self::default();
153 c.max_restore_ops =
154 parse_pos_u32(&get, "AIEN_KV_STORE_MAX_RESTORE_OPS", c.max_restore_ops)?;
155 c.max_park_ops = parse_pos_u32(&get, "AIEN_KV_STORE_MAX_PARK_OPS", c.max_park_ops)?;
156 c.max_waiters_per_job = parse_pos_u32(
157 &get,
158 "AIEN_KV_STORE_MAX_WAITERS_PER_JOB",
159 c.max_waiters_per_job,
160 )?;
161 c.max_inflight_bytes = parse_pos_u64(
162 &get,
163 "AIEN_KV_STORE_MAX_INFLIGHT_BYTES",
164 c.max_inflight_bytes,
165 )?;
166 c.drain_ms = parse_nonneg_u64(&get, "AIEN_KV_STORE_DRAIN_MS", c.drain_ms)?;
167 Ok(c)
168 }
169
170 pub fn from_env() -> Result<Self, ConfigError> {
171 Self::from_lookup(|n| std::env::var(n).ok())
172 }
173}
174
175/// The two intake classes (ADR 7.1). A flush counts as a park (C2 choice).
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub enum Class {
178 Restore,
179 Park,
180}
181
182/// How `submit_load_coalesced` placed a request.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum LoadTicket {
185 Started(JobId),
186 Attached(JobId),
187}
188
189impl LoadTicket {
190 pub fn job(&self) -> JobId {
191 match *self {
192 LoadTicket::Started(j) | LoadTicket::Attached(j) => j,
193 }
194 }
195}
196
197#[derive(Debug, Clone, Default, PartialEq, Eq)]
198pub struct WorkerStats {
199 pub submitted_restore: u64,
200 pub submitted_park: u64,
201 pub queue_full_total: u64,
202 pub dispatched_restore: u64,
203 pub dispatched_park: u64,
204 pub max_restore_run_with_park_waiting: u32,
205 pub coalesced_total: u64,
206 pub attach_refused_total: u64,
207 pub store_dedup_total: u64,
208 pub stale_completions_total: u64,
209 pub terminal_done: u64,
210 pub terminal_failed: u64,
211 pub terminal_cancelled: u64,
212 pub peak_completion_queue: u64,
213 pub completion_overflow_total: u64,
214 pub peak_restore_queue: u64,
215 pub peak_park_queue: u64,
216 pub inner_refusals_total: u64,
217 pub inner_protocol_errors: u64,
218 pub indeterminate_total: u64,
219 pub shutdown_unfinished_jobs: u64,
220 pub shutdown_unfinished_bytes: u64,
221}
222
223#[derive(Clone, Copy, PartialEq, Eq)]
224enum JobKind {
225 Store,
226 Load,
227 Flush,
228}
229
230enum Payload {
231 Store {
232 header: ChunkHeader,
233 src: PinnedSource,
234 },
235 Load {
236 expect: ChunkHeader,
237 dst: PinnedDest,
238 },
239 Flush,
240}
241
242impl Payload {
243 /// Lend the blocks to the inner store: the store gets a view on a lease,
244 /// the worker keeps the caller's guard. `on_return` runs when the store
245 /// drops the lease.
246 fn lend(self, on_return: impl FnOnce() + Send + 'static) -> (Payload, Option<HolderGuard>) {
247 match self {
248 Payload::Store { header, src } => {
249 let (src, real) = src.lend(on_return);
250 (Payload::Store { header, src }, Some(real))
251 }
252 Payload::Load { expect, dst } => {
253 let (dst, real) = dst.lend(on_return);
254 (Payload::Load { expect, dst }, Some(real))
255 }
256 Payload::Flush => (Payload::Flush, None),
257 }
258 }
259
260 fn into_guard(self) -> Option<HolderGuard> {
261 match self {
262 Payload::Store { src, .. } => Some(src.into_guard()),
263 Payload::Load { dst, .. } => Some(dst.into_guard()),
264 Payload::Flush => None,
265 }
266 }
267}
268
269#[derive(Clone, Copy, PartialEq, Eq)]
270enum Status {
271 Queued,
272 Dispatching,
273 Dispatched(JobId),
274}
275
276struct WorkerJob {
277 id: JobId,
278 class: Class,
279 kind: JobKind,
280 inc: Incarnation,
281 key: ChunkKey,
282 bytes: u64,
283 payload_len: u64,
284 reserved: u64,
285 submitted_at: Instant,
286 stage: JobStage,
287 status: Status,
288 cancelling: bool,
289 payload: Option<Payload>,
290 progress_seen: bool,
291 /// Every request riding this job, the opener first. Each gets its own
292 /// completions carrying its own token (ADR 5.3), including waiters that
293 /// withdrew their interest: a terminal is emitted only after the shared
294 /// I/O ended, so "my terminal arrived" always means "nothing more will
295 /// touch the landing holder on my behalf" (ADR 5.5, 7.3).
296 waiters: Vec<Waiter>,
297 /// The caller's own guard while the inner store holds a lease on the
298 /// same blocks (Grok C5 P1-2, P1-3). Loads hand it back with their
299 /// terminals; stores release it at the terminal.
300 landing: Option<HolderGuard>,
301 /// Set when the blocks were lent; becomes true when the inner store drops
302 /// its lease (it can no longer touch the blocks).
303 lease_back: Option<Arc<AtomicBool>>,
304 /// The job lost its link to the inner store (the worker thread panicked,
305 /// or the store answered with an id another live job already holds). It
306 /// ends with this failure only once the store gave the lease back, so a
307 /// caller never reuses blocks the store may still write (Grok C5 P1-3).
308 orphaned: Option<PlatformError>,
309}
310
311impl WorkerJob {
312 /// The inner store may still read or write this job's blocks.
313 fn store_holds_lease(&self) -> bool {
314 self.lease_back
315 .as_ref()
316 .is_some_and(|b| !b.load(Ordering::SeqCst))
317 }
318}
319
320/// One request riding a job.
321#[derive(Clone, Copy)]
322struct Waiter {
323 inc: Incarnation,
324 /// The request cancelled its interest. It still gets its one terminal when
325 /// the job ends; it no longer keeps the shared job alive.
326 detached: bool,
327}
328
329impl Waiter {
330 fn new(inc: Incarnation) -> Self {
331 Self {
332 inc,
333 detached: false,
334 }
335 }
336}
337
338type HandedJob = (JobId, Class, Incarnation, ChunkKey, Payload);
339
340struct State {
341 cfg: WorkerConfig,
342 paused: bool,
343 closed: bool,
344 worker_dropped: bool,
345 panicked: bool,
346 next_job: u64,
347 restore_queue: VecDeque<JobId>,
348 park_queue: VecDeque<JobId>,
349 restore_credits: u32,
350 restore_run_with_park_waiting: u32,
351 restore_ops: u32,
352 park_ops: u32,
353 restore_bytes: u64,
354 park_bytes: u64,
355 reserved_bytes: u64,
356 dispatched_count: u32,
357 jobs: BTreeMap<JobId, WorkerJob>,
358 by_inner: BTreeMap<JobId, JobId>,
359 /// The live store job of each key: at most one, so the inner store can
360 /// never merge two worker jobs into one (Grok C5 P1-1).
361 store_by_key: BTreeMap<[u8; 32], JobId>,
362 coalesce: CoalesceTable,
363 completions: VecDeque<Completion>,
364 dispatch_log: Vec<(JobId, Class)>,
365 /// Jobs taken from the queues (status `Dispatching`) and waiting for the
366 /// worker thread to hand them to the inner store. Filled under the lock.
367 handed: VecDeque<HandedJob>,
368 stats: WorkerStats,
369 published_total: u64,
370 shutdown_cancelled: u64,
371 shutdown_published_before: Option<u64>,
372 inner_shutdown_requested: bool,
373 inner_shutdown_called: bool,
374 graveyard: Vec<HolderGuard>,
375}
376
377impl State {
378 fn new(cfg: WorkerConfig) -> Self {
379 let limits = CoalesceLimits {
380 max_waiters_per_job: cfg.max_waiters_per_job,
381 max_waiters_total: cfg.max_waiters_total,
382 };
383 let paused = cfg.start_paused;
384 Self {
385 cfg,
386 paused,
387 closed: false,
388 worker_dropped: false,
389 panicked: false,
390 next_job: 1,
391 restore_queue: VecDeque::new(),
392 park_queue: VecDeque::new(),
393 restore_credits: 3,
394 restore_run_with_park_waiting: 0,
395 restore_ops: 0,
396 park_ops: 0,
397 restore_bytes: 0,
398 park_bytes: 0,
399 reserved_bytes: 0,
400 dispatched_count: 0,
401 jobs: BTreeMap::new(),
402 by_inner: BTreeMap::new(),
403 store_by_key: BTreeMap::new(),
404 coalesce: CoalesceTable::new(limits),
405 completions: VecDeque::new(),
406 dispatch_log: Vec::new(),
407 handed: VecDeque::new(),
408 stats: WorkerStats::default(),
409 published_total: 0,
410 shutdown_cancelled: 0,
411 shutdown_published_before: None,
412 inner_shutdown_requested: false,
413 inner_shutdown_called: false,
414 graveyard: Vec::new(),
415 }
416 }
417
418 fn completion_capacity(&self) -> usize {
419 3 * (self.cfg.max_restore_ops as usize + self.cfg.max_park_ops as usize)
420 }
421
422 fn park_byte_limit(&self) -> u64 {
423 self.cfg.max_inflight_bytes / 4
424 }
425
426 fn restore_byte_limit(&self) -> u64 {
427 self.cfg.max_inflight_bytes - self.park_byte_limit()
428 }
429
430 fn queue_full(&mut self) -> PlatformError {
431 self.stats.queue_full_total += 1;
432 PlatformError::QueueFull
433 }
434
435 fn check_store_state(
436 &mut self,
437 store_state: StoreState,
438 needs_open: bool,
439 ) -> Result<(), PlatformError> {
440 if self.closed || self.panicked {
441 return Err(PlatformError::DeviceUnavailable);
442 }
443 if store_state == StoreState::Recovering {
444 return Err(self.queue_full());
445 }
446 if store_state == StoreState::Failed || (needs_open && store_state == StoreState::Degraded)
447 {
448 return Err(PlatformError::DeviceUnavailable);
449 }
450 Ok(())
451 }
452
453 /// Completion slots held for waiters beyond each job's opener: one terminal
454 /// per extra load waiter, a progress report and a terminal per extra store
455 /// waiter. Held until the caller polls (ADR 7.1).
456 fn waiter_slots(&self) -> usize {
457 self.jobs
458 .values()
459 .map(|j| {
460 let per = if j.kind == JobKind::Store { 2 } else { 1 };
461 j.waiters.len().saturating_sub(1) * per
462 })
463 .sum()
464 }
465
466 /// Add `inc` as a waiter of `job`. Refused when the waiter bounds or the
467 /// completion capacity (counting this waiter's slots) would be exceeded,
468 /// and when `inc` already rides the job: two completions with one token
469 /// could not be told apart.
470 fn try_attach(&mut self, job: JobId, inc: Incarnation) -> Result<(), PlatformError> {
471 let per = match self.jobs.get(&job) {
472 Some(j) if j.kind != JobKind::Flush && !j.cancelling => {
473 if j.waiters.iter().any(|w| w.inc == inc) {
474 return Err(PlatformError::TaskRejected(String::from(
475 "incarnation already waits on this job",
476 )));
477 }
478 if j.kind == JobKind::Store {
479 2
480 } else {
481 1
482 }
483 }
484 _ => {
485 return Err(PlatformError::TaskRejected(String::from(
486 "not an in-flight load",
487 )))
488 }
489 };
490 if self.completions.len() + 3 * self.jobs.len() + self.waiter_slots() + per
491 > self.completion_capacity()
492 {
493 self.stats.attach_refused_total += 1;
494 return Err(self.queue_full());
495 }
496 match self.coalesce.attach(job) {
497 Ok(_) => {
498 self.jobs
499 .get_mut(&job)
500 .expect("job")
501 .waiters
502 .push(Waiter::new(inc));
503 Ok(())
504 }
505 Err(AttachRefused::JobFull | AttachRefused::TotalFull) => {
506 self.stats.attach_refused_total += 1;
507 Err(self.queue_full())
508 }
509 Err(AttachRefused::NoSuchJob) => Err(PlatformError::TaskRejected(String::from(
510 "not an in-flight load",
511 ))),
512 }
513 }
514
515 fn credit_check(&mut self, class: Class, bytes: u64) -> Result<(), PlatformError> {
516 let (ops, max_ops, used_bytes, limit) = match class {
517 Class::Park => (
518 self.park_ops,
519 self.cfg.max_park_ops,
520 self.park_bytes,
521 self.park_byte_limit(),
522 ),
523 Class::Restore => (
524 self.restore_ops,
525 self.cfg.max_restore_ops,
526 self.restore_bytes,
527 self.restore_byte_limit(),
528 ),
529 };
530 let slots = self.completions.len() + 3 * self.jobs.len() + self.waiter_slots() + 3;
531 if ops >= max_ops || used_bytes + bytes > limit || slots > self.completion_capacity() {
532 return Err(self.queue_full());
533 }
534 Ok(())
535 }
536
537 fn push_completion(&mut self, c: Completion) {
538 self.completions.push_back(c);
539 let len = self.completions.len();
540 if len > self.completion_capacity() {
541 self.stats.completion_overflow_total += 1;
542 }
543 self.stats.peak_completion_queue = self.stats.peak_completion_queue.max(len as u64);
544 }
545
546 fn finish_job(
547 &mut self,
548 mut job: WorkerJob,
549 terminal: Terminal,
550 stage: JobStage,
551 publish: PublishOutcome,
552 elapsed_us: Option<u64>,
553 ) {
554 match job.class {
555 Class::Park => {
556 self.park_ops -= 1;
557 self.park_bytes -= job.bytes;
558 }
559 Class::Restore => {
560 self.restore_ops -= 1;
561 self.restore_bytes -= job.bytes;
562 }
563 }
564 self.reserved_bytes -= job.reserved;
565 job.reserved = 0;
566 if matches!(job.status, Status::Dispatching | Status::Dispatched(_)) {
567 self.dispatched_count -= 1;
568 }
569 if let Status::Dispatched(inner_id) = job.status {
570 if self.by_inner.get(&inner_id) == Some(&job.id) {
571 self.by_inner.remove(&inner_id);
572 }
573 }
574 if job.kind != JobKind::Flush {
575 self.coalesce.close(job.id);
576 }
577 if job.kind == JobKind::Store && self.store_by_key.get(&job.key.0 .0) == Some(&job.id) {
578 self.store_by_key.remove(&job.key.0 .0);
579 }
580 if publish == PublishOutcome::Indeterminate {
581 self.stats.indeterminate_total += 1;
582 }
583 if matches!(stage, JobStage::Published | JobStage::Durable) && job.kind == JobKind::Store {
584 self.published_total += 1;
585 }
586 match &terminal {
587 Terminal::Done(_) => self.stats.terminal_done += 1,
588 Terminal::Failed(_) => self.stats.terminal_failed += 1,
589 Terminal::Cancelled => {
590 self.stats.terminal_cancelled += 1;
591 if self.closed {
592 self.shutdown_cancelled += 1;
593 }
594 }
595 }
596 // The caller's guard: lent to the store (`landing`) or never dispatched
597 // (`payload`). A completed load hands it back with every waiter's
598 // terminal, so the landing blocks stay alive until the caller has
599 // adopted them and dropped its completion (Grok C5 P1-2). Any other
600 // terminal releases it now: there is nothing to adopt.
601 let guard = job
602 .landing
603 .take()
604 .or_else(|| job.payload.take().and_then(Payload::into_guard));
605 let done = matches!(terminal, Terminal::Done(_));
606 let holder = match (job.kind, guard) {
607 (JobKind::Load, Some(g)) if done => Some(LandingHolder::new(g)),
608 (_, Some(g)) => {
609 self.graveyard.push(g);
610 None
611 }
612 (_, None) => None,
613 };
614 let elapsed = elapsed_us.unwrap_or_else(|| job.submitted_at.elapsed().as_micros() as u64);
615 // One terminal per waiter, each carrying that waiter's own token. The
616 // job's I/O has ended here (inner terminal, or never dispatched).
617 let waiters = if job.waiters.is_empty() {
618 alloc::vec![Waiter::new(job.inc)]
619 } else {
620 core::mem::take(&mut job.waiters)
621 };
622 for w in waiters {
623 self.push_completion(Completion {
624 job: job.id,
625 incarnation: w.inc,
626 key: job.key,
627 stage,
628 terminal: Some(terminal.clone()),
629 publish,
630 bytes: job.payload_len,
631 elapsed_us: elapsed,
632 holder: holder.clone(),
633 });
634 }
635 }
636
637 /// End every orphaned job whose lease the store has given back.
638 fn reap_orphans(&mut self) {
639 let ids: Vec<JobId> = self
640 .jobs
641 .values()
642 .filter(|j| j.orphaned.is_some() && !j.store_holds_lease())
643 .map(|j| j.id)
644 .collect();
645 for id in ids {
646 let mut job = self.jobs.remove(&id).expect("orphan");
647 let err = job.orphaned.take().expect("orphan error");
648 let stage = job.stage;
649 self.finish_job(
650 job,
651 Terminal::Failed(err),
652 stage,
653 PublishOutcome::NotApplicable,
654 None,
655 );
656 }
657 }
658
659 /// Shutdown and drop: cancel every job the store has not been given yet
660 /// (queued, or handed over but not yet submitted) and mark jobs that are
661 /// inside a submit call right now, so the worker forwards the cancel as
662 /// soon as the store has them (Grok C5 P2-4). Returns the handed payloads
663 /// so their leases drop outside the lock, and the dispatched jobs to
664 /// cancel in the store.
665 fn cancel_unstarted(&mut self) -> (Vec<HandedJob>, Vec<(JobId, JobId)>) {
666 let mut ids = Vec::new();
667 ids.extend(self.restore_queue.drain(..));
668 ids.extend(self.park_queue.drain(..));
669 let handed: Vec<HandedJob> = self.handed.drain(..).collect();
670 ids.extend(handed.iter().map(|h| h.0));
671 for id in ids {
672 if let Some(job) = self.jobs.remove(&id) {
673 let stage = job.stage;
674 self.finish_job(
675 job,
676 Terminal::Cancelled,
677 stage,
678 PublishOutcome::NotApplicable,
679 None,
680 );
681 }
682 }
683 let mut disp = Vec::new();
684 for j in self.jobs.values_mut() {
685 let cancellable = match j.kind {
686 JobKind::Flush => false,
687 JobKind::Load => true,
688 JobKind::Store => j.stage < JobStage::Completed,
689 };
690 if !cancellable || j.cancelling || j.orphaned.is_some() {
691 continue;
692 }
693 match j.status {
694 Status::Dispatching => j.cancelling = true,
695 Status::Dispatched(inner_id) => {
696 j.cancelling = true;
697 disp.push((j.id, inner_id));
698 }
699 Status::Queued => {}
700 }
701 }
702 (handed, disp)
703 }
704
705 /// Move queued jobs into the hand-over slot, as many as the dispatch depth
706 /// allows. Runs under the lock; never touches the inner store.
707 fn hand_over(&mut self) {
708 while let Some(h) = self.pop_next_to_dispatch() {
709 self.handed.push_back(h);
710 }
711 }
712
713 fn pop_next_to_dispatch(&mut self) -> Option<HandedJob> {
714 if self.paused || self.closed || self.panicked {
715 return None;
716 }
717 if self.dispatched_count >= self.cfg.dispatch_depth.max(1) {
718 return None;
719 }
720 loop {
721 let has_r = !self.restore_queue.is_empty();
722 let has_p = !self.park_queue.is_empty();
723 let class = match (has_r, has_p) {
724 (false, false) => return None,
725 (true, false) => Class::Restore,
726 (false, true) => {
727 self.restore_credits = 3;
728 self.restore_run_with_park_waiting = 0;
729 Class::Park
730 }
731 (true, true) => {
732 if self.restore_credits > 0 {
733 self.restore_credits -= 1;
734 self.restore_run_with_park_waiting += 1;
735 self.stats.max_restore_run_with_park_waiting = self
736 .stats
737 .max_restore_run_with_park_waiting
738 .max(self.restore_run_with_park_waiting);
739 Class::Restore
740 } else {
741 self.restore_credits = 3;
742 self.restore_run_with_park_waiting = 0;
743 Class::Park
744 }
745 }
746 };
747 let id = match class {
748 Class::Restore => self.restore_queue.pop_front()?,
749 Class::Park => self.park_queue.pop_front()?,
750 };
751 let Some(job) = self.jobs.get_mut(&id) else {
752 continue;
753 };
754 // The store gets a lease on the blocks; the worker keeps the
755 // caller's guard, so the store dropping the view (at any time,
756 // even before its terminal is polled) never frees them.
757 let back = Arc::new(AtomicBool::new(false));
758 let flag = back.clone();
759 let (payload, real) = job
760 .payload
761 .take()
762 .expect("queued job payload")
763 .lend(move || flag.store(true, Ordering::SeqCst));
764 if real.is_some() {
765 job.landing = real;
766 job.lease_back = Some(back);
767 }
768 job.status = Status::Dispatching;
769 self.dispatched_count += 1;
770 match class {
771 Class::Restore => self.stats.dispatched_restore += 1,
772 Class::Park => self.stats.dispatched_park += 1,
773 }
774 self.dispatch_log.push((id, class));
775 return Some((id, class, job.inc, job.key, payload));
776 }
777 }
778}
779
780struct Shared {
781 state: Mutex<State>,
782 cv: Condvar,
783}
784
785impl Shared {
786 fn lock(&self) -> MutexGuard<'_, State> {
787 self.state.lock().unwrap_or_else(|e| e.into_inner())
788 }
789
790 fn with<R>(&self, f: impl FnOnce(&mut State) -> R) -> R {
791 let (r, garbage) = {
792 let mut g = self.lock();
793 let r = f(&mut g);
794 (r, std::mem::take(&mut g.graveyard))
795 };
796 drop(garbage);
797 r
798 }
799}
800
801pub struct StorageWorker {
802 inner: Arc<dyn KvStore>,
803 shared: Arc<Shared>,
804}
805
806impl Drop for StorageWorker {
807 fn drop(&mut self) {
808 let (handed, to_cancel) = self.shared.with(|s| {
809 s.worker_dropped = true;
810 s.closed = true;
811 s.inner_shutdown_requested = true;
812 let r = s.cancel_unstarted();
813 self.shared.cv.notify_all();
814 r
815 });
816 drop(handed);
817 self.forward_cancels(to_cancel);
818 }
819}
820
821fn validate_store_header(
822 ns: &NamespaceId,
823 header: &ChunkHeader,
824 src: &PinnedSource,
825) -> Result<(), PlatformError> {
826 if header.namespace_id != *ns
827 || header.payload_len == 0
828 || src.total_bytes() != Some(header.payload_len)
829 || header.block_size == 0
830 || src.block_count() == 0
831 || src.block_count() > MAX_SEGMENTS
832 {
833 return Err(PlatformError::InvalidLayout);
834 }
835 let full = (src.block_count() as u64 - 1) * header.block_size as u64;
836 let tail = (header.token_count as u64).checked_sub(full);
837 match tail {
838 Some(t)
839 if t >= 1 && t <= header.block_size as u64 && t == src.tail_valid_tokens() as u64 =>
840 {
841 Ok(())
842 }
843 _ => Err(PlatformError::InvalidLayout),
844 }
845}
846
847fn validate_load_dest(
848 key: ChunkKey,
849 payload_len: Option<u64>,
850 expect: &ChunkHeader,
851 dst: &PinnedDest,
852) -> Result<u64, PlatformError> {
853 let len = payload_len.ok_or(PlatformError::ObjectNotFound(key.0))?;
854 if expect.chunk_key != key
855 || expect.payload_len != len
856 || dst.total_bytes() != Some(len)
857 || dst.block_bytes() == 0
858 {
859 return Err(PlatformError::InvalidLayout);
860 }
861 Ok(len)
862}
863
864fn worker_loop(
865 inner: Arc<dyn KvStore>,
866 shared: Arc<Shared>,
867 mut drive: impl FnMut() + Send + 'static,
868) {
869 loop {
870 let step = catch_unwind(AssertUnwindSafe(|| {
871 // 1. Dispatch up to depth.
872 while let Some((w_id, _class, inc, key, payload)) = shared.with(|s| {
873 s.hand_over();
874 s.handed.pop_front()
875 }) {
876 let res = match payload {
877 Payload::Store { header, src } => inner.submit_store(header, src, inc),
878 Payload::Load { expect, dst } => inner.submit_load(key, &expect, dst, inc),
879 Payload::Flush => inner.submit_flush(inc),
880 };
881 let mut cancel_inner = None;
882 shared.with(|s| match res {
883 Ok(inner_id) => {
884 let taken = s.by_inner.get(&inner_id).is_some_and(|o| *o != w_id);
885 if taken {
886 s.stats.inner_protocol_errors += 1;
887 }
888 let Some(job) = s.jobs.get_mut(&w_id) else {
889 return;
890 };
891 job.status = Status::Dispatched(inner_id);
892 if taken {
893 // The store merged this job into another live
894 // one: its completions belong to that job. This
895 // one fails once the store drops its lease.
896 job.orphaned = Some(PlatformError::HardwareFault(String::from(
897 "store merged two jobs",
898 )));
899 return;
900 }
901 s.by_inner.insert(inner_id, w_id);
902 if job.cancelling {
903 cancel_inner = Some((w_id, inner_id));
904 }
905 }
906 Err(e) => {
907 s.stats.inner_refusals_total += 1;
908 if let Some(job) = s.jobs.remove(&w_id) {
909 let stage = job.stage;
910 s.finish_job(
911 job,
912 Terminal::Failed(e),
913 stage,
914 PublishOutcome::NotApplicable,
915 None,
916 );
917 }
918 shared.cv.notify_all();
919 }
920 });
921 if let Some((w_id, inner_id)) = cancel_inner {
922 if inner.cancel(inner_id) == CancelOutcome::TooLate {
923 shared.with(|s| {
924 if let Some(j) = s.jobs.get_mut(&w_id) {
925 j.cancelling = false;
926 }
927 });
928 }
929 }
930 }
931
932 // 2. Call inner.shutdown(0) on the worker thread once requested.
933 let call_inner_shutdown = shared.with(|s| {
934 if s.inner_shutdown_requested && !s.inner_shutdown_called {
935 s.inner_shutdown_called = true;
936 true
937 } else {
938 false
939 }
940 });
941 if call_inner_shutdown {
942 let _ = inner.shutdown(0);
943 }
944
945 // 3. Drive the inner store and reap completions.
946 // Drive only when something can progress. A paused, idle worker still polls
947 // the store (cheap, and it does not advance the store's clock or start
948 // background work), so a stalled store is felt by the worker thread
949 // alone and never by callers.
950 let should_drive = shared
951 .with(|s| !s.paused || s.dispatched_count > 0 || s.closed || s.worker_dropped);
952 if should_drive {
953 drive();
954 }
955 // Reap completions.
956 {
957 let comps = inner.poll(64);
958 if !comps.is_empty() {
959 shared.with(|s| {
960 for c in comps {
961 let Some(&w_id) = s.by_inner.get(&c.job) else {
962 s.stats.stale_completions_total += 1;
963 continue;
964 };
965 let Some(job) = s.jobs.get(&w_id) else {
966 s.stats.stale_completions_total += 1;
967 continue;
968 };
969 if job.inc != c.incarnation {
970 s.stats.stale_completions_total += 1;
971 continue;
972 }
973 match &c.terminal {
974 None => {
975 let job = s.jobs.get_mut(&w_id).expect("job");
976 if job.progress_seen || c.stage <= job.stage {
977 s.stats.stale_completions_total += 1;
978 continue;
979 }
980 job.progress_seen = true;
981 job.stage = c.stage;
982 if c.stage >= JobStage::Completed && job.kind == JobKind::Store
983 {
984 s.reserved_bytes -= job.reserved;
985 job.reserved = 0;
986 }
987 let waiters = job.waiters.clone();
988 let (key, c_stage) = (job.key, c.stage);
989 for w in waiters {
990 s.push_completion(Completion {
991 job: w_id,
992 incarnation: w.inc,
993 key,
994 stage: c_stage,
995 terminal: None,
996 publish: c.publish,
997 bytes: c.bytes,
998 elapsed_us: c.elapsed_us,
999 holder: None,
1000 });
1001 }
1002 }
1003 Some(term) => {
1004 let job = s.jobs.remove(&w_id).expect("job");
1005 s.finish_job(
1006 job,
1007 term.clone(),
1008 c.stage,
1009 c.publish,
1010 Some(c.elapsed_us),
1011 );
1012 }
1013 }
1014 }
1015 shared.cv.notify_all();
1016 });
1017 }
1018 }
1019 if call_inner_shutdown {
1020 shared.with(|_| {
1021 shared.cv.notify_all();
1022 });
1023 }
1024 }));
1025
1026 if step.is_err() {
1027 // Jobs the store never got: their leases drop here, outside the lock.
1028 let handed: Vec<HandedJob> = shared.with(|s| {
1029 s.panicked = true;
1030 s.closed = true;
1031 s.restore_queue.clear();
1032 s.park_queue.clear();
1033 s.handed.drain(..).collect()
1034 });
1035 drop(handed);
1036 // A job whose blocks the store still holds stays unfinished (its
1037 // guard kept) until the store lets go; `poll` and `shutdown` reap
1038 // it then (Grok C5 P1-3). The rest fail now, once.
1039 shared.with(|s| {
1040 for j in s.jobs.values_mut() {
1041 j.orphaned = Some(PlatformError::HardwareFault(String::from(
1042 "storage worker panicked",
1043 )));
1044 }
1045 s.reap_orphans();
1046 shared.cv.notify_all();
1047 });
1048 return;
1049 }
1050
1051 // Exit once dropped and all dispatched jobs have finished.
1052 let (done, idle_wait) = shared.with(|s| {
1053 s.reap_orphans();
1054 if s.worker_dropped && s.dispatched_count == 0 {
1055 return (true, None);
1056 }
1057 let can_dispatch = !s.paused
1058 && !s.closed
1059 && s.dispatched_count < s.cfg.dispatch_depth.max(1)
1060 && (!s.restore_queue.is_empty() || !s.park_queue.is_empty());
1061 if can_dispatch || s.dispatched_count > 0 {
1062 (false, Some(s.cfg.idle_poll))
1063 } else {
1064 (false, Some(s.cfg.idle_poll.max(Duration::from_micros(200))))
1065 }
1066 });
1067 if done {
1068 return;
1069 }
1070 if let Some(dur) = idle_wait {
1071 if dur.is_zero() {
1072 thread::yield_now();
1073 } else {
1074 let g = shared.lock();
1075 if !g.worker_dropped
1076 && (!g.inner_shutdown_requested || g.inner_shutdown_called)
1077 && (g.paused || (g.restore_queue.is_empty() && g.park_queue.is_empty()))
1078 && g.dispatched_count == 0
1079 {
1080 let _ = shared.cv.wait_timeout(g, dur);
1081 }
1082 }
1083 }
1084 }
1085}
1086
1087impl StorageWorker {
1088 pub fn spawn(
1089 inner: Arc<dyn KvStore>,
1090 config: WorkerConfig,
1091 drive: impl FnMut() + Send + 'static,
1092 ) -> Result<StorageWorker, PlatformError> {
1093 let shared = Arc::new(Shared {
1094 state: Mutex::new(State::new(config)),
1095 cv: Condvar::new(),
1096 });
1097 let inner_w = inner.clone();
1098 let shared_w = shared.clone();
1099 thread::Builder::new()
1100 .name(String::from("aien-kv-worker"))
1101 .spawn(move || worker_loop(inner_w, shared_w, drive))
1102 .map_err(|_| PlatformError::DeviceUnavailable)?;
1103 Ok(StorageWorker { inner, shared })
1104 }
1105
1106 pub fn pause_dispatch(&self) {
1107 self.shared.with(|s| {
1108 s.paused = true;
1109 });
1110 }
1111
1112 pub fn resume_dispatch(&self) {
1113 self.shared.with(|s| {
1114 s.paused = false;
1115 s.hand_over();
1116 self.shared.cv.notify_all();
1117 });
1118 }
1119
1120 pub fn submit_load_coalesced(
1121 &self,
1122 key: ChunkKey,
1123 expect: &ChunkHeader,
1124 make_dst: impl FnOnce() -> PinnedDest,
1125 inc: Incarnation,
1126 ) -> Result<LoadTicket, PlatformError> {
1127 let cap = self.inner.capacity();
1128 // Fast path: attach to an in-flight load if one exists.
1129 let attached = self
1130 .shared
1131 .with(|s| -> Result<Option<LoadTicket>, PlatformError> {
1132 s.check_store_state(cap.state, false)?;
1133 if let Some(job) = s.coalesce.find(Share::Load, &key) {
1134 s.try_attach(job, inc)?;
1135 s.stats.coalesced_total += 1;
1136 return Ok(Some(LoadTicket::Attached(job)));
1137 }
1138 Ok(None)
1139 })?;
1140 if let Some(t) = attached {
1141 return Ok(t);
1142 }
1143
1144 let found = self.inner.lookup(&[key]);
1145 let payload_len = found.into_iter().next().flatten();
1146 let mut dst_slot = Some(make_dst());
1147 let res = self.shared.with(|s| {
1148 s.check_store_state(cap.state, false)?;
1149 if let Some(job) = s.coalesce.find(Share::Load, &key) {
1150 s.try_attach(job, inc)?;
1151 s.stats.coalesced_total += 1;
1152 return Ok(LoadTicket::Attached(job));
1153 }
1154 let dst = dst_slot.as_ref().ok_or(PlatformError::InvalidLayout)?;
1155 let len = validate_load_dest(key, payload_len, expect, dst)?;
1156 let bytes = len + HEADER_REGION;
1157 s.credit_check(Class::Restore, bytes)?;
1158 let id = JobId(s.next_job);
1159 s.next_job += 1;
1160 s.restore_ops += 1;
1161 s.restore_bytes += bytes;
1162 s.stats.submitted_restore += 1;
1163 s.restore_queue.push_back(id);
1164 s.stats.peak_restore_queue =
1165 s.stats.peak_restore_queue.max(s.restore_queue.len() as u64);
1166 s.coalesce.open(Share::Load, &key, id);
1167 let dst = dst_slot.take().expect("dst");
1168 s.jobs.insert(
1169 id,
1170 WorkerJob {
1171 id,
1172 class: Class::Restore,
1173 kind: JobKind::Load,
1174 inc,
1175 key,
1176 bytes,
1177 payload_len: len,
1178 reserved: 0,
1179 submitted_at: Instant::now(),
1180 stage: JobStage::Submitted,
1181 status: Status::Queued,
1182 cancelling: false,
1183 payload: Some(Payload::Load {
1184 expect: *expect,
1185 dst,
1186 }),
1187 progress_seen: false,
1188 waiters: alloc::vec![Waiter::new(inc)],
1189 landing: None,
1190 lease_back: None,
1191 orphaned: None,
1192 },
1193 );
1194 self.shared.cv.notify_all();
1195 Ok(LoadTicket::Started(id))
1196 });
1197 drop(dst_slot);
1198 res
1199 }
1200
1201 pub fn load_in_flight(&self, key: &ChunkKey) -> Option<JobId> {
1202 self.shared.with(|s| s.coalesce.find(Share::Load, key))
1203 }
1204
1205 pub fn stats(&self) -> WorkerStats {
1206 self.shared.with(|s| s.stats.clone())
1207 }
1208
1209 pub fn dispatch_order(&self) -> Vec<(JobId, Class)> {
1210 self.shared.with(|s| s.dispatch_log.clone())
1211 }
1212
1213 pub fn inner_job(&self, job: JobId) -> Option<JobId> {
1214 self.shared.with(|s| match s.jobs.get(&job)?.status {
1215 Status::Dispatched(inner_id) => Some(inner_id),
1216 _ => None,
1217 })
1218 }
1219
1220 pub fn state_lock_is_free(&self) -> bool {
1221 match self.shared.state.try_lock() {
1222 Ok(_) => true,
1223 Err(TryLockError::Poisoned(_)) => true,
1224 Err(TryLockError::WouldBlock) => false,
1225 }
1226 }
1227}
1228
1229impl KvStore for StorageWorker {
1230 fn namespace(&self) -> NamespaceId {
1231 self.inner.namespace()
1232 }
1233
1234 fn capacity(&self) -> Capacity {
1235 let mut cap = self.inner.capacity();
1236 self.shared.with(|s| {
1237 if s.panicked {
1238 cap.state = StoreState::Failed;
1239 }
1240 cap.reserved_bytes = s.reserved_bytes;
1241 cap.restore_ops = s.restore_ops;
1242 cap.max_restore_ops = s.cfg.max_restore_ops;
1243 cap.park_ops = s.park_ops;
1244 cap.max_park_ops = s.cfg.max_park_ops;
1245 cap.inflight_bytes = s.restore_bytes + s.park_bytes;
1246 cap.max_inflight_bytes = s.cfg.max_inflight_bytes;
1247 cap.max_waiters_per_job = s.cfg.max_waiters_per_job;
1248 });
1249 cap
1250 }
1251
1252 fn lookup(&self, keys: &[ChunkKey]) -> Vec<Option<u64>> {
1253 self.inner.lookup(keys)
1254 }
1255
1256 fn submit_store(
1257 &self,
1258 header: ChunkHeader,
1259 src: PinnedSource,
1260 inc: Incarnation,
1261 ) -> Result<JobId, PlatformError> {
1262 let ns = self.inner.namespace();
1263 let cap = self.inner.capacity();
1264 let mut src_slot = Some(src);
1265 let res = self.shared.with(|s| {
1266 s.check_store_state(cap.state, true)?;
1267 let src_ref = src_slot.as_ref().ok_or(PlatformError::InvalidLayout)?;
1268 validate_store_header(&ns, &header, src_ref)?;
1269 let key = header.chunk_key;
1270 // At most one live store job per key (Grok C5 P1-1): the inner
1271 // store dedups a second store of a key into the first, so a second
1272 // worker job would lose its completions to the first and leak its
1273 // park slot. A request joins the live job or is told to retry.
1274 if let Some(&existing) = s.store_by_key.get(&key.0 .0) {
1275 let job_ok = s.jobs.get(&existing).is_some_and(|j| !j.cancelling);
1276 let already = s
1277 .jobs
1278 .get(&existing)
1279 .is_some_and(|j| j.waiters.iter().any(|w| w.inc == inc && !w.detached));
1280 if job_ok && already {
1281 // The same request asked twice: one ride, one terminal.
1282 s.stats.store_dedup_total += 1;
1283 return Ok(existing);
1284 }
1285 if job_ok && s.coalesce.find(Share::Store, &key) == Some(existing) {
1286 match s.try_attach(existing, inc) {
1287 Ok(()) => {
1288 s.stats.store_dedup_total += 1;
1289 return Ok(existing);
1290 }
1291 Err(PlatformError::QueueFull) => return Err(PlatformError::QueueFull),
1292 Err(_) => {}
1293 }
1294 }
1295 return Err(s.queue_full());
1296 }
1297 let bytes = header.payload_len + HEADER_REGION;
1298 s.credit_check(Class::Park, bytes)?;
1299 let id = JobId(s.next_job);
1300 s.next_job += 1;
1301 s.park_ops += 1;
1302 s.park_bytes += bytes;
1303 s.reserved_bytes += bytes;
1304 s.stats.submitted_park += 1;
1305 s.park_queue.push_back(id);
1306 s.stats.peak_park_queue = s.stats.peak_park_queue.max(s.park_queue.len() as u64);
1307 s.coalesce.open(Share::Store, &key, id);
1308 s.store_by_key.insert(key.0 .0, id);
1309 let src = src_slot.take().expect("src");
1310 s.jobs.insert(
1311 id,
1312 WorkerJob {
1313 id,
1314 class: Class::Park,
1315 kind: JobKind::Store,
1316 inc,
1317 key,
1318 bytes,
1319 payload_len: header.payload_len,
1320 reserved: bytes,
1321 submitted_at: Instant::now(),
1322 stage: JobStage::Submitted,
1323 status: Status::Queued,
1324 cancelling: false,
1325 payload: Some(Payload::Store { header, src }),
1326 progress_seen: false,
1327 waiters: alloc::vec![Waiter::new(inc)],
1328 landing: None,
1329 lease_back: None,
1330 orphaned: None,
1331 },
1332 );
1333 self.shared.cv.notify_all();
1334 Ok(id)
1335 });
1336 drop(src_slot);
1337 res
1338 }
1339
1340 fn submit_load(
1341 &self,
1342 key: ChunkKey,
1343 expect: &ChunkHeader,
1344 dst: PinnedDest,
1345 inc: Incarnation,
1346 ) -> Result<JobId, PlatformError> {
1347 let cap = self.inner.capacity();
1348 let found = self.inner.lookup(&[key]);
1349 let payload_len = found.into_iter().next().flatten();
1350 let mut dst_slot = Some(dst);
1351 let res = self.shared.with(|s| {
1352 s.check_store_state(cap.state, false)?;
1353 let dst_ref = dst_slot.as_ref().ok_or(PlatformError::InvalidLayout)?;
1354 let len = validate_load_dest(key, payload_len, expect, dst_ref)?;
1355 let bytes = len + HEADER_REGION;
1356 s.credit_check(Class::Restore, bytes)?;
1357 let id = JobId(s.next_job);
1358 s.next_job += 1;
1359 s.restore_ops += 1;
1360 s.restore_bytes += bytes;
1361 s.stats.submitted_restore += 1;
1362 s.restore_queue.push_back(id);
1363 s.stats.peak_restore_queue =
1364 s.stats.peak_restore_queue.max(s.restore_queue.len() as u64);
1365 s.coalesce.open(Share::Load, &key, id);
1366 let dst = dst_slot.take().expect("dst");
1367 s.jobs.insert(
1368 id,
1369 WorkerJob {
1370 id,
1371 class: Class::Restore,
1372 kind: JobKind::Load,
1373 inc,
1374 key,
1375 bytes,
1376 payload_len: len,
1377 reserved: 0,
1378 submitted_at: Instant::now(),
1379 stage: JobStage::Submitted,
1380 status: Status::Queued,
1381 cancelling: false,
1382 payload: Some(Payload::Load {
1383 expect: *expect,
1384 dst,
1385 }),
1386 progress_seen: false,
1387 waiters: alloc::vec![Waiter::new(inc)],
1388 landing: None,
1389 lease_back: None,
1390 orphaned: None,
1391 },
1392 );
1393 self.shared.cv.notify_all();
1394 Ok(id)
1395 });
1396 drop(dst_slot);
1397 res
1398 }
1399
1400 fn submit_flush(&self, inc: Incarnation) -> Result<JobId, PlatformError> {
1401 let cap = self.inner.capacity();
1402 self.shared.with(|s| {
1403 s.check_store_state(cap.state, false)?;
1404 s.credit_check(Class::Park, 0)?;
1405 let id = JobId(s.next_job);
1406 s.next_job += 1;
1407 s.park_ops += 1;
1408 s.stats.submitted_park += 1;
1409 s.park_queue.push_back(id);
1410 s.stats.peak_park_queue = s.stats.peak_park_queue.max(s.park_queue.len() as u64);
1411 s.jobs.insert(
1412 id,
1413 WorkerJob {
1414 id,
1415 class: Class::Park,
1416 kind: JobKind::Flush,
1417 inc,
1418 key: ChunkKey(ObjectId([0; 32])),
1419 bytes: 0,
1420 payload_len: 0,
1421 reserved: 0,
1422 submitted_at: Instant::now(),
1423 stage: JobStage::Submitted,
1424 status: Status::Queued,
1425 cancelling: false,
1426 payload: Some(Payload::Flush),
1427 progress_seen: false,
1428 waiters: alloc::vec![Waiter::new(inc)],
1429 landing: None,
1430 lease_back: None,
1431 orphaned: None,
1432 },
1433 );
1434 self.shared.cv.notify_all();
1435 Ok(id)
1436 })
1437 }
1438
1439 fn attach_waiter(&self, job: JobId, inc: Incarnation) -> Result<(), PlatformError> {
1440 self.shared.with(|s| {
1441 let is_load = s
1442 .jobs
1443 .get(&job)
1444 .is_some_and(|j| j.kind == JobKind::Load && !j.cancelling);
1445 if !is_load {
1446 return Err(PlatformError::TaskRejected(String::from(
1447 "not an in-flight load",
1448 )));
1449 }
1450 s.try_attach(job, inc)
1451 })
1452 }
1453
1454 fn poll(&self, max: usize) -> Vec<Completion> {
1455 self.shared.with(|s| {
1456 s.reap_orphans();
1457 let n = max.min(s.completions.len());
1458 s.completions.drain(..n).collect()
1459 })
1460 }
1461
1462 /// Cancel on behalf of the request that opened the job (ADR 5.5: cancel
1463 /// own waiter only). A request that attached later cancels with
1464 /// [`StorageWorker::cancel_waiter`] and its own token; repeating a cancel
1465 /// never removes someone else's interest.
1466 fn cancel(&self, job: JobId) -> CancelOutcome {
1467 let Some(opener) = self.shared.with(|s| s.jobs.get(&job).map(|j| j.inc)) else {
1468 return CancelOutcome::TooLate;
1469 };
1470 self.cancel_waiter(job, opener)
1471 }
1472
1473 fn pin(&self, keys: &[ChunkKey]) -> Result<PinToken, PlatformError> {
1474 self.inner.pin(keys)
1475 }
1476
1477 fn unpin(&self, token: PinToken) {
1478 self.inner.unpin(token);
1479 }
1480
1481 fn delete(&self, keys: &[ChunkKey]) -> u64 {
1482 let filtered: Vec<ChunkKey> = self.shared.with(|s| {
1483 keys.iter()
1484 .copied()
1485 .filter(|k| !s.coalesce.has(Share::Load, k) && !s.coalesce.has(Share::Store, k))
1486 .collect()
1487 });
1488 if filtered.is_empty() {
1489 return 0;
1490 }
1491 self.inner.delete(&filtered)
1492 }
1493
1494 fn recover_step(&self, slice_ms: u64) -> RecoveryProgress {
1495 self.inner.recover_step(slice_ms)
1496 }
1497
1498 fn shutdown(&self, intake_deadline_ms: u64) -> DrainReport {
1499 self.shutdown_impl(intake_deadline_ms)
1500 }
1501}
1502
1503impl StorageWorker {
1504 /// Withdraw the interest of the request named `inc` in `job`.
1505 ///
1506 /// * Other requests still want the job: `TooLate`, the job goes on.
1507 /// * `inc` was the last interested request: the job itself is cancelled
1508 /// (`Cancelled` if it never reached the store or the store accepted the
1509 /// cancel, else `TooLate`).
1510 /// * `inc` does not ride the job, or already withdrew: `TooLate`, nothing
1511 /// changes.
1512 ///
1513 /// Whatever the answer, every request that rode the job (including `inc`)
1514 /// receives exactly one terminal completion, and only after the job's I/O
1515 /// ended; a request releases what it owns only after polling it.
1516 pub fn cancel_waiter(&self, job: JobId, inc: Incarnation) -> CancelOutcome {
1517 let action = self.shared.with(|s| {
1518 let Some(j) = s.jobs.get_mut(&job) else {
1519 return Err(CancelOutcome::TooLate);
1520 };
1521 if j.kind == JobKind::Flush {
1522 return Err(CancelOutcome::TooLate);
1523 }
1524 let Some(w) = j.waiters.iter_mut().find(|w| w.inc == inc && !w.detached) else {
1525 return Err(CancelOutcome::TooLate);
1526 };
1527 w.detached = true;
1528 match s.coalesce.detach(job) {
1529 Detach::Remaining(_) => return Err(CancelOutcome::TooLate),
1530 Detach::Unknown | Detach::Last => {}
1531 }
1532 let j = s.jobs.get_mut(&job).expect("job");
1533 if matches!(j.status, Status::Dispatching) {
1534 // The worker forwards the cancel once the store has the job.
1535 j.cancelling = true;
1536 return Err(CancelOutcome::TooLate);
1537 }
1538 match j.status {
1539 Status::Queued => {
1540 let id = j.id;
1541 let class = j.class;
1542 match class {
1543 Class::Restore => s.restore_queue.retain(|&x| x != id),
1544 Class::Park => s.park_queue.retain(|&x| x != id),
1545 }
1546 let job = s.jobs.remove(&id).expect("queued job");
1547 let stage = job.stage;
1548 s.finish_job(
1549 job,
1550 Terminal::Cancelled,
1551 stage,
1552 PublishOutcome::NotApplicable,
1553 None,
1554 );
1555 self.shared.cv.notify_all();
1556 Err(CancelOutcome::Cancelled)
1557 }
1558 Status::Dispatched(inner_id) => {
1559 j.cancelling = true;
1560 Ok(inner_id)
1561 }
1562 Status::Dispatching => Err(CancelOutcome::TooLate),
1563 }
1564 });
1565 match action {
1566 Err(outcome) => outcome,
1567 Ok(inner_id) => {
1568 let out = self.inner.cancel(inner_id);
1569 if out == CancelOutcome::TooLate {
1570 self.shared.with(|s| {
1571 if let Some(j) = s.jobs.get_mut(&job) {
1572 j.cancelling = false;
1573 }
1574 });
1575 } else {
1576 self.shared.cv.notify_all();
1577 }
1578 out
1579 }
1580 }
1581 }
1582
1583 /// Ask the store to cancel dispatched jobs (outside the state lock); a job
1584 /// the store refuses goes on and keeps accepting nothing new.
1585 fn forward_cancels(&self, to_cancel: Vec<(JobId, JobId)>) {
1586 for (w_id, inner_id) in to_cancel {
1587 if self.inner.cancel(inner_id) == CancelOutcome::TooLate {
1588 self.shared.with(|s| {
1589 if let Some(j) = s.jobs.get_mut(&w_id) {
1590 j.cancelling = false;
1591 }
1592 });
1593 }
1594 }
1595 self.shared.cv.notify_all();
1596 }
1597
1598 fn shutdown_impl(&self, intake_deadline_ms: u64) -> DrainReport {
1599 let deadline = Instant::now() + Duration::from_millis(intake_deadline_ms);
1600 let to_cancel = self.shared.with(|s| {
1601 s.closed = true;
1602 s.inner_shutdown_requested = true;
1603 if s.shutdown_published_before.is_none() {
1604 s.shutdown_published_before = Some(s.published_total);
1605 }
1606 let r = s.cancel_unstarted();
1607 self.shared.cv.notify_all();
1608 r
1609 });
1610 let (handed, to_cancel) = to_cancel;
1611 drop(handed);
1612 self.forward_cancels(to_cancel);
1613
1614 loop {
1615 let done = self.shared.with(|s| {
1616 s.reap_orphans();
1617 s.jobs.is_empty() && (s.inner_shutdown_called || s.panicked)
1618 });
1619 if done {
1620 break;
1621 }
1622 let now = Instant::now();
1623 if now >= deadline {
1624 break;
1625 }
1626 let wait = (deadline - now).min(Duration::from_millis(5));
1627 let g = self.shared.lock();
1628 if !g.jobs.is_empty() || !g.inner_shutdown_called {
1629 let _ = self.shared.cv.wait_timeout(g, wait);
1630 }
1631 }
1632
1633 self.shared.with(|s| {
1634 let unfinished: Vec<UnfinishedJob> = s
1635 .jobs
1636 .values()
1637 .map(|j| UnfinishedJob {
1638 job: j.id,
1639 key: j.key,
1640 bytes: j.bytes,
1641 stage: j.stage,
1642 })
1643 .collect();
1644 s.stats.shutdown_unfinished_jobs = unfinished.len() as u64;
1645 s.stats.shutdown_unfinished_bytes = unfinished.iter().map(|u| u.bytes).sum();
1646 let base = s.shutdown_published_before.unwrap_or(s.published_total);
1647 DrainReport {
1648 published: s.published_total.saturating_sub(base),
1649 cancelled: s.shutdown_cancelled,
1650 unfinished,
1651 }
1652 })
1653 }
1654}