{"record":{"id":"4581b4c3cfd50203","repo":"clockworklabs/SpacetimeDB","slug":"timestamp-before-unix-epoch-4581b4","errorCode":null,"errorMessage":"timestamp before unix epoch","messagePattern":"timestamp before unix epoch","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/sats/src/uuid.rs","lineNumber":133,"sourceCode":"    /// let counter = std::cell::Cell::new(1);\n    /// // Use the `ReducerContext::rng()` | `ProcedureContext::rng()` to generate random bytes,\n    /// // or call `ReducerContext::new_uuid_v7()` / `ProcedureContext::new_uuid_v7()`\n    /// let random_bytes = [0u8; 4];\n    /// let uuid = Uuid::from_counter_v7(&counter, now, &random_bytes).unwrap();\n    ///\n    /// assert_eq!(\n    ///     \"0000647e-5180-7000-8000-000200000000\",\n    ///     uuid.to_string(),\n    /// );\n    /// ```\n    pub fn from_counter_v7(counter: &Cell<u32>, now: Timestamp, random_bytes: &[u8; 4]) -> anyhow::Result<Self> {\n        // Monotonic counter value (31 bits)\n        let counter_val = counter.get();\n        counter.set(counter_val.wrapping_add(1) & 0x7FFF_FFFF);\n\n        let ts_ms = now\n            .to_duration_since_unix_epoch()\n            .expect(\"timestamp before unix epoch\")\n            .as_millis() as i64\n            & 0xFFFFFFFFFFFF;\n\n        let mut bytes = [0u8; 16];\n\n        // unix_ts_ms (48 bits)\n        bytes[0] = (ts_ms >> 40) as u8;\n        bytes[1] = (ts_ms >> 32) as u8;\n        bytes[2] = (ts_ms >> 24) as u8;\n        bytes[3] = (ts_ms >> 16) as u8;\n        bytes[4] = (ts_ms >> 8) as u8;\n        bytes[5] = ts_ms as u8;\n\n        // version & variant\n        // bytes[6] = uuid::Version::SortRand;\n        // bytes[8] = Variant::RFC4122\n\n        // Counter bits","sourceCodeStart":115,"sourceCodeEnd":151,"githubUrl":"https://github.com/clockworklabs/SpacetimeDB/blob/6dee26c6efc2856793e12b148a59742964f5d783/crates/sats/src/uuid.rs#L115-L151","documentation":"Panic in `Uuid::from_counter_v7`, SpacetimeDB's UUIDv7 generator. It converts the `now: Timestamp` argument via `to_duration_since_unix_epoch().expect(\"timestamp before unix epoch\")`; a Timestamp earlier than 1970 returns `Err` (the Err encodes the pre-epoch offset) and the expect panics. UUIDv7 embeds a positive millisecond timestamp, so pre-epoch times are unsupported by construction.","triggerScenarios":"Generating a UUIDv7 while the system clock (or the injected `now` value) reads before 1970-01-01: broken RTC/VM clock, NTP step-back in tests, or code passing a deliberately negative Timestamp (e.g. `UNIX_EPOCH - x` arithmetic) into ID generation.","commonSituations":"Machines booting with dead CMOS batteries into pre-1970 dates; sandboxes/containers with clock skew; test fixtures constructing fixed Timestamps below the epoch; feeding historical dates into ID generation by mistake.","solutions":["Check and fix the system clock (enable NTP; verify `date -u` shows post-1970) — the clock, not the code, is usually wrong.","Guard ID-generation call sites: `if now.to_duration_since_unix_epoch().is_err() { use fallback }` or clamp `now` to `Timestamp::UNIX_EPOCH`.","Validate any externally-supplied Timestamp before passing it to `from_counter_v7`.","In tests, use realistic fixed timestamps (post-1970) rather than epoch-relative negatives."],"exampleFix":"// before: panics when clock/ts predates 1970\nlet id = Uuid::from_counter_v7(&counter, now, &rand)?;\n\n// after: clamp pre-epoch times to the epoch\nlet now = if now.to_duration_since_unix_epoch().is_err() { Timestamp::UNIX_EPOCH } else { now };\nlet id = Uuid::from_counter_v7(&counter, now, &rand)?;","handlingStrategy":"validation","validationCode":"fn uuid_now(now: Timestamp, counter: &Cell<u32>, rnd: &[u8; 4]) -> anyhow::Result<Uuid> {\n    let now = if now.to_duration_since_unix_epoch().is_err() {\n        Timestamp::UNIX_EPOCH // clamp: UUIDv7 cannot encode pre-epoch\n    } else { now };\n    Ok(Uuid::from_counter_v7(counter, now, rnd)?)\n}","typeGuard":null,"tryCatchPattern":"let r = std::panic::catch_unwind(AssertUnwindSafe(|| Uuid::from_counter_v7(&c, now, &rnd)));\nmatch r { Ok(v) => v?, Err(_) => return Err(ClockError::pre_epoch) }","preventionTips":["Enable NTP and verify the host clock reads post-1970 before relying on ID generation.","Validate externally-supplied Timestamps before passing them to UUID generation.","In tests, use fixed post-epoch timestamps only."],"tags":["rust","spacetimedb","uuid","timestamp","unix-epoch","clock","panic"],"backgroundTag":"pre-epoch-timestamp","analyzedSha":"6dee26c6efc2856793e12b148a59742964f5d783","analyzedAt":"2026-08-20T06:08:37.179Z","contentChangedAt":"2026-08-20T06:08:37.179Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}