Skip to content
Merged
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
5 changes: 4 additions & 1 deletion docs/development/QUALITY_GATES.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ Host health and library snapshots read only the public library identity fields.
The snapshot counts printers and active outbound loans within the same SQLite
read transaction as inventory. Paired Clients order successful summary reads by
request. An overlapping Dashboard read updates its own projection independently
of ordinary summaries. Tests complete requests out of order with equal Host
of ordinary summaries. Settings compares the displayed request number with the
latest saved request after opening, refreshing or checking the Host. It reads
the saved summary only when needed. Unversioned summaries use Host timestamps.
Tests complete requests out of order with equal Host
timestamps and exercise the fallback for older Hosts. API tests cover legacy loan directions, returned
loans, deleted spools and unreadable fields outside the response.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ fn delayed_summary_returns_the_committed_rows_and_rejects_an_old_pairing() {
for switch_target in [false, true] {
let (tx, rx) = std::sync::mpsc::channel::<std::path::PathBuf>();
let later = LibrarySyncCachedSnapshotRow {
client_request: None,
dashboard_stock: None,
captured_at: "2026-12-01 12:00:00".into(),
app_version: None,
Expand Down
16 changes: 10 additions & 6 deletions src-tauri/src/library_sync_settings_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub(crate) async fn get_library_sync_settings(
cache_domains: Option<Vec<LibrarySyncCacheDomain>>,
expected_generation: Option<u64>,
fetched_snapshot_at: Option<String>,
fetched_request: Option<i64>,
) -> Result<LibrarySyncSettingsRow, String> {
let state = state.inner().clone();
run_library_sync_blocking(move || {
Expand All @@ -65,6 +66,7 @@ pub(crate) async fn get_library_sync_settings(
cache_domains.as_deref(),
expected_generation,
fetched_snapshot_at.as_deref(),
fetched_request,
)
})
.await
Expand All @@ -75,14 +77,16 @@ fn get_library_sync_settings_blocking(
cache_domains: Option<&[LibrarySyncCacheDomain]>,
expected_generation: Option<u64>,
fetched_snapshot_at: Option<&str>,
fetched_request: Option<i64>,
) -> Result<LibrarySyncSettingsRow, String> {
if let Some(domains) = cache_domains {
let _target_guard = lock_secure_credential_mutation()?;
let settings = with_db(state, |db| {
db.get_library_sync_settings_at_generation(
db.get_library_sync_settings_after_summary(
domains,
expected_generation,
fetched_snapshot_at,
fetched_request,
)
})?;
return settings_with_secure_pairing_state(state, settings);
Expand Down Expand Up @@ -662,7 +666,7 @@ mod tests {
db.set_setting("low_stock_policy_json", "not-json")
});

let damaged = get_library_sync_settings_blocking(&state, None, None, None)
let damaged = get_library_sync_settings_blocking(&state, None, None, None, None)
.expect("settings remain available for policy repair");
assert!(!damaged.low_stock_policy_valid);

Expand All @@ -687,7 +691,7 @@ mod tests {
#[test]
fn host_settings_bump_inventory_only_when_normalized_low_stock_policy_changes() {
let state = test_state();
let initial = get_library_sync_settings_blocking(&state, None, None, None)
let initial = get_library_sync_settings_blocking(&state, None, None, None, None)
.expect("load initial settings");
let initial_revision =
with_test_database(&state, |db| db.library_domain_revisions()).inventory;
Expand Down Expand Up @@ -868,7 +872,7 @@ mod tests {
.expect("read runtime")
.is_none());
assert!(
!get_library_sync_settings_blocking(&state, None, None, None)
!get_library_sync_settings_blocking(&state, None, None, None, None)
.expect("read settings")
.client_auth_paired
);
Expand Down Expand Up @@ -918,7 +922,7 @@ mod tests {
.expect("read runtime")
.is_none());
assert!(
!get_library_sync_settings_blocking(&state, None, None, None)
!get_library_sync_settings_blocking(&state, None, None, None, None)
.expect("read settings")
.client_auth_paired
);
Expand Down Expand Up @@ -1196,7 +1200,7 @@ mod tests {
store_library_sync_device_token_bytes(&state, host, &[0xff, 0xfe])
.expect("store corrupt token fixture");

let settings = get_library_sync_settings_blocking(&state, None, None, None)
let settings = get_library_sync_settings_blocking(&state, None, None, None, None)
.expect("settings remain available for repair");
assert!(settings.client_auth_paired);
assert!(load_library_sync_device_token_optional(&state, host).is_err());
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/library_sync_snapshot_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub(crate) fn fetch_library_sync_snapshot_blocking(
}

let snapshot = LibrarySyncCachedSnapshotRow {
client_request: None,
dashboard_stock: parsed.dashboard_stock,
captured_at: parsed.captured_at,
app_version: parsed.app_version,
Expand Down
1 change: 1 addition & 0 deletions src/backend/database_library_sync_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub(crate) fn save_library_sync_cached_snapshot(
let encode = |snapshot: &LibrarySyncCachedSnapshotRow| {
serde_json::to_string(snapshot).map_err(|error| InventoryError::Db(error.to_string()))
};
snapshot.client_request = Some(request);
let publish_summary = advance_saved_request(&tx, SAVED_SUMMARY_REQUEST, request)?;
let publish_dashboard =
dashboard && advance_saved_request(&tx, SAVED_DASHBOARD_REQUEST, request)?;
Expand Down
16 changes: 16 additions & 0 deletions src/backend/database_library_sync_facade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,29 @@ impl FilamentDatabase {
domains: &[LibrarySyncCacheDomain],
expected_generation: Option<u64>,
fetched_snapshot_at: Option<&str>,
) -> InventoryResult<LibrarySyncSettingsRow> {
self.get_library_sync_settings_after_summary(
domains,
expected_generation,
fetched_snapshot_at,
None,
)
}

pub fn get_library_sync_settings_after_summary(
&self,
domains: &[LibrarySyncCacheDomain],
expected_generation: Option<u64>,
fetched_snapshot_at: Option<&str>,
fetched_request: Option<i64>,
) -> InventoryResult<LibrarySyncSettingsRow> {
self.with_read_transaction(|db| {
super::database_library_sync_settings::read_library_sync_settings(
db.connection(),
Some(domains),
expected_generation,
fetched_snapshot_at,
fetched_request,
)
})
}
Expand Down
3 changes: 3 additions & 0 deletions src/backend/database_library_sync_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ pub struct LibrarySyncSettingsRow {

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct LibrarySyncCachedSnapshotRow {
/// Assigned by the paired Client when publishing this response.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_request: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dashboard_stock: Option<super::dashboard_stock::DashboardStock>,
pub captured_at: String,
Expand Down
46 changes: 39 additions & 7 deletions src/backend/database_library_sync_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,15 @@ pub(crate) fn get_library_sync_page_status(
pub(crate) fn get_library_sync_settings(
conn: &Connection,
) -> InventoryResult<LibrarySyncSettingsRow> {
read_library_sync_settings(conn, None, None, None)
read_library_sync_settings(conn, None, None, None, None)
}

pub(crate) fn read_library_sync_settings(
conn: &Connection,
domains: Option<&[LibrarySyncCacheDomain]>,
expected_generation: Option<u64>,
fetched_snapshot_at: Option<&str>,
fetched_request: Option<i64>,
) -> InventoryResult<LibrarySyncSettingsRow> {
use LibrarySyncCacheDomain::*;
let LibrarySyncPageStatusRow {
Expand Down Expand Up @@ -115,12 +116,23 @@ pub(crate) fn read_library_sync_settings(
Err(rusqlite::Error::FromSqlConversionFailure(_, _, _)) => (Default::default(), false),
Err(error) => return Err(error.into()),
};
// Overlapping Host reads can commit a newer summary before the page paints.
// Compare the small timestamp and only recover the payload for a stale reply.
let newer_snapshot = match fetched_snapshot_at {
Some(fetched) if target_matches => get_setting(conn, SNAPSHOT_CAPTURED_AT_KEY)?
.is_some_and(|saved| saved.as_str() > fetched),
_ => false,
// Read the full summary only if another successful request overtook this
// view. Pre-sequence snapshots keep the timestamp fallback.
let newer_snapshot = if !target_matches {
false
} else if let Some(request) = fetched_request {
conn.query_row(
"SELECT EXISTS(SELECT 1 FROM settings WHERE key=?1 AND CAST(value AS INTEGER)>?2)",
rusqlite::params![
super::database_library_sync_cache::SAVED_SUMMARY_REQUEST,
request
],
|row| row.get(0),
)?
} else if let Some(fetched) = fetched_snapshot_at {
get_setting(conn, SNAPSHOT_CAPTURED_AT_KEY)?.is_some_and(|saved| saved.as_str() > fetched)
} else {
false
};
let dashboard = domains.is_some_and(|selected| selected.contains(&DashboardStock));
let compact = selected_cache(conn, dashboard, DASHBOARD_SNAPSHOT_KEY)?;
Expand Down Expand Up @@ -421,6 +433,7 @@ mod tests {
.unwrap()
.target_generation;
let mut summary = LibrarySyncCachedSnapshotRow {
client_request: None,
captured_at: "time-a".into(),
app_version: None,
library_id: target.library_id.clone(),
Expand Down Expand Up @@ -489,6 +502,7 @@ mod tests {
db.apply_schema().unwrap();
let library_id = db.get_library_sync_library_id().unwrap();
let base = LibrarySyncCachedSnapshotRow {
client_request: None,
captured_at: "2026-12-01 12:00:00".into(),
app_version: None,
library_id,
Expand All @@ -503,6 +517,7 @@ mod tests {
dashboard_stock: None,
};
let reply = |order: i64, with_stock: bool| LibrarySyncCachedSnapshotRow {
client_request: Some(order),
active_loans: order,
dashboard_stock: with_stock.then(Default::default),
..base.clone()
Expand Down Expand Up @@ -605,6 +620,23 @@ mod tests {
assert!(read(&[Spools], generation, None).is_err());
// A stale Host summary is the only successful read that needs the saved summary.
assert!(read(&[], generation, Some("2026-11-01 11:59:59")).is_err());
set_setting(
conn,
super::super::database_library_sync_cache::SAVED_SUMMARY_REQUEST,
"10",
)
.unwrap();
let after = |expected, request, captured_at| {
db.get_library_sync_settings_after_summary(
&[],
Some(expected),
Some(captured_at),
Some(request),
)
};
assert!(after(generation, 10, "2000-01-01").is_ok());
assert!(after(generation, 9, "2099-01-01").is_err());
assert!(after(generation - 1, 9, "2099-01-01").is_ok());
let replacement = read(&[Spools], generation - 1, Some("older")).unwrap();
assert_eq!(replacement.target_generation, generation);
assert!(replacement.cached_spools.is_none());
Expand Down
2 changes: 2 additions & 0 deletions src/backend/filament_database_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ fn seed_all_library_sync_host_caches(
) -> Result<(), String> {
db.save_library_sync_host_snapshot(
LibrarySyncCachedSnapshotRow {
client_request: None,
dashboard_stock: Some(Default::default()),
captured_at: "2026-08-26 10:00:00".to_string(),
app_version: Some("0.32.1".to_string()),
Expand Down Expand Up @@ -4404,6 +4405,7 @@ fn library_sync_settings_default_and_persist_cleanly() {
low_stock_policy: Default::default(),
low_stock_policy_valid: true,
cached_snapshot: Some(LibrarySyncCachedSnapshotRow {
client_request: None,
dashboard_stock: None,
captured_at: "2026-04-09 10:00:00".to_string(),
app_version: None,
Expand Down
32 changes: 30 additions & 2 deletions ui/src/lib/settings_data_source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,33 @@ test("snapshot refresh accepts a newer saved summary only from the same library"
}
});

test("Settings refresh and Host checks use Client request order across Host clock changes", async () => {
const visible = remoteSnapshot({ client_request: 10 });
for (const [saved, expected] of [
[remoteSnapshot({ client_request: 11 }), "saved"],
[remoteSnapshot({ client_request: 11, captured_at: "2000-01-01" }), "saved"],
[remoteSnapshot({ client_request: 9, captured_at: "2099-01-01" }), "visible"],
[remoteSnapshot({ client_request: 11, library_id: "other" }), "visible"],
] as const) {
const settings = { ...pairedSettings, cached_snapshot: saved };
const read: NonNullable<Parameters<typeof settingsAfterHostCheck>[2]> = async (domains, generation, at, request) => {
assert.deepEqual(domains, []);
assert.equal(generation, 7);
assert.equal(at, visible.captured_at);
assert.equal(request, 10);
return settings;
};
const refresh = await refreshLibrarySyncSnapshot("http://host", visible.library_id, 7, {
fetchHostSnapshot: async () => visible,
loadSyncSettings: read,
});
assert.ok(refresh.ok);
const checked = await settingsAfterHostCheck({ ...pairedSettings, cached_snapshot: visible }, true, read);
assert.equal(refresh.snapshot, expected === "saved" ? saved : visible);
assert.equal(checked.cached_snapshot, refresh.snapshot);
}
});

test("refreshLibrarySyncSnapshot rejects incomplete host targets before fetching", async () => {
await assert.rejects(
() =>
Expand Down Expand Up @@ -583,7 +610,7 @@ test("refreshLibrarySyncSnapshot rejects a response after the client target gene

test("Settings requests only failed cache domains, including a disconnected Host", async () => {
const cachedSummary = remoteSnapshot({ device_name: "cached" });
const liveSummary = remoteSnapshot({ device_name: "live" });
const liveSummary = remoteSnapshot({ device_name: "live", client_request: 8 });
for (const failed of [[], ["printers"], ["spools"], ["snapshot"], ["catalog", "printerSettings"],
["catalog", "printerSettings", "printers", "spools", "snapshot"]]) {
const calls: string[][] = [];
Expand All @@ -593,11 +620,12 @@ test("Settings requests only failed cache domains, including a disconnected Host
};
const result = await loadSettingsPageData({
includeSpoolRows: true,
loadSyncSettings: async (domains, generation, fetchedAt) => {
loadSyncSettings: async (domains, generation, fetchedAt, request) => {
assert.ok(domains);
calls.push([...domains]);
if (calls.length === 2) {
assert.equal(generation, 7);
assert.equal(request, failed.includes("snapshot") ? undefined : liveSummary.client_request);
assert.equal(fetchedAt, failed.includes("snapshot") ? undefined : liveSummary.captured_at);
}
return {
Expand Down
22 changes: 12 additions & 10 deletions ui/src/lib/settings_data_source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,26 +114,28 @@ function sameSettingsTarget(left: LibrarySyncSettings, right: LibrarySyncSetting

function latestSettingsSnapshot(settings: LibrarySyncSettings, fetched: LibrarySyncRemoteSnapshot | null) {
const saved = settings.cached_snapshot;
if (saved?.library_id === settings.library_id.trim() && saved.captured_at &&
(!fetched || saved.captured_at >= fetched.captured_at)) {
return saved;
if (!saved?.captured_at || saved.library_id !== settings.library_id.trim()) return fetched;
if (!fetched) return saved;
if (saved.client_request !== undefined && fetched.client_request !== undefined) {
return saved.client_request >= fetched.client_request ? saved : fetched;
}
return fetched;
return saved.captured_at && saved.captured_at >= fetched.captured_at ? saved : fetched;
}

// Checking reachability does not fetch a new summary. Keep the displayed
// summary for a successful check and consult its cache only on failure.
// A reachability check can finish after another view publishes a summary.
export async function settingsAfterHostCheck(
previous: LibrarySyncSettings | null,
succeeded: boolean,
loadSettings = getLibrarySyncSettings,
) {
const current = await loadSettings(succeeded ? [] : ["snapshot"], previous?.target_generation);
const visible = succeeded ? previous?.cached_snapshot : null;
const current = await loadSettings(succeeded ? [] : ["snapshot"], previous?.target_generation,
visible?.captured_at, visible?.client_request);
if (!previous) return current;
if (!sameSettingsTarget(previous, current)) {
throw new Error("Host connection changed while validating.");
}
return succeeded ? { ...current, cached_snapshot: previous.cached_snapshot } : current;
return succeeded ? { ...current, cached_snapshot: latestSettingsSnapshot(current, visible ?? null) } : current;
}

async function loadClientSettings(
Expand Down Expand Up @@ -180,7 +182,7 @@ async function loadClientSettings(
if (includeSpoolRows && spools?.status !== "fulfilled") fallback.push("spools");
if (snapshot?.status !== "fulfilled") fallback.push("snapshot");
const fetched = snapshot?.status === "fulfilled" ? snapshot.value : null;
const current = await loadSyncSettings(fallback, settings.target_generation, fetched?.captured_at);
const current = await loadSyncSettings(fallback, settings.target_generation, fetched?.captured_at, fetched?.client_request);
const librarySyncSnapshot = latestSettingsSnapshot(current, fetched);
return {
snapshot: neutralPrinterSettingsSnapshot(),
Expand Down Expand Up @@ -238,7 +240,7 @@ export async function refreshLibrarySyncSnapshot(
{ dashboard: false, expectedGeneration: expectedTargetGeneration })]);
const fetched = read.status === "fulfilled" ? read.value : null;
const syncSettings = await loadSyncSettings(
fetched ? [] : ["snapshot"], expectedTargetGeneration, fetched?.captured_at,
fetched ? [] : ["snapshot"], expectedTargetGeneration, fetched?.captured_at, fetched?.client_request,
);
const refreshedTarget =
syncSettings.mode === "CLIENT"
Expand Down
4 changes: 3 additions & 1 deletion ui/src/lib/tauri_library_sync_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ export type DashboardStock = {
};

export type LibrarySyncRemoteSnapshot = {
client_request?: number;
dashboard_stock?: DashboardStock | null;
captured_at: string;
/** Missing on older Hosts and their cached snapshots. */
Expand Down Expand Up @@ -224,8 +225,9 @@ export async function getLibrarySyncSettings(
cacheDomains?: readonly LibrarySyncCacheDomain[],
expectedGeneration?: number,
fetchedSnapshotAt?: string,
fetchedRequest?: number,
) {
return invoke<LibrarySyncSettings>("get_library_sync_settings", cacheDomains && { cacheDomains, expectedGeneration, fetchedSnapshotAt });
return invoke<LibrarySyncSettings>("get_library_sync_settings", cacheDomains && { cacheDomains, expectedGeneration, fetchedSnapshotAt, fetchedRequest });
}

export async function getLibraryDomainRevisions() {
Expand Down
Loading