Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/tinymemory-tools/src/lifecycle/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub struct RecallSettings {
pub compaction_timeout_ms: u64,
/// How long queued belief builds wait for newer writes.
pub build_delay_secs: u64,
/// Maximum number of background jobs that may call the engine at once.
pub concurrency: usize,
}

impl Default for RecallSettings {
Expand All @@ -81,6 +83,7 @@ impl Default for RecallSettings {
date_hint: false,
compaction_timeout_ms: 8_000,
build_delay_secs: 300,
concurrency: 1,
}
}
}
Expand All @@ -107,6 +110,7 @@ impl RecallSettings {
100,
30_000,
)?;
validate_range("concurrency", self.concurrency, 1, 32)?;
validate_build_delay_secs(self.build_delay_secs)?;
Ok(())
}
Expand Down
262 changes: 260 additions & 2 deletions crates/tinymemory-tools/src/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@

mod types;

use std::sync::Arc;
use std::collections::HashSet;
use std::sync::{Arc, Mutex as StdMutex};

use chrono::{Duration, Utc};
use futures::lock::Mutex;
use futures::{StreamExt, lock::Mutex, stream};
use sha2::{Digest, Sha256};
use tinymemory_api::{MemoryEngine, Namespace};

Expand All @@ -41,6 +42,24 @@ pub struct JobQueue<S: QueueStore> {
/// Serialises read-modify-writes. Held across a run, so two runs never
/// take the same job.
lock: Mutex<()>,
active: Arc<StdMutex<HashSet<String>>>,
}

struct ActiveClaims {
active: Arc<StdMutex<HashSet<String>>>,
ids: Vec<String>,
}

impl Drop for ActiveClaims {
fn drop(&mut self) {
let mut active = self
.active
.lock()
.unwrap_or_else(|error| error.into_inner());
for id in &self.ids {
active.remove(id);
}
}
}

/// The stable id of `job` under `root`: a digest, so a duplicate merges.
Expand Down Expand Up @@ -70,6 +89,125 @@ fn queued(root: &str, job: BackgroundJob) -> QueuedJob {
}
}

struct RunResult {
record: JobRun,
retry: Option<QueuedJob>,
follow_ups: Vec<QueuedJob>,
}

async fn run_entry(engine: Arc<dyn MemoryEngine>, mut entry: QueuedJob) -> RunResult {
let layout = entry
.root
.parse::<Namespace>()
.ok()
.and_then(|root| MemoryLayout::new(root).ok())
.unwrap_or_default();
let runner = BackgroundRunner::new(engine, layout);
let name = entry.job.name().to_string();
let mut record = JobRun {
id: entry.id.clone(),
job: name.clone(),
root: entry.root.clone(),
ran_at: Utc::now(),
outcome: String::new(),
reason: None,
built: None,
stored: 0,
};
match runner.run(entry.job.clone()).await {
Ok(report) => {
record.outcome = match &report.outcome {
JobOutcome::Done => "done",
JobOutcome::Started => "started",
JobOutcome::Scheduled => "scheduled",
JobOutcome::Skipped { .. } => "skipped",
}
.to_string();
if let JobOutcome::Skipped { reason } = &report.outcome {
record.reason = Some(reason.clone());
}
record.built = report
.consolidation
.as_ref()
.and_then(|receipt| receipt.built);
record.stored = report.stored.len();
let follow_ups = report
.follow_ups
.into_iter()
.map(|job| queued(&entry.root, job))
.collect();
log::info!(
"[memory:jobs] ran id={} job={name} outcome={} built={:?}",
entry.id,
record.outcome,
record.built
);
RunResult {
record,
retry: None,
follow_ups,
}
}
Err(error) => {
let account_wide = EngineFailure::from(error.clone()).is_account_wide();
if !account_wide {
entry.attempts += 1;
}
entry.last_error = Some(error.to_string());
record.outcome = "failed".to_string();
log::warn!(
"[memory:jobs] run failed id={} job={name} attempts={} account_wide={account_wide}: {error}",
entry.id,
entry.attempts
);
let retry = if entry.attempts < MAX_ATTEMPTS {
record.reason = Some(error.to_string());
Some(entry)
} else {
record.reason = Some(format!(
"dropped after {MAX_ATTEMPTS} failed attempts: {error}"
));
None
};
RunResult {
record,
retry,
follow_ups: Vec::new(),
}
}
}
}

fn matches_selection(
entry: &QueuedJob,
selection: &Selection,
cutoff: chrono::DateTime<Utc>,
) -> bool {
match selection {
Selection::Due => entry.queued_at <= cutoff,
Selection::All => true,
Selection::One(id) => &entry.id == id,
}
}

fn merge_entry(target: &mut QueuedJob, incoming: QueuedJob) {
target.attempts = target.attempts.max(incoming.attempts);
if incoming.queued_at < target.queued_at {
target.queued_at = incoming.queued_at;
}
if incoming.last_error.is_some() {
target.last_error = incoming.last_error;
}
}

fn merge_pending(state: &mut QueueState, entry: QueuedJob) {
if let Some(existing) = state.pending.iter_mut().find(|known| known.id == entry.id) {
merge_entry(existing, entry);
} else {
state.pending.push(entry);
}
}

impl<S: QueueStore> std::fmt::Debug for JobQueue<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JobQueue").finish_non_exhaustive()
Expand All @@ -82,6 +220,7 @@ impl<S: QueueStore> JobQueue<S> {
Self {
store,
lock: Mutex::new(()),
active: Arc::new(StdMutex::new(HashSet::new())),
}
}

Expand Down Expand Up @@ -149,6 +288,24 @@ impl<S: QueueStore> JobQueue<S> {
) -> Result<Vec<JobRun>, QueueError> {
let _guard = self.lock.lock().await;
let mut state = self.store.load();
let active_ids = self
.active
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone();
let mut recovered = Vec::new();
let mut active_in_flight = Vec::new();
for entry in state.in_flight.drain(..) {
if active_ids.contains(&entry.id) {
active_in_flight.push(entry);
} else {
recovered.push(entry);
}
}
state.in_flight = active_in_flight;
for entry in recovered {
merge_pending(&mut state, entry);
}
let cutoff = Utc::now() - Duration::seconds(i64::try_from(build_delay_secs).unwrap_or(0));
let (take, keep): (Vec<QueuedJob>, Vec<QueuedJob>) =
state.pending.drain(..).partition(|entry| match &selection {
Expand Down Expand Up @@ -248,6 +405,107 @@ impl<S: QueueStore> JobQueue<S> {
self.write(&state);
Ok(runs)
}

/// Runs selected jobs with at most `concurrency` jobs in flight.
///
/// A value of zero is treated as one. Queue state is locked only while
/// claiming jobs and recording results, never while a job awaits the engine.
///
/// # Errors
/// [`QueueError::NoSuchJob`] when [`Selection::One`] names a job that is
/// not queued, or [`QueueError::Store`] when a claim or result cannot be
/// persisted; the queue is left recoverable.
pub async fn run_with_concurrency(
&self,
engine: Arc<dyn MemoryEngine>,
selection: Selection,
build_delay_secs: u64,
concurrency: usize,
) -> Result<Vec<JobRun>, QueueError> {
let active = Arc::clone(&self.active);
let (take, _claims) = {
let _guard = self.lock.lock().await;
let mut state = self.store.load();
let cutoff =
Utc::now() - Duration::seconds(i64::try_from(build_delay_secs).unwrap_or(0));
let active_ids = active.lock().unwrap_or_else(|error| error.into_inner());
let mut take = Vec::new();
let mut pending = Vec::new();
let mut in_flight = Vec::new();
for entry in state.in_flight.drain(..) {
if active_ids.contains(&entry.id) || !matches_selection(&entry, &selection, cutoff)
{
in_flight.push(entry);
} else {
take.push(entry);
}
}
for entry in state.pending.drain(..) {
if active_ids.contains(&entry.id) || !matches_selection(&entry, &selection, cutoff)
{
pending.push(entry);
} else if let Some(existing) = take.iter_mut().find(|known| known.id == entry.id) {
merge_entry(existing, entry);
} else {
take.push(entry);
}
}
state.pending = pending;
state.in_flight = in_flight;
if let Selection::One(id) = &selection
&& take.is_empty()
{
return Err(QueueError::NoSuchJob(id.clone()));
}
state.in_flight.extend(take.iter().cloned());
self.store.save(&state).map_err(QueueError::Store)?;
let ids = take
.iter()
.map(|entry| entry.id.clone())
.collect::<Vec<_>>();
drop(active_ids);
active
.lock()
.unwrap_or_else(|error| error.into_inner())
.extend(ids.iter().cloned());
(
take,
ActiveClaims {
active: Arc::clone(&active),
ids,
},
)
};

let results = stream::iter(
take.into_iter()
.map(|entry| run_entry(Arc::clone(&engine), entry)),
)
.buffered(concurrency.max(1))
.collect::<Vec<_>>()
.await;

let _guard = self.lock.lock().await;
let mut state = self.store.load();
let mut runs = Vec::with_capacity(results.len());
for result in results {
state.in_flight.retain(|entry| entry.id != result.record.id);
if let Some(retry) = result.retry {
merge_pending(&mut state, retry);
}
for follow_up in result.follow_ups {
merge_pending(&mut state, follow_up);
}
runs.push(result.record);
}
let mut history = runs.clone();
history.reverse();
history.append(&mut state.history);
history.truncate(MAX_HISTORY);
state.history = history;
self.store.save(&state).map_err(QueueError::Store)?;
Ok(runs)
}
}

#[cfg(test)]
Expand Down
Loading