diff --git a/changelog.d/engine-local-date-time.md b/changelog.d/engine-local-date-time.md new file mode 100644 index 000000000..65eaaaedd --- /dev/null +++ b/changelog.d/engine-local-date-time.md @@ -0,0 +1,3 @@ +## Added + +- The runtime validates `format: local-date-time` and uses the collection’s `settings.timezone` to compare and sort floating date-times alongside instants. Collections without a zone keep floating values as strings and report a `timezone_required` warning. diff --git a/runtime/crates/conformance/src/ops.rs b/runtime/crates/conformance/src/ops.rs index 2c1bdb82c..49100f605 100644 --- a/runtime/crates/conformance/src/ops.rs +++ b/runtime/crates/conformance/src/ops.rs @@ -252,7 +252,7 @@ fn detect_moves(input: &Value) -> Value { } fn evaluate_cel(group: Group<'_>, input: &Value) -> Value { - use mdbn_core::cel::{Activation, CelValue, compile, record_activation}; + use mdbn_core::cel::{Activation, CelValue, compile}; use mdbn_core::state::StateView; let path = input["path"].as_str().unwrap_or(""); let source = group.setup["files"][path].as_str().unwrap_or(""); @@ -274,7 +274,13 @@ fn evaluate_cel(group: Group<'_>, input: &Value) -> Value { let values = catalog.record_values(path, &types, doc.frontmatter()); let effective = catalog.effective_frontmatter(&types, &values); let file = links.file_value(path, doc.frontmatter(), doc.body()); - record_activation(&values, &effective, CelValue::from_value(&file)) + catalog.record_activation( + &types, + path, + &values, + &effective, + CelValue::from_value(&file), + ) }; act.with_links(&links); act.with_clock(captured_clock(input)); diff --git a/runtime/crates/core/src/cel/mod.rs b/runtime/crates/core/src/cel/mod.rs index dfa189752..fd3d9fd88 100644 --- a/runtime/crates/core/src/cel/mod.rs +++ b/runtime/crates/core/src/cel/mod.rs @@ -168,29 +168,38 @@ pub fn record_activation<'a>(raw: &Map, effective: &Map, file: CelValue) -> Acti }, _ => None, }; + let map = |fields| { + let map = value::map_from(fields); + match path.as_deref() { + Some(path) => map.with_origin(path), + None => map, + } + }; + bind_record(map(raw), map(effective), file, path.as_deref()) +} + +pub(crate) fn bind_record<'a>( + raw: CelMap, + effective: CelMap, + file: CelValue, + path: Option<&str>, +) -> Activation<'a> { let mut act = Activation::new(); - for (k, v) in effective.iter() { - act.bind(k, CelValue::from_value(v)); + for (key, value) in effective.iter() { + if let Key::String(name) = key { + act.bind(name.to_string(), value.clone()); + } } - act.bind("record", record_map(effective, path.as_deref())) - .bind("raw", record_map(raw, path.as_deref())) + act.bind("record", CelValue::Map(std::sync::Arc::new(effective))) + .bind("raw", CelValue::Map(std::sync::Arc::new(raw))) .bind("file", file) .unbound_as_null(); - if let Some(p) = &path { - act.with_record_path(p); + if let Some(path) = path { + act.with_record_path(path); } act } -pub(crate) fn record_map(fields: &Map, path: Option<&str>) -> CelValue { - let map = value::map_from(fields); - let map = match path { - Some(path) => map.with_origin(path), - None => map, - }; - CelValue::Map(std::sync::Arc::new(map)) -} - // Compiled programs are cached and shared across threads by hosts. const _: () = { const fn assert_send_sync() {} diff --git a/runtime/crates/core/src/cel/time.rs b/runtime/crates/core/src/cel/time.rs index 9fce3140b..47633ea65 100644 --- a/runtime/crates/core/src/cel/time.rs +++ b/runtime/crates/core/src/cel/time.rs @@ -148,6 +148,24 @@ impl Timestamp { Timestamp::checked(secs, nanos) } + /// Resolve a record date-time using only the durable collection zone. + pub(crate) fn from_record( + s: &str, + accepts_offset: bool, + zone: Option, + ) -> Option { + if let Some(zone) = zone + && let Some(local) = LocalDateTime::parse(s) + { + return local.resolve(zone); + } + if accepts_offset { + Self::parse(s).ok() + } else { + None + } + } + /// RFC 3339 in UTC with `Z`, fractional seconds only as needed (CEL's /// `string(timestamp)`). pub fn to_rfc3339(self) -> String { @@ -172,6 +190,70 @@ impl Timestamp { } } +/// Calendar and clock fields before a time zone assigns them an instant. +pub(crate) struct LocalDateTime { + wall_seconds: i64, + nanos: u32, +} + +impl LocalDateTime { + pub(crate) fn parse(s: &str) -> Option { + if !s.is_ascii() || s.as_bytes().get(10) != Some(&b'T') { + return None; + } + let (year, month, day) = parse_full_date(&s[..10])?; + let clock = s.get(11..)?; + let (hours, minutes) = (num(clock.get(..2)?)?, num(clock.get(3..5)?)?); + if clock.as_bytes().get(2) != Some(&b':') || hours > 23 || minutes > 59 { + return None; + } + let (mut seconds, mut nanos) = (0, 0); + if !clock[5..].is_empty() { + let rest = clock[5..].strip_prefix(':')?; + seconds = num(rest.get(..2)?)?; + if seconds > 59 { + return None; + } + if !rest[2..].is_empty() { + let fraction = rest[2..].strip_prefix('.')?; + if fraction.is_empty() || !fraction.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + // CEL timestamps retain the first nine fractional digits. + for (digit, place) in fraction.bytes().zip((0..9).rev()) { + nanos += u32::from(digit - b'0') * 10_u32.pow(place); + } + } + } + Some(Self { + wall_seconds: days_from_civil(year, month, day) * 86_400 + + hours * 3600 + + minutes * 60 + + seconds, + nanos, + }) + } + + fn resolve(self, zone: NamedZone) -> Option { + // IANA offsets are bounded by one day. Sample either side of the + // local time as in Temporal's compatible disambiguation. + let before = zone.offset_at(self.wall_seconds - 86_400); + let after = zone.offset_at(self.wall_seconds + 86_400); + let with_before = self.wall_seconds - i64::from(before); + let with_after = self.wall_seconds - i64::from(after); + // At an overlap both are valid; with_before is earlier. In a gap + // neither is valid; with_before advances the clock by the full gap. + let seconds = if before == after || zone.offset_at(with_before) == before { + with_before + } else if zone.offset_at(with_after) == after { + with_after + } else { + with_before + }; + Timestamp::checked(seconds, self.nanos).ok() + } +} + impl Duration { fn checked(nanos: i128) -> Result { if nanos.abs() > i128::from(MAX_DURATION_SECONDS) * NANOS { @@ -320,12 +402,17 @@ pub(crate) fn civil_from_days(z: i64) -> (i64, i64, i64) { /// `YYYY-MM-DD` with a valid day. pub(crate) fn parse_date(s: &str) -> Option<(i64, i64, i64)> { + parse_full_date(s).filter(|(year, _, _)| *year >= 1) +} + +/// RFC 3339 full-date (the grammar also admits year 0000). +pub(crate) fn parse_full_date(s: &str) -> Option<(i64, i64, i64)> { let b = s.as_bytes(); - if b.len() != 10 || b[4] != b'-' || b[7] != b'-' { + if !s.is_ascii() || b.len() != 10 || b[4] != b'-' || b[7] != b'-' { return None; } let (y, m, d) = (num(&s[0..4])?, num(&s[5..7])?, num(&s[8..10])?); - (y >= 1 && (1..=12).contains(&m) && (1..=days_in_month(y, m)).contains(&d)).then_some((y, m, d)) + ((1..=12).contains(&m) && (1..=days_in_month(y, m)).contains(&d)).then_some((y, m, d)) } pub(crate) fn format_date(y: i64, m: i64, d: i64) -> String { @@ -798,6 +885,20 @@ fn rule(p: &mut &str) -> Option<(DayRule, i32)> { mod tests { use super::*; + #[test] + fn floating_clock_disambiguation_uses_the_transition_length() { + let zone = Some(NamedZone::get("Australia/Lord_Howe").unwrap()); + for (local, instant) in [ + ("2026-10-04T02:15:03.25", "2026-10-03T15:45:03.25Z"), + ("2026-04-05T01:45", "2026-04-04T14:45:00Z"), + ] { + assert_eq!( + Timestamp::from_record(local, false, zone), + Timestamp::parse(instant).ok() + ); + } + } + #[test] fn timestamps() { let t = Timestamp::parse("2026-06-20T00:00:00Z").unwrap(); diff --git a/runtime/crates/core/src/cel/time/tzdb.rs b/runtime/crates/core/src/cel/time/tzdb.rs index ec2b3aaaf..e21147cbe 100644 --- a/runtime/crates/core/src/cel/time/tzdb.rs +++ b/runtime/crates/core/src/cel/time/tzdb.rs @@ -52,6 +52,14 @@ pub struct NamedZone { name: &'static str, } +impl PartialEq for NamedZone { + fn eq(&self, other: &Self) -> bool { + self.name == other.name + } +} + +impl Eq for NamedZone {} + impl NamedZone { /// Look up a named IANA zone in the release pinned by this build's semantics. pub fn get(name: &str) -> Result { diff --git a/runtime/crates/core/src/cel/value.rs b/runtime/crates/core/src/cel/value.rs index 68526c9d4..b3121c984 100644 --- a/runtime/crates/core/src/cel/value.rs +++ b/runtime/crates/core/src/cel/value.rs @@ -208,43 +208,49 @@ impl CelValue { } } - /// Convert a frontmatter value, typing date-times (spec 10 "Temporal - /// Values"): a string at a location for which `date_time` returns true - /// becomes a timestamp when it is a valid RFC 3339 date-time, and stays a - /// string otherwise. A location is the list of object keys from the root, - /// with `"[]"` for an array item. The caller decides the locations from - /// the matched schemas (`format: date-time` in every matched schema). + /// Bind RFC 3339 instants at schema-declared date-time locations. pub fn from_value_typed(v: &Value, date_time: &dyn Fn(&[&str]) -> bool) -> CelValue { - fn go(v: &Value, at: &mut Vec, date_time: &dyn Fn(&[&str]) -> bool) -> CelValue { - match v { - Value::Text(s) => { - let loc: Vec<&str> = at.iter().map(String::as_str).collect(); - if date_time(&loc) - && let Ok(t) = super::time::Timestamp::parse(s) - { - return CelValue::Timestamp(t); - } - CelValue::string(s) - } - Value::List(l) => { - at.push("[]".to_owned()); - let items = l.iter().map(|x| go(x, at, date_time)).collect(); + Self::from_value_at(v, &mut Vec::new(), None, &|loc| { + date_time(loc).then_some(crate::jsonschema::DateTimeFormats::BOTH) + }) + } + + /// Bind instants and floating clock times at schema-declared locations. + pub(crate) fn from_value_at<'a>( + v: &'a Value, + at: &mut Vec<&'a str>, + zone: Option, + date_time: &dyn Fn(&[&str]) -> Option, + ) -> CelValue { + match v { + Value::Text(s) => date_time(at) + .and_then(|formats| { + Timestamp::from_record(s, formats.offset, zone.filter(|_| formats.local)) + }) + .map_or_else(|| Self::string(s), Self::Timestamp), + Value::List(items) => { + at.push("[]"); + let items = items + .iter() + .map(|v| Self::from_value_at(v, at, zone, date_time)) + .collect(); + at.pop(); + Self::List(Arc::new(items)) + } + Value::Map(fields) => { + let mut out = CelMap::new(); + for (key, value) in fields.iter() { + at.push(key); + out.insert( + Key::String(key.into()), + Self::from_value_at(value, at, zone, date_time), + ); at.pop(); - CelValue::List(Arc::new(items)) - } - Value::Map(m) => { - let mut out = CelMap::new(); - for (k, x) in m.iter() { - at.push(k.to_owned()); - out.insert(Key::String(Arc::from(k)), go(x, at, date_time)); - at.pop(); - } - CelValue::Map(Arc::new(out)) } - other => CelValue::from_value(other), + Self::Map(Arc::new(out)) } + other => Self::from_value(other), } - go(v, &mut Vec::new(), date_time) } /// Convert to a frontmatter value, where the data model can hold it diff --git a/runtime/crates/core/src/jsonschema.rs b/runtime/crates/core/src/jsonschema.rs index 13019146e..803f43c9e 100644 --- a/runtime/crates/core/src/jsonschema.rs +++ b/runtime/crates/core/src/jsonschema.rs @@ -16,8 +16,8 @@ //! - `pattern` and `patternProperties` use the mdbase regex profile: the //! `regex-lite` engine, unanchored. `\p{..}`, `\P{..}`, backreferences and //! look-around make the schema invalid (`invalid_pattern`). -//! - `format` asserts `date`, `time` and `date-time` (RFC 3339; offsets are -//! required). Other formats are annotations. +//! - `format` asserts RFC 3339 `date`, `time`, and `date-time`, plus the +//! offset-free mdbase `local-date-time`. Other formats are annotations. //! - Only fragment references (`#`, `#/...`) resolve. HTTP(S) references are //! `schema_ref_forbidden`; anything else is `schema_ref_unresolved`. Cycles //! that apply a schema to the same instance again (through `$ref` and the @@ -144,6 +144,36 @@ enum Format { Date, Time, DateTime, + LocalDateTime, +} + +/// The date-time spellings admitted at a typed location. Each matched schema +/// narrows this set, while branches in an eligible union expand it. +#[derive(Clone, Copy, Default)] +pub(crate) struct DateTimeFormats { + pub offset: bool, + pub local: bool, +} + +impl DateTimeFormats { + pub const BOTH: Self = Self { + offset: true, + local: true, + }; + + pub fn intersect(self, other: Self) -> Self { + Self { + offset: self.offset && other.offset, + local: self.local && other.local, + } + } + + fn for_format(format: Format) -> Self { + Self { + offset: format == Format::DateTime, + local: format == Format::LocalDateTime, + } + } } #[derive(Debug, Clone)] @@ -436,6 +466,7 @@ impl Compiler<'_> { k.format = match m.get("format").and_then(Value::as_str) { Some("date") => Some(Format::Date), Some("time") => Some(Format::Time), + Some("local-date-time") => Some(Format::LocalDateTime), Some("date-time") => Some(Format::DateTime), _ => None, }; @@ -661,7 +692,7 @@ fn percent_decode(s: &str) -> Option { } /// Escape a key as an RFC 6901 token. -fn escape(key: &str) -> String { +pub(crate) fn escape(key: &str) -> String { key.replace('~', "~0").replace('/', "~1") } @@ -689,6 +720,94 @@ fn resolve_pointer<'v>(doc: &'v Value, pointer: &str) -> Option<&'v Value> { } impl CompiledSchema { + /// Keywords at this node and along its locally resolved reference chain. + /// Compilation has already rejected in-place reference cycles. + fn referenced(&self, node: u32) -> impl Iterator { + let keywords = |node| match &self.nodes[idx(node)].kind { + NodeKind::Schema(k) => Some(k.as_ref()), + NodeKind::Bool(_) => None, + }; + std::iter::successors(keywords(node), move |k| k.reference.and_then(keywords)) + } + + /// A branch of a date-time union must explicitly declare a string and + /// a date-time format. Reference siblings constrain the same instance. + fn union_branch_formats(&self, node: u32) -> Option { + let mut string = false; + let mut formats = None; + for k in self.referenced(node) { + if let Some(types) = &k.types { + if types.as_slice() != [JsonType::String] { + return None; + } + string = true; + } + if let Some(format) = k.format { + if !matches!(format, Format::DateTime | Format::LocalDateTime) { + return None; + } + let current = DateTimeFormats::for_format(format); + formats = Some(formats.unwrap_or(DateTimeFormats::BOTH).intersect(current)); + } + } + formats.filter(|_| string) + } + + /// Only properties and items introduce typed child locations. All declarations + /// reached via local references apply together, including reference siblings. + pub(crate) fn date_time_formats(&self, location: &[&str]) -> Option { + let mut nodes = vec![self.entry]; + for key in location { + let mut children: Vec<_> = nodes + .iter() + .flat_map(|&node| self.referenced(node)) + .filter_map(|k| { + if *key == "[]" { + k.items + } else { + k.properties + .iter() + .find(|(name, _)| name == key) + .map(|(_, id)| *id) + } + }) + .collect(); + if children.is_empty() { + return None; + } + children.sort_unstable(); + children.dedup(); + nodes = children; + } + let mut eligible = false; + let mut common = DateTimeFormats::BOTH; + for k in nodes.into_iter().flat_map(|node| self.referenced(node)) { + if let Some(format) = k.format { + eligible |= matches!(format, Format::DateTime | Format::LocalDateTime); + common = common.intersect(DateTimeFormats::for_format(format)); + } + for branches in [&k.any_of, &k.one_of] { + if branches.is_empty() { + continue; + } + let formats = + branches + .iter() + .try_fold(DateTimeFormats::default(), |mut union, &id| { + let branch = self.union_branch_formats(id)?; + union.offset |= branch.offset; + union.local |= branch.local; + Some(union) + }); + if let Some(formats) = formats { + eligible = true; + common = common.intersect(formats); + } + } + } + eligible.then_some(common) + } + /// Validate `instance`. Empty means valid. See the module docs for the /// issue order. pub fn validate(&self, instance: &Value) -> Vec { @@ -907,20 +1026,22 @@ impl CompiledSchema { let ok = match f { Format::Date => is_date(s), Format::Time => is_time(s), + Format::LocalDateTime => crate::cel::time::LocalDateTime::parse(s).is_some(), Format::DateTime => is_date_time(s), }; if !ok { let name = match f { - Format::Date => "date", - Format::Time => "time", - Format::DateTime => "date-time", + Format::Date => "RFC 3339 date", + Format::Time => "RFC 3339 time", + Format::LocalDateTime => "local-date-time", + Format::DateTime => "RFC 3339 date-time", }; out.push(SchemaIssue { code: "format_invalid".into(), keyword: "format", instance_path: path.to_owned(), schema_path: at("format"), - message: format!("not a valid RFC 3339 {name}"), + message: format!("not a valid {name}"), }); } } @@ -1247,35 +1368,16 @@ fn digits(s: &str) -> Option { s.parse().ok() } -fn days_in_month(year: u32, month: u32) -> u32 { - match month { - 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, - 4 | 6 | 9 | 11 => 30, - 2 if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) => { - 29 - } - 2 => 28, - _ => 0, - } -} - -/// RFC 3339 `full-date`: `YYYY-MM-DD`. +/// RFC 3339 full-date. fn is_date(s: &str) -> bool { - let b = s.as_bytes(); - if b.len() != 10 || b[4] != b'-' || b[7] != b'-' { - return false; - } - let (Some(y), Some(m), Some(d)) = (digits(&s[..4]), digits(&s[5..7]), digits(&s[8..])) else { - return false; - }; - (1..=12).contains(&m) && d >= 1 && d <= days_in_month(y, m) + crate::cel::time::parse_full_date(s).is_some() } /// RFC 3339 `full-time`: `HH:MM:SS[.frac](Z|±HH:MM)`. A leap second (`:60`) /// is valid only at 23:59 UTC. fn is_time(s: &str) -> bool { let b = s.as_bytes(); - if b.len() < 9 || b[2] != b':' || b[5] != b':' { + if !s.is_ascii() || b.len() < 9 || b[2] != b':' || b[5] != b':' { return false; } let (Some(h), Some(mi), Some(sec)) = (digits(&s[..2]), digits(&s[3..5]), digits(&s[6..8])) @@ -1357,6 +1459,61 @@ mod tests { (c.to_owned(), p.to_owned()) } + #[test] + fn local_clock_format_is_offset_free_and_calendar_checked() { + let schema = compile(&v("{type: string, format: local-date-time}"), "").unwrap(); + for clock in [ + "2026-11-27T08:00", + "2026-11-27T08:00:00", + "2024-02-29T23:59:59.01234567890", + ] { + assert!(schema.validate(&Value::string(clock)).is_empty(), "{clock}"); + } + for clock in [ + "2026-02-30T08:00", + "2025-02-29T08:00", + "2026-11-27T24:00", + "2026-11-27T08:60", + "2026-11-27T08:00:60", + "2026-11-27T08:00:00Z", + "2026-11-27T08:00:00+10:00", + "2026-11-27T08:00-04:00", + "2026-11-27 08:00", + "2026-11-27T08:00:00.", + "2026-11-27T08:00.5", + "2026-11-27T08:00:00.٥", + "2026-11-27", + ] { + assert_eq!( + schema.validate(&Value::string(clock))[0].code, + "format_invalid", + "{clock}" + ); + } + } + + #[test] + fn reference_siblings_narrow_date_time_spellings_at_the_same_field() { + let schema = compile( + &v(r##" +$defs: + event: + properties: + at: {type: string, format: date-time} +$ref: '#/$defs/event' +properties: + at: {type: string, format: local-date-time} +"##), + "", + ) + .unwrap(); + let formats = schema.date_time_formats(&["at"]).unwrap(); + assert!(!formats.local && !formats.offset); + for value in ["2026-11-01T01:30", "2026-11-01T01:30:00Z"] { + assert_eq!(schema.validate(&v(&format!("at: '{value}'"))).len(), 1); + } + } + #[test] fn types() { assert!(ok("type: integer", "3")); diff --git a/runtime/crates/core/src/lifecycle.rs b/runtime/crates/core/src/lifecycle.rs index e4946074f..8dceaa506 100644 --- a/runtime/crates/core/src/lifecycle.rs +++ b/runtime/crates/core/src/lifecycle.rs @@ -239,13 +239,6 @@ fn guard_passes( path: &str, clock: &OpClock, ) -> Result { - let previous = ctx.previous; - // Date-time fields bind as timestamps (spec 10), in the draft and `old`. - let typed = |m: &Map| { - CelValue::from_value_typed(&Value::Map(m.clone()), &|loc: &[&str]| { - ctx.catalog.is_date_time(ctx.types, loc) - }) - }; use crate::cel::{self, CelValue}; let fail = |message: String| LifecycleError { code: "lifecycle_expression_error".into(), @@ -258,18 +251,14 @@ fn guard_passes( .into_iter() .collect(), )); - let mut act = cel::record_activation(draft, draft, file); - if let CelValue::Map(m) = typed(draft) { - for (k, v) in m.iter() { - if let cel::Key::String(name) = k { - act.bind(name.to_string(), v.clone()); - } - } - act.bind("record", CelValue::Map(m.clone())); - act.bind("raw", CelValue::Map(m)); - } + let mut act = ctx + .catalog + .record_activation(ctx.types, path, draft, draft, file); act.with_clock(cel_clock(clock.instant_ms, &clock.local_date, &clock.tz)); - act.bind("old", typed(&previous.cloned().unwrap_or_default())); + let old = ctx.previous.map_or_else(cel::CelMap::new, |m| { + ctx.catalog.cel_record(ctx.types, path, m) + }); + act.bind("old", CelValue::Map(std::sync::Arc::new(old))); act.bind( "operation", CelValue::from_value(&Value::Map( diff --git a/runtime/crates/core/src/links.rs b/runtime/crates/core/src/links.rs index 972e16194..6da978faf 100644 --- a/runtime/crates/core/src/links.rs +++ b/runtime/crates/core/src/links.rs @@ -1098,21 +1098,24 @@ impl<'a> CelLinks<'a> { let doc = Document::parse_at(&rec.path, &*rec.source); let fm = doc.frontmatter(); let types = self.catalog.membership(&rec.path, fm).types; - let effective = self.catalog.effective_values(&rec.path, &types, fm); + let values = self.catalog.record_values(&rec.path, &types, fm); + let effective = self.catalog.effective_frontmatter(&types, &values); let mut m = CelMap::new().with_origin(&rec.path); let key = |s: &str| Key::String(std::sync::Arc::from(s)); + let effective = std::sync::Arc::new(self.catalog.cel_record(&types, &rec.path, &effective)); + m.insert(key("record"), CelValue::Map(effective.clone())); m.insert( - key("record"), - crate::cel::record_map(&effective, Some(&rec.path)), + key("raw"), + CelValue::Map(std::sync::Arc::new( + self.catalog.cel_record(&types, &rec.path, &values), + )), ); - let values = self.catalog.record_values(&rec.path, &types, fm); - m.insert(key("raw"), crate::cel::record_map(&values, Some(&rec.path))); m.insert( key("file"), CelValue::from_value(&self.file_value(&rec.path, &values, doc.body())), ); for (k, v) in effective.iter() { - m.insert(key(k), CelValue::from_value(v)); + m.insert(k.clone(), v.clone()); } Some(CelValue::Map(std::sync::Arc::new(m))) } diff --git a/runtime/crates/core/src/plan/contract_records/tests.rs b/runtime/crates/core/src/plan/contract_records/tests.rs index 3a4e0e6d4..b870944a8 100644 --- a/runtime/crates/core/src/plan/contract_records/tests.rs +++ b/runtime/crates/core/src/plan/contract_records/tests.rs @@ -250,3 +250,38 @@ fn promote_types_an_untyped_record_in_the_same_write() { .unwrap_err(); assert_eq!(err.reason.as_deref(), Some("data_contract_promote_typed")); } + +#[test] +fn contract_read_and_write_keep_local_date_time_fields_verbatim() { + let ty = type_source("card"); + let local = "2026-11-27T08:00"; + for annotation in [ + "{type: string, format: local-date-time}", + "{anyOf: [{type: string, format: date-time}, {type: string, format: local-date-time}]}", + ] { + let contract = CONTRACT.replace("name: {type: string}", &format!("name: {annotation}")); + let catalog = Catalog::load([ + ("mdbase.yaml", "spec_version: '0.3.0'"), + ("_contracts/card.md", &contract), + ("_types/card.md", &ty), + ]); + let doc = DOC.replace("label: Old", &format!("label: '{local}'")); + let floating = RecordSource { + path: "a.md", + source: &doc, + }; + let view = contract_record(&catalog, &selector(None), floating).unwrap(); + assert_eq!(view.fields.get("name"), Some(&Value::string(local))); + assert!( + contract_write( + &catalog, + &selector(None), + Some(floating), + &fields("{done: true}"), + &[] + ) + .is_ok() + ); + assert!(contract_record(&catalog, &selector(None), record()).is_err()); + } +} diff --git a/runtime/crates/core/src/query/indexed.rs b/runtime/crates/core/src/query/indexed.rs index 53fae3d25..61a530beb 100644 --- a/runtime/crates/core/src/query/indexed.rs +++ b/runtime/crates/core/src/query/indexed.rs @@ -57,6 +57,25 @@ pub enum TemporalHint { Date, /// Valid RFC 3339 date-time with an offset. DateTime, + /// A date-time location whose floating values resolve in this collection zone. + ZonedDateTime { + /// Durable zone for floating values. + zone: crate::cel::time::NamedZone, + /// Every matched schema also admits the offset spelling. + accepts_offset: bool, + }, +} + +impl TemporalHint { + /// Stable annotation stored alongside an atom. The zone is already bound + /// by the generation and the atom contains the resolved instant. + pub fn code(self) -> u8 { + match self { + Self::None => 0, + Self::Date => 1, + Self::DateTime | Self::ZonedDateTime { .. } => 2, + } + } } /// A compact, lossless SQL BLOB order key. Its Rust ordering is the SQL oracle. @@ -348,40 +367,36 @@ impl IndexFieldSpec { /// A hint is present only when every matched type is known and declares the /// same unambiguous date/date-time format. Stores do not call this themselves. pub fn temporal_hint(catalog: &Catalog, types: &[String], path: &[String]) -> TemporalHint { - schemas_temporal_hint( - types.iter().map(|name| { - catalog - .type_named(name) - .map(|t| (&t.schema_document, t.schema_entry.as_str())) - }), - path, - ) -} - -pub(crate) fn schemas_temporal_hint<'a>( - schemas: impl Iterator>, - path: &[String], -) -> TemporalHint { let location: Vec<_> = path.iter().map(String::as_str).collect(); - let mut common = None; - for schema in schemas { - let Some((document, entry)) = schema else { - return TemporalHint::None; - }; - let format = crate::types::schema_at(document, entry, &location) - .and_then(|s| s.get("format")) - .and_then(Value::as_str); - let hint = match format { - Some("date") => TemporalHint::Date, - Some("date-time") => TemporalHint::DateTime, - _ => return TemporalHint::None, - }; - if common.is_some_and(|old| old != hint) { - return TemporalHint::None; + if let Some(formats) = catalog.date_time_formats(types, &location) { + if formats.local + && let Some(zone) = catalog.named_zone() + { + return TemporalHint::ZonedDateTime { + zone, + accepts_offset: formats.offset, + }; } - common = Some(hint); + return if formats.offset { + TemporalHint::DateTime + } else { + TemporalHint::None + }; + } + if !types.is_empty() + && types.iter().all(|name| { + catalog.type_named(name).is_some_and(|t| { + crate::types::schema_at(&t.schema_document, &t.schema_entry, &location) + .and_then(|s| s.get("format")) + .and_then(Value::as_str) + == Some("date") + }) + }) + { + TemporalHint::Date + } else { + TemporalHint::None } - common.unwrap_or(TemporalHint::None) } /// Project trusted top-level effective fields, with read defaults and per-record @@ -422,6 +437,10 @@ fn temporal_text(s: &str, hint: TemporalHint) -> Option { TemporalHint::Date if s.len() == 10 => Timestamp::parse(&format!("{s}T00:00:00Z")).ok(), TemporalHint::Date => None, TemporalHint::DateTime => Timestamp::parse(s).ok(), + TemporalHint::ZonedDateTime { + zone, + accepts_offset, + } => Timestamp::from_record(s, accepts_offset, Some(zone)), } } @@ -432,7 +451,7 @@ pub struct IndexGeneration { pub generation: u64, /// Confirmed log snapshot. pub head_seq: u64, - /// Catalog/schema/read-default fingerprint. + /// Catalog fingerprint including schemas, read defaults, and the collection timezone. pub catalog_hash: [u8; 32], /// Semantic version of the materialized keys. pub sem: [u32; 2], diff --git a/runtime/crates/core/src/query/lower.rs b/runtime/crates/core/src/query/lower.rs index a0cb63eb4..6d7d1d806 100644 --- a/runtime/crates/core/src/query/lower.rs +++ b/runtime/crates/core/src/query/lower.rs @@ -268,12 +268,10 @@ impl Lowerer<'_> { _ => return false, }; let location: Vec<_> = path.iter().map(String::as_str).collect(); - self.catalog.types().iter().any(|t| { - crate::types::schema_at(&t.schema_document, &t.schema_entry, &location) - .and_then(|s| s.get("format")) - .and_then(Value::as_str) - == Some("date-time") - }) + self.catalog + .types() + .iter() + .any(|t| t.schema.0.date_time_formats(&location).is_some()) } fn effective(&self, path: Vec) -> FieldRef { diff --git a/runtime/crates/core/src/query/mod.rs b/runtime/crates/core/src/query/mod.rs index c2fd080c8..c85e32f57 100644 --- a/runtime/crates/core/src/query/mod.rs +++ b/runtime/crates/core/src/query/mod.rs @@ -450,10 +450,6 @@ pub struct QueryPlan { pub read_defaults: Vec<(String, Map)>, /// Captured catalog for canonical persisted path values. pub value_catalog: crate::types::Catalog, - /// Matched-type schema documents and entry pointers, captured at compile - /// time for spec 10 date-time typing: (lower-case type name, document, entry). - /// Persisted and effective frontmatter remain unchanged. - pub date_time_schemas: Vec<(String, Value, String)>, /// The compiled `where`. pub where_program: Option, /// Named projections, in evaluation (dependency) order. @@ -679,17 +675,6 @@ pub fn compile(query: &Query, catalog: &Catalog) -> Result crate::cel::Activation<'a> { - use crate::cel::{CelValue, Key}; - let schemas: Vec<_> = record - .types - .iter() - .filter_map(|name| { - self.date_time_schemas - .iter() - .find(|(n, _, _)| *n == name.to_lowercase()) - }) - .collect(); - let typed = |m: &Map| { - let value = CelValue::from_value_typed(&Value::Map(m.clone()), &|location| { - !schemas.is_empty() - && schemas.len() == record.types.len() - && schemas.iter().all(|(_, document, entry)| { - crate::types::schema_at(document, entry, location) - .and_then(|s| s.get("format")) - .and_then(Value::as_str) - == Some("date-time") - }) - }); - match value { - CelValue::Map(m) => { - CelValue::Map(std::sync::Arc::new((*m).clone().with_origin(record.path))) - } - other => other, - } - }; let values = self.value_catalog .record_values(record.path, record.types, record.frontmatter); - let mut act = crate::cel::record_activation(&values, effective, file); - let effective = typed(effective); - if let CelValue::Map(m) = &effective { - for (key, value) in m.iter() { - if let Key::String(name) = key - && !matches!(&**name, "record" | "raw" | "file") - { - act.bind(name.to_string(), value.clone()); - } - } - } - act.bind("record", effective); - act.bind("raw", typed(&values)); - act + self.value_catalog + .record_activation(record.types, record.path, &values, effective, file) } /// The canonical residual: does `record` match `types` and `where`? @@ -1132,15 +1077,13 @@ impl QueryPlan { selections.get_str(&p[0]).cloned() } FieldRef::Effective(p) | FieldRef::Persisted(p) => { - Some(CelValue::from_value_typed(value, &|tail| { - let path: Vec<_> = p - .iter() - .cloned() - .chain(tail.iter().map(|s| (*s).to_owned())) - .collect(); - self.sort_hint(&FieldRef::Persisted(path), record.types) - == indexed::TemporalHint::DateTime - })) + let mut path = p.iter().map(String::as_str).collect(); + Some(CelValue::from_value_at( + value, + &mut path, + self.value_catalog.named_zone(), + &|location| self.value_catalog.date_time_formats(record.types, location), + )) } FieldRef::File(n) => match file_cel { CelValue::Map(m) => m.get_str(n).cloned(), @@ -1149,10 +1092,11 @@ impl QueryPlan { _ => None, } .unwrap_or_else(|| CelValue::from_value(value)); - let hint = if matches!(native, CelValue::Timestamp(_)) { - indexed::TemporalHint::DateTime - } else { - self.sort_hint(field, record.types) + let hint = match self.sort_hint(field, record.types) { + indexed::TemporalHint::None if matches!(native, CelValue::Timestamp(_)) => { + indexed::TemporalHint::DateTime + } + hint => hint, }; groups::Input::new(value, native, hint, budget) } @@ -1213,15 +1157,7 @@ impl QueryPlan { FieldRef::Effective(p) | FieldRef::Persisted(p) => p, _ => return indexed::TemporalHint::None, }; - indexed::schemas_temporal_hint( - types.iter().map(|name| { - self.date_time_schemas - .iter() - .find(|(n, _, _)| *n == name.to_lowercase()) - .map(|(_, document, entry)| (document, entry.as_str())) - }), - path, - ) + indexed::temporal_hint(&self.value_catalog, types, path) } /// The sort value of `field` for a record. diff --git a/runtime/crates/core/src/types.rs b/runtime/crates/core/src/types.rs index f0ddd3e8f..a64db0ba4 100644 --- a/runtime/crates/core/src/types.rs +++ b/runtime/crates/core/src/types.rs @@ -854,21 +854,75 @@ impl Catalog { self.effective_frontmatter(types, &self.record_values(path, types, raw)) } - /// Whether every one of `types` (at least one) declares `format: - /// date-time` for the frontmatter location `location` (object keys, `"[]"` - /// for an array item). CEL binds such strings as timestamps (spec 10 - /// "Temporal Values"; `cel::CelValue::from_value_typed`). + /// Whether every matched schema declares a date-time at this location. pub fn is_date_time(&self, types: &[String], location: &[&str]) -> bool { - let defs: Vec<&TypeDef> = types.iter().filter_map(|n| self.type_named(n)).collect(); - !defs.is_empty() - && defs.iter().all(|t| { - schema_at(&t.schema_document, &t.schema_entry, location) - .and_then(|s| s.get("format")) - .and_then(Value::as_str) - == Some("date-time") + self.date_time_formats(types, location).is_some() + } + + pub(crate) fn date_time_formats( + &self, + types: &[String], + location: &[&str], + ) -> Option { + if types.is_empty() { + return None; + } + types + .iter() + .try_fold(crate::jsonschema::DateTimeFormats::BOTH, |common, name| { + Some( + common.intersect( + self.type_named(name)? + .schema + .0 + .date_time_formats(location)?, + ), + ) }) } + /// Record values for CEL, retaining the origin for relative link resolution. + pub(crate) fn cel_record( + &self, + types: &[String], + path: &str, + fields: &Map, + ) -> crate::cel::CelMap { + let mut map = crate::cel::CelMap::new().with_origin(path); + let zone = self.named_zone(); + let mut location = Vec::new(); + for (key, value) in fields.iter() { + location.push(key); + let value = crate::cel::CelValue::from_value_at(value, &mut location, zone, &|loc| { + self.date_time_formats(types, loc) + }); + map.insert(crate::cel::Key::String(key.into()), value); + location.pop(); + } + map + } + + /// Bind a matched record in a CEL record context (Chapter 10). + pub fn record_activation<'a>( + &self, + types: &[String], + path: &str, + raw: &Map, + effective: &Map, + file: crate::cel::CelValue, + ) -> crate::cel::Activation<'a> { + crate::cel::bind_record( + self.cel_record(types, path, raw), + self.cel_record(types, path, effective), + file, + Some(path), + ) + } + + pub(crate) fn named_zone(&self) -> Option { + crate::cel::time::NamedZone::get(self.settings.timezone.as_deref()?).ok() + } + /// The types a record at `path` with persisted `frontmatter` matches /// (spec 07 "Matching Decision Process"). Nondeterministic match expressions /// invalidate their type at load and never participate in membership. diff --git a/runtime/crates/core/src/validate.rs b/runtime/crates/core/src/validate.rs index 8e6b0d982..419129f8a 100644 --- a/runtime/crates/core/src/validate.rs +++ b/runtime/crates/core/src/validate.rs @@ -122,6 +122,7 @@ pub fn validate_record_at( let mut out = membership.issues; let (values, path_issues) = catalog.record_values_with_issues(path, &membership.types, fm); out.extend(path_issues); + out.extend(timezone_warnings(catalog, &membership.types, &values)); let instance = Value::Map(values); for name in &membership.types { let Some(t) = catalog.type_named(name) else { @@ -142,6 +143,85 @@ pub fn validate_record_at( out } +/// Warning-only single-record diagnostics for floating values with no collection +/// zone. Read defaults participate because CEL binds effective metadata too. +pub fn timezone_warnings( + catalog: &Catalog, + types: &[String], + values: &crate::value::Map, +) -> Vec { + if catalog.settings().timezone.is_some() || types.is_empty() { + return Vec::new(); + } + fn visit<'a>( + v: &'a Value, + schema_path: &mut Vec<&'a str>, + pointer: &str, + catalog: &Catalog, + types: &[String], + out: &mut Vec, + ) { + match v { + Value::Text(s) + if crate::cel::time::LocalDateTime::parse(s).is_some() + && catalog + .date_time_formats(types, schema_path) + .is_some_and(|f| f.local) => + { + out.push( + Issue::new( + "timezone_required", + Severity::Warning, + Tier::SingleRecord, + "Set settings.timezone on the collection to resolve floating date-times.", + ) + .at(pointer), + ); + } + Value::Map(m) => { + for (key, child) in m.iter() { + schema_path.push(key); + visit( + child, + schema_path, + &format!("{pointer}/{}", crate::jsonschema::escape(key)), + catalog, + types, + out, + ); + schema_path.pop(); + } + } + Value::List(items) => { + schema_path.push("[]"); + for (index, child) in items.iter().enumerate() { + visit( + child, + schema_path, + &format!("{pointer}/{index}"), + catalog, + types, + out, + ); + } + schema_path.pop(); + } + _ => {} + } + } + let mut out = Vec::new(); + let effective = catalog.effective_frontmatter(types, values); + visit( + &Value::Map(effective), + &mut Vec::new(), + "", + catalog, + types, + &mut out, + ); + out +} + fn map1(k: &str, v: Value) -> Value { Value::Map([(k.to_owned(), v)].into_iter().collect()) } @@ -366,6 +446,7 @@ pub fn apply_level( Level::Off if !explicit_validate => Vec::new(), Level::Warn | Level::Off => issues .into_iter() + .filter(|i| level != Level::Off || i.code != "timezone_required") .map(|mut i| { i.severity = Severity::Warning; i diff --git a/runtime/crates/core/tests/plan.rs b/runtime/crates/core/tests/plan.rs index 803cf0148..ccd6a0fb0 100644 --- a/runtime/crates/core/tests/plan.rs +++ b/runtime/crates/core/tests/plan.rs @@ -693,3 +693,59 @@ fn resurrection_never_rejects_random_writes() { "only {rejected_at_head} head rejections exercised" ); } + +#[test] +fn floating_fields_warn_at_submit_without_rewriting_or_blocking_the_record() { + use mdbn_core::intent::Level; + use mdbn_core::validate::{self, Severity}; + let mut state = base_state(); + state.insert_resource("_types/task.md", &TASK.replace("title: {type: string}", + "title: {type: string}\n at: {type: array, items: {type: string, format: local-date-time}}")); + let local = "2026-11-27T08:00"; + let m = mutation(vec![Op::Create(Create { + id: id(10), + type_name: Some("task".into()), + frontmatter: patch(&[ + ("title", Value::string("New")), + ("at", Value::List(vec![Value::string(local)])), + ]), + ..Create::default() + })]); + for (level, label) in [ + (Level::Off, "off"), + (Level::Warn, "warn"), + (Level::Error, "error"), + ] { + state.insert_resource( + "mdbase.yaml", + &CONFIG.replace("validation: warn", &format!("validation: {label}")), + ); + let p = mdbn_core::plan( + &m, + &state, + &PlanOptions { + stage: Stage::Submit { level }, + }, + ) + .unwrap(); + let source = doc_of(&p, id(10)); + assert!(source.contains(local)); + assert!(source.contains("2026-01-01T00:00:00.000Z")); + let validated = validate::apply_level( + validate::validate_record(&state.catalog(), "tasks/New.md", &source), + level, + true, + ); + let submitted: Vec<_> = p.issues.iter().map(|r| r.issue.clone()).collect(); + for issues in [validated, submitted] { + if level == Level::Off { + assert!(issues.is_empty()); + } else { + assert_eq!(issues.len(), 1, "{issues:?}"); + assert_eq!(issues[0].code, "timezone_required"); + assert_eq!(issues[0].severity, Severity::Warning); + assert_eq!(issues[0].location.as_deref(), Some("/at/0")); + } + } + } +} diff --git a/runtime/crates/core/tests/query_index_execution.rs b/runtime/crates/core/tests/query_index_execution.rs index ac0a43e3e..93e7051a0 100644 --- a/runtime/crates/core/tests/query_index_execution.rs +++ b/runtime/crates/core/tests/query_index_execution.rs @@ -391,3 +391,161 @@ fn projected_temporal_type_lookup_matches_catalog_unicode_case_rules() { [projected[0].0.temporal] ); } + +#[test] +fn floating_times_share_instants_across_cel_sorting_and_index_projection() { + let schema = TASK.replace("at: {type: string, format: date-time}", r##"at: {anyOf: [{$ref: '#/$defs/instant'}, {$ref: '#/$defs/local'}]} + start: {oneOf: [{$ref: '#/$defs/local'}, {$ref: '#/$defs/instant'}]} + clock: {$ref: '#/$defs/local'} + due: {anyOf: [{type: string, format: date}, {$ref: '#/$defs/instant'}, {$ref: '#/$defs/local'}]} + nested: {type: array, items: {$ref: '#/$defs/local'}} + partial: {anyOf: [{type: string, format: date-time}, {format: local-date-time}]}"##) + .replace("collection:", r#" $defs: + instant: {type: string, format: date-time} + local: {type: string, format: local-date-time} +collection:"#); + for zone in [None, Some("America/New_York")] { + let mut config = "spec_version: '0.3.0'\n".to_owned(); + if let Some(zone) = zone { + config.push_str(&format!("settings: {{timezone: {zone}}}\n")); + } + let c = Catalog::load([ + ("mdbase.yaml", config.as_str()), + ("_types/task.md", schema.as_str()), + ("_types/other.md", OTHER), + ]); + assert!(c.is_valid(), "{:?}", c.issues()); + let types = vec!["task".into()]; + let local = "2026-11-01T01:30"; + // During the New York overlap this is 05:30Z (the earlier 01:30). + let mut fields = fm(Value::string(local)); + for key in ["clock", "start", "due", "partial"] { + fields.insert(key, Value::string(local)); + } + fields.insert( + "nested", + Value::List(vec![Value::string("2026-03-08T02:30:12.12345678987")]), + ); + let offset = fm(Value::string("2026-11-01T06:00:00Z")); + let a = QueryRecord { + path: "tasks/a.md", + types: &types, + frontmatter: &fields, + body: None, + mtime: None, + }; + let b = QueryRecord { + path: "tasks/b.md", + frontmatter: &offset, + ..a.clone() + }; + let expr = if zone.is_some() { + r#"at == timestamp("2026-11-01T05:30:00Z") && raw.at == at && start == at && clock == at && record.nested[0] == timestamp("2026-03-08T07:30:12.123456789Z")"# + } else { + r#"at == "2026-11-01T01:30" && raw.at == at && start == at && clock == at && record.nested[0] == "2026-03-08T02:30:12.12345678987""# + }; + let filter = format!("where: '{expr} && due == \"{local}\" && partial == due'"); + let plan = query::compile(&parse(&filter), &c).unwrap(); + assert_eq!(plan.matches(&a, &env()), query::Verdict::Match); + let types = vec!["task".into(), "other".into()]; + assert!(!c.is_date_time(&types, &["at"])); + assert_eq!( + c.effective_values(a.path, a.types, &fields).get("at"), + fields.get("at") + ); + + for key in ["at", "start", "clock"] { + let query = parse(&format!("where: 'raw.{key} != \"{local}\"'")); + let plan = query::compile(&query, &c).unwrap(); + assert_eq!(plan.candidate, query::Candidate::All); + assert!(!plan.exact); + } + let plan = query::compile(&parse("order_by: [{field: at}]"), &c).unwrap(); + let ae = plan.evaluate(&a, &env(), None); + let be = plan.evaluate(&b, &env(), None); + let expected = if zone.is_some() { + Ordering::Less + } else { + Ordering::Greater + }; + assert_eq!(plan.compare(&a, &b), expected); + assert_eq!( + plan.compare_evaluated((a.path, &ae), (b.path, &be)), + expected + ); + let atom = |r: &QueryRecord| { + indexed::project_index_fields(&c, r, &[FieldRef::Effective(vec!["at".into()])], 128) + .unwrap() + .remove(0) + .1 + }; + assert_eq!(atom(&a).cmp(&atom(&b)), expected); + assert_eq!( + atom(&a).kind(), + if zone.is_some() { + AtomKind::Temporal + } else { + AtomKind::Text + } + ); + } +} + +#[test] +fn a_spelling_rejected_by_any_matched_format_stays_text_without_a_zone_warning() { + use mdbn_core::validate::validate_record; + let local_only = TASK + .replace("name: task", "name: floating") + .replace("format: date-time", "format: local-date-time"); + for zone in ["", "settings: {timezone: America/New_York}"] { + let config = format!("spec_version: '0.3.0'\n{zone}\n"); + let c = Catalog::load([ + ("mdbase.yaml", config.as_str()), + ("_types/task.md", TASK), + ("_types/floating.md", local_only.as_str()), + ]); + for (types, text) in [ + (vec!["task".to_owned()], "2026-11-01T01:30"), + (vec!["floating".to_owned()], "2026-11-01T06:00:00Z"), + ( + vec!["task".to_owned(), "floating".to_owned()], + "2026-11-01T01:30", + ), + ( + vec!["task".to_owned(), "floating".to_owned()], + "2026-11-01T06:00:00Z", + ), + ] { + let source = format!("---\ntype: [{}]\nat: '{text}'\n---\n", types.join(", ")); + let issues = validate_record(&c, "tasks/a.md", &source); + assert_eq!( + issues.iter().map(|i| i.code.as_str()).collect::>(), + ["format_invalid"] + ); + let fields = fm(Value::string(text)); + let r = QueryRecord { + path: "tasks/a.md", + types: &types, + frontmatter: &fields, + body: None, + mtime: None, + }; + let plan = query::compile( + &parse(&format!( + "where: 'at == \"{text}\"'\norder_by: [{{field: at}}]" + )), + &c, + ) + .unwrap(); + assert_eq!(plan.matches(&r, &env()), query::Verdict::Match); + let key = indexed::project_index_fields( + &c, + &r, + &[FieldRef::Effective(vec!["at".into()])], + 128, + ) + .unwrap(); + assert_eq!(key[0].1.kind(), AtomKind::Text); + } + } +} diff --git a/runtime/crates/mdbase/tests/collection.rs b/runtime/crates/mdbase/tests/collection.rs index 4778fa526..98e378b85 100644 --- a/runtime/crates/mdbase/tests/collection.rs +++ b/runtime/crates/mdbase/tests/collection.rs @@ -342,3 +342,68 @@ fn second_host_is_refused() { drop(col); let _ = std::fs::remove_dir_all(&root); } + +#[test] +fn changing_only_the_zone_reorders_existing_records_and_preserves_floating_values() { + let root = dir("floating-times"); + std::fs::create_dir_all(root.join("_types")).unwrap(); + let config = "spec_version: '0.3.0'\nsettings:\n validation: error\n"; + std::fs::write(root.join("mdbase.yaml"), config).unwrap(); + std::fs::write(root.join("_types/task.md"), TASK_TYPE.replace( + "{ type: string, format: date }", + "{ anyOf: [{type: string, format: date-time}, {type: string, format: local-date-time}] }", + )).unwrap(); + let col = Collection::open(&root).unwrap(); + let create = |name: &str, due: &str| { + col.create( + Create::at(format!("tasks/{name}.md")) + .field("type", "task") + .field("title", name) + .field("status", "open") + .field("due", due), + ) + .unwrap() + }; + let local = "2026-11-01T01:30"; + let floating = create("floating", local); + let offset = create("offset", "2026-11-01T06:00:00Z"); + let updated = col + .update(Update::at(&floating).set("title", "Updated")) + .unwrap(); + let read = col.get("tasks/floating.md").unwrap().unwrap(); + for issues in [ + &floating.issues, + &updated.issues, + &read.issues, + &col.validate_one(&floating).unwrap(), + ] { + assert_eq!(issues.len(), 1, "{issues:?}"); + assert_eq!(issues[0].code, "timezone_required"); + } + assert!(offset.issues.is_empty()); + let order = || { + col.query(Query::of_type("task").order_by("due", Order::Asc)) + .unwrap() + .records + .into_iter() + .map(|r| r.id) + .collect::>() + }; + assert_eq!(order(), [offset.id, floating.id]); + for (zone, expected) in [ + ("America/New_York", [floating.id, offset.id]), + ("America/Los_Angeles", [offset.id, floating.id]), + ] { + std::fs::write( + root.join("mdbase.yaml"), + format!("{config} timezone: {zone}\n"), + ) + .unwrap(); + col.rescan().unwrap(); + assert_eq!(order(), expected); + let read = col.get("tasks/floating.md").unwrap().unwrap(); + assert!(read.issues.is_empty()); + assert_eq!(read.revision, updated.revision); + assert_eq!(read.get("due"), Some(&json!(local))); + } +} diff --git a/runtime/crates/replica/src/plan.rs b/runtime/crates/replica/src/plan.rs index 89d38f7df..9154e1445 100644 --- a/runtime/crates/replica/src/plan.rs +++ b/runtime/crates/replica/src/plan.rs @@ -283,8 +283,10 @@ fn project_record_fields( /// The projection algorithm identity, independent of log position and key codec. /// Bump whenever membership/default/atom projection semantics change. -/// Version 4 adds the `file.mtime` index atom. -pub const QUERY_PROJECTION_VERSION: u64 = 4; +/// Version 5 resolves floating date-time atoms in the collection zone. +/// The resource digest below includes the complete mdbase.yaml, so changing +/// settings.timezone invalidates rows even when no schema changes. +pub const QUERY_PROJECTION_VERSION: u64 = 5; /// Convert the supported configured fields to neutral store identities, preserving /// declared order. Duplicate or unsupported fields fail, never silently deduplicate. @@ -419,7 +421,7 @@ fn project_query_row( .zip(declarations.iter().cloned()) .map(|((spec, atom), field)| QueryFieldValue { field, - temporal_hint: spec.temporal as u8, + temporal_hint: spec.temporal.code(), atom: QueryAtom { kind: atom.kind() as u8, key: atom.key().to_vec(), diff --git a/runtime/crates/replica/src/replica/submit.rs b/runtime/crates/replica/src/replica/submit.rs index 74be5e0a9..a8682b0a6 100644 --- a/runtime/crates/replica/src/replica/submit.rs +++ b/runtime/crates/replica/src/replica/submit.rs @@ -23,26 +23,23 @@ pub(crate) fn rejection_problem(r: &mdbn_core::plan::Rejection) -> mdbn_wire::cl // Problem.issues is the submitted-record diagnostic envelope. Global // catalog issues need a separately authorized describe/diagnostics route. if code == ErrorCode::InvalidRecord && !r.issues.is_empty() { - p.issues = Some( - r.issues - .iter() - .map(|issue| mdbn_wire::client::Issue { - code: issue.code.clone(), - severity: match issue.severity { - mdbn_core::validate::Severity::Error => mdbn_wire::client::Severity::Error, - mdbn_core::validate::Severity::Warning => { - mdbn_wire::client::Severity::Warning - } - }, - message: issue.message.clone(), - details: issue_details(issue), - }) - .collect(), - ); + p.issues = Some(r.issues.iter().map(wire_issue).collect()); } p } +fn wire_issue(issue: &mdbn_core::validate::Issue) -> mdbn_wire::client::Issue { + mdbn_wire::client::Issue { + code: issue.code.clone(), + severity: match issue.severity { + mdbn_core::validate::Severity::Error => mdbn_wire::client::Severity::Error, + mdbn_core::validate::Severity::Warning => mdbn_wire::client::Severity::Warning, + }, + message: issue.message.clone(), + details: issue_details(issue), + } +} + fn issue_details(issue: &mdbn_core::validate::Issue) -> Option { let location = issue.location.as_deref().filter(|loc| !loc.is_empty()); let type_name = issue.type_name.as_deref().filter(|name| !name.is_empty()); @@ -707,6 +704,14 @@ pub(crate) fn parsed_record_view( include: &Include, ) -> RecordView { let values = catalog.record_values(path, &types, doc.frontmatter()); + let diagnostics = if include.diagnostics == Some(true) + && catalog.settings().validation != mdbn_core::intent::Level::Off + { + let issues = mdbn_core::validate::timezone_warnings(catalog, &types, &values); + (!issues.is_empty()).then(|| issues.iter().map(wire_issue).collect()) + } else { + None + }; RecordView { id: *id, path: path.to_string(), @@ -740,7 +745,7 @@ pub(crate) fn parsed_record_view( hold: None, unresolved: None, }, - diagnostics: None, + diagnostics, values: None, mtime, } diff --git a/runtime/crates/replica/tests/query_index_projection.rs b/runtime/crates/replica/tests/query_index_projection.rs index b21813897..bfa660175 100644 --- a/runtime/crates/replica/tests/query_index_projection.rs +++ b/runtime/crates/replica/tests/query_index_projection.rs @@ -145,7 +145,7 @@ fn neutral_index_row_contains_actual_path_types_and_all_declared_fields() { assert_eq!(projected.fields[0].atom.kind, 2); assert_eq!( projected.fields[1].temporal_hint, - TemporalHint::DateTime as u8 + TemporalHint::DateTime.code() ); assert_eq!(projected.fields[2].atom.kind, 255); assert!(project_record_query_index_row(&c, &r, &[field("at"), field("at")], 256).is_err()); @@ -373,11 +373,11 @@ fn declared_profile_uses_compiled_ref_allof_properties_and_exact_top_level_names #[test] fn empty_generation_frame_binds_key_codec_and_projection_algorithm_versions() { - // Independent frame oracle: key codec 2, projection algorithm 4, SEM 1.1, no resources + // Independent frame oracle: key codec 2, projection algorithm 5, SEM 1.1, no resources // or declared fields. This is a SHA frame test, not an authorization witness. let mut frame = b"mdbase/v1/query-index-generation\0".to_vec(); frame.push(2); - for word in [4u64, 1, 1, 0, 0] { + for word in [5u64, 1, 1, 0, 0] { frame.extend_from_slice(&word.to_be_bytes()); } assert_eq!( @@ -450,3 +450,31 @@ fn rows_carry_the_body_index_text_unless_the_capture_leaves_bodies_out() { ); assert!(captured.without_body().project_row(&r).is_ok()); } + +#[test] +fn zone_change_invalidates_rows_and_reprojects_the_same_floating_bytes() { + let task = TASK.replace("format: date-time", "format: local-date-time"); + let capture = |zone| { + let config = format!("spec_version: '0.3.0'\nsettings: {{timezone: {zone}}}\n"); + let resources = [ + ("mdbase.yaml".into(), config), + ("_types/task.md".into(), task.clone()), + ]; + QueryProjectionContext::capture( + &resources, + mdbn_wire::common::Version { major: 1, minor: 1 }, + &[field("at")], + 256, + ) + .unwrap() + }; + let eastern = capture("America/New_York"); + let utc = capture("UTC"); + assert_ne!(eastern.generation(), utc.generation()); + let record = row("tasks/a.md", "---\nat: '2026-11-01T01:30'\n---\n"); + let new_key = utc.project_row(&record).unwrap().fields.remove(0); + let old_key = eastern.project_row(&record).unwrap().fields.remove(0); + assert_eq!(old_key.temporal_hint, new_key.temporal_hint); + assert_eq!(old_key.atom.kind, 3); + assert_ne!(old_key.atom, new_key.atom); +} diff --git a/runtime/packages/sdk/scripts/runtime-methods.json b/runtime/packages/sdk/scripts/runtime-methods.json index 389d02af0..e2c01a7eb 100644 --- a/runtime/packages/sdk/scripts/runtime-methods.json +++ b/runtime/packages/sdk/scripts/runtime-methods.json @@ -1,6 +1,6 @@ { "source": { - "commit": "d4087ec97ff6923651f62216c3f2392b440b5812", + "commit": "10cb483f38b359d22c8d90892b99361381590050", "path": "runtime/crates/replica/src/frames.rs" }, "methods": [ diff --git a/runtime/packages/sdk/src/application/asset-pins.json b/runtime/packages/sdk/src/application/asset-pins.json index 91e6c86fb..ee643fc9a 100644 --- a/runtime/packages/sdk/src/application/asset-pins.json +++ b/runtime/packages/sdk/src/application/asset-pins.json @@ -1,11 +1,11 @@ { "runtime": { - "sha256": "23e1a12bc4fab4c62077c35592701f4305a5176e4aba5a33acab30171a047438", - "bytes": 4063591, - "maxBytes": 4063591, + "sha256": "87dbf3a587668ef2238aee243b1ab904c34845a40c0e39373371d3932d80fd9e", + "bytes": 4070902, + "maxBytes": 4070902, "source": { "repository": "mdbase-dev/mdbase-connect", - "commit": "d4087ec97ff6923651f62216c3f2392b440b5812" + "commit": "10cb483f38b359d22c8d90892b99361381590050" } }, "sqlite": {