8000 fix(deps): replace chrono with strict built-in UTC timestamps (#900) by adityamukho · Pull Request #922 · project-minigraf/minigraf · GitHub
[go: up one dir, main page]

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
2 changes: 2 additions & 0 deletions CHANGELOG.md
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **Strict UTC timestamps (v3.0.0 behaviour change, #900)**: removed the unmaintained `chrono` dependency (RUSTSEC-2026-0543) without a replacement crate. Accept only `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM:SSZ`, or `YYYY-MM-DDTHH:MM:SS.fZ` with 1–9 ASCII fractional digits, truncated to milliseconds (also before 1970), and years 0000–9999. Newly rejected with INT-004: lowercase `z`, the `UTC` suffix, any whitespace, single-digit fields, one- or two-digit years, negative years, leap seconds, more than nine fractional digits, empty fractions and comma fractions. Offsets, lowercase `t`, missing seconds, five-digit years, invalid calendar/clock fields, non-ASCII digits and trailing characters remain rejected. Formatting keeps whole-second UTC output and returns INT-005 outside the same year range.

- **v3 binary-size CI budget**: raise the enforced distribution-binary limit from 1,240 to 1,250 KiB (1,280,000 bytes). Unchanged production source measured 1,242 KiB after CI moved to Rust 1.100.0 and a newer runner image; the additional headroom changes no production code or build settings.

- **INT-001 text** (#824): `a WriteTransaction is already in progress on this thread; use tx.execute() instead` now reads `a write transaction is already in progress on this thread; use tx.execute() instead`, since owned and browser transactions raise it too. The code and the calls that raise it for a borrowed transaction are unchanged.
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ cargo run < demos/demo_negation.txt

3a. **`src/query/engine/`** — Streaming query engine (#473), runs every query (#551): `plan.rs` (the operator tree of every query, or the executor's error code for it: patterns, expression clauses, `not`/`not-join` and `or`/`or-join`, and rule invocations, read as patterns of their relations (`plan_rules`, #548; a magic-set head constant is `HeadArg::Const`), in `optimizer::plan` order, then the `or`s in text order, then the deferred `not`s; an `or` branch or a `not` body is planned as a `:where` is; a clause list with no pattern first starts from `Seed`; a constant no cell equals is `Term::Never`, a scan that reads nothing; `:as-of` resolved when the query opens (`Snapshot::tx_bound`: a counter bound when `tx_id` rises with `tx_count`, else `TxBound::Timestamp`: committed `tx_count` ranges and pending `tx_id <= t`); a per-fact pseudo-attribute pattern reads the metadata column its source's scan fills (the hidden variable the parser named, #594), and `:db/valid-at` joins as `[e _ _]`; plain `:find` variables, aggregates with `:with`, and window functions, over an aggregate's groups too), `scan.rs` (one pattern over committed key ranges via `CommittedReader::key_source`/`live_keys`, AVET ranges for cross-kind constants, then the pending range by whole runs; one entity per probe for a join), `join.rs` (`IndexNestedLoopJoin` when the pattern's entity is bound, or, under a constant attribute and entity not constant, its value (#721: per outer row the AVET ranges of the values that join-equal it and the attribute's pending facts with its key, read once per query in `IdSpace::probes`; an entity cell needs the keyword naming it, known only where the query made the entity from a keyword (rule heads, magic seeds), else the join becomes the planner's `HashJoin`); `HashJoin` otherwise, and on a relation; `JoinKey`: floats by IEEE `==`, a keyword equals a ref to the entity it names), `filter.rs` (`Filter`/`Bind` and pseudo-attribute steps over batches; a `Bind` on a bound slot keeps the rows where the result is join-equal, #596), `collect.rs` (`CollectSet`, #316: `[(collect-set ?e :a) ?s]` per row probes `[e :a ?v]` as an `IndexNestedLoopJoin` does and binds the values as one set, `#{}` when none, metered; `Expr::CollectSet`, parsed only as a whole binding clause), `anti.rs` (`AntiJoin`, #546: a body with the same rows for every outer row runs once into a hash set of its imported-variable keys; any other body, or one whose first pattern's entity is imported, runs per outer row from `seed.rs`'s one-row `Seed`, via `Operator::rewind`; never deduplicates), `aggregate.rs` (`Aggregate`, #547: a hash table of groups keyed on cells as `Value`'s `Ord` compares values, one entry when ungrouped; `count`/`count-distinct` on cells, other aggregates on values via `datalog::aggregate::Agg`; groups sorted by value and finished in that order; a float group shows its least value by `value_order`; #641/#781 certify a complete grouping tuple as `Grouping::Ordered`: count/count-distinct/sum/avg, fixed-scalar extrema and Integer/nil sum-distinct; one varying ordered slot plus permitted scalar constants/repetitions, including :with (which retains Sort), no window/callback/CollectSet; one active group, bounded output batches, shared finish_group, internal DICT-cache eviction; unproved arguments and registered finalizers keep full-drain validation), `order.rs` and `order/arguments.rs` (#641/#781: snapshot-bound grouping/order and argument-domain proofs of the complete result order; safe committed integer/float/Boolean ranges can set the private `ScanSpec.index` hint to AVET and omit Sort, with `plan.find` restored from Sort.cols; entity-and-attribute scans retain EAVT; pending/staged records in that range, callbacks and CollectSet keep the original strategies; DICT comparators prove only window partition adjacency, never final Sort or aggregate group order; mixed integer/float keys can prove grouping order but keep Sort, and unique group keys discharge tie suffixes; `minigraf::__input_order` forces fallback under `test-hooks`), `sort.rs` (`Sort`, #306: the `:find` columns as values, in the full order of `:order-by` — its keys, then every other `:find` column ascending, by `datalog::aggregate::row_order`/`value_order`; under a `:limit` a heap of the best `offset + limit` rows; reads its whole input, dropping the DICT lookups after each batch, metered; its rows turned back into cells only as returned), `limit.rs` (`Limit`, #306: skips `offset` rows, passes on at most `limit`, then closes its child so nothing below reads more; planned after the last step, after `Builder::finish`, and after `Sort`), `window.rs` (`Window`, #547: holds each input row's passed-on cells and its named variables' values, then computes every window with `datalog::aggregate::windows`, the executor's code, and returns the rows in input order; #641 resolves compatible built-in windows to `WindowPartitioned`, retaining one partition and charged lookahead, coalescing completed partitions into bounded output batches, evicting DICT caches at internal input/result boundaries; full-input mode keeps query-lifetime caches), `union.rs`/`distinct.rs` (`Union` and `Distinct`, #546: each `or` branch planned as a `not` body is, hashed into a table or run per outer row; then one row per distinct binding, as the executor's `Value`s compare; `:distinct` adds `DistinctFind` after aggregates/windows and before sorting/pagination, keyed on final `:find` columns by aggregate-group equality, with canonical float zero/NaN output including set elements, #493), `cell.rs`/`batch.rs` (id cells in columnar batches of 1,024), `ids.rs` (DICT and provisional ids, `keyword_eid`), `project.rs` (ids → values for returned rows only; bounded stack UUID hints share DICT paths, with cache insertion and charges in projection order, #530), `relation.rs`/`recursive.rs` (#548: rule queries; a relation per evaluated predicate holds its derived rows, a set by `encode_value` identity, appended per round so `Old`/`Delta`/`Full` are ranges; `Recursive` runs each stratum's semi-naive rounds, one run per same-stratum top-level invocation, a rule reading its stratum otherwise run in full every round; scans read derived rows after committed and pending ones, with `nil` metadata), `meter.rs` (#549: one `Meter` per query, shared by every holder of state through a `Held` — hash join build sides, `not`/`or` tables, distinct sets, aggregate groups, window rows, rule relations and their temporaries, `IdSpace`, the set a `CollectSet` builds; each entry charged by a per-entry estimate including retained set elements and strings before it is inserted, containers grown with `try_reserve`, released on `rewind`/`close`/drop; over `OpenOptions::query_memory_limit`, or a refused allocation, is `QRY-012`; `Stream::close` drops the operator tree, keeping its counters). `mod.rs`: `Operator` (`next_batch`/`rewind`/`close`/`counters`), `Stream` (the operator tree over an owned `Snapshot`, pulled one batch at a time). `DatalogExecutor::open` / `execute_query` run every query on it: a cursor gets the `Stream` (`Answer::Stream`), `execute` drains it.

4. **`src/temporal.rs`** — UTC-only timestamp parsing (avoids chrono CVE GHSA-wcg3-cvx6-7396)
4. **`src/temporal.rs`** — Dependency-free strict UTC timestamp parsing and formatting, Gregorian years 0000–9999 (#900)

5. **`src/repl.rs`** — Interactive REPL; TTY-aware (suppresses prompts/banner for piped input)

Expand Down Expand Up @@ -249,7 +249,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are

## Test Coverage

**2172 tests** (2149 active, 23 ignored; unit + integration + doc). Browser-only inventory is separate: #894 adds 14 wasm tests (95 main-thread / 128 dedicated-worker tests in total); see `docs/testing/894-idb-flush-recovery.md` for execution results. Engine answers once checked by the executor are frozen in `tests/answers/` (#551).
**2181 tests** (2158 active, 23 ignored; unit + integration + example + doc). Browser-only inventory is separate: #894 adds 14 wasm tests (95 main-thread / 128 dedicated-worker tests in total); see `docs/testing/894-idb-flush-recovery.md` for execution results. Engine answers once checked by the executor are frozen in `tests/answers/` (#551).
See `docs/TEST_COVERAGE.md` for the full per-file breakdown.

The #760 deterministic storage suite adds three native unit tests in a separate `--cfg minigraf_shuttle` build, outside the default count. Run only `graph::storage::deterministic::` with that cfg; ordinary unit tests do not enter its scheduler. `deterministic-schedules.yml` runs relevant v3 PRs on Linux/macOS/Windows plus Linux MSRV, and larger nightly/manual searches with replay artifacts. The identical main workflow activates the v3 schedule after both PRs merge. See `docs/testing/deterministic-schedules.md` for scope, controls and findings.
Expand Down
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ serde = { version = "1.0", features = ["derive"] }
postcard = { version = "1.0", features = ["alloc"] }
crc32fast = "1.4"
anyhow = "1.0"
chrono = { version = "0.4", features = ["serde", "std"], default-features = false }
uuid = { version = "1.0", features = ["v5", "serde"] }
regex-lite = "0.1.9"
serde_json = { version = "1.0", optional = true }
Expand Down
6 changes: 1 addition & 5 deletions deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ targets = [
all-features = true

[advisories]
# chrono is unmaintained (all versions); not a vulnerability. Ignored until
# it is replaced (#900).
ignore = [
{ id = "RUSTSEC-2026-0543", reason = "chrono unmaintained; replacement tracked in #900" },
]
ignore = []

[licenses]
# Permissive licenses compatible with Minigraf's MIT OR Apache-2.0.
Expand Down
30 changes: 19 additions & 11 deletions docs/ERROR_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -3854,26 +3854,34 @@ but fires at the API layer's own materialization step.
**Error text**: `invalid timestamp: {}`

**Cause**: `parse_timestamp` (used for `:as-of`, `:valid-at`, `:valid-from`,
and `:valid-to` date strings) rejected the input — either a timezone offset
was present (only UTC `Z` timestamps are supported, to avoid chrono's local
timezone handling, GHSA-wcg3-cvx6-7396), or the string did not parse as an
RFC 3339 datetime or `YYYY-MM-DD` date.
and `:valid-to` date strings) rejected an invalid calendar date, clock field or
format. From v3.0.0, accepted forms are exactly `YYYY-MM-DD` (midnight UTC),
`YYYY-MM-DDTHH:MM:SSZ`, and `YYYY-MM-DDTHH:MM:SS.fZ`, where `f` is 1–9 ASCII
digits. Fractions are truncated to milliseconds, never rounded up, including
before 1970 (`1969-12-31T23:59:59.9999Z` is -1 ms).

**Resolution**:
- Use a UTC timestamp like `"2024-01-15T10:00:00Z"` or a bare date like
`"2024-01-15"`. Do not include a timezone offset such as `+05:30`.
- Use ASCII digits only: four year digits (0000–9999) and two digits for every
other field. Use a valid Gregorian day (including the century leap-year rule), hours 00–23,
minutes and seconds 00–59, and uppercase `T` and `Z`.
- Do not include whitespace, timezone offsets (including `-00:00`), a `UTC`
suffix, lowercase `t`/`z`, signed or short years, single-digit fields, leap
seconds, comma fractions, empty fractions, more than nine fractional digits,
or trailing characters.

### INT-005 Millisecond value outside supported datetime range

**Error text**: `millisecond value {} is outside the supported datetime range`

**Cause**: `millis_to_timestamp_string` was given a millisecond value
outside the range chrono can represent as a UTC datetime. `i64::MAX`
(`VALID_TIME_FOREVER`) must never be passed to this function directly —
callers should check for the sentinel before formatting.
**Cause**: `millis_to_timestamp_string` was given a value outside
0000-01-01T00:00:00Z through 9999-12-31T23:59:59.999Z, inclusive
(-62,167,219,200,000 through 253,402,300,799,999 Unix milliseconds).
The output is `YYYY-MM-DDTHH:MM:SSZ`, flooring to whole seconds.
`i64::MAX` (`VALID_TIME_FOREVER`) is outside this range.

**Resolution**:
- Check for `VALID_TIME_FOREVER` before formatting a `valid_to` value.
- Check for `VALID_TIME_FOREVER` before formatting a `valid_to` value and
ensure other millisecond values fall within the supported range.

### INT-006 Internal parser error: expected token

Expand Down
29 changes: 26 additions & 3 deletions docs/TEST_COVERAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,29 @@

## Coverage Summary

**#900 strict UTC timestamps**: `src/temporal.rs` has 13 tests (seven added),
including all 328 frozen chrono 0.4.45 vectors in
`src/temporal/chrono_vectors.rs`, whole-second vector round trips, strict syntax
and INT-004 rejections, Gregorian leap/calendar/clock boundaries, formatter range
edges and INT-005, and UTF-8 insertions at every byte offset. Two native proptests
cover arbitrary in-range milliseconds (flooring to seconds) and arbitrary strings
(no panics). `tests/bitemporal_test.rs` has 13 tests (one added), checking strict
forms through `:as-of`, `:valid-at`, and both statement/per-fact
`:valid-from`/`:valid-to` maps. `examples/perf_envelope.rs` has two tests (one
added), including millisecond formatting and its unsigned transaction-time range.
`src/db.rs` retains 55 native unit tests (plus one WASI-only test); its pending-metadata test now formats the
millisecond timestamp without chrono. The existing large-transaction window test
continues to exercise the whole-second formatter. No error codes were added or
removed. Browser-only test counts are unchanged.

Verification on 2026-11-27: full default `cargo test` passes 2,158 tests with
23 ignored and zero failures. Formatting, strict `--all-targets --all-features`
Clippy, the browser WASM library build, and all four cargo-deny checks pass.
Removing chrono shrinks the dist binary by 22,704 bytes (measured with the same
local toolchain before and after). Root and fuzz resolved lockfiles contain no
chrono package; archived golden fixture generators and audit evidence are
unchanged.

**#894 evaluator follow-up**: the nonempty smaller-import abort regression raises
the flush suite to 14 browser-only tests (95 main-thread / 128 dedicated-worker
tests in the inventory). Native counts are unchanged. The test checks failed-handle
Expand All @@ -19,12 +42,12 @@ are documented in the [PR 1 evidence](testing/894-idb-flush-recovery.md).

| | Default features | With `--features test-hooks` |
|---|---|---|
| **Active** | 2,149 | 2,187 |
| **Active** | 2,158 | 2,196 |
| **Ignored** | 23 | 32 |
| **Total** | 2,172 | 2,219 |
| **Total** | 2,181 | 2,228 |

Counts above are the current Cargo test inventory (active versus ignored),
including #441, #777, #789, #781, #794, #795, #837, #865, #869, #870, #861, #863, #871, #872 and #824 (Linux). Verification results below identify which suites ran.
including #900, #441, #777, #789, #781, #794, #795, #837, #865, #869, #870, #861, #863, #871, #872 and #824 (Linux). Verification results below identify which suites ran.

**#441 verification (2026-11-14)**: the full native default suite passes
(2,149 active, 23 ignored), including the grammar verifier and eight new
Expand Down
67 changes: 64 additions & 3 deletions examples/perf_envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,9 +771,55 @@ fn tx_time(fixture: &Path, tx_count: u64) -> anyhow::Result<String> {
.next_batch(1)?
.and_then(|b| b.into_iter().next())
.ok_or_else(|| anyhow::anyhow!("no transaction {tx_count}"))?;
let t = chrono::DateTime::from_timestamp_millis(i64::try_from(rec.tx_id)?)
.ok_or_else(|| anyhow::anyhow!("tx_id {} out of range", rec.tx_id))?;
Ok(t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string())
format_tx_time(rec.tx_id)
}

/// The harness only formats unsigned transaction times (1970–9999). Keep this
/// small helper local: the library's timestamp utilities are not a public API.
#[cfg(not(target_arch = "wasm32"))]
fn format_tx_time(millis: u64) -> anyhow::Result<String> {
anyhow::ensure!(millis <= 253_402_300_799_999, "tx_id {millis} out of range");
let leap = |year: u64| {
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
};
let mut days = millis / 86_400_000;
let mut year = 1970;
loop {
let length = if leap(year) { 366 } else { 365 };
if days < length {
break;
}
days -= length;
year += 1;
}
let mut month = 1;
for length in [
31,
if leap(year) { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
] {
if days < length {
break;
}
days -= length;
month += 1;
}
let day = days + 1;
let seconds = millis / 1000 % 86_400;
let (hour, minute, second) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
let fraction = millis % 1000;
Ok(format!(
"{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{fraction:03}Z"
))
}

/// Open time and RSS after open, then checkpoint times, on a copy of the fixture.
Expand Down Expand Up @@ -957,6 +1003,21 @@ fn main() {}
mod tests {
use super::*;

#[test]
fn timestamp_formatter_preserves_milliseconds_and_range() {
for (millis, expected) in [
(0, "1970-01-01T00:00:00.000Z"),
(1, "1970-01-01T00:00:00.001Z"),
(951_782_400_999, "2000-02-29T00:00:00.999Z"),
(4_107_542_400_001, "2100-03-01T00:00:00.001Z"),
(253_402_300_799_999, "9999-12-31T23:59:59.999Z"),
] {
assert_eq!(format_tx_time(millis).unwrap(), expected);
}
assert!(format_tx_time(253_402_300_800_000).is_err());
assert!(format_tx_time(u64::MAX).is_err());
}

fn records(path: &Path) -> Vec<minigraf::FactRecord> {
let db = OpenOptions::new()
.read_only(true)
Expand Down
7 changes: 3 additions & 4 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2983,7 +2983,6 @@ mod tests {

#[test]
fn test_write_transaction_pending_metadata_is_stable_across_reads() {
use chrono::{SecondsFormat, Utc};
use std::time::Duration;

let db = Minigraf::in_memory().unwrap();
Expand Down Expand Up @@ -3044,9 +3043,9 @@ mod tests {
);
db.inner.fact_storage.load_fact(future_fact).unwrap();

let as_of_timestamp = chrono::DateTime::<Utc>::from_timestamp_millis(tx_id)
.unwrap()
.to_rfc3339_opts(SecondsFormat::Millis, true);
let mut as_of_timestamp = crate::temporal::millis_to_timestamp_string(tx_id).unwrap();
as_of_timestamp.pop(); // Replace the trailing Z with millisecond precision.
as_of_timestamp.push_str(&format!(".{:03}Z", tx_id.rem_euclid(1000)));
let as_of_query = format!(
r#"(query [:find ?age :as-of "{}" :where [:alice :person/age ?age]])"#,
as_of_timestamp
Expand Down
Loading
Loading
0