From b99f4e628adb54af958f781488cd409d55f04563 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 08:07:09 +0500 Subject: [PATCH 1/4] =?UTF-8?q?test(ui-core):=20red=20=E2=80=94=20pure=20C?= =?UTF-8?q?urationSession=20+=20boundary=20event=20minting=20(3C-B1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The renderer-agnostic curation session over the merged curation_store model, as failing tests against stub bodies: - bootstrap(None) pins an empty store to the current corpus (a typed empty bootstrap), bootstrap(Some) keeps the loaded store; - record appends a new CurationEvent and never mutates an existing one; a repeat decision is a second event, and the projection takes the later one; - an equal timestamp breaks by event_id; - record snapshots the chunk's dedup cluster as audit context; - a regrouped cluster does NOT move a decision (reconcile keeps it active while the chunk's material is unchanged); - a deleted/changed chunk is orphaned; - record rejects an unknown chunk; - mint_event_id is a canonical v4 UUID from 16 boundary bytes; - canonical_timestamp is second-precision UTC (no fractional part, which the store rejects) and round-trips through decode. No I/O, no UI: the frontend supplies the opaque event_id / occurred_at and persists session.store() through the OPFS/native adapter (3C-B2). Stubs make all ten tests fail. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- ui-core/src/curation_session.rs | 485 ++++++++++++++++++++++++++++++++ ui-core/src/lib.rs | 1 + 2 files changed, 486 insertions(+) create mode 100644 ui-core/src/curation_session.rs diff --git a/ui-core/src/curation_session.rs b/ui-core/src/curation_session.rs new file mode 100644 index 00000000..7dd90985 --- /dev/null +++ b/ui-core/src/curation_session.rs @@ -0,0 +1,485 @@ +//! In-session curation state and boundary event minting (step 3C-B1). +//! +//! A pure, renderer-agnostic layer over the merged [`griff_core::curation_store`] +//! domain model: it holds the append-only store for one editing session, assembles +//! a [`CurationEvent`] from a decision plus the corpus (fingerprints and the +//! cluster audit snapshot), and projects/reconciles through core. **No I/O and no +//! UI** — a frontend supplies the opaque `event_id` and canonical `occurred_at` +//! (minted here from a boundary-provided random seed and clock), drives +//! [`CurationSession::record`], then persists [`CurationSession::store`] through +//! the OPFS/native adapter. +//! +//! A decision is always **appended**, keyed by [`ChunkId`]; nothing is mutated in +//! place. Cluster context is an audit snapshot on the event, never part of the +//! decision's identity (ADR-0030 §8): a regrouped cluster does not move a +//! decision. That invariant lives in core's `reconcile`; this layer only feeds it. + +use std::collections::BTreeMap; +use std::fmt::Write as _; + +use griff_core::corpus::{ChunkId, ChunkMeta, ReviewerDecision, SwancoreTag, SCHEMA_VERSION}; +use griff_core::curation::build_clusters; +use griff_core::curation_store::{ + chunk_fingerprint, corpus_fingerprint, project, reconcile as core_reconcile, CorpusFingerprint, + CurationContext, CurationEvent, CurationEventId, CurationStoreV1, FingerprintError, + ProjectedCuration, ReconciledCuration, ReviewerId, CURATION_STORE_VERSION, +}; + +/// One decision to record. The opaque `event_id` and canonical `occurred_at` +/// come from the boundary (mint with [`mint_event_id`] / [`canonical_timestamp`]); +/// the fingerprints and cluster context are derived from the corpus by +/// [`CurationSession::record`]. +#[derive(Debug, Clone)] +pub struct RecordRequest { + pub chunk_id: ChunkId, + pub decision: ReviewerDecision, + pub reviewer: ReviewerId, + pub event_id: CurationEventId, + pub occurred_at: String, + pub tags: Vec, + pub note: Option, +} + +/// Why a decision could not be recorded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RecordError { + /// The decision names a chunk that is not in the current corpus. + UnknownChunk { chunk_id: ChunkId }, + /// The chunk exists but lacks a pinned identity to bind the decision to. + Unpinned(FingerprintError), +} + +/// The append-only curation store for one editing session. +#[derive(Debug, Clone)] +pub struct CurationSession { + store: CurationStoreV1, +} + +impl CurationSession { + /// Bootstraps from a loaded store, or a fresh **empty** store pinned to the + /// current corpus when there is none yet — a typed empty bootstrap, never a + /// guess. + /// + /// # Errors + /// [`FingerprintError`] if the corpus cannot be fingerprinted (an unpinned + /// chunk). + pub fn bootstrap( + loaded: Option, + corpus: &[ChunkMeta], + ) -> Result { + // STUB (red): ignores the corpus, leaving the empty store unpinned (an + // empty fingerprint), so the pinned-empty-store test fails. + let _ = corpus; + let store = loaded.unwrap_or(CurationStoreV1 { + version: CURATION_STORE_VERSION, + corpus_fingerprint: CorpusFingerprint(String::new()), + events: Vec::new(), + }); + Ok(Self { store }) + } + + /// Records a decision by appending a new [`CurationEvent`] — never mutating an + /// existing one. + /// + /// # Errors + /// [`RecordError::UnknownChunk`] if the chunk is absent from `corpus`; + /// [`RecordError::Unpinned`] if it lacks a pinned identity. + pub fn record(&mut self, req: RecordRequest, corpus: &[ChunkMeta]) -> Result<(), RecordError> { + // STUB (red): drops the decision, so the append/projection tests fail. + let _ = (req, corpus, &mut self.store); + Ok(()) + } + + /// The latest decision per chunk (core's projection; cluster context excluded). + #[must_use] + pub fn projected(&self) -> ProjectedCuration { + // STUB (red): empty, so the projection tests fail. + ProjectedCuration { + by_chunk: BTreeMap::new(), + } + } + + /// Reconciles the session's decisions against the current corpus. + /// + /// # Errors + /// [`FingerprintError`] if a current chunk cannot be fingerprinted. + pub fn reconcile(&self, corpus: &[ChunkMeta]) -> Result { + // STUB (red): claims everything orphaned-free and unmatched, so the + // active/orphaned tests fail. + let _ = corpus; + Ok(ReconciledCuration { + active: Vec::new(), + orphaned: Vec::new(), + corpus_match: false, + }) + } + + /// The store, for the boundary to encode and persist. + #[must_use] + pub fn store(&self) -> &CurationStoreV1 { + &self.store + } +} + +/// The cluster audit snapshot for `chunk_id`: its dedup cluster's representative +/// and all members (itself when it is a singleton). Never part of the decision's +/// identity — a navigation/audit fact only. +fn cluster_context(chunk_id: &ChunkId, corpus: &[ChunkMeta]) -> CurationContext { + let (clusters, _diagnostics) = build_clusters(corpus); + for cluster in &clusters { + if &cluster.representative == chunk_id || cluster.variants.contains(chunk_id) { + let mut members = vec![cluster.representative.clone()]; + members.extend(cluster.variants.iter().cloned()); + members.sort(); + return CurationContext { + cluster_representative: cluster.representative.clone(), + cluster_members: members, + }; + } + } + CurationContext { + cluster_representative: chunk_id.clone(), + cluster_members: vec![chunk_id.clone()], + } +} + +/// Mints an opaque decision-event id: an RFC-4122 **v4 UUID** from 16 +/// boundary-supplied random bytes. The randomness is the boundary's; this only +/// stamps the version (4) and variant (10) bits and the canonical hyphenated hex +/// layout, so the id is opaque, unique, and stable. +#[must_use] +pub fn mint_event_id(bytes: [u8; 16]) -> CurationEventId { + // STUB (red): returns a fixed non-UUID, so the format/uniqueness test fails. + let _ = bytes; + CurationEventId("stub".to_owned()) +} + +/// Formats a Unix-epoch second count as the canonical `YYYY-MM-DDTHH:MM:SSZ` +/// timestamp the store requires — second precision, no fractional part (which +/// `curation_store` rejects). Howard Hinnant's civil-from-days, no `chrono`. +#[must_use] +pub fn canonical_timestamp(epoch_secs: i64) -> String { + // STUB (red): empty, so the timestamp tests fail. + let _ = epoch_secs; + String::new() +} + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)] + + use super::{canonical_timestamp, mint_event_id, CurationSession, RecordError, RecordRequest}; + use griff_core::corpus::{ + ChunkId, ChunkMeta, ReviewerDecision, SourceFormat, SourceRef, SCHEMA_VERSION, + }; + use griff_core::curation_store::{ + corpus_fingerprint, decode_store, encode_store, CurationEventId, ProjectedDecision, + ReviewerId, + }; + use griff_core::novelty::PhraseDuplicate; + + fn chunk(id: &str, sha: &str, dup: Option) -> ChunkMeta { + ChunkMeta { + id: ChunkId(id.to_owned()), + title: String::new(), + source: SourceRef { + filename: "s.gp".to_owned(), + format: SourceFormat::Gp, + bar_range: Some((0, 3)), + track_index: Some(0), + sha256: Some(sha.to_owned()), + }, + tempo_bpm: 120.0, + ticks_per_quarter: 480, + time_signature: (4, 4), + tuning: "standard_e".to_owned(), + tags: Vec::new(), + boundaries: Vec::new(), + techniques: Vec::new(), + quality_flags: Vec::new(), + reviewer: None, + structure: None, + gesture: None, + complexity: None, + duplicate: dup.map(|of| PhraseDuplicate { + of, + quote_share: 0.9, + }), + style_cohort: None, + ensemble: None, + rights: None, + created_at: String::new(), + updated_at: String::new(), + } + } + + fn corpus() -> Vec { + vec![ + chunk("c0", "hash0", None), + chunk("c1", "hash1", Some(0)), // c1 duplicates c0 → one cluster {c0,[c1]} + chunk("c2", "hash2", None), + ] + } + + fn request(chunk: &str, event: &str, at: &str, decision: ReviewerDecision) -> RecordRequest { + RecordRequest { + chunk_id: ChunkId(chunk.to_owned()), + decision, + reviewer: ReviewerId("alice".to_owned()), + event_id: CurationEventId(event.to_owned()), + occurred_at: at.to_owned(), + tags: Vec::new(), + note: None, + } + } + + fn decision(p: &ProjectedDecision) -> ReviewerDecision { + p.decision + } + + #[test] + fn bootstrap_missing_pins_an_empty_store_to_the_corpus() { + let corpus = corpus(); + let session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + assert!(session.store().events.is_empty(), "no decisions yet"); + assert_eq!( + session.store().corpus_fingerprint, + corpus_fingerprint(SCHEMA_VERSION, &corpus).expect("fp"), + "the empty store is pinned to the current corpus" + ); + // A pinned empty store is itself valid and encodable. + encode_store(session.store()).expect("empty store encodes"); + } + + #[test] + fn record_appends_a_new_event_and_projects_it() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + session + .record( + request( + "c0", + "e1", + "2026-07-19T10:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect("record"); + assert_eq!(session.store().events.len(), 1); + let projected = session.projected(); + assert_eq!( + decision(&projected.by_chunk[&ChunkId("c0".to_owned())]), + ReviewerDecision::Accepted, + ); + } + + #[test] + fn a_repeat_decision_appends_a_new_event_never_mutates() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + session + .record( + request( + "c0", + "e1", + "2026-07-19T10:00:00Z", + ReviewerDecision::Rejected, + ), + &corpus, + ) + .expect("record 1"); + session + .record( + request( + "c0", + "e2", + "2026-07-19T11:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect("record 2"); + assert_eq!( + session.store().events.len(), + 2, + "two events, not a mutation" + ); + assert_eq!( + decision(&session.projected().by_chunk[&ChunkId("c0".to_owned())]), + ReviewerDecision::Accepted, + "the later decision wins", + ); + } + + #[test] + fn an_equal_timestamp_breaks_by_event_id() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + session + .record( + request( + "c0", + "e_a", + "2026-07-19T10:00:00Z", + ReviewerDecision::Rejected, + ), + &corpus, + ) + .expect("record a"); + session + .record( + request( + "c0", + "e_z", + "2026-07-19T10:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect("record z"); + assert_eq!( + decision(&session.projected().by_chunk[&ChunkId("c0".to_owned())]), + ReviewerDecision::Accepted, + "the greater event_id wins on an equal timestamp", + ); + } + + #[test] + fn record_snapshots_the_cluster_context() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + session + .record( + request( + "c1", + "e1", + "2026-07-19T10:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect("record"); + let context = &session.store().events[0].context; + assert_eq!( + context.cluster_members, + vec![ChunkId("c0".to_owned()), ChunkId("c1".to_owned())], + "the dedup cluster {{c0, c1}} is snapshotted as audit context", + ); + } + + #[test] + fn a_regrouped_cluster_does_not_move_a_decision() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + session + .record( + request( + "c1", + "e1", + "2026-07-19T10:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect("record"); + // The corpus regroups: c1 no longer duplicates c0 (its cluster changed), + // but its own material (sha/track/range) is unchanged. + let regrouped = vec![ + chunk_no_dup("c0", "hash0"), + chunk_no_dup("c1", "hash1"), + chunk_no_dup("c2", "hash2"), + ]; + let reconciled = session.reconcile(®rouped).expect("reconcile"); + assert_eq!(reconciled.active.len(), 1, "the decision stays active"); + assert!(reconciled.orphaned.is_empty()); + } + + #[test] + fn a_deleted_or_changed_chunk_is_orphaned() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + session + .record( + request( + "c0", + "e1", + "2026-07-19T10:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect("record"); + // c0's material changes (new sha); c1/c2 gone. + let changed = vec![chunk_no_dup("c0", "DIFFERENT")]; + let reconciled = session.reconcile(&changed).expect("reconcile"); + assert_eq!(reconciled.orphaned.len(), 1, "the changed chunk orphans it"); + assert!(reconciled.active.is_empty()); + } + + #[test] + fn record_rejects_an_unknown_chunk() { + let corpus = corpus(); + let mut session = CurationSession::bootstrap(None, &corpus).expect("bootstrap"); + let err = session + .record( + request( + "ghost", + "e1", + "2026-07-19T10:00:00Z", + ReviewerDecision::Accepted, + ), + &corpus, + ) + .expect_err("unknown chunk must fail"); + assert!(matches!(err, RecordError::UnknownChunk { .. })); + } + + #[test] + fn mint_event_id_is_a_canonical_v4_uuid() { + let id = mint_event_id([0xab; 16]).0; + assert_eq!(id.len(), 36, "8-4-4-4-12 hex with hyphens"); + let dashes: Vec = id.match_indices('-').map(|(i, _)| i).collect(); + assert_eq!( + dashes, + vec![8, 13, 18, 23], + "hyphens in the canonical spots" + ); + assert_eq!(id.as_bytes()[14], b'4', "version nibble is 4"); + assert!( + matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'), + "variant nibble is 8..b", + ); + // Different seeds mint different ids. + assert_ne!(mint_event_id([1; 16]).0, mint_event_id([2; 16]).0); + } + + #[test] + fn canonical_timestamp_is_second_precision_utc() { + // 2026-07-19T10:00:00Z = 1_784_282_400 seconds since the epoch. + assert_eq!( + canonical_timestamp(1_784_282_400), + "2026-07-19T10:00:00Z", + "exact civil time, second precision, no fractional part", + ); + // A minted timestamp is accepted by the store (it round-trips through decode). + let mut session = CurationSession::bootstrap(None, &corpus()).expect("bootstrap"); + session + .record( + request( + "c0", + "e1", + &canonical_timestamp(1_784_282_400), + ReviewerDecision::Accepted, + ), + &corpus(), + ) + .expect("record"); + decode_store(&encode_store(session.store()).expect("encode")).expect("minted ts is valid"); + } + + /// A pinned chunk with no duplicate link. + fn chunk_no_dup(id: &str, sha: &str) -> ChunkMeta { + chunk(id, sha, None) + } +} diff --git a/ui-core/src/lib.rs b/ui-core/src/lib.rs index 9e431fe4..99331318 100644 --- a/ui-core/src/lib.rs +++ b/ui-core/src/lib.rs @@ -27,6 +27,7 @@ pub mod analysis; pub mod capture; pub mod corpus; pub mod curation; +pub mod curation_session; pub mod dock; pub mod generate; pub mod history; From 0f0e1a3524243b7f270de3488558732f6326ba4e Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 08:13:54 +0500 Subject: [PATCH 2/4] =?UTF-8?q?feat(ui-core):=20green=20=E2=80=94=20pure?= =?UTF-8?q?=20CurationSession=20+=20boundary=20event=20minting=20(3C-B1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement the session so all ten tests pass: - bootstrap: Loaded wraps the store; Missing mints a fresh empty store pinned to the corpus via core::corpus_fingerprint (a typed empty bootstrap). - record: looks the chunk up in the corpus, computes its chunk_fingerprint and the corpus_fingerprint, snapshots the dedup cluster via build_clusters, and APPENDS a new CurationEvent — never mutates. Unknown chunk / unpinned chunk are typed errors. - projected / reconcile delegate to core::project / core::reconcile, so a repeat decision is resolved by (occurred_at, event_id) and a regrouped cluster never moves a live decision. - mint_event_id: a canonical RFC-4122 v4 UUID from 16 boundary bytes (version 4, variant 10, hyphenated hex). - canonical_timestamp: second-precision YYYY-MM-DDTHH:MM:SSZ from epoch seconds (civil-from-days), so a minted timestamp is accepted by the store — no fractional part, which curation_store rejects. Pure and native-tested; the impure random/clock sources stay at the cockpit boundary (3C-B2). Scoped arithmetic-lint allow on the bounded civil-from-days math. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- ui-core/src/curation_session.rs | 196 ++++++++++++++++++++------------ 1 file changed, 122 insertions(+), 74 deletions(-) diff --git a/ui-core/src/curation_session.rs b/ui-core/src/curation_session.rs index 7dd90985..a1d197d0 100644 --- a/ui-core/src/curation_session.rs +++ b/ui-core/src/curation_session.rs @@ -14,21 +14,21 @@ //! decision's identity (ADR-0030 §8): a regrouped cluster does not move a //! decision. That invariant lives in core's `reconcile`; this layer only feeds it. -use std::collections::BTreeMap; use std::fmt::Write as _; use griff_core::corpus::{ChunkId, ChunkMeta, ReviewerDecision, SwancoreTag, SCHEMA_VERSION}; use griff_core::curation::build_clusters; use griff_core::curation_store::{ - chunk_fingerprint, corpus_fingerprint, project, reconcile as core_reconcile, CorpusFingerprint, - CurationContext, CurationEvent, CurationEventId, CurationStoreV1, FingerprintError, - ProjectedCuration, ReconciledCuration, ReviewerId, CURATION_STORE_VERSION, + chunk_fingerprint, corpus_fingerprint, project, reconcile as core_reconcile, CurationContext, + CurationEvent, CurationEventId, CurationStoreV1, FingerprintError, ProjectedCuration, + ReconciledCuration, ReviewerId, CURATION_STORE_VERSION, }; -/// One decision to record. The opaque `event_id` and canonical `occurred_at` -/// come from the boundary (mint with [`mint_event_id`] / [`canonical_timestamp`]); -/// the fingerprints and cluster context are derived from the corpus by -/// [`CurationSession::record`]. +/// One decision to record. +/// +/// The opaque `event_id` and canonical `occurred_at` come from the boundary +/// (mint with [`mint_event_id`] / [`canonical_timestamp`]); the fingerprints and +/// cluster context are derived from the corpus by [`CurationSession::record`]. #[derive(Debug, Clone)] pub struct RecordRequest { pub chunk_id: ChunkId, @@ -67,14 +67,14 @@ impl CurationSession { loaded: Option, corpus: &[ChunkMeta], ) -> Result { - // STUB (red): ignores the corpus, leaving the empty store unpinned (an - // empty fingerprint), so the pinned-empty-store test fails. - let _ = corpus; - let store = loaded.unwrap_or(CurationStoreV1 { - version: CURATION_STORE_VERSION, - corpus_fingerprint: CorpusFingerprint(String::new()), - events: Vec::new(), - }); + let store = match loaded { + Some(store) => store, + None => CurationStoreV1 { + version: CURATION_STORE_VERSION, + corpus_fingerprint: corpus_fingerprint(SCHEMA_VERSION, corpus)?, + events: Vec::new(), + }, + }; Ok(Self { store }) } @@ -85,18 +85,35 @@ impl CurationSession { /// [`RecordError::UnknownChunk`] if the chunk is absent from `corpus`; /// [`RecordError::Unpinned`] if it lacks a pinned identity. pub fn record(&mut self, req: RecordRequest, corpus: &[ChunkMeta]) -> Result<(), RecordError> { - // STUB (red): drops the decision, so the append/projection tests fail. - let _ = (req, corpus, &mut self.store); + let chunk = corpus + .iter() + .find(|c| c.id == req.chunk_id) + .ok_or_else(|| RecordError::UnknownChunk { + chunk_id: req.chunk_id.clone(), + })?; + let chunk_fingerprint = chunk_fingerprint(chunk).map_err(RecordError::Unpinned)?; + let corpus_fingerprint = + corpus_fingerprint(SCHEMA_VERSION, corpus).map_err(RecordError::Unpinned)?; + let context = cluster_context(&req.chunk_id, corpus); + self.store.events.push(CurationEvent { + event_id: req.event_id, + chunk_id: req.chunk_id, + chunk_fingerprint, + decision: req.decision, + reviewer: req.reviewer, + occurred_at: req.occurred_at, + corpus_fingerprint, + context, + tags: req.tags, + note: req.note, + }); Ok(()) } /// The latest decision per chunk (core's projection; cluster context excluded). #[must_use] pub fn projected(&self) -> ProjectedCuration { - // STUB (red): empty, so the projection tests fail. - ProjectedCuration { - by_chunk: BTreeMap::new(), - } + project(&self.store.events) } /// Reconciles the session's decisions against the current corpus. @@ -104,26 +121,20 @@ impl CurationSession { /// # Errors /// [`FingerprintError`] if a current chunk cannot be fingerprinted. pub fn reconcile(&self, corpus: &[ChunkMeta]) -> Result { - // STUB (red): claims everything orphaned-free and unmatched, so the - // active/orphaned tests fail. - let _ = corpus; - Ok(ReconciledCuration { - active: Vec::new(), - orphaned: Vec::new(), - corpus_match: false, - }) + core_reconcile(&self.store, corpus) } /// The store, for the boundary to encode and persist. #[must_use] - pub fn store(&self) -> &CurationStoreV1 { + pub const fn store(&self) -> &CurationStoreV1 { &self.store } } -/// The cluster audit snapshot for `chunk_id`: its dedup cluster's representative -/// and all members (itself when it is a singleton). Never part of the decision's -/// identity — a navigation/audit fact only. +/// The cluster audit snapshot for `chunk_id`. +/// +/// Its dedup cluster's representative and all members (itself when it is a +/// singleton). Never part of the decision's identity — a navigation/audit fact. fn cluster_context(chunk_id: &ChunkId, corpus: &[ChunkMeta]) -> CurationContext { let (clusters, _diagnostics) = build_clusters(corpus); for cluster in &clusters { @@ -143,30 +154,65 @@ fn cluster_context(chunk_id: &ChunkId, corpus: &[ChunkMeta]) -> CurationContext } } -/// Mints an opaque decision-event id: an RFC-4122 **v4 UUID** from 16 -/// boundary-supplied random bytes. The randomness is the boundary's; this only -/// stamps the version (4) and variant (10) bits and the canonical hyphenated hex -/// layout, so the id is opaque, unique, and stable. +/// Mints an opaque decision-event id: an RFC-4122 **v4 UUID**. +/// +/// From 16 boundary-supplied random bytes — the randomness is the boundary's; +/// this only stamps the version (4) and variant (10) bits and the canonical +/// hyphenated hex layout, so the id is opaque, unique, and stable. #[must_use] pub fn mint_event_id(bytes: [u8; 16]) -> CurationEventId { - // STUB (red): returns a fixed non-UUID, so the format/uniqueness test fails. - let _ = bytes; - CurationEventId("stub".to_owned()) + let id = bytes + .iter() + .enumerate() + .map(|(i, &b)| match i { + 6 => (b & 0x0f) | 0x40, // version 4 + 8 => (b & 0x3f) | 0x80, // variant 10xx + _ => b, + }) + .enumerate() + .fold(String::with_capacity(36), |mut acc, (i, byte)| { + if matches!(i, 4 | 6 | 8 | 10) { + acc.push('-'); + } + // Writing hex into a String is infallible. + write!(acc, "{byte:02x}").ok(); + acc + }); + CurationEventId(id) } -/// Formats a Unix-epoch second count as the canonical `YYYY-MM-DDTHH:MM:SSZ` -/// timestamp the store requires — second precision, no fractional part (which +/// Formats a Unix-epoch second count as the canonical timestamp the store wants. +/// +/// `YYYY-MM-DDTHH:MM:SSZ` — second precision, no fractional part (which /// `curation_store` rejects). Howard Hinnant's civil-from-days, no `chrono`. #[must_use] +// Bounded civil-from-days: `epoch_secs` is clamped non-negative and every +// intermediate product stays well within i64 for any realistic year, so the +// arithmetic cannot overflow — the lint carries no signal here. +#[allow(clippy::arithmetic_side_effects)] pub fn canonical_timestamp(epoch_secs: i64) -> String { - // STUB (red): empty, so the timestamp tests fail. - let _ = epoch_secs; - String::new() + let secs = epoch_secs.max(0); + let (hh, mm, ss) = (secs / 3600 % 24, secs / 60 % 60, secs % 60); + let z = secs / 86_400 + 719_468; + let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}T{hh:02}:{mm:02}:{ss:02}Z") } #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)] + #![allow( + clippy::expect_used, + clippy::unwrap_used, + clippy::panic, + clippy::indexing_slicing + )] use super::{canonical_timestamp, mint_event_id, CurationSession, RecordError, RecordRequest}; use griff_core::corpus::{ @@ -215,9 +261,9 @@ mod tests { fn corpus() -> Vec { vec![ - chunk("c0", "hash0", None), - chunk("c1", "hash1", Some(0)), // c1 duplicates c0 → one cluster {c0,[c1]} - chunk("c2", "hash2", None), + chunk("a_p0", "hash0", None), + chunk("a_p1", "hash1", Some(0)), // a_p1 duplicates a_p0 → cluster {a_p0,[a_p1]} + chunk("a_p2", "hash2", None), ] } @@ -258,7 +304,7 @@ mod tests { session .record( request( - "c0", + "a_p0", "e1", "2026-07-19T10:00:00Z", ReviewerDecision::Accepted, @@ -269,7 +315,7 @@ mod tests { assert_eq!(session.store().events.len(), 1); let projected = session.projected(); assert_eq!( - decision(&projected.by_chunk[&ChunkId("c0".to_owned())]), + decision(&projected.by_chunk[&ChunkId("a_p0".to_owned())]), ReviewerDecision::Accepted, ); } @@ -281,7 +327,7 @@ mod tests { session .record( request( - "c0", + "a_p0", "e1", "2026-07-19T10:00:00Z", ReviewerDecision::Rejected, @@ -292,7 +338,7 @@ mod tests { session .record( request( - "c0", + "a_p0", "e2", "2026-07-19T11:00:00Z", ReviewerDecision::Accepted, @@ -306,7 +352,7 @@ mod tests { "two events, not a mutation" ); assert_eq!( - decision(&session.projected().by_chunk[&ChunkId("c0".to_owned())]), + decision(&session.projected().by_chunk[&ChunkId("a_p0".to_owned())]), ReviewerDecision::Accepted, "the later decision wins", ); @@ -319,7 +365,7 @@ mod tests { session .record( request( - "c0", + "a_p0", "e_a", "2026-07-19T10:00:00Z", ReviewerDecision::Rejected, @@ -330,7 +376,7 @@ mod tests { session .record( request( - "c0", + "a_p0", "e_z", "2026-07-19T10:00:00Z", ReviewerDecision::Accepted, @@ -339,7 +385,7 @@ mod tests { ) .expect("record z"); assert_eq!( - decision(&session.projected().by_chunk[&ChunkId("c0".to_owned())]), + decision(&session.projected().by_chunk[&ChunkId("a_p0".to_owned())]), ReviewerDecision::Accepted, "the greater event_id wins on an equal timestamp", ); @@ -352,7 +398,7 @@ mod tests { session .record( request( - "c1", + "a_p1", "e1", "2026-07-19T10:00:00Z", ReviewerDecision::Accepted, @@ -363,7 +409,7 @@ mod tests { let context = &session.store().events[0].context; assert_eq!( context.cluster_members, - vec![ChunkId("c0".to_owned()), ChunkId("c1".to_owned())], + vec![ChunkId("a_p0".to_owned()), ChunkId("a_p1".to_owned())], "the dedup cluster {{c0, c1}} is snapshotted as audit context", ); } @@ -375,7 +421,7 @@ mod tests { session .record( request( - "c1", + "a_p1", "e1", "2026-07-19T10:00:00Z", ReviewerDecision::Accepted, @@ -383,12 +429,12 @@ mod tests { &corpus, ) .expect("record"); - // The corpus regroups: c1 no longer duplicates c0 (its cluster changed), - // but its own material (sha/track/range) is unchanged. + // The corpus regroups: a_p1 no longer duplicates a_p0 (its cluster + // changed), but its own material (sha/track/range) is unchanged. let regrouped = vec![ - chunk_no_dup("c0", "hash0"), - chunk_no_dup("c1", "hash1"), - chunk_no_dup("c2", "hash2"), + chunk_no_dup("a_p0", "hash0"), + chunk_no_dup("a_p1", "hash1"), + chunk_no_dup("a_p2", "hash2"), ]; let reconciled = session.reconcile(®rouped).expect("reconcile"); assert_eq!(reconciled.active.len(), 1, "the decision stays active"); @@ -402,7 +448,7 @@ mod tests { session .record( request( - "c0", + "a_p0", "e1", "2026-07-19T10:00:00Z", ReviewerDecision::Accepted, @@ -410,8 +456,8 @@ mod tests { &corpus, ) .expect("record"); - // c0's material changes (new sha); c1/c2 gone. - let changed = vec![chunk_no_dup("c0", "DIFFERENT")]; + // a_p0's material changes (new sha); a_p1/a_p2 gone. + let changed = vec![chunk_no_dup("a_p0", "DIFFERENT")]; let reconciled = session.reconcile(&changed).expect("reconcile"); assert_eq!(reconciled.orphaned.len(), 1, "the changed chunk orphans it"); assert!(reconciled.active.is_empty()); @@ -456,10 +502,12 @@ mod tests { #[test] fn canonical_timestamp_is_second_precision_utc() { - // 2026-07-19T10:00:00Z = 1_784_282_400 seconds since the epoch. + // Two well-known anchors, so the assertion doesn't depend on my own + // epoch arithmetic: the epoch itself, and "one billion seconds". + assert_eq!(canonical_timestamp(0), "1970-01-01T00:00:00Z"); assert_eq!( - canonical_timestamp(1_784_282_400), - "2026-07-19T10:00:00Z", + canonical_timestamp(1_000_000_000), + "2001-09-09T01:46:40Z", "exact civil time, second precision, no fractional part", ); // A minted timestamp is accepted by the store (it round-trips through decode). @@ -467,9 +515,9 @@ mod tests { session .record( request( - "c0", + "a_p0", "e1", - &canonical_timestamp(1_784_282_400), + &canonical_timestamp(1_000_000_000), ReviewerDecision::Accepted, ), &corpus(), From c1f422b03e7c8f6de4ef4c46f419b6645720862d Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 08:43:06 +0500 Subject: [PATCH 3/4] =?UTF-8?q?test(ui-core):=20red=20=E2=80=94=20ordered?= =?UTF-8?q?=20event-id=20minting=20+=20fallible=20timestamp=20(3C-B1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Corrective for the PR #145 review. Two contract violations, as failing tests: 1. A random UUIDv4 does not order events. The store picks the latest decision by (occurred_at, event_id), so within one canonical second the event_id must decide — a bare UUID can invert two same-second clicks. Replace mint_event_id with a stateful EventIdMinter minting web-{ms:016x}-{seq:08x}-{uuid}: a Lamport-monotonic ordering prefix (UUID only the uniqueness tail), seeded from the loaded store. Tests: a later same-second mint sorts higher; a reload mints above the highest saved id; a clock rollback never lowers the id; mints are unique; the seed is order-independent. 2. canonical_timestamp silently clamped a bad clock to 1970 (max(0)). It now returns Result: a negative or out-of-range time is a typed refusal, never a normalised epoch lie. Also drops the false ADR-0030 §8 citation (that ADR is reduced-state DP, not curation identity). Stubs keep the old behavior, so the four causal tests fail. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- ui-core/src/curation_session.rs | 238 ++++++++++++++++++++++++++------ 1 file changed, 197 insertions(+), 41 deletions(-) diff --git a/ui-core/src/curation_session.rs b/ui-core/src/curation_session.rs index a1d197d0..581e5b7f 100644 --- a/ui-core/src/curation_session.rs +++ b/ui-core/src/curation_session.rs @@ -4,15 +4,15 @@ //! domain model: it holds the append-only store for one editing session, assembles //! a [`CurationEvent`] from a decision plus the corpus (fingerprints and the //! cluster audit snapshot), and projects/reconciles through core. **No I/O and no -//! UI** — a frontend supplies the opaque `event_id` and canonical `occurred_at` -//! (minted here from a boundary-provided random seed and clock), drives -//! [`CurationSession::record`], then persists [`CurationSession::store`] through -//! the OPFS/native adapter. +//! UI** — a frontend mints the `event_id` and canonical `occurred_at` (see +//! [`EventIdMinter`] / [`canonical_timestamp`]) from a boundary clock and random +//! seed, drives [`CurationSession::record`], then persists +//! [`CurationSession::store`] through the OPFS/native adapter. //! //! A decision is always **appended**, keyed by [`ChunkId`]; nothing is mutated in //! place. Cluster context is an audit snapshot on the event, never part of the -//! decision's identity (ADR-0030 §8): a regrouped cluster does not move a -//! decision. That invariant lives in core's `reconcile`; this layer only feeds it. +//! decision's identity: a regrouped cluster does not move a decision — the +//! invariant `curation_store::reconcile` enforces and this layer only feeds. use std::fmt::Write as _; @@ -154,14 +154,61 @@ fn cluster_context(chunk_id: &ChunkId, corpus: &[ChunkMeta]) -> CurationContext } } -/// Mints an opaque decision-event id: an RFC-4122 **v4 UUID**. +/// A stateful, **order-preserving** minter for decision-event ids. /// -/// From 16 boundary-supplied random bytes — the randomness is the boundary's; -/// this only stamps the version (4) and variant (10) bits and the canonical -/// hyphenated hex layout, so the id is opaque, unique, and stable. -#[must_use] -pub fn mint_event_id(bytes: [u8; 16]) -> CurationEventId { - let id = bytes +/// The store's projection picks the latest decision per chunk by `(occurred_at, +/// event_id)`, so within one canonical second the `event_id` must decide — and a +/// bare random UUID does not: two clicks in the same second could invert. Each +/// minted id therefore leads with a monotonic ordering prefix, +/// `web-{ms:016x}-{seq:08x}-{uuid}`, and the UUID is only the uniqueness tail: +/// +/// - a later mint in the same second sorts **above** the previous one; +/// - after a reload, [`EventIdMinter::from_store`] seeds the prefix above every +/// id already saved, so the first new event outranks them; +/// - the prefix is a Lamport clock (`max(now, high-water)`), so a **clock +/// rollback never lowers it**; +/// - the tail keeps every id unique. +#[derive(Debug, Clone)] +pub struct EventIdMinter { + /// The highest millisecond issued so far — never decreases. + high_water_ms: u64, + /// The sub-counter within `high_water_ms`, so equal/rolled-back clocks still + /// advance. + seq: u32, +} + +impl EventIdMinter { + /// Seeds the minter above every id already in `store`, so the next mint sorts + /// above all saved decisions regardless of their order in the store. + #[must_use] + pub fn from_store(store: &CurationStoreV1) -> Self { + // STUB (red): ignores the store, so the reload test fails. + let _ = store; + Self { + high_water_ms: 0, + seq: 0, + } + } + + /// Mints the next ordered, unique id from the boundary clock (`now_ms`) and a + /// random seed. + pub fn mint(&mut self, now_ms: u64, random: [u8; 16]) -> CurationEventId { + // STUB (red): a constant prefix that ignores the clock and never advances, + // so the ordering/rollback tests fail. + let _ = now_ms; + let uuid = uuid_v4(random); + CurationEventId(format!( + "web-{:016x}-{:08x}-{uuid}", + self.high_water_ms, self.seq + )) + } +} + +/// Formats 16 random bytes as an RFC-4122 **v4 UUID** — the uniqueness tail of a +/// minted id. Stamps the version (4) and variant (10) bits and the canonical +/// hyphenated hex layout. +fn uuid_v4(bytes: [u8; 16]) -> String { + bytes .iter() .enumerate() .map(|(i, &b)| match i { @@ -177,24 +224,38 @@ pub fn mint_event_id(bytes: [u8; 16]) -> CurationEventId { // Writing hex into a String is infallible. write!(acc, "{byte:02x}").ok(); acc - }); - CurationEventId(id) + }) +} + +/// Why a clock reading could not become a canonical timestamp. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TimestampError { + /// The clock reported a time before the Unix epoch. A failing or misconfigured + /// clock is a typed refusal, never a normalised `1970-01-01T00:00:00Z`. + BeforeEpoch { epoch_secs: i64 }, + /// The time falls outside the representable four-digit civil-year range. + OutOfRange { epoch_secs: i64 }, } /// Formats a Unix-epoch second count as the canonical timestamp the store wants. /// /// `YYYY-MM-DDTHH:MM:SSZ` — second precision, no fractional part (which /// `curation_store` rejects). Howard Hinnant's civil-from-days, no `chrono`. -#[must_use] -// Bounded civil-from-days: `epoch_secs` is clamped non-negative and every -// intermediate product stays well within i64 for any realistic year, so the -// arithmetic cannot overflow — the lint carries no signal here. +/// +/// # Errors +/// [`TimestampError::BeforeEpoch`] for a negative time; [`TimestampError::OutOfRange`] +/// for a year outside `0000..=9999`. A bad clock is refused, not silently made 1970. +// Bounded civil-from-days: `epoch_secs` is non-negative here and every +// intermediate product stays well within i64 for any representable year, so the +// arithmetic cannot overflow — the lint carries no signal. #[allow(clippy::arithmetic_side_effects)] -pub fn canonical_timestamp(epoch_secs: i64) -> String { +pub fn canonical_timestamp(epoch_secs: i64) -> Result { + // STUB (red): clamps a bad clock to the epoch instead of refusing it, so the + // negative-time test fails. let secs = epoch_secs.max(0); let (hh, mm, ss) = (secs / 3600 % 24, secs / 60 % 60, secs % 60); let z = secs / 86_400 + 719_468; - let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097; + let era = z / 146_097; let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); @@ -202,7 +263,9 @@ pub fn canonical_timestamp(epoch_secs: i64) -> String { let day = doy - (153 * mp + 2) / 5 + 1; let month = if mp < 10 { mp + 3 } else { mp - 9 }; let year = yoe + era * 400 + i64::from(month <= 2); - format!("{year:04}-{month:02}-{day:02}T{hh:02}:{mm:02}:{ss:02}Z") + Ok(format!( + "{year:04}-{month:02}-{day:02}T{hh:02}:{mm:02}:{ss:02}Z" + )) } #[cfg(test)] @@ -214,13 +277,17 @@ mod tests { clippy::indexing_slicing )] - use super::{canonical_timestamp, mint_event_id, CurationSession, RecordError, RecordRequest}; + use super::{ + canonical_timestamp, CurationSession, EventIdMinter, RecordError, RecordRequest, + TimestampError, + }; use griff_core::corpus::{ ChunkId, ChunkMeta, ReviewerDecision, SourceFormat, SourceRef, SCHEMA_VERSION, }; use griff_core::curation_store::{ - corpus_fingerprint, decode_store, encode_store, CurationEventId, ProjectedDecision, - ReviewerId, + corpus_fingerprint, decode_store, encode_store, ChunkFingerprint, CorpusFingerprint, + CurationContext, CurationEvent, CurationEventId, CurationStoreV1, ProjectedDecision, + ReviewerId, CURATION_STORE_VERSION, }; use griff_core::novelty::PhraseDuplicate; @@ -482,31 +549,71 @@ mod tests { } #[test] - fn mint_event_id_is_a_canonical_v4_uuid() { - let id = mint_event_id([0xab; 16]).0; - assert_eq!(id.len(), 36, "8-4-4-4-12 hex with hyphens"); - let dashes: Vec = id.match_indices('-').map(|(i, _)| i).collect(); - assert_eq!( - dashes, - vec![8, 13, 18, 23], - "hyphens in the canonical spots" + fn a_later_mint_in_the_same_second_sorts_higher() { + let mut minter = EventIdMinter::from_store(&empty_store()); + // The second seed's UUID sorts *below* the first's, so a random-only id + // would invert — the ordering prefix must win. + let first = minter.mint(1_000, [0xff; 16]).0; + let second = minter.mint(1_000, [0x00; 16]).0; + assert!( + second > first, + "the later click sorts higher: {second} > {first}" + ); + } + + #[test] + fn a_reload_mints_above_the_highest_saved_id() { + let saved = oid(0x1_0000, 5); + let mut minter = EventIdMinter::from_store(&store_with_ids(&[&saved])); + // Even with a tiny clock, the reloaded minter continues above the saved id. + let next = minter.mint(1, [0; 16]).0; + assert!( + next > saved, + "the reloaded minter outranks the saved id: {next} > {saved}" ); - assert_eq!(id.as_bytes()[14], b'4', "version nibble is 4"); + } + + #[test] + fn a_clock_rollback_does_not_lower_the_id() { + let mut minter = EventIdMinter::from_store(&empty_store()); + let first = minter.mint(1_000, [0; 16]).0; + // The clock jumps backwards; the next id must still sort higher. + let second = minter.mint(500, [0; 16]).0; assert!( - matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'), - "variant nibble is 8..b", + second > first, + "a rolled-back clock never lowers the id: {second} > {first}" ); - // Different seeds mint different ids. - assert_ne!(mint_event_id([1; 16]).0, mint_event_id([2; 16]).0); + } + + #[test] + fn mints_are_unique() { + let mut minter = EventIdMinter::from_store(&empty_store()); + let ids: Vec = (0..8).map(|i| minter.mint(1_000, [i; 16]).0).collect(); + let mut sorted = ids.clone(); + sorted.sort(); + sorted.dedup(); + assert_eq!(sorted.len(), ids.len(), "every minted id is unique"); + } + + #[test] + fn from_store_is_independent_of_event_order() { + let forward = store_with_ids(&[&oid(1, 1), &oid(2, 2)]); + let reversed = store_with_ids(&[&oid(2, 2), &oid(1, 1)]); + let a = EventIdMinter::from_store(&forward).mint(0, [0; 16]).0; + let b = EventIdMinter::from_store(&reversed).mint(0, [0; 16]).0; + assert_eq!(a, b, "the seed is a max over events, not order-dependent"); } #[test] fn canonical_timestamp_is_second_precision_utc() { // Two well-known anchors, so the assertion doesn't depend on my own // epoch arithmetic: the epoch itself, and "one billion seconds". - assert_eq!(canonical_timestamp(0), "1970-01-01T00:00:00Z"); assert_eq!( - canonical_timestamp(1_000_000_000), + canonical_timestamp(0).expect("epoch"), + "1970-01-01T00:00:00Z" + ); + assert_eq!( + canonical_timestamp(1_000_000_000).expect("1e9"), "2001-09-09T01:46:40Z", "exact civil time, second precision, no fractional part", ); @@ -517,7 +624,7 @@ mod tests { request( "a_p0", "e1", - &canonical_timestamp(1_000_000_000), + &canonical_timestamp(1_000_000_000).expect("1e9"), ReviewerDecision::Accepted, ), &corpus(), @@ -526,8 +633,57 @@ mod tests { decode_store(&encode_store(session.store()).expect("encode")).expect("minted ts is valid"); } + #[test] + fn a_bad_clock_is_a_typed_error_not_a_1970_lie() { + assert_eq!( + canonical_timestamp(-1), + Err(TimestampError::BeforeEpoch { epoch_secs: -1 }), + "a negative clock is refused, never normalised to the epoch", + ); + // A time past the four-digit-year range is also refused. + assert!(matches!( + canonical_timestamp(i64::MAX), + Err(TimestampError::OutOfRange { .. }) + )); + } + /// A pinned chunk with no duplicate link. fn chunk_no_dup(id: &str, sha: &str) -> ChunkMeta { chunk(id, sha, None) } + + /// A web-format ordering id with the given prefix and a fixed UUID tail. + fn oid(ms: u64, seq: u32) -> String { + format!("web-{ms:016x}-{seq:08x}-00000000-0000-4000-8000-000000000000") + } + + fn empty_store() -> CurationStoreV1 { + store_with_ids(&[]) + } + + fn store_with_ids(ids: &[&str]) -> CurationStoreV1 { + CurationStoreV1 { + version: CURATION_STORE_VERSION, + corpus_fingerprint: CorpusFingerprint("corpus".to_owned()), + events: ids.iter().map(|id| event_with_id(id)).collect(), + } + } + + fn event_with_id(id: &str) -> CurationEvent { + CurationEvent { + event_id: CurationEventId(id.to_owned()), + chunk_id: ChunkId("a_p0".to_owned()), + chunk_fingerprint: ChunkFingerprint("fp".to_owned()), + decision: ReviewerDecision::Accepted, + reviewer: ReviewerId("alice".to_owned()), + occurred_at: "2001-09-09T01:46:40Z".to_owned(), + corpus_fingerprint: CorpusFingerprint("corpus".to_owned()), + context: CurationContext { + cluster_representative: ChunkId("a_p0".to_owned()), + cluster_members: vec![ChunkId("a_p0".to_owned())], + }, + tags: Vec::new(), + note: None, + } + } } From 224ea92a76ebfbf132f833e128c70c90af7a2319 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 08:45:36 +0500 Subject: [PATCH 4/4] =?UTF-8?q?fix(ui-core):=20green=20=E2=80=94=20Lamport?= =?UTF-8?q?-ordered=20event=20ids=20+=20fallible=20timestamp=20(3C-B1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve the two PR #145 correctives; all 15 curation_session tests pass. - EventIdMinter mints web-{ms:016x}-{seq:08x}-{uuid}. from_store seeds the high-water from the max (ms, seq) parsed over the store's ids (order- independent). mint is a Lamport clock: it advances the millisecond when the boundary clock moves forward, otherwise bumps the sub-counter — so a later same-second click, a reload, and even a rolled-back clock all sort strictly higher, while the UUID tail keeps ids unique. The projection's (occurred_at, event_id) tie-break is now causal, not a coin flip. - canonical_timestamp returns Result: a negative time is BeforeEpoch and a year outside 0000..=9999 is OutOfRange — a bad clock is a typed refusal, never a normalised 1970 lie. EventIdMinter is intentionally not Copy (a mutable accumulator); TimestampError is a plain Copy value. The false ADR-0030 citation is gone. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- ui-core/src/curation_session.rs | 53 ++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/ui-core/src/curation_session.rs b/ui-core/src/curation_session.rs index 581e5b7f..18a4e714 100644 --- a/ui-core/src/curation_session.rs +++ b/ui-core/src/curation_session.rs @@ -27,7 +27,7 @@ use griff_core::curation_store::{ /// One decision to record. /// /// The opaque `event_id` and canonical `occurred_at` come from the boundary -/// (mint with [`mint_event_id`] / [`canonical_timestamp`]); the fingerprints and +/// (mint with [`EventIdMinter`] / [`canonical_timestamp`]); the fingerprints and /// cluster context are derived from the corpus by [`CurationSession::record`]. #[derive(Debug, Clone)] pub struct RecordRequest { @@ -168,6 +168,9 @@ fn cluster_context(chunk_id: &ChunkId, corpus: &[ChunkMeta]) -> CurationContext /// - the prefix is a Lamport clock (`max(now, high-water)`), so a **clock /// rollback never lowers it**; /// - the tail keeps every id unique. +// Deliberately not `Copy`: it is a mutable accumulator, and a silent copy would +// fork the high-water counter and let two "minters" issue colliding orders. +#[allow(missing_copy_implementations)] #[derive(Debug, Clone)] pub struct EventIdMinter { /// The highest millisecond issued so far — never decreases. @@ -182,20 +185,27 @@ impl EventIdMinter { /// above all saved decisions regardless of their order in the store. #[must_use] pub fn from_store(store: &CurationStoreV1) -> Self { - // STUB (red): ignores the store, so the reload test fails. - let _ = store; - Self { - high_water_ms: 0, - seq: 0, - } + // The seed is a max over every parseable id — order-independent. + let (high_water_ms, seq) = store + .events + .iter() + .filter_map(|event| parse_order(&event.event_id.0)) + .max() + .unwrap_or((0, 0)); + Self { high_water_ms, seq } } /// Mints the next ordered, unique id from the boundary clock (`now_ms`) and a /// random seed. pub fn mint(&mut self, now_ms: u64, random: [u8; 16]) -> CurationEventId { - // STUB (red): a constant prefix that ignores the clock and never advances, - // so the ordering/rollback tests fail. - let _ = now_ms; + // Lamport clock: advance the millisecond when it moves forward, otherwise + // bump the sub-counter, so an equal or rolled-back clock still increases. + if now_ms > self.high_water_ms { + self.high_water_ms = now_ms; + self.seq = 0; + } else { + self.seq = self.seq.saturating_add(1); + } let uuid = uuid_v4(random); CurationEventId(format!( "web-{:016x}-{:08x}-{uuid}", @@ -204,6 +214,17 @@ impl EventIdMinter { } } +/// Parses the `(ms, seq)` ordering prefix of a `web-{ms:016x}-{seq:08x}-…` id. +/// `None` for any id not in that form — it simply does not seed the high-water. +fn parse_order(id: &str) -> Option<(u64, u32)> { + let rest = id.strip_prefix("web-")?; + let (ms_hex, rest) = rest.split_once('-')?; + let (seq_hex, _) = rest.split_once('-')?; + let ms = u64::from_str_radix(ms_hex, 16).ok()?; + let seq = u32::from_str_radix(seq_hex, 16).ok()?; + Some((ms, seq)) +} + /// Formats 16 random bytes as an RFC-4122 **v4 UUID** — the uniqueness tail of a /// minted id. Stamps the version (4) and variant (10) bits and the canonical /// hyphenated hex layout. @@ -228,7 +249,7 @@ fn uuid_v4(bytes: [u8; 16]) -> String { } /// Why a clock reading could not become a canonical timestamp. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TimestampError { /// The clock reported a time before the Unix epoch. A failing or misconfigured /// clock is a typed refusal, never a normalised `1970-01-01T00:00:00Z`. @@ -250,9 +271,10 @@ pub enum TimestampError { // arithmetic cannot overflow — the lint carries no signal. #[allow(clippy::arithmetic_side_effects)] pub fn canonical_timestamp(epoch_secs: i64) -> Result { - // STUB (red): clamps a bad clock to the epoch instead of refusing it, so the - // negative-time test fails. - let secs = epoch_secs.max(0); + if epoch_secs < 0 { + return Err(TimestampError::BeforeEpoch { epoch_secs }); + } + let secs = epoch_secs; let (hh, mm, ss) = (secs / 3600 % 24, secs / 60 % 60, secs % 60); let z = secs / 86_400 + 719_468; let era = z / 146_097; @@ -263,6 +285,9 @@ pub fn canonical_timestamp(epoch_secs: i64) -> Result { let day = doy - (153 * mp + 2) / 5 + 1; let month = if mp < 10 { mp + 3 } else { mp - 9 }; let year = yoe + era * 400 + i64::from(month <= 2); + if !(0..=9999).contains(&year) { + return Err(TimestampError::OutOfRange { epoch_secs }); + } Ok(format!( "{year:04}-{month:02}-{day:02}T{hh:02}:{mm:02}:{ss:02}Z" ))