Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(frontend): make the clock self-heal and the boundary guard complete

zchpeter2de05b4b2ef4
diff --git a/docs/design/timestamp-display.md b/docs/design/timestamp-display.md
index 5ccb71fbf6..cd53c93c7d 100644
--- a/docs/design/timestamp-display.md
+++ b/docs/design/timestamp-display.md
@@ -272,8 +272,11 @@ no seconds per D5. Relative age may accompany it in the tooltip.
- **Every time-varying reading comes as a pair** — the function that renders it and the
function returning the first instant its output will differ (`Infinity` if never). The pair
lives together and is tested together: sampled across ages, the reading is constant up to
- that instant and differs at it. The samples include sub-millisecond timestamps and a turn of
- the year, where a boundary a fraction early or a seasonal change otherwise hides. A boundary
+ that instant and differs at it, followed across several successive boundaries so a reading
+ that leaves a value and later returns to it cannot hide a skipped span. The samples include
+ sub-millisecond timestamps, starts off the whole minute, and a turn of the year, where a
+ boundary a fraction early, one computed from a rounded clock, or a seasonal change otherwise
+ hides. A boundary
borrowed from a different reading, or re-derived by hand beside one, is the defect this rules
out — the two drift silently, and a test of the boundary alone cannot see it.
- **A boundary is evaluated no later than its reading.** Evaluated after, it can see a change
@@ -281,8 +284,9 @@ no seconds per D5. Relative age may accompany it in the tooltip.
- **The shared clock accepts any instant.** Deadlines are wall-clock instants but timers skip
time the machine sleeps, so the clock re-checks at least once a minute: a display is at most
a minute behind after sleep or a clock adjustment. It wakes only the subscribers that are due,
- retires each woken deadline until the display declares its next one, and leaves a short gap
- after each wake so a boundary that keeps naming a past instant cannot spin it.
+ re-checks a woken display that names the same instant again after a resync interval rather
+ than on every other display's wake, and leaves a short gap after each wake so a boundary that
+ keeps naming a past instant cannot spin it.
- Guarded by fake-timer tests and a sweep of render-time `Date.now()` over the touched surfaces
at implementation time — a review pass, not a lint: telling render scope from handlers and
effects statically would flag most legitimate uses.
diff --git a/frontend/src/components/IssueTable.tsx b/frontend/src/components/IssueTable.tsx
index b3d9a1cc4f..381fdde7d4 100644
--- a/frontend/src/components/IssueTable.tsx
+++ b/frontend/src/components/IssueTable.tsx
@@ -637,9 +637,9 @@ export const IssueListItem = memo(function IssueListItem({
const issueProject = useMemo(() => projectOfIssue(issue), [issue]);
- const createTimeTs = Math.floor(
- getTimeForPbTimestampProtoEs(issue.createTime, 0) / 1000
- );
+ const createTimeTs = issue.createTime
+ ? Math.floor(getTimeForPbTimestampProtoEs(issue.createTime) / 1000)
+ : undefined;
const issueUrl = useMemo(() => {
const issueRoute = getIssueRoute(issue);
@@ -769,9 +769,13 @@ export const IssueListItem = memo(function IssueListItem({
</div>
<div className="flex items-center flex-wrap gap-x-1 text-xs text-control-light mt-1">
<span className="opacity-80">#{extractIssueUID(issue.name)}</span>
- <span>&middot;</span>
- {t("common.created")}
- <HumanizeTs ts={createTimeTs} />
+ {createTimeTs !== undefined && (
+ <>
+ <span>&middot;</span>
+ {t("common.created")}
+ <HumanizeTs ts={createTimeTs} />
+ </>
+ )}
<span>&middot;</span>
{getAccountTypeByEmail(creator.email) === AccountType.USER ? (
<UserHoverCard
diff --git a/frontend/src/hooks/useNow.test.tsx b/frontend/src/hooks/useNow.test.tsx
index 02aeecd303..4b473c8b32 100644
--- a/frontend/src/hooks/useNow.test.tsx
+++ b/frontend/src/hooks/useNow.test.tsx
@@ -65,7 +65,7 @@ describe("useNow", () => {
test("wakes a subscriber at its deadline and not before", () => {
const deadlineMs = Date.now() + 1_000;
- const { root, renders } = mount([{ changesAtMs: () => deadlineMs }]);
+ const { renders } = mount([{ changesAtMs: () => deadlineMs }]);
act(() => {
vi.advanceTimersByTime(999);
@@ -76,15 +76,13 @@ describe("useNow", () => {
vi.advanceTimersByTime(1);
});
expect(renders).toEqual([2]);
-
- act(() => root.unmount());
});
test("waits quietly for a deadline beyond the platform timer ceiling", () => {
// setTimeout holds its delay in 32 bits; anything past ~24.8 days fires at
// once. A date waiting for the year to turn is ordinary input.
const deadlineMs = Date.now() + 90 * DAY_MS;
- const { root, renders } = mount([{ changesAtMs: () => deadlineMs }]);
+ const { renders } = mount([{ changesAtMs: () => deadlineMs }]);
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
act(() => {
@@ -97,8 +95,6 @@ describe("useNow", () => {
vi.advanceTimersByTime(90 * DAY_MS);
});
expect(renders).toEqual([2]);
-
- act(() => root.unmount());
});
test("wakes each due subscriber once and re-arms once for the lot", () => {
@@ -109,7 +105,7 @@ describe("useNow", () => {
const probes = Array.from({ length: 50 }, () => ({
changesAtMs: () => (Date.now() < firstMs ? firstMs : secondMs),
}));
- const { root, renders } = mount(probes);
+ const { renders } = mount(probes);
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
act(() => {
@@ -117,8 +113,6 @@ describe("useNow", () => {
});
expect(renders.every((count) => count === 2)).toBe(true);
expect(setTimeoutSpy.mock.calls.length).toBeLessThanOrEqual(2);
-
- act(() => root.unmount());
});
test("catches up when the wall clock passes a deadline the timer has not", () => {
@@ -146,7 +140,30 @@ describe("useNow", () => {
expect(renders[0]).toBeLessThanOrEqual(6);
});
- test("leaves a subscriber whose boundary did not advance to its last reading", () => {
+ test("re-checks a woken subscriber whose boundary did not advance", () => {
+ // A wall clock stepped back between the wake and its render, or a boundary
+ // held stale by a memo, names the instant that just passed a second time.
+ let stepBackMs = 0;
+ const deadlineMs = Date.now() + 1_000;
+ const { renders } = mount([
+ { changesAtMs: () => (Date.now() - stepBackMs < deadlineMs ? deadlineMs : deadlineMs + 60_000) },
+ ]);
+
+ act(() => {
+ vi.advanceTimersByTime(1_000);
+ stepBackMs = 2;
+ vi.setSystemTime(Date.now() - stepBackMs);
+ });
+ expect(renders).toEqual([2]);
+
+ // Re-checked once a resync interval has passed on the wall clock.
+ act(() => {
+ vi.advanceTimersByTime(61_000);
+ });
+ expect(renders[0]).toBeGreaterThan(2);
+ });
+
+ test("does not re-wake a stuck subscriber on every neighbour's tick", () => {
const stuckMs = Date.now() + 500;
const { renders } = mount([
{ changesAtMs: () => stuckMs },
@@ -172,9 +189,7 @@ describe("useNow", () => {
});
test("holds nothing for a display that does not vary with time", () => {
- const { root } = mount([{ changesAtMs: () => undefined }]);
+ mount([{ changesAtMs: () => undefined }]);
expect(vi.getTimerCount()).toBe(0);
-
- act(() => root.unmount());
});
});
diff --git a/frontend/src/hooks/useNow.ts b/frontend/src/hooks/useNow.ts
index d384881a48..d84c54339a 100644
--- a/frontend/src/hooks/useNow.ts
+++ b/frontend/src/hooks/useNow.ts
@@ -5,9 +5,10 @@ import { useEffect, useReducer } from "react";
*
* Each subscriber declares the instant its rendering next changes, so the clock
* holds one timeout, set for the earliest of those, and wakes only the
- * subscribers that are due. A woken subscriber is retired until it re-renders
- * and declares its next instant; one whose boundary fails to advance keeps its
- * last reading rather than being woken again.
+ * subscribers that are due. A woken subscriber normally re-renders and declares
+ * its next instant; one that names the same instant again -- a wall clock
+ * stepped back before the render, or a boundary held stale -- is re-checked
+ * after a resync interval rather than on every neighbour's tick.
*/
type Subscriber = {
changesAtMs: number;
@@ -53,18 +54,15 @@ function arm(changesAtMs: number): void {
}
function tick(): void {
- timer = undefined;
- armedForMs = Number.POSITIVE_INFINITY;
const nowMs = Date.now();
lastTickMs = nowMs;
let nextMs = Number.POSITIVE_INFINITY;
for (const subscriber of subscribers) {
if (subscriber.changesAtMs <= nowMs) {
- subscriber.changesAtMs = Number.POSITIVE_INFINITY;
+ subscriber.changesAtMs = nowMs + RESYNC_MS;
subscriber.wake();
- } else {
- nextMs = Math.min(nextMs, subscriber.changesAtMs);
}
+ nextMs = Math.min(nextMs, subscriber.changesAtMs);
}
arm(nextMs);
}
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
index 95d65c15f0..9f3044d4a3 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
@@ -11,7 +11,8 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
getAccessGrantDisplayStatus: vi.fn(),
getAccessGrantDisplayStatusText: vi.fn(),
- getAccessGrantExpireTimeMs: vi.fn(),
+ getActiveAccessGrantDeadlineMs: vi.fn(),
+ nextAccessGrantDisplayStatusChangeAt: vi.fn(),
getAccessGrantStatusTagType: vi.fn(),
}));
@@ -36,7 +37,9 @@ vi.mock("react-i18next", () => ({
vi.mock("@/utils/accessGrant", () => ({
getAccessGrantDisplayStatus: mocks.getAccessGrantDisplayStatus,
getAccessGrantDisplayStatusText: mocks.getAccessGrantDisplayStatusText,
- getAccessGrantExpireTimeMs: mocks.getAccessGrantExpireTimeMs,
+ getActiveAccessGrantDeadlineMs: mocks.getActiveAccessGrantDeadlineMs,
+ nextAccessGrantDisplayStatusChangeAt:
+ mocks.nextAccessGrantDisplayStatusChangeAt,
getAccessGrantStatusTagType: mocks.getAccessGrantStatusTagType,
}));
@@ -142,7 +145,10 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({ t: (key: string) => key });
mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");
mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");
- mocks.getAccessGrantExpireTimeMs.mockReturnValue(undefined);
+ mocks.getActiveAccessGrantDeadlineMs.mockReturnValue(undefined);
+ mocks.nextAccessGrantDisplayStatusChangeAt.mockReturnValue(
+ Number.POSITIVE_INFINITY
+ );
mocks.getAccessGrantStatusTagType.mockReturnValue("success");
({ AccessGrantItem } = await import("./AccessGrantItem"));
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
index 30132cc16f..11da7c2216 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
@@ -6,16 +6,14 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { useNow } from "@/hooks/useNow";
import { cn } from "@/lib/utils";
-import {
- type AccessGrant,
- AccessGrant_Status,
-} from "@/types/proto-es/v1/access_grant_service_pb";
+import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import {
getAccessGrantDisplayStatus,
getAccessGrantDisplayStatusText,
- getAccessGrantExpireTimeMs,
getAccessGrantStatusTagType,
+ getActiveAccessGrantDeadlineMs,
+ nextAccessGrantDisplayStatusChangeAt,
} from "@/utils/accessGrant";
import {
formatAbsoluteDateTime,
@@ -49,14 +47,14 @@ export function AccessGrantItem({
}: Props) {
const { t } = useTranslation();
- // Only an activated grant counts down. The countdown's last step is its
- // deadline passing, so it also schedules the expired badge.
- const deadlineMs =
- grant.status === AccessGrant_Status.ACTIVE
- ? getAccessGrantExpireTimeMs(grant)
- : undefined;
+ const deadlineMs = getActiveAccessGrantDeadlineMs(grant);
useNow(
- deadlineMs === undefined ? undefined : nextCountdownChangeAt(deadlineMs)
+ Math.min(
+ nextAccessGrantDisplayStatusChangeAt(grant),
+ deadlineMs === undefined
+ ? Number.POSITIVE_INFINITY
+ : nextCountdownChangeAt(deadlineMs)
+ )
);
const displayStatus = getAccessGrantDisplayStatus(grant, issue);
diff --git a/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx b/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx
index 6195c89888..5145d56679 100644
--- a/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx
+++ b/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx
@@ -148,9 +148,6 @@ vi.mock("./HistorySearchInput", () => ({
vi.mock("@/types", () => ({
DEBOUNCE_SEARCH_DELAY: 300,
- getDateForPbTimestampProtoEs: vi.fn((ts: unknown) =>
- ts ? new Date("2024-01-15T10:30:00Z") : new Date(0)
- ),
getTimeForPbTimestampProtoEs: vi.fn((ts: unknown, defaultValue = 0) =>
ts ? new Date("2024-01-15T10:30:00Z").getTime() : defaultValue
),
diff --git a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx b/frontend/src/routes/project/ProjectPlanDashboardPage.tsx
index 5c15c315b6..0c36962d2c 100644
--- a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx
+++ b/frontend/src/routes/project/ProjectPlanDashboardPage.tsx
@@ -378,7 +378,7 @@ interface PlanColumn {
interface PlanRowContext {
creator: { title: string; name: string };
- updateTimeTs: number;
+ updateTimeTs: number | undefined;
approvalTag: { label: string; variant: ReviewBadge["variant"] } | undefined;
isDeleted: boolean;
draftState: PlanDraftState;
@@ -509,12 +509,15 @@ function PlanTable({
defaultWidth: 152,
minWidth: 100,
resizable: true,
- render: (_plan, ctx) => (
- <HumanizeTs
- ts={ctx.updateTimeTs}
- className="text-control-light whitespace-nowrap"
- />
- ),
+ render: (_plan, ctx) =>
+ ctx.updateTimeTs === undefined ? (
+ "-"
+ ) : (
+ <HumanizeTs
+ ts={ctx.updateTimeTs}
+ className="text-control-light whitespace-nowrap"
+ />
+ ),
},
],
[t, isMobile]
@@ -604,9 +607,9 @@ function PlanRow({
);
const creator = creatorUser || unknownUser(plan.creator);
- const updateTimeTs = Math.floor(
- getTimeForPbTimestampProtoEs(plan.updateTime, 0) / 1000
- );
+ const updateTimeTs = plan.updateTime
+ ? Math.floor(getTimeForPbTimestampProtoEs(plan.updateTime) / 1000)
+ : undefined;
const planUrl = useMemo(() => {
return router.resolve({
diff --git a/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx b/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx
index f4c7316301..da1f7005d4 100644
--- a/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx
+++ b/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx
@@ -245,8 +245,9 @@ function ReleaseRow({ release }: { release: Release }) {
const showFiles = release.files.slice(0, MAX_SHOW_FILES_COUNT);
- const createTimeTs =
- getTimeForPbTimestampProtoEs(release.createTime, 0) / 1000;
+ const createTimeTs = release.createTime
+ ? getTimeForPbTimestampProtoEs(release.createTime) / 1000
+ : undefined;
const url = `/${release.name}`;
@@ -294,7 +295,7 @@ function ReleaseRow({ release }: { release: Release }) {
</div>
</TableCell>
<TableCell>
- <HumanizeTs ts={createTimeTs} />
+ {createTimeTs === undefined ? "-" : <HumanizeTs ts={createTimeTs} />}
</TableCell>
</TableRow>
);
diff --git a/frontend/src/types/timestamp.test.ts b/frontend/src/types/timestamp.test.ts
new file mode 100644
index 0000000000..8c99a3310e
--- /dev/null
+++ b/frontend/src/types/timestamp.test.ts
@@ -0,0 +1,25 @@
+// @vitest-environment node
+import { timestampFromMs } from "@bufbuild/protobuf/wkt";
+import { describe, expect, test } from "vitest";
+import { getTimeForPbTimestampProtoEs } from "./timestamp";
+
+describe("getTimeForPbTimestampProtoEs", () => {
+ test("reads milliseconds, keeping the sub-millisecond nanos", () => {
+ const timestamp = timestampFromMs(1_772_452_800_123);
+ timestamp.nanos += 500_000;
+ expect(getTimeForPbTimestampProtoEs(timestamp)).toBe(1_772_452_800_123.5);
+ });
+
+ test("uses the caller's fallback for an absent timestamp", () => {
+ expect(getTimeForPbTimestampProtoEs(undefined, 0)).toBe(0);
+ });
+
+ test("refuses to invent a time when a caller bypasses the types", () => {
+ // Substituting the current time would show "now" as when something
+ // happened; the overloads make this unreachable from typed code.
+ const untyped = getTimeForPbTimestampProtoEs as unknown as (
+ timestamp?: undefined
+ ) => number;
+ expect(() => untyped(undefined)).toThrow();
+ });
+});
diff --git a/frontend/src/types/timestamp.ts b/frontend/src/types/timestamp.ts
index 9e9e0e9ebe..1be6c9729a 100644
--- a/frontend/src/types/timestamp.ts
+++ b/frontend/src/types/timestamp.ts
@@ -16,9 +16,12 @@ export function getTimeForPbTimestampProtoEs(
): number;
export function getTimeForPbTimestampProtoEs(
timestamp?: TimestampProtoEs,
- defaultValue = Date.now()
+ defaultValue?: number
): number {
if (!timestamp) {
+ if (defaultValue === undefined) {
+ throw new Error("An absent timestamp needs an explicit fallback");
+ }
return defaultValue;
}
return Number(timestamp.seconds) * 1000 + timestamp.nanos / 1000000;
diff --git a/frontend/src/utils/accessGrant.ts b/frontend/src/utils/accessGrant.ts
index eab811906a..005332483e 100644
--- a/frontend/src/utils/accessGrant.ts
+++ b/frontend/src/utils/accessGrant.ts
@@ -7,11 +7,7 @@ import {
} from "@/types/proto-es/v1/access_grant_service_pb";
import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
-import {
- formatAbsoluteDateTime,
- hasPassed,
- nextPassedAt,
-} from "@/utils/datetime";
+import { hasPassed, nextPassedAt } from "@/utils/datetime";
export type AccessGrantFilterStatus =
| "ACTIVE"
@@ -39,7 +35,7 @@ export const getAccessGrantExpireTimeMs = (
export const getAccessGrantExpirationText = (
grant: AccessGrant
):
- | { type: "datetime"; value: string }
+ | { type: "datetime" }
| { type: "duration"; value: string }
| { type: "never" } => {
if (grant.expiration.case === "expireTime") {
@@ -52,8 +48,7 @@ export const getAccessGrantExpirationText = (
// later would render as "1d4h", which misleads reviewers about
// the actual granted window. Show the absolute expire datetime
// alone instead. Bot review #3370767734.
- const ms = getTimeForPbTimestampProtoEs(grant.expiration.value);
- return { type: "datetime", value: formatAbsoluteDateTime(ms) };
+ return { type: "datetime" };
}
if (grant.expiration.case === "ttl") {
// Pending grants still carry the requested TTL — safe to format.
@@ -71,16 +66,20 @@ export const getAccessGrantExpirationText = (
return { type: "never" };
};
+/** The deadline of an activated grant, the only kind that can expire. */
+export const getActiveAccessGrantDeadlineMs = (
+ grant: AccessGrant
+): number | undefined =>
+ grant.status === AccessGrant_Status.ACTIVE
+ ? getAccessGrantExpireTimeMs(grant)
+ : undefined;
+
export const getAccessGrantDisplayStatus = (
grant: AccessGrant,
issue?: Issue
): AccessGrantDisplayStatus => {
- const expireMs = getAccessGrantExpireTimeMs(grant);
- if (
- grant.status === AccessGrant_Status.ACTIVE &&
- expireMs !== undefined &&
- hasPassed(expireMs)
- ) {
+ const deadlineMs = getActiveAccessGrantDeadlineMs(grant);
+ if (deadlineMs !== undefined && hasPassed(deadlineMs)) {
return "EXPIRED";
}
switch (grant.status) {
@@ -107,10 +106,10 @@ export const getAccessGrantDisplayStatus = (
export const nextAccessGrantDisplayStatusChangeAt = (
grant: AccessGrant
): number => {
- const expireMs = getAccessGrantExpireTimeMs(grant);
- return grant.status === AccessGrant_Status.ACTIVE && expireMs !== undefined
- ? nextPassedAt(expireMs)
- : Number.POSITIVE_INFINITY;
+ const deadlineMs = getActiveAccessGrantDeadlineMs(grant);
+ return deadlineMs === undefined
+ ? Number.POSITIVE_INFINITY
+ : nextPassedAt(deadlineMs);
};
export const getAccessGrantDisplayStatusText = (
diff --git a/frontend/src/utils/datetime.test.ts b/frontend/src/utils/datetime.test.ts
index a31359227a..ff4a7e25cf 100644
--- a/frontend/src/utils/datetime.test.ts
+++ b/frontend/src/utils/datetime.test.ts
@@ -27,7 +27,6 @@ import {
formatQueueTime,
formatRelativeTime,
hasPassed,
- nextAbsoluteDateChangeAt,
nextCountdownChangeAt,
nextDaysLeftChangeAt,
nextPassedAt,
@@ -38,6 +37,11 @@ import {
readDaysLeft,
} from "./datetime";
+const SECOND_MS = 1_000;
+const MINUTE_MS = 60_000;
+const HOUR_MS = 3_600_000;
+const DAY_MS = 86_400_000;
+
describe("formatRelativeTime", () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -191,11 +195,6 @@ describe("formatOperationalDateTime", () => {
});
});
-const SECOND_MS = 1_000;
-const MINUTE_MS = 60_000;
-const HOUR_MS = 3_600_000;
-const DAY_MS = 86_400_000;
-
// Ages around every edge the relative reading has: the "now" threshold, each
// unit switch, the half-unit points where a rounded count turns over, and the
// 30-day switch. Negative ages are future timestamps.
@@ -230,52 +229,76 @@ const SAMPLED_AGES_MS = [
].flatMap((ageMs) => (ageMs === 0 ? [0] : [ageMs, -ageMs]));
// The contract a boundary keeps with the reading it schedules: the reading
-// holds right up to the named instant and changes at it, and the boundary names
-// that same instant from anywhere before it. A boundary checked on its own
-// cannot see that it was derived from the wrong reading.
+// holds throughout the span up to the named instant, the boundary names that
+// same instant from anywhere inside the span, and the reading changes at it.
+// Each check follows the chain for several links, starting every link where
+// the last one ended, so a reading that leaves a value and later returns to it
+// cannot hide a skipped span. A boundary checked on its own cannot see that it
+// was derived from the wrong reading.
+const CHAIN_LINKS = 3;
+const SPAN_PROBES = [0.25, 0.5, 0.75];
+// A reading with no boundary is sampled out past a New Year from any start.
+const FINAL_PROBES_MS = [
+ HOUR_MS,
+ DAY_MS,
+ 7 * DAY_MS,
+ 15 * DAY_MS,
+ 30 * DAY_MS,
+ 60 * DAY_MS,
+ 200 * DAY_MS,
+ 400 * DAY_MS,
+];
+
const expectBoundaryMatchesReading = (
read: (tsMs: number) => string,
nextChangeAt: (tsMs: number) => number,
tsMs: number
) => {
- const startMs = Date.now();
- const reading = read(tsMs);
- const changesAtMs = nextChangeAt(tsMs);
- if (changesAtMs === Number.POSITIVE_INFINITY) {
- // Far enough to cross a New Year from any start.
- for (const laterMs of [HOUR_MS, DAY_MS, 100 * DAY_MS, 400 * DAY_MS]) {
- vi.setSystemTime(startMs + laterMs);
+ for (let link = 0; link < CHAIN_LINKS; link++) {
+ const startMs = Date.now();
+ const reading = read(tsMs);
+ const changesAtMs = nextChangeAt(tsMs);
+ if (changesAtMs === Number.POSITIVE_INFINITY) {
+ for (const laterMs of FINAL_PROBES_MS) {
+ vi.setSystemTime(startMs + laterMs);
+ expect(read(tsMs)).toBe(reading);
+ }
+ return;
+ }
+ expect(changesAtMs).toBeGreaterThan(startMs);
+ const spanMs = changesAtMs - startMs;
+ for (const probeMs of [
+ ...SPAN_PROBES.map((at) => startMs + Math.floor(spanMs * at)),
+ Math.ceil(changesAtMs) - 1,
+ ]) {
+ vi.setSystemTime(probeMs);
expect(read(tsMs)).toBe(reading);
+ expect(nextChangeAt(tsMs)).toBe(changesAtMs);
}
- return;
- }
- expect(changesAtMs).toBeGreaterThan(startMs);
- for (const beforeMs of [
- startMs + Math.floor((changesAtMs - startMs) / 2),
- Math.ceil(changesAtMs) - 1,
- ]) {
- vi.setSystemTime(beforeMs);
- expect(read(tsMs)).toBe(reading);
- expect(nextChangeAt(tsMs)).toBe(changesAtMs);
+ vi.setSystemTime(changesAtMs);
+ expect(read(tsMs)).not.toBe(reading);
}
- vi.setSystemTime(changesAtMs);
- expect(read(tsMs)).not.toBe(reading);
};
-// Production timestamps carry sub-millisecond nanos, and `HumanizeTs` rounds
-// them through seconds and back; whole-millisecond ones alone hide any
-// boundary that lands a fraction early. The late-December start puts a New
-// Year inside every window.
-const BOUNDARY_STARTS = ["2026-03-02T12:00:00Z", "2026-12-31T15:30:00Z"];
+// Production timestamps carry sub-millisecond nanos, which hide a boundary
+// that lands a fraction early; a start off the whole minute exposes a boundary
+// computed from a rounded clock; the other two starts sit just before and
+// exactly on the pinned zone's New Year.
+const BOUNDARY_STARTS = [
+ "2026-03-02T12:00:17.371Z",
+ "2026-12-31T15:30:00Z",
+ "2026-12-31T16:00:00Z",
+];
const TIMESTAMP_FRACTIONS_MS = [0, 0.25, 0.999];
const boundaryCases = <T>(offsets: T[]) =>
BOUNDARY_STARTS.flatMap((start) =>
offsets.flatMap((offset) =>
- TIMESTAMP_FRACTIONS_MS.flatMap((fractionMs) => [
- { start, offset, fractionMs, viaSeconds: false },
- { start, offset, fractionMs, viaSeconds: true },
- ])
+ TIMESTAMP_FRACTIONS_MS.map((fractionMs) => ({
+ start,
+ offset,
+ fractionMs,
+ }))
)
);
@@ -285,15 +308,6 @@ const startAt = (start: string) => {
return startMs;
};
-const timestampOf = (
- instantMs: number,
- fractionMs: number,
- viaSeconds: boolean
-) => {
- const tsMs = instantMs + fractionMs;
- return viaSeconds ? (tsMs / 1000) * 1000 : tsMs;
-};
-
describe("reading boundaries", () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -304,37 +318,25 @@ describe("reading boundaries", () => {
});
test.each(boundaryCases(SAMPLED_AGES_MS))(
- "names the instant the work-queue reading changes (age $offset ms from $start, +$fractionMs ms, via seconds: $viaSeconds)",
- ({ start, offset, fractionMs, viaSeconds }) => {
+ "names the instant the work-queue reading changes (age $offset ms from $start, +$fractionMs ms)",
+ ({ start, offset, fractionMs }) => {
const startMs = startAt(start);
expectBoundaryMatchesReading(
formatQueueTime,
nextQueueTimeChangeAt,
- timestampOf(startMs - offset, fractionMs, viaSeconds)
- );
- }
- );
-
- test.each(boundaryCases(SAMPLED_AGES_MS))(
- "names the instant the absolute date reading changes (age $offset ms from $start, +$fractionMs ms, via seconds: $viaSeconds)",
- ({ start, offset, fractionMs, viaSeconds }) => {
- const startMs = startAt(start);
- expectBoundaryMatchesReading(
- formatAbsoluteDate,
- nextAbsoluteDateChangeAt,
- timestampOf(startMs - offset, fractionMs, viaSeconds)
+ startMs - offset + fractionMs
);
}
);
test.each(boundaryCases(SAMPLED_AGES_MS))(
- "names the instant the relative reading changes (age $offset ms from $start, +$fractionMs ms, via seconds: $viaSeconds)",
- ({ start, offset, fractionMs, viaSeconds }) => {
+ "names the instant the relative reading changes (age $offset ms from $start, +$fractionMs ms)",
+ ({ start, offset, fractionMs }) => {
const startMs = startAt(start);
expectBoundaryMatchesReading(
formatRelativeTime,
nextRelativeTimeChangeAt,
- timestampOf(startMs - offset, fractionMs, viaSeconds)
+ startMs - offset + fractionMs
);
}
);
@@ -393,13 +395,13 @@ describe("deadline readings", () => {
describe.each(pairs)("%s", (_name, read, nextChangeAt) => {
test.each(boundaryCases(SAMPLED_REMAINING_MS))(
- "names the instant the reading changes ($offset ms left from $start, +$fractionMs ms, via seconds: $viaSeconds)",
- ({ start, offset, fractionMs, viaSeconds }) => {
+ "names the instant the reading changes ($offset ms left from $start, +$fractionMs ms)",
+ ({ start, offset, fractionMs }) => {
const startMs = startAt(start);
expectBoundaryMatchesReading(
read,
nextChangeAt,
- timestampOf(startMs + offset, fractionMs, viaSeconds)
+ startMs + offset + fractionMs
);
}
);
diff --git a/frontend/src/utils/datetime.ts b/frontend/src/utils/datetime.ts
index 1f1a469c35..5f23c1ed9a 100644
--- a/frontend/src/utils/datetime.ts
+++ b/frontend/src/utils/datetime.ts
@@ -163,11 +163,6 @@ export function nextRelativeTimeChangeAt(timestampMs: number): number {
return relativeTimeChangeAt(timestampMs, Date.now());
}
-/** The first instant `formatAbsoluteDate` renders this timestamp differently. */
-export function nextAbsoluteDateChangeAt(timestampMs: number): number {
- return absoluteDateChangeAt(timestampMs, Date.now());
-}
-
/**
* The first instant `formatQueueTime` renders this timestamp differently, or
* `Infinity` once it has settled on a date for good.
@@ -176,10 +171,11 @@ export function nextQueueTimeChangeAt(timestampMs: number): number {
const nowMs = Date.now();
const diffMs = nowMs - timestampMs;
if (Math.abs(diffMs) < RELATIVE_THRESHOLD_MS) {
- const changesAtMs = relativeTimeChangeAt(timestampMs, nowMs);
- return diffMs < 0
- ? changesAtMs
- : Math.min(changesAtMs, Math.ceil(timestampMs + RELATIVE_THRESHOLD_MS));
+ // A future timestamp's relative boundary always comes before the switch.
+ return Math.min(
+ relativeTimeChangeAt(timestampMs, nowMs),
+ Math.ceil(timestampMs + RELATIVE_THRESHOLD_MS)
+ );
}
// Past the switch it reads as a date, and a future one counts back into
// the relative window.