Repository navigation
Expand file tree
/
Copy pathschema-baseline.ts
More file actions
131 lines (120 loc) · 7.39 KB
/
Copy pathschema-baseline.ts
File metadata and controls
131 lines (120 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { diffAdditiveToolSchemas, diffToolSchemas, type ToolSchema } from "@/lib/capability-probe.server";
// Schema drift is compared per subject (endpoint + negotiated protocol version),
// and a new shape must be seen on 2 consecutive probes before it counts as drift.
// Why: behind a load balancer during a rolling deploy, probes alternate between
// old and new nodes; naive cycle-to-cycle diffs would report phantom drift.
type Schemas = Record<string, ToolSchema>;
export type SchemaState = {
baselines: Record<string, Schemas>;
pending?: { version: string; schemas: Schemas } | null;
// Recent observations (24h window) used to tell a converging deploy from a split fleet.
seen?: { at: string; version: string; hash: string }[];
// Last confirmed shape transition per protocol version; kept beyond the 24h window.
transitions?: Record<string, { from_hash: string; to_hash: string; transitioned_at: string }>;
// Append-only audit trail of every confirmed transition per protocol version (oldest first).
// Never pruned by the 24h window, so a change stays auditable after it leaves the card window.
history?: Record<string, { from_hash: string; to_hash: string; transitioned_at: string }[]>;
// Non-breaking changes of the last confirmed transition per protocol version.
additive?: Record<string, { changes: string[]; at: string }>;
};
export const FLEET_WINDOW_MS = 24 * 3600_000;
export const FLEET_MIN_SPAN_MS = 6 * 3600_000;
export type FleetView = {
window_hours: 24;
distinct_shapes_24h: number;
observations_24h: number;
complete_observations_24h: number;
last_complete_at: string | null;
verdict: "unobserved_24h" | "single_shape" | "converging" | "split_fleet";
last_transition: { from_hash: string; to_hash: string; transitioned_at: string } | null;
// Every confirmed transition for this subject, oldest first; survives the 24h window.
transition_history: { from_hash: string; to_hash: string; transitioned_at: string }[];
};
// Cap per-version history so a flapping subject cannot grow state without bound;
// 50 confirmed transitions is far beyond any real deploy cadence.
export const TRANSITION_HISTORY_MAX = 50;
// No complete samples = unobserved, not stable. Several shapes alternating for 6h+ (an older shape
// reappears after a newer one) = split fleet behind one endpoint, not drift.
export function fleetView(state: SchemaState, version: string | null, nowMs: number): FleetView {
const v = version ?? "unknown";
// Only complete tools/list probes enter seen (the caller gates partial probes).
const complete = (state.seen ?? []).filter((o) => o.version === v && Number.isFinite(Date.parse(o.at)) && Date.parse(o.at) <= nowMs)
.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
const lastComplete = complete.at(-1);
const obs = complete.filter((o) => nowMs - Date.parse(o.at) <= FLEET_WINDOW_MS);
const distinct = new Set(obs.map((o) => o.hash)).size;
let verdict: FleetView["verdict"] = obs.length === 0 ? "unobserved_24h" : distinct === 1 ? "single_shape" : "converging";
if (distinct >= 2) {
const firstSeen = new Map<string, number>();
let alternated = false;
obs.forEach((o, i) => {
if (!firstSeen.has(o.hash)) firstSeen.set(o.hash, i);
else if (i > 0 && obs[i - 1]?.hash !== o.hash) alternated = true;
});
const first = obs[0];
const last = obs.at(-1);
const span = first && last ? Date.parse(last.at) - Date.parse(first.at) : 0;
if (alternated && span >= FLEET_MIN_SPAN_MS) verdict = "split_fleet";
}
return { window_hours: 24, distinct_shapes_24h: distinct, observations_24h: obs.length, complete_observations_24h: obs.length, last_complete_at: lastComplete?.at ?? null, verdict, last_transition: state.transitions?.[v] ?? null, transition_history: state.history?.[v] ?? [] };
}
// Recompute at read time: failed/partial probes do not refresh the stored subject.
// Missing legacy history is unknown, not a fabricated zero or a fresh timestamp.
export function comparisonSubjectView(stored: string | null, state: SchemaState | null, nowMs: number) {
if (!stored) return null;
try {
const subject = JSON.parse(stored);
if (!subject || typeof subject !== "object" || Array.isArray(subject)) return null;
return {
...subject,
fleet: state && Array.isArray(state.seen)
? fleetView(state, subject.protocol_version ?? null, nowMs)
: subject.fleet ? { ...subject.fleet, complete_observations_24h: null, last_complete_at: null, last_transition: null, transition_history: [] } : null,
};
} catch { return null; }
}
function stable(v: unknown): string {
if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
if (v && typeof v === "object") {
return `{${Object.keys(v as object).sort().map((k) => `${JSON.stringify(k)}:${stable((v as any)[k])}`).join(",")}}`;
}
return JSON.stringify(v ?? null);
}
function fnv(s: string): string {
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
return h.toString(16).padStart(8, "0");
}
export function schemaSubject(endpoint: string, version: string | null, schemas: Schemas) {
const v = version ?? "unknown";
const toolUnion = Object.keys(schemas).sort();
return { endpoint, protocol_version: v, tool_union: toolUnion, key: `${v}:${fnv(stable(toolUnion))}:${fnv(stable(schemas))}` };
}
export function advanceSchemaBaseline(
prevState: SchemaState | null,
legacySchemas: Schemas | null,
version: string | null,
schemas: Schemas,
nowMs: number = Date.now(),
): { state: SchemaState; changes: string[]; status: "baseline" | "stable" | "pending_confirmation" | "confirmed_drift" } {
const v = version ?? "unknown";
const seen = [...(prevState?.seen ?? []), { at: new Date(nowMs).toISOString(), version: v, hash: fnv(stable(schemas)) }]
.filter((o) => nowMs - Date.parse(o.at) <= FLEET_WINDOW_MS)
.slice(-200);
const state: SchemaState = { baselines: { ...(prevState?.baselines ?? {}) }, pending: prevState?.pending ?? null, seen, ...(prevState?.transitions ? { transitions: { ...prevState.transitions } } : {}), ...(prevState?.history ? { history: { ...prevState.history } } : {}), ...(prevState?.additive ? { additive: { ...prevState.additive } } : {}) };
if (!prevState && legacySchemas && Object.keys(legacySchemas).length > 0) state.baselines[v] = legacySchemas;
const base = state.baselines[v];
if (!base) { state.baselines[v] = schemas; state.pending = null; return { state, changes: [], status: "baseline" }; }
if (stable(base) === stable(schemas)) { state.pending = null; return { state, changes: [], status: "stable" }; }
if (state.pending && state.pending.version === v && stable(state.pending.schemas) === stable(schemas)) {
const changes = diffToolSchemas(base, schemas);
state.baselines[v] = schemas; state.pending = null;
const transition = { from_hash: fnv(stable(base)), to_hash: fnv(stable(schemas)), transitioned_at: new Date(nowMs).toISOString() };
state.transitions = { ...(state.transitions ?? {}), [v]: transition };
state.history = { ...(state.history ?? {}), [v]: [...(state.history?.[v] ?? []), transition].slice(-TRANSITION_HISTORY_MAX) };
state.additive = { ...(state.additive ?? {}), [v]: { changes: diffAdditiveToolSchemas(base, schemas), at: new Date(nowMs).toISOString() } };
return { state, changes, status: "confirmed_drift" };
}
state.pending = { version: v, schemas };
return { state, changes: [], status: "pending_confirmation" };
}