Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(frontend): prove the boundary guard and close the clock's gaps
zchpeter598aed6e92dc
diff --git a/docs/design/timestamp-display.md b/docs/design/timestamp-display.mdindex ca04433bd0..5ccb71fbf6 100644--- a/docs/design/timestamp-display.md+++ b/docs/design/timestamp-display.md@@ -272,12 +272,17 @@ 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 thefunction returning the first instant its output will differ (`Infinity` if never). The pairlives together and is tested together: sampled across ages, the reading is constant up to- that instant and differs at it. 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.- - **The shared clock accepts any instant.** It clamps to the platform timer ceiling and re-arms,- wakes only the subscribers that are due, and relies on each woken subscriber declaring a- strictly later instant.+ 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+ 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+ the reading just missed, name the change after that, and leave the stale reading on screen.+ - **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.- Guarded by fake-timer tests and a sweep of render-time `Date.now()` over the touched surfacesat implementation time — a review pass, not a lint: telling render scope from handlers andeffects statically would flag most legitimate uses.@@ -338,7 +343,7 @@ points where the implementation had to choose:The staleness rule holds through `useNow` and the reading pairs described under Implementationshape. The clock replaced the ad-hoc interval behind the plan-detail created time, and the pairscover the displays that had no clock at all: the SQL-editor grant countdown, the masking-exemption-expiry label, and the access-grant roster's expired badge.+expiry label, the sample-instance expiry alert, and the access-grant expired badge.The rule governs displays of time. Two kinds of clock read stay outside it: **query membership** —the masking-exemption status filter, the role-expiry reminder's "within two days" list — which,diff --git a/frontend/src/components/HumanizeTs.tsx b/frontend/src/components/HumanizeTs.tsxindex e555f1f5f5..266a21f0c3 100644--- a/frontend/src/components/HumanizeTs.tsx+++ b/frontend/src/components/HumanizeTs.tsx@@ -1,3 +1,4 @@+import type { ComponentType } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@/components/ui/tooltip";import { useNow } from "@/hooks/useNow";@@ -28,7 +29,6 @@ interface HumanizeTsProps {/** Unix timestamp in seconds. */ts: number;mode?: TimeDisplayMode;- /** Applied to the element that renders the time, which is the only one. */className?: string;/*** Whether to reveal the hidden reading on hover. Defaults to true.@@ -39,13 +39,6 @@ interface HumanizeTsProps {tooltip?: boolean;}-const FORMATTERS: Record<TimeDisplayMode, (tsMs: number) => string> = {- queue: formatQueueTime,- compact: formatCompactDateTime,- operational: formatOperationalDateTime,- datetime: formatAbsoluteDateTime,-};-// Tooltip bodies mount only while open, so as components they cost nothing// for the rows nobody hovers, and a time-varying one can keep counting.function FullDateTime({ tsMs }: { tsMs: number }) {@@ -57,11 +50,31 @@ function RelativeAge({ tsMs }: { tsMs: number }) {return <>{formatRelativeTime(tsMs)}</>;}+// Each mode's label, the boundary that keeps it current if it changes with+// time, and the reading its tooltip restores: the full date-time for every+// reduced form, the age for the full one.+const MODES: Record<+ TimeDisplayMode,+ {+ format: (tsMs: number) => string;+ nextChangeAt?: (tsMs: number) => number;+ Hidden: ComponentType<{ tsMs: number }>;+ }+> = {+ queue: {+ format: formatQueueTime,+ nextChangeAt: nextQueueTimeChangeAt,+ Hidden: FullDateTime,+ },+ compact: { format: formatCompactDateTime, Hidden: FullDateTime },+ operational: { format: formatOperationalDateTime, Hidden: FullDateTime },+ datetime: { format: formatAbsoluteDateTime, Hidden: RelativeAge },+};+/*** Renders a timestamp in the form its surface calls for, and by default- * reveals on hover the reading its label hides: the full date-time for every- * reduced form, the age for the full one. This is the single canonical way to- * display a record timestamp across the app.+ * reveals on hover the reading its label hides. This is the single canonical+ * way to display a record timestamp across the app.*/export function HumanizeTs({ts,@@ -72,22 +85,15 @@ export function HumanizeTs({// Subscribe to locale changes so the rendered strings update on a language switch.useTranslation();const tsMs = ts * 1000;- // Only the work-queue label ages; the absolute labels never change, so they- // take no place on the shared clock.- useNow(mode === "queue" ? nextQueueTimeChangeAt(tsMs) : undefined);- const label = FORMATTERS[mode](tsMs);+ const { format, nextChangeAt, Hidden } = MODES[mode];+ useNow(nextChangeAt?.(tsMs));+ const label = format(tsMs);if (!tooltip) {return <span className={className}>{label}</span>;}return (<Tooltip- content={- mode === "datetime" ? (- <RelativeAge tsMs={tsMs} />- ) : (- <FullDateTime tsMs={tsMs} />- )- }+ content={<Hidden tsMs={tsMs} />}render={<span className={className} />}>{label}diff --git a/frontend/src/components/SampleExpirationAlert.tsx b/frontend/src/components/SampleExpirationAlert.tsxindex 7c93925023..af7f281e56 100644--- a/frontend/src/components/SampleExpirationAlert.tsx+++ b/frontend/src/components/SampleExpirationAlert.tsx@@ -1,11 +1,14 @@import { useTranslation } from "react-i18next";import { Alert } from "@/components/ui/alert";+import { useNow } from "@/hooks/useNow";import { normalizeInstanceName } from "@/lib/resourceName";import { useAppStore } from "@/stores/app";import { getTimeForPbTimestampProtoEs } from "@/types";-import { formatAbsoluteDateTime } from "@/utils";--const DAY_MS = 24 * 60 * 60 * 1000;+import {+ formatAbsoluteDateTime,+ nextDaysLeftChangeAt,+ readDaysLeft,+} from "@/utils/datetime";type SampleExpirationAlertProps = Readonly<{instanceName: string;@@ -21,20 +24,27 @@ export function SampleExpirationAlert({({ instance }) => instance === canonicalInstanceName)?.expireTime;- if (!expireTime) {+ const expireTimeMs = expireTime+ ? getTimeForPbTimestampProtoEs(expireTime)+ : undefined;+ useNow(+ expireTimeMs === undefined ? undefined : nextDaysLeftChangeAt(expireTimeMs)+ );++ if (expireTimeMs === undefined) {return null;}- const expireTimeMs = getTimeForPbTimestampProtoEs(expireTime);const formattedExpireTime = formatAbsoluteDateTime(expireTimeMs);- const remainingMs = expireTimeMs - Date.now();+ const daysLeft = readDaysLeft(expireTimeMs);const description =- remainingMs > 0- ? t("instance.sample-expiration-future", {- count: Math.ceil(remainingMs / DAY_MS),+ daysLeft.kind === "passed"+ ? t("instance.sample-expiration-expired", {time: formattedExpireTime,})- : t("instance.sample-expiration-expired", {+ : t("instance.sample-expiration-future", {+ // The last day counts as one.+ count: daysLeft.kind === "days" ? daysLeft.days : 1,time: formattedExpireTime,});diff --git a/frontend/src/components/task-run-log/SectionContent.tsx b/frontend/src/components/task-run-log/SectionContent.tsxindex aef71e8c43..9a7bd68935 100644--- a/frontend/src/components/task-run-log/SectionContent.tsx+++ b/frontend/src/components/task-run-log/SectionContent.tsx@@ -51,17 +51,15 @@ export function SectionContent({<span className="w-6 shrink-0 text-right text-control-placeholder tabular-nums">{index + 1}</span>- {item.timeMs > 0 ? (- <Tooltip content={formatAbsoluteDateTime(item.timeMs)}>- <span className="shrink-0 text-control-placeholder tabular-nums">- {item.time}- </span>- </Tooltip>- ) : (+ <Tooltip+ content={+ item.timeMs > 0 ? formatAbsoluteDateTime(item.timeMs) : undefined+ }+ ><span className="shrink-0 text-control-placeholder tabular-nums">{item.time}</span>- )}+ </Tooltip>{item.relativeTime ? (<span className="shrink-0 text-control-placeholder tabular-nums">{item.relativeTime}diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsxindex 696da0a5df..b428375173 100644--- a/frontend/src/components/ui/tooltip.tsx+++ b/frontend/src/components/ui/tooltip.tsx@@ -13,6 +13,8 @@ interface TooltipProps {readonly onOpenChange?: ComponentProps<typeof BaseTooltip.Root>["onOpenChange"];+ /** The trigger element; defaults to an inline-flex wrapper around `children`. */+ readonly render?: ComponentProps<typeof BaseTooltip.Trigger>["render"];}export function Tooltip({@@ -24,10 +26,7 @@ export function Tooltip({open,onOpenChange,render,-}: TooltipProps & {- /** The trigger element; defaults to an inline-flex wrapper around `children`. */- readonly render?: ComponentProps<typeof BaseTooltip.Trigger>["render"];-}) {+}: TooltipProps) {if (!content) {return <>{children}</>;}@@ -66,47 +65,8 @@ export function Tooltip({* div instead of an inline span. Use this when wrapping block content like* form sections.*/-export function BlockTooltip({- content,- children,- side = "top",- delayDuration = 100,- popupClassName,- render,- open,- onOpenChange,-}: TooltipProps & {- readonly render?: ComponentProps<typeof BaseTooltip.Trigger>["render"];-}) {- if (!content) {- return <>{children}</>;- }-+export function BlockTooltip({ render, ...props }: TooltipProps) {return (- <BaseTooltip.Root open={open} onOpenChange={onOpenChange}>- <BaseTooltip.Trigger- delay={delayDuration}- render={render ?? <div className="flex-1 min-w-0" />}- >- {children}- </BaseTooltip.Trigger>- <BaseTooltip.Portal container={getLayerRoot("overlay")}>- <BaseTooltip.Positioner- side={side}- sideOffset={4}- className={LAYER_SURFACE_CLASS}- >- <BaseTooltip.Popup- className={cn(- "max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md",- popupClassName- )}- >- {content}- <BaseTooltip.Arrow className="fill-main" />- </BaseTooltip.Popup>- </BaseTooltip.Positioner>- </BaseTooltip.Portal>- </BaseTooltip.Root>+ <Tooltip {...props} render={render ?? <div className="flex-1 min-w-0" />} />);}diff --git a/frontend/src/hooks/useNow.test.tsx b/frontend/src/hooks/useNow.test.tsxindex 39bcc650ef..02aeecd303 100644--- a/frontend/src/hooks/useNow.test.tsx+++ b/frontend/src/hooks/useNow.test.tsx@@ -121,6 +121,48 @@ describe("useNow", () => {act(() => root.unmount());});+ test("catches up when the wall clock passes a deadline the timer has not", () => {+ // Timers do not count time the machine sleeps, so after a night asleep the+ // wall clock can be past a deadline that the timer still waits hours for.+ const deadlineMs = Date.now() + 2 * 3_600_000;+ const { renders } = mount([{ changesAtMs: () => deadlineMs }]);++ vi.setSystemTime(Date.now() + 3 * 3_600_000);+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(renders).toEqual([2]);+ });++ test("does not spin on a boundary that keeps naming a past instant", () => {+ const { renders } = mount([{ changesAtMs: () => Date.now() - 1 }]);++ // Step as a browser would, committing between timer turns.+ for (let step = 0; step < 100; step++) {+ act(() => {+ vi.advanceTimersByTime(10);+ });+ }+ expect(renders[0]).toBeLessThanOrEqual(6);+ });++ test("leaves a subscriber whose boundary did not advance to its last reading", () => {+ const stuckMs = Date.now() + 500;+ const { renders } = mount([+ { changesAtMs: () => stuckMs },+ // A neighbour that wakes every second.+ { changesAtMs: () => Math.floor(Date.now() / 1_000) * 1_000 + 1_000 },+ ]);++ for (let second = 0; second < 10; second++) {+ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ }+ expect(renders[0]).toBe(2);+ expect(renders[1]).toBeGreaterThanOrEqual(10);+ });+test("releases the timer when the last subscriber leaves", () => {const { root } = mount([{ changesAtMs: () => Date.now() + 1_000 }]);expect(vi.getTimerCount()).toBe(1);diff --git a/frontend/src/hooks/useNow.ts b/frontend/src/hooks/useNow.tsindex 766ad86832..d384881a48 100644--- a/frontend/src/hooks/useNow.ts+++ b/frontend/src/hooks/useNow.ts@@ -5,10 +5,9 @@ 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 re-renders and must declare a- * strictly later instant; one that does not is left out of the next deadline,- * so a boundary that fails to advance freezes its label rather than spinning- * the clock. A display that never changes with time subscribes to nothing.+ * 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.*/type Subscriber = {changesAtMs: number;@@ -18,10 +17,16 @@ type Subscriber = {const subscribers = new Set<Subscriber>();let timer: ReturnType<typeof setTimeout> | undefined;let armedForMs = Number.POSITIVE_INFINITY;+let lastTickMs = Number.NEGATIVE_INFINITY;-// setTimeout keeps its delay in a signed 32-bit integer and fires at once when-// asked for more, so a far deadline is reached in steps of at most this.-const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;+// Deadlines are wall-clock instants, but timers do not count time the machine+// sleeps and the wall clock can be adjusted, so the clock re-checks at least+// this often however far its earliest deadline is. It also keeps delays inside+// setTimeout's 32-bit range.+const RESYNC_MS = 60_000;+// A boundary that names a past instant on every render would otherwise re-arm+// at zero delay and spin.+const MIN_WAKE_GAP_MS = 250;function disarm(): void {if (timer !== undefined) {@@ -37,10 +42,13 @@ function arm(changesAtMs: number): void {return;}armedForMs = changesAtMs;- const delayMs = Math.min(- Math.max(changesAtMs - Date.now(), 0),- MAX_TIMER_DELAY_MS+ const nowMs = Date.now();+ // Bounded above too, so a clock stepped backward cannot stretch the gap.+ const gapMs = Math.min(+ Math.max(lastTickMs + MIN_WAKE_GAP_MS - nowMs, 0),+ MIN_WAKE_GAP_MS);+ const delayMs = Math.min(Math.max(changesAtMs - nowMs, gapMs), RESYNC_MS);timer = setTimeout(tick, delayMs);}@@ -48,12 +56,11 @@ function tick(): void {timer = undefined;armedForMs = Number.POSITIVE_INFINITY;const nowMs = Date.now();- // Woken subscribers still hold the instant that just passed until they- // re-render, so the next deadline comes only from those still waiting; each- // woken one re-arms the clock as it declares its next instant.+ lastTickMs = nowMs;let nextMs = Number.POSITIVE_INFINITY;for (const subscriber of subscribers) {if (subscriber.changesAtMs <= nowMs) {+ subscriber.changesAtMs = Number.POSITIVE_INFINITY;subscriber.wake();} else {nextMs = Math.min(nextMs, subscriber.changesAtMs);@@ -63,8 +70,12 @@ function tick(): void {}/**- * Re-renders the caller once `changesAtMs` arrives. Pass `undefined` for a- * display that does not vary with time; it then holds no subscription.+ * Re-renders the caller once `changesAtMs` arrives; `undefined` or `Infinity`+ * holds no subscription.+ *+ * Compute `changesAtMs` before the reading it schedules. Computed after, it can+ * see a change the reading just missed, name the change after that, and leave+ * the stale reading on screen.*/export function useNow(changesAtMs: number | undefined): void {// A counter rather than the time: setting a timestamp can bail out when two@@ -83,8 +94,7 @@ export function useNow(changesAtMs: number | undefined): void {return () => {subscribers.delete(subscriber);// Leaving the timer armed for a departed subscriber costs at most one- // early wake, which re-arms from those remaining; only an empty clock- // needs no timer at all.+ // early wake, which re-arms from those remaining.if (subscribers.size === 0) {disarm();}diff --git a/frontend/src/lib/taskRun.ts b/frontend/src/lib/taskRun.tsindex fcc7640290..cce089cd75 100644--- a/frontend/src/lib/taskRun.ts+++ b/frontend/src/lib/taskRun.ts@@ -73,12 +73,12 @@ export const getTaskRunWaitingMessage = (return t("task-run.status.enqueued");}if (taskRun.status === TaskRun_Status.RUNNING && taskRun.schedulerInfo) {- const cause = taskRun.schedulerInfo.waitingCause;- if (cause?.cause?.case === "parallelTasksLimit") {+ const { reportTime, waitingCause } = taskRun.schedulerInfo;+ // The scheduler stamps a report time on every waiting cause it records;+ // without one there is no "last report" to name.+ if (waitingCause?.cause?.case === "parallelTasksLimit" && reportTime) {return t("task-run.status.waiting-max-tasks-per-rollout", {- time: formatAbsoluteDateTime(- getTimeForPbTimestampProtoEs(taskRun.schedulerInfo.reportTime)- ),+ time: formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(reportTime)),});}}diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsxindex c7c42b299c..95d65c15f0 100644--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx@@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),getAccessGrantDisplayStatus: vi.fn(),getAccessGrantDisplayStatusText: vi.fn(),- getAccessGrantExpirationText: vi.fn(),getAccessGrantExpireTimeMs: vi.fn(),getAccessGrantStatusTagType: vi.fn(),}));@@ -37,7 +36,6 @@ vi.mock("react-i18next", () => ({vi.mock("@/utils/accessGrant", () => ({getAccessGrantDisplayStatus: mocks.getAccessGrantDisplayStatus,getAccessGrantDisplayStatusText: mocks.getAccessGrantDisplayStatusText,- getAccessGrantExpirationText: mocks.getAccessGrantExpirationText,getAccessGrantExpireTimeMs: mocks.getAccessGrantExpireTimeMs,getAccessGrantStatusTagType: mocks.getAccessGrantStatusTagType,}));@@ -144,7 +142,6 @@ beforeEach(async () => {mocks.useTranslation.mockReturnValue({ t: (key: string) => key });mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");- mocks.getAccessGrantExpirationText.mockReturnValue({ type: "never" });mocks.getAccessGrantExpireTimeMs.mockReturnValue(undefined);mocks.getAccessGrantStatusTagType.mockReturnValue("success");diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsxindex 261ecb52fa..30132cc16f 100644--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx@@ -6,12 +6,15 @@ import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";import { useNow } from "@/hooks/useNow";import { cn } from "@/lib/utils";-import { getTimeForPbTimestampProtoEs } from "@/types";-import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";+import {+ type AccessGrant,+ AccessGrant_Status,+} 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,} from "@/utils/accessGrant";import {@@ -46,26 +49,26 @@ 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;+ useNow(+ deadlineMs === undefined ? undefined : nextCountdownChangeAt(deadlineMs)+ );+const displayStatus = getAccessGrantDisplayStatus(grant, issue);const isActive = displayStatus === "ACTIVE";const isExpired = displayStatus === "EXPIRED";const isRejectedOrCanceled =displayStatus !== "ACTIVE" && displayStatus !== "PENDING";const statusLabel = getAccessGrantDisplayStatusText(grant, issue);- // Only an activated grant carries a fixed deadline; a pending one holds a- // duration that starts counting at approval, so it has nothing to count down.- const deadlineMs =- (isActive || isExpired) && grant.expiration.case === "expireTime"- ? getTimeForPbTimestampProtoEs(grant.expiration.value)- : undefined;const statusTagType = getAccessGrantStatusTagType(displayStatus);const badgeVariant = mapTagTypeToBadgeVariant(statusTagType);- useNow(- deadlineMs === undefined ? undefined : nextCountdownChangeAt(deadlineMs)- );-// The countdown is the one form that hides the deadline, so it alone carries// it in a tooltip; the other two are interpolated sentences and state the// deadline in full themselves.diff --git a/frontend/src/modules/sql-editor/components/HistoryPane.tsx b/frontend/src/modules/sql-editor/components/HistoryPane.tsxindex f48c181a19..d3533bc88e 100644--- a/frontend/src/modules/sql-editor/components/HistoryPane.tsx+++ b/frontend/src/modules/sql-editor/components/HistoryPane.tsx@@ -29,11 +29,8 @@ import {import { useAppStore } from "@/stores/app";import { DEBOUNCE_SEARCH_DELAY, getTimeForPbTimestampProtoEs } from "@/types";import type { QueryHistory } from "@/types/proto-es/v1/query_history_service_pb";-import {- extractProjectResourceName,- extractQueryHistoryUID,- formatAbsoluteDateTime,-} from "@/utils";+import { extractProjectResourceName, extractQueryHistoryUID } from "@/utils";+import { queryHistoryTabTitle } from "@/utils/v1/queryHistory";import { HistorySearchInput } from "./HistorySearchInput";/**@@ -121,12 +118,6 @@ export function HistoryPane() {[resetPageToken, historyQuery]);- // A tab title cannot host a tooltip, so it names the time in full.- const titleOfQueryHistory = (h: QueryHistory) =>- h.createTime- ? `Query history at ${formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(h.createTime))}`- : "Query history";-const handleHistoryClick = async (history: QueryHistory) => {const { statement } = history;const tabsState = getSQLEditorTabsState();@@ -138,7 +129,7 @@ export function HistoryPane() {} else {tabsState.addTab({- title: titleOfQueryHistory(history),+ title: queryHistoryTabTitle(history),statement,},/* beside */ truediff --git a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsxindex e07e5cedca..a7b1028783 100644--- a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx+++ b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx@@ -37,7 +37,6 @@ import {import { useAppStore } from "@/stores/app";import {DEFAULT_SQL_EDITOR_TAB_MODE,- getTimeForPbTimestampProtoEs,isValidDatabaseName,isValidInstanceName,isValidProjectName,@@ -49,13 +48,13 @@ import {extractInstanceResourceName,extractProjectResourceName,extractSavedQueryID,- formatAbsoluteDateTime,generateSimpleSelectAllStatement,getDatabaseEngine,getSheetStatement,isSavedQueryReadableV1,storageKeySqlEditorSidebarTab,} from "@/utils";+import { queryHistoryTabTitle } from "@/utils/v1/queryHistory";import { SQLEditorHomePage } from "./SQLEditorHomePage";// Route-name set for the unsaved-changes leave guard. `router.beforeEach`@@ -411,12 +410,9 @@ export function SQLEditorRouteShell() {}}- const title = history.createTime- ? `Query history at ${formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(history.createTime))}`- : "Query history";const tab = getSQLEditorTabsState().addTab({- title,+ title: queryHistoryTabTitle(history),statement: history.statement,...(connection ? { connection } : {}),},diff --git a/frontend/src/routes/project/ProjectAccessGrantsPage.tsx b/frontend/src/routes/project/ProjectAccessGrantsPage.tsxindex 0c59e16297..56064cfc4e 100644--- a/frontend/src/routes/project/ProjectAccessGrantsPage.tsx+++ b/frontend/src/routes/project/ProjectAccessGrantsPage.tsx@@ -57,11 +57,12 @@ import {type AccessGrantDisplayStatus,getAccessGrantDisplayStatus,getAccessGrantDisplayStatusText,+ getAccessGrantExpireTimeMs,getAccessGrantStatusTagType,getDefaultPagination,hasProjectPermissionV2,+ nextAccessGrantDisplayStatusChangeAt,} from "@/utils";-import { nextPassedAt } from "@/utils/datetime";import { extractDatabaseResourceName } from "@/utils/v1/database";type SortKey = "creator" | "create_time" | "expire_time";@@ -746,24 +747,13 @@ function AccessGrantRow({onRevoke: () => void;}) {const { t } = useTranslation();+ useNow(nextAccessGrantDisplayStatusChangeAt(grant));const status = getAccessGrantDisplayStatus(grant, issue);const createdTimeMs = grant.createTime? getTimeForPbTimestampProtoEs(grant.createTime): undefined;-- // The roster's creation column is meta on a management list, read for- // freshness; the grant's operational fact is when it lapses.- const expireTimeMs =- grant.expiration.case === "expireTime"- ? getTimeForPbTimestampProtoEs(grant.expiration.value)- : undefined;- // An active grant's badge turns to expired when its deadline passes.- useNow(- status === "ACTIVE" && expireTimeMs !== undefined- ? nextPassedAt(expireTimeMs)- : undefined- );+ const expireTimeMs = getAccessGrantExpireTimeMs(grant);return (<TableRow>diff --git a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsxindex d4dbdd673a..1e6181c044 100644--- a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx+++ b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx@@ -1087,29 +1087,14 @@ function ExemptionGrantSection({const title = useMemo(() => generateGrantTitle(grant), [grant]);- const daysLeft = grant.expirationTimestamp- ? readDaysLeft(grant.expirationTimestamp)- : undefined;useNow(grant.expirationTimestamp? nextDaysLeftChangeAt(grant.expirationTimestamp): undefined);- const isExpired = daysLeft?.kind === "passed";-- const expiryLabel = (() => {- switch (daysLeft?.kind) {- case "today":- return t("project.masking-exemption.expires-today");- case "days":- return t("project.masking-exemption.expires-in-days", {- days: daysLeft.days,- count: daysLeft.days,- });- default:- return "";- }- })();+ const daysLeft = grant.expirationTimestamp+ ? readDaysLeft(grant.expirationTimestamp)+ : undefined;return (<div>@@ -1127,7 +1112,11 @@ function ExemptionGrantSection({)}/><span className="font-medium text-sm">{title}</span>- {grant.expirationTimestamp && isExpired ? (+ {!grant.expirationTimestamp || !daysLeft ? (+ <span className="text-xs font-medium text-amber-600">+ {t("settings.sensitive-data.never-expires")}+ </span>+ ) : daysLeft.kind === "passed" ? (<><HumanizeTsclassName="text-xs text-control-light line-through"@@ -1138,10 +1127,15 @@ function ExemptionGrantSection({({t("sql-editor.expired")})</span></>- ) : grant.expirationTimestamp ? (+ ) : (<><span className="text-xs font-medium text-info">- {expiryLabel}+ {daysLeft.kind === "days"+ ? t("project.masking-exemption.expires-in-days", {+ days: daysLeft.days,+ count: daysLeft.days,+ })+ : t("project.masking-exemption.expires-today")}</span><span className="text-xs text-control-light">(@@ -1152,10 +1146,6 @@ function ExemptionGrantSection({)</span></>- ) : (- <span className="text-xs font-medium text-warning">- {t("settings.sensitive-data.never-expires")}- </span>)}</div><Buttondiff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsxindex 2fc3425c91..4a62efa154 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx@@ -71,6 +71,7 @@ vi.mock("@/utils", () => ({vi.mock("@/utils/accessGrant", () => ({getAccessGrantExpirationText: () => ({ type: "never" }),+ getAccessGrantExpireTimeMs: () => undefined,}));vi.mock("../context/IssueDetailContext", () => ({diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsxindex 59ff609fc9..5e271c762a 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx@@ -6,10 +6,13 @@ import { HumanizeTs } from "@/components/HumanizeTs";import { useProjectByName } from "@/hooks/useProjectByName";import { useAppStore } from "@/stores/app";import { projectNamePrefix } from "@/stores/modules/v1/common";-import { getTimeForPbTimestampProtoEs, isValidDatabaseName } from "@/types";+import { isValidDatabaseName } from "@/types";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";import { extractProjectResourceName, hasProjectPermissionV2 } from "@/utils";-import { getAccessGrantExpirationText } from "@/utils/accessGrant";+import {+ getAccessGrantExpirationText,+ getAccessGrantExpireTimeMs,+} from "@/utils/accessGrant";import { useIssueDetailContext } from "../context/IssueDetailContext";export function IssueDetailAccessGrantDetails() {@@ -80,6 +83,9 @@ export function IssueDetailAccessGrantDetails() {const expirationInfo = accessGrant? getAccessGrantExpirationText(accessGrant): { type: "never" as const };+ const expireTimeMs = accessGrant+ ? getAccessGrantExpireTimeMs(accessGrant)+ : undefined;return (<div className="flex flex-col gap-y-4">@@ -175,15 +181,8 @@ export function IssueDetailAccessGrantDetails() {// post-activation (input-only proto field); we// can't recover it without double-counting the// approval wait. Bot review #3370767734.- accessGrant.expiration.case === "expireTime" && (- <HumanizeTs- mode="operational"- ts={- getTimeForPbTimestampProtoEs(- accessGrant.expiration.value- ) / 1000- }- />+ expireTimeMs !== undefined && (+ <HumanizeTs mode="operational" ts={expireTimeMs / 1000} />)}</div></div>diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailTaskRunTable.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailTaskRunTable.tsxindex 7bd151f8f3..a338d55a5c 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailTaskRunTable.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailTaskRunTable.tsx@@ -1,3 +1,4 @@+import type { Timestamp } from "@bufbuild/protobuf/wkt";import { useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";@@ -20,7 +21,7 @@ import {} from "@/lib/taskRun";import { useAppStore } from "@/stores/app";import { projectNamePrefix } from "@/stores/modules/v1/common";-import { getDateForPbTimestampProtoEs } from "@/types";+import { getTimeForPbTimestampProtoEs } from "@/types";import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";import { databaseForTask, extractTaskUID, humanizeDurationV1 } from "@/utils";import { useIssueDetailContext } from "../context/IssueDetailContext";@@ -175,24 +176,14 @@ function IssueDetailTaskRunComment({ taskRun }: { taskRun: TaskRun }) {);}-function IssueDetailTaskRunDateCell({- date,-}: {- date?: Parameters<typeof getDateForPbTimestampProtoEs>[0];-}) {+function IssueDetailTaskRunDateCell({ date }: { date?: Timestamp }) {if (!date) {return <span className="text-control-light">-</span>;}-- const parsedDate = getDateForPbTimestampProtoEs(date);- if (!parsedDate) {- return <span className="text-control-light">-</span>;- }-return (<HumanizeTsmode="compact"- ts={parsedDate.getTime() / 1000}+ ts={getTimeForPbTimestampProtoEs(date) / 1000}className="text-sm text-control"/>);diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsxindex 8099013bc9..63bb039962 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx@@ -32,10 +32,7 @@ export function PlanDetailMeta() {() => extractUserEmail(page.plan.creator),[page.plan.creator]);- const createdTimeTs = useMemo(- () => getTimeForPbTimestampProtoEs(page.plan.createTime, 0),- [page.plan.createTime]- );+ const createdTimeTs = getTimeForPbTimestampProtoEs(page.plan.createTime, 0);const allowChangeLabels = useMemo(() => {if (!project || !page.issue || page.issue.status !== IssueStatus.OPEN) {return false;diff --git a/frontend/src/types/timestamp.ts b/frontend/src/types/timestamp.tsindex 5cc129bf52..9e9e0e9ebe 100644--- a/frontend/src/types/timestamp.ts+++ b/frontend/src/types/timestamp.ts@@ -1,15 +1,28 @@import type { Timestamp as TimestampProtoEs } from "@bufbuild/protobuf/wkt";// Helper functions for proto-es timestamps (which use bigint for seconds)-export const getTimeForPbTimestampProtoEs = (++/**+ * Milliseconds since the epoch. A timestamp that may be absent needs an explicit+ * fallback: substituting the current time silently would show "now" as when+ * something happened.+ */+export function getTimeForPbTimestampProtoEs(+ timestamp: TimestampProtoEs+): number;+export function getTimeForPbTimestampProtoEs(+ timestamp: TimestampProtoEs | undefined,+ defaultValue: number+): number;+export function getTimeForPbTimestampProtoEs(timestamp?: TimestampProtoEs,defaultValue = Date.now()-): number => {+): number {if (!timestamp) {return defaultValue;}return Number(timestamp.seconds) * 1000 + timestamp.nanos / 1000000;-};+}export const getDateForPbTimestampProtoEs = (timestamp?: TimestampProtoEsdiff --git a/frontend/src/utils/accessGrant.test.ts b/frontend/src/utils/accessGrant.test.tsnew file mode 100644index 0000000000..8aa80148b8--- /dev/null+++ b/frontend/src/utils/accessGrant.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { create } from "@bufbuild/protobuf";+import { DurationSchema, timestampFromMs } from "@bufbuild/protobuf/wkt";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ AccessGrant_Status,+ AccessGrantSchema,+} from "@/types/proto-es/v1/access_grant_service_pb";++vi.mock("@/lib/i18n", () => ({+ default: { language: "en-US", t: (key: string) => key },+}));++import {+ getAccessGrantDisplayStatus,+ getAccessGrantExpireTimeMs,+ nextAccessGrantDisplayStatusChangeAt,+} from "./accessGrant";++const HOUR_MS = 3_600_000;+const DAY_MS = 86_400_000;++const grantWithDeadline = (status: AccessGrant_Status, deadlineMs: number) =>+ create(AccessGrantSchema, {+ status,+ expiration: { case: "expireTime", value: timestampFromMs(deadlineMs) },+ });++describe("access grant status over time", () => {+ const baseMs = new Date("2026-03-02T12:00:00Z").getTime();++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(baseMs);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ test("an activated grant reads expired from the instant after its deadline", () => {+ const deadlineMs = baseMs + HOUR_MS;+ const grant = grantWithDeadline(AccessGrant_Status.ACTIVE, deadlineMs);++ const changesAtMs = nextAccessGrantDisplayStatusChangeAt(grant);+ expect(changesAtMs).toBe(deadlineMs + 1);++ vi.setSystemTime(changesAtMs - 1);+ expect(getAccessGrantDisplayStatus(grant)).toBe("ACTIVE");+ expect(nextAccessGrantDisplayStatusChangeAt(grant)).toBe(changesAtMs);++ vi.setSystemTime(changesAtMs);+ expect(getAccessGrantDisplayStatus(grant)).toBe("EXPIRED");+ });++ test.each([+ ["an expired", AccessGrant_Status.ACTIVE, baseMs - HOUR_MS],+ ["a pending", AccessGrant_Status.PENDING, baseMs + HOUR_MS],+ ["a revoked", AccessGrant_Status.REVOKED, baseMs + HOUR_MS],+ ])(+ "%s grant's status has nothing left to change",+ (_, status, deadlineMs) => {+ const grant = grantWithDeadline(status, deadlineMs);+ const status0 = getAccessGrantDisplayStatus(grant);++ expect(nextAccessGrantDisplayStatusChangeAt(grant)).toBe(+ Number.POSITIVE_INFINITY+ );+ vi.setSystemTime(baseMs + 400 * DAY_MS);+ expect(getAccessGrantDisplayStatus(grant)).toBe(status0);+ }+ );++ test("a pending grant's ttl is a duration, not a deadline", () => {+ // Taken as `now + ttl`, it would name a different instant on every render.+ const grant = create(AccessGrantSchema, {+ status: AccessGrant_Status.PENDING,+ expiration: {+ case: "ttl",+ value: create(DurationSchema, { seconds: BigInt(HOUR_MS / 1000) }),+ },+ });++ expect(getAccessGrantExpireTimeMs(grant)).toBeUndefined();+ expect(nextAccessGrantDisplayStatusChangeAt(grant)).toBe(+ Number.POSITIVE_INFINITY+ );+ });+});diff --git a/frontend/src/utils/accessGrant.ts b/frontend/src/utils/accessGrant.tsindex 315e8cea64..eab811906a 100644--- a/frontend/src/utils/accessGrant.ts+++ b/frontend/src/utils/accessGrant.ts@@ -7,7 +7,11 @@ 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 } from "@/utils/datetime";+import {+ formatAbsoluteDateTime,+ hasPassed,+ nextPassedAt,+} from "@/utils/datetime";export type AccessGrantFilterStatus =| "ACTIVE"@@ -21,17 +25,16 @@ export type AccessGrantDisplayStatus =| "CANCELED"| "UNKNOWN";+/**+ * The fixed deadline of a grant, if it has one. A pending grant holds a ttl+ * instead: a duration that starts at approval, which names no instant yet.+ */export const getAccessGrantExpireTimeMs = (grant: AccessGrant-): number | undefined => {- if (grant.expiration.case === "expireTime") {- return getTimeForPbTimestampProtoEs(grant.expiration.value);- }- if (grant.expiration.case === "ttl") {- return Date.now() + Number(grant.expiration.value.seconds) * 1000;- }- return undefined;-};+): number | undefined =>+ grant.expiration.case === "expireTime"+ ? getTimeForPbTimestampProtoEs(grant.expiration.value)+ : undefined;export const getAccessGrantExpirationText = (grant: AccessGrant@@ -100,6 +103,16 @@ export const getAccessGrantDisplayStatus = (}};+/** The first instant `getAccessGrantDisplayStatus` reads this grant differently. */+export const nextAccessGrantDisplayStatusChangeAt = (+ grant: AccessGrant+): number => {+ const expireMs = getAccessGrantExpireTimeMs(grant);+ return grant.status === AccessGrant_Status.ACTIVE && expireMs !== undefined+ ? nextPassedAt(expireMs)+ : Number.POSITIVE_INFINITY;+};+export const getAccessGrantDisplayStatusText = (grant: AccessGrant,issue?: Issuediff --git a/frontend/src/utils/datetime.test.ts b/frontend/src/utils/datetime.test.tsindex 8b7cd23ebc..a31359227a 100644--- a/frontend/src/utils/datetime.test.ts+++ b/frontend/src/utils/datetime.test.ts@@ -27,6 +27,7 @@ import {formatQueueTime,formatRelativeTime,hasPassed,+ nextAbsoluteDateChangeAt,nextCountdownChangeAt,nextDaysLeftChangeAt,nextPassedAt,@@ -52,13 +53,6 @@ describe("formatRelativeTime", () => {expect(result).toBe("now");});- test("supports overriding the 'now' threshold", () => {- const result = formatRelativeTime(Date.now() - 5000, {- nowThresholdMs: 3000,- });- expect(result).toContain("seconds ago");- });-test("returns 'X seconds ago' for 10-59 seconds", () => {const result = formatRelativeTime(Date.now() - 30_000);expect(result).toContain("seconds ago");@@ -236,8 +230,9 @@ 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. A boundary checked-// on its own cannot see that it was derived from the wrong 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.const expectBoundaryMatchesReading = (read: (tsMs: number) => string,nextChangeAt: (tsMs: number) => number,@@ -247,78 +242,105 @@ const expectBoundaryMatchesReading = (const reading = read(tsMs);const changesAtMs = nextChangeAt(tsMs);if (changesAtMs === Number.POSITIVE_INFINITY) {- for (const laterMs of [- MINUTE_MS,- HOUR_MS,- DAY_MS,- 20 * DAY_MS,- 100 * DAY_MS,- ]) {+ // 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);expect(read(tsMs)).toBe(reading);}return;}expect(changesAtMs).toBeGreaterThan(startMs);- vi.setSystemTime(startMs + Math.floor((changesAtMs - startMs) / 2));- expect(read(tsMs)).toBe(reading);- vi.setSystemTime(changesAtMs - 1);- expect(read(tsMs)).toBe(reading);+ 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);};-describe("reading boundaries", () => {- const baseMs = new Date("2026-03-02T12:00:00Z").getTime();+// 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"];+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 },+ ])+ )+ );+const startAt = (start: string) => {+ const startMs = new Date(start).getTime();+ vi.setSystemTime(startMs);+ 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();- vi.setSystemTime(baseMs);});afterEach(() => {vi.useRealTimers();});- test.each(SAMPLED_AGES_MS)(- "names the instant the work-queue reading changes (age %i ms)",- (ageMs) => {+ 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 }) => {+ const startMs = startAt(start);expectBoundaryMatchesReading(formatQueueTime,nextQueueTimeChangeAt,- baseMs - ageMs+ timestampOf(startMs - offset, fractionMs, viaSeconds));});- test.each(SAMPLED_AGES_MS)(- "names the instant the relative reading changes (age %i ms)",- (ageMs) => {+ 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(- formatRelativeTime,- nextRelativeTimeChangeAt,- baseMs - ageMs+ formatAbsoluteDate,+ nextAbsoluteDateChangeAt,+ timestampOf(startMs - offset, fractionMs, viaSeconds));});- test.each([-100_000, 100_000])(- "names the same instant on every render inside a bucket (offset %i)",- (offsetMs) => {- const ts = Date.now() + offsetMs;- const first = nextQueueTimeChangeAt(ts);-- // A value that drifted with the clock would re-key the subscription on- // every render, so the shared clock would thrash through a list.- vi.advanceTimersByTime(100);- expect(nextQueueTimeChangeAt(ts)).toBe(first);+ 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 }) => {+ const startMs = startAt(start);+ expectBoundaryMatchesReading(+ formatRelativeTime,+ nextRelativeTimeChangeAt,+ timestampOf(startMs - offset, fractionMs, viaSeconds)+ );});});describe("deadline readings", () => {- const baseMs = new Date("2026-03-02T12:00:00Z").getTime();-// Time left before a deadline, around each edge the readings have: passing,// every minute and the one-day line, and whole days beyond it.const SAMPLED_REMAINING_MS = [@@ -344,6 +366,8 @@ describe("deadline readings", () => {400 * DAY_MS,];+ const baseMs = new Date("2026-03-02T12:00:00Z").getTime();+beforeEach(() => {vi.useFakeTimers();vi.setSystemTime(baseMs);@@ -353,38 +377,33 @@ describe("deadline readings", () => {vi.useRealTimers();});- test.each(SAMPLED_REMAINING_MS)(- "names the instant the countdown changes (%i ms left)",- (remainingMs) => {- expectBoundaryMatchesReading(- (targetMs) => JSON.stringify(readCountdown(targetMs)),- nextCountdownChangeAt,- baseMs + remainingMs- );- }- );-- test.each(SAMPLED_REMAINING_MS)(- "names the instant the days-left reading changes (%i ms left)",- (remainingMs) => {- expectBoundaryMatchesReading(- (targetMs) => JSON.stringify(readDaysLeft(targetMs)),- nextDaysLeftChangeAt,- baseMs + remainingMs- );- }- );-- test.each(SAMPLED_REMAINING_MS)(- "names the instant a deadline passes (%i ms left)",- (remainingMs) => {- expectBoundaryMatchesReading(- (targetMs) => String(hasPassed(targetMs)),- nextPassedAt,- baseMs + remainingMs- );- }- );+ const pairs = [+ [+ "countdown",+ (targetMs: number) => JSON.stringify(readCountdown(targetMs)),+ nextCountdownChangeAt,+ ],+ [+ "days-left",+ (targetMs: number) => JSON.stringify(readDaysLeft(targetMs)),+ nextDaysLeftChangeAt,+ ],+ ["passed", (targetMs: number) => String(hasPassed(targetMs)), nextPassedAt],+ ] as const;++ 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 }) => {+ const startMs = startAt(start);+ expectBoundaryMatchesReading(+ read,+ nextChangeAt,+ timestampOf(startMs + offset, fractionMs, viaSeconds)+ );+ }+ );+ });test("counts down in hours and minutes within the last day", () => {expect(diff --git a/frontend/src/utils/datetime.ts b/frontend/src/utils/datetime.tsindex a2e8087c29..1f1a469c35 100644--- a/frontend/src/utils/datetime.ts+++ b/frontend/src/utils/datetime.ts@@ -6,11 +6,7 @@ const HOUR_MS = 60 * MINUTE_MS;const DAY_MS = 24 * HOUR_MS;export const RELATIVE_THRESHOLD_MS = 30 * DAY_MS;-export const DEFAULT_NOW_THRESHOLD_MS = 10_000;--type RelativeTimeFormatOptions = {- nowThresholdMs?: number;-};+const NOW_THRESHOLD_MS = 10 * SECOND_MS;export function getActiveLocale(): string {return i18n.language;@@ -24,16 +20,16 @@ type RelativeUnit = {// The units a relative reading counts in, each from the age it takes over at.// Below the first, the reading is "now". Both `formatRelativeTime` and the-// boundaries that schedule it read this table, so the two cannot drift apart.-const relativeUnits = (nowThresholdMs: number): RelativeUnit[] => [- { fromMs: nowThresholdMs, unitMs: SECOND_MS, unit: "second" },+// boundary that schedules it read this table, so the two cannot drift apart.+const RELATIVE_UNITS: readonly RelativeUnit[] = [+ { fromMs: NOW_THRESHOLD_MS, unitMs: SECOND_MS, unit: "second" },{ fromMs: MINUTE_MS, unitMs: MINUTE_MS, unit: "minute" },{ fromMs: HOUR_MS, unitMs: HOUR_MS, unit: "hour" },{ fromMs: DAY_MS, unitMs: DAY_MS, unit: "day" },];-const unitIndexForAge = (units: RelativeUnit[], ageMs: number): number =>- units.findLastIndex((unit) => ageMs >= unit.fromMs);+const unitIndexForAge = (ageMs: number): number =>+ RELATIVE_UNITS.findLastIndex((unit) => ageMs >= unit.fromMs);// Building an Intl formatter costs tens of times more than formatting with one,// and these run in every table cell, so each is built once per locale. The time@@ -58,11 +54,7 @@ const dateTimeFormatter = (): Intl.DateTimeFormat =>cachedFormatter(name, (locale) => new Intl.DateTimeFormat(locale, options));-export function formatRelativeTime(- timestampMs: number,- options: RelativeTimeFormatOptions = {}-): string {- const { nowThresholdMs = DEFAULT_NOW_THRESHOLD_MS } = options;+export function formatRelativeTime(timestampMs: number): string {const diffMs = Date.now() - timestampMs;const ageMs = Math.abs(diffMs);const rtf = cachedFormatter(@@ -70,12 +62,11 @@ export function formatRelativeTime((locale) => new Intl.RelativeTimeFormat(locale, { numeric: "auto" }));- const units = relativeUnits(nowThresholdMs);- const index = unitIndexForAge(units, ageMs);+ const index = unitIndexForAge(ageMs);if (index < 0) {return rtf.format(0, "second");}- const { unitMs, unit } = units[index];+ const { unitMs, unit } = RELATIVE_UNITS[index];const sign = diffMs >= 0 ? -1 : 1;return rtf.format(sign * Math.round(ageMs / unitMs), unit);}@@ -134,60 +125,47 @@ export function formatOperationalDateTime(timestampMs: number): string {}).format(timestampMs);}-/**- * The ages bracketing `ageMs` at which a relative reading changes: the latest- * at or below it and the earliest above it. A reading changes where its unit- * switches and, because the count is rounded, at every half unit in between.- * At `capMs` it stops counting altogether.- */-function relativeChangePoints(- ageMs: number,- nowThresholdMs: number,- capMs: number-): { atOrBelowMs?: number; aboveMs: number } {- if (ageMs >= capMs) {- return { atOrBelowMs: capMs, aboveMs: Number.POSITIVE_INFINITY };- }- const units = relativeUnits(nowThresholdMs);- const index = unitIndexForAge(units, ageMs);+function relativeTimeChangeAt(timestampMs: number, nowMs: number): number {+ const diffMs = nowMs - timestampMs;+ const ageMs = Math.abs(diffMs);+ const index = unitIndexForAge(ageMs);+ // Inside the "now" window the reading holds across the timestamp itself,+ // until the past side leaves the window.if (index < 0) {- return { aboveMs: Math.min(units[0].fromMs, capMs) };+ return Math.ceil(timestampMs + NOW_THRESHOLD_MS);}- const { fromMs, unitMs } = units[index];- const toMs = Math.min(- units[index + 1]?.fromMs ?? Number.POSITIVE_INFINITY,- capMs- );- return {- atOrBelowMs: Math.max(- (Math.floor(ageMs / unitMs - 0.5) + 0.5) * unitMs,- fromMs- ),- aboveMs: Math.min((Math.floor(ageMs / unitMs + 0.5) + 0.5) * unitMs, toMs),- };+ // The reading prints a rounded count, so it changes at every half unit as+ // well as where the unit switches.+ const { fromMs, unitMs } = RELATIVE_UNITS[index];+ const count = Math.round(ageMs / unitMs);+ if (diffMs >= 0) {+ const toMs = RELATIVE_UNITS[index + 1]?.fromMs ?? Number.POSITIVE_INFINITY;+ return Math.ceil(timestampMs + Math.min((count + 0.5) * unitMs, toMs));+ }+ // A future timestamp counts down: its reading changes the moment its age+ // drops below the change point at or under it.+ return Math.floor(timestampMs - Math.max((count - 0.5) * unitMs, fromMs)) + 1;}-function nextRelativeReadingChangeAt(- timestampMs: number,- nowThresholdMs: number,- capMs: number-): number {- const diffMs = Date.now() - timestampMs;- const { atOrBelowMs, aboveMs } = relativeChangePoints(- Math.abs(diffMs),- nowThresholdMs,- capMs+function absoluteDateChangeAt(timestampMs: number, nowMs: number): number {+ // A date shows its year unless it falls in the current one, so it changes+ // when the current year turns into or out of the timestamp's.+ const year = new Date(timestampMs).getFullYear();+ return (+ [year, year + 1]+ .map((y) => new Date(y, 0, 1).getTime())+ .find((yearStartMs) => yearStartMs > nowMs) ?? Number.POSITIVE_INFINITY);- if (diffMs >= 0) {- return Math.ceil(timestampMs + aboveMs);- }- // A future timestamp counts down, so its reading changes the moment its age- // drops below the change point at or under it. Inside the "now" window there- // is none: "now" holds across the timestamp until the past side leaves it.- if (atOrBelowMs === undefined) {- return Math.ceil(timestampMs + nowThresholdMs);- }- return Math.floor(timestampMs - atOrBelowMs) + 1;+}++/** The first instant `formatRelativeTime` renders this timestamp differently. */+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());}/**@@ -195,33 +173,21 @@ function nextRelativeReadingChangeAt(* `Infinity` once it has settled on a date for good.*/export function nextQueueTimeChangeAt(timestampMs: number): number {- const changesAtMs = nextRelativeReadingChangeAt(- timestampMs,- DEFAULT_NOW_THRESHOLD_MS,- RELATIVE_THRESHOLD_MS- );- if (Math.abs(Date.now() - timestampMs) < RELATIVE_THRESHOLD_MS) {- return changesAtMs;+ 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 date shows its year unless it falls in the current one, so the reading- // also changes when the current year turns into or out of the timestamp's.- const timestampYear = new Date(timestampMs).getFullYear();- const yearTurnsMs = [timestampYear, timestampYear + 1]- .map((year) => new Date(year, 0, 1).getTime())- .find((yearStartMs) => yearStartMs > Date.now());- return Math.min(changesAtMs, yearTurnsMs ?? Number.POSITIVE_INFINITY);-}--/** The first instant `formatRelativeTime` renders this timestamp differently. */-export function nextRelativeTimeChangeAt(- timestampMs: number,- options: RelativeTimeFormatOptions = {}-): number {- return nextRelativeReadingChangeAt(- timestampMs,- options.nowThresholdMs ?? DEFAULT_NOW_THRESHOLD_MS,- Number.POSITIVE_INFINITY- );+ // Past the switch it reads as a date, and a future one counts back into+ // the relative window.+ const reentersAtMs =+ diffMs < 0+ ? Math.floor(timestampMs - RELATIVE_THRESHOLD_MS) + 1+ : Number.POSITIVE_INFINITY;+ return Math.min(reentersAtMs, absoluteDateChangeAt(timestampMs, nowMs));}// Readings of a deadline. Each is paired with the first instant it changes, so@@ -269,10 +235,10 @@ export function nextCountdownChangeAt(targetMs: number): number {}// The count is whole minutes left, so it drops the moment the time left// falls below the current count. With no minute left, that is the deadline.- const thresholdMs =- remainingMs >= DAY_MS- ? DAY_MS- : Math.floor(remainingMs / MINUTE_MS) * MINUTE_MS;+ const thresholdMs = Math.min(+ Math.floor(remainingMs / MINUTE_MS) * MINUTE_MS,+ DAY_MS+ );return Math.floor(targetMs - thresholdMs) + 1;}diff --git a/frontend/src/utils/v1/queryHistory.ts b/frontend/src/utils/v1/queryHistory.tsindex cf0a5229c9..99d5c2c032 100644--- a/frontend/src/utils/v1/queryHistory.ts+++ b/frontend/src/utils/v1/queryHistory.ts@@ -1,4 +1,6 @@-import { UNKNOWN_ID } from "@/types";+import { getTimeForPbTimestampProtoEs, UNKNOWN_ID } from "@/types";+import type { QueryHistory } from "@/types/proto-es/v1/query_history_service_pb";+import { formatAbsoluteDateTime } from "@/utils/datetime";// Extracts the query history UID from a resource name like// `projects/{project}/queryHistories/{id}`.@@ -7,3 +9,9 @@ export const extractQueryHistoryUID = (name: string) => {const matches = pattern.exec(name);return matches?.[1] ?? `${UNKNOWN_ID}`;};++// A tab title cannot host a tooltip, so it names the time in full.+export const queryHistoryTabTitle = (history: QueryHistory): string =>+ history.createTime+ ? `Query history at ${formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(history.createTime))}`+ : "Query history";