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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/engine-local-date-time.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 8 additions & 2 deletions runtime/crates/conformance/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("");
Expand All @@ -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));
Expand Down
39 changes: 24 additions & 15 deletions runtime/crates/core/src/cel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: Send + Sync>() {}
Expand Down
105 changes: 103 additions & 2 deletions runtime/crates/core/src/cel/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NamedZone>,
) -> Option<Self> {
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 {
Expand All @@ -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<Self> {
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<Timestamp> {
// 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<Duration, TimeError> {
if nanos.abs() > i128::from(MAX_DURATION_SECONDS) * NANOS {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down
8 changes: 8 additions & 0 deletions runtime/crates/core/src/cel/time/tzdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NamedZone, TimeError> {
Expand Down
70 changes: 38 additions & 32 deletions runtime/crates/core/src/cel/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>, 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<super::time::NamedZone>,
date_time: &dyn Fn(&[&str]) -> Option<crate::jsonschema::DateTimeFormats>,
) -> 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
Expand Down
Loading
Loading