@bli-cockpit/telemetry-core 0.1.84 → 0.1.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,6 +44,40 @@ export declare const CollectorHeartbeatSyncStatusSchema: z.ZodEnum<{
44
44
  fail: "fail";
45
45
  not_run: "not_run";
46
46
  }>;
47
+ /**
48
+ * BLI-23181. What the staging gate measured on this tick's volume, and how much
49
+ * Tower itself keeps there. Before this the fleet board could say a machine
50
+ * was paused for low disk but not how low, against which floor, or whether
51
+ * Tower's own bytes were part of the reason: "is it us filling their disk?"
52
+ * had no server-side answer.
53
+ *
54
+ * Byte counts and one gate label only, never a path. `free_bytes`,
55
+ * `total_bytes` and `floor_bytes` are null when the platform could not read
56
+ * the volume (logged on the collector); `collector_bytes` is everything the
57
+ * collector keeps under its state dir, study folders excluded — the same
58
+ * number the 512 MiB ceiling bounds.
59
+ */
60
+ export declare const CollectorDiskGateSchema: z.ZodEnum<{
61
+ open: "open";
62
+ low_disk: "low_disk";
63
+ state_over_ceiling: "state_over_ceiling";
64
+ staging_at_cap: "staging_at_cap";
65
+ }>;
66
+ export type CollectorDiskGate = z.infer<typeof CollectorDiskGateSchema>;
67
+ export declare const CollectorDiskReadingSchema: z.ZodObject<{
68
+ free_bytes: z.ZodNullable<z.ZodNumber>;
69
+ total_bytes: z.ZodNullable<z.ZodNumber>;
70
+ floor_bytes: z.ZodNullable<z.ZodNumber>;
71
+ collector_bytes: z.ZodNumber;
72
+ staging_bytes: z.ZodNumber;
73
+ gate: z.ZodEnum<{
74
+ open: "open";
75
+ low_disk: "low_disk";
76
+ state_over_ceiling: "state_over_ceiling";
77
+ staging_at_cap: "staging_at_cap";
78
+ }>;
79
+ }, z.core.$strict>;
80
+ export type CollectorDiskReading = z.infer<typeof CollectorDiskReadingSchema>;
47
81
  export declare const CollectorHeartbeatSchema: z.ZodObject<{
48
82
  schema_version: z.ZodLiteral<"collector-heartbeat.v1">;
49
83
  generated_at: z.ZodString;
@@ -77,6 +111,19 @@ export declare const CollectorHeartbeatSchema: z.ZodObject<{
77
111
  sessions_pending_upload: z.ZodOptional<z.ZodNumber>;
78
112
  staging_uncommitted_bytes: z.ZodOptional<z.ZodNumber>;
79
113
  staging_uncommitted_reason: z.ZodOptional<z.ZodString>;
114
+ disk: z.ZodOptional<z.ZodObject<{
115
+ free_bytes: z.ZodNullable<z.ZodNumber>;
116
+ total_bytes: z.ZodNullable<z.ZodNumber>;
117
+ floor_bytes: z.ZodNullable<z.ZodNumber>;
118
+ collector_bytes: z.ZodNumber;
119
+ staging_bytes: z.ZodNumber;
120
+ gate: z.ZodEnum<{
121
+ open: "open";
122
+ low_disk: "low_disk";
123
+ state_over_ceiling: "state_over_ceiling";
124
+ staging_at_cap: "staging_at_cap";
125
+ }>;
126
+ }, z.core.$strict>>;
80
127
  memory_install: z.ZodOptional<z.ZodObject<{
81
128
  schema_version: z.ZodLiteral<"memory-install-receipt.v1">;
82
129
  checked_at: z.ZodString;
@@ -52,6 +52,36 @@ export const CollectorHeartbeatSyncStatusSchema = z.enum([
52
52
  "skipped",
53
53
  "not_run",
54
54
  ]);
55
+ /**
56
+ * BLI-23181. What the staging gate measured on this tick's volume, and how much
57
+ * Tower itself keeps there. Before this the fleet board could say a machine
58
+ * was paused for low disk but not how low, against which floor, or whether
59
+ * Tower's own bytes were part of the reason: "is it us filling their disk?"
60
+ * had no server-side answer.
61
+ *
62
+ * Byte counts and one gate label only, never a path. `free_bytes`,
63
+ * `total_bytes` and `floor_bytes` are null when the platform could not read
64
+ * the volume (logged on the collector); `collector_bytes` is everything the
65
+ * collector keeps under its state dir, study folders excluded — the same
66
+ * number the 512 MiB ceiling bounds.
67
+ */
68
+ export const CollectorDiskGateSchema = z.enum([
69
+ "open",
70
+ "low_disk",
71
+ "state_over_ceiling",
72
+ "staging_at_cap",
73
+ ]);
74
+ const ByteCountSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
75
+ export const CollectorDiskReadingSchema = z
76
+ .object({
77
+ free_bytes: ByteCountSchema.nullable(),
78
+ total_bytes: ByteCountSchema.nullable(),
79
+ floor_bytes: ByteCountSchema.nullable(),
80
+ collector_bytes: ByteCountSchema,
81
+ staging_bytes: ByteCountSchema,
82
+ gate: CollectorDiskGateSchema,
83
+ })
84
+ .strict();
55
85
  export const CollectorHeartbeatSchema = z
56
86
  .object({
57
87
  schema_version: z.literal(COLLECTOR_HEARTBEAT_SCHEMA_VERSION),
@@ -156,6 +186,12 @@ export const CollectorHeartbeatSchema = z
156
186
  .max(120)
157
187
  .regex(/^[a-z0-9_:.-]+$/iu)
158
188
  .optional(),
189
+ /**
190
+ * BLI-23181. The volume the gate measured and Tower's own footprint on it.
191
+ * Optional like every counter here: an absent reading means "this collector
192
+ * predates it or could not measure", never "the disk is fine".
193
+ */
194
+ disk: CollectorDiskReadingSchema.optional(),
159
195
  /**
160
196
  * BLI-3729. Is BLI Memory actually switched on for both agent hosts on
161
197
  * this machine? Six words computed by reading the host configs BACK, not
@@ -0,0 +1,41 @@
1
+ export declare const IMAGE_DESCRIPTION_STATE_FILENAME = "image-descriptions.json";
2
+ export declare const IMAGE_DESCRIPTION_STATE_SCHEMA = "cockpit-image-descriptions.v1";
3
+ /** Oldest keys leave first past this many (about 5 MB on disk). */
4
+ export declare const IMAGE_DESCRIPTION_STATE_MAX_KEYS = 150000;
5
+ /** Oldest failures leave first past this many. */
6
+ export declare const IMAGE_FAILED_STATE_MAX_KEYS = 5000;
7
+ /** A lock file older than this belongs to a writer that died. */
8
+ export declare const IMAGE_STATE_LOCK_STALE_MS = 30000;
9
+ export declare function imageStateKey(sha256: string): string;
10
+ export declare function imageDescriptionStatePath(stateDir: string): string;
11
+ /**
12
+ * An image the door answered about and could not describe (BLI-16979). The same bytes will meet the
13
+ * same answer, so the sender waits before it sends them again. Holds a reason label and times only.
14
+ */
15
+ export interface FailedImageRecord {
16
+ reason: string;
17
+ attempts: number;
18
+ /** Epoch milliseconds before which the image is not sent again. */
19
+ retry_after: number;
20
+ }
21
+ /** How long to leave an image alone after its Nth failed attempt. */
22
+ export declare function imageRetryDelayMs(attempts: number, permanent: boolean): number;
23
+ export interface ImageDescriptionState {
24
+ /** Keys already described, oldest first. */
25
+ described: string[];
26
+ failed: Record<string, FailedImageRecord>;
27
+ }
28
+ /** The state on disk. Missing is empty; unreadable or corrupt is empty and said out loud. */
29
+ export declare function readImageDescriptionState(stateDir: string): Promise<ImageDescriptionState>;
30
+ /**
31
+ * Both writers' entries survive: described keys are the union (the caller's order first, then keys
32
+ * only the disk has), and a failure the disk holds that the caller does not is kept unless that
33
+ * image is described by now. When both hold a failure the one with more attempts wins.
34
+ */
35
+ export declare function mergeImageDescriptionStates(mine: ImageDescriptionState, disk: ImageDescriptionState): ImageDescriptionState;
36
+ /**
37
+ * Read the file under the lock, let `next` build the new state from what is really on disk, and
38
+ * write it atomically. A lock that cannot be taken within five seconds is logged and the update
39
+ * still runs: a rare lost update costs a repeat send, a blocked describer would cost every image.
40
+ */
41
+ export declare function updateImageDescriptionState(stateDir: string, next: (disk: ImageDescriptionState) => ImageDescriptionState): Promise<ImageDescriptionState>;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The machine's record of which images the describe door has already answered for, shared by the
3
+ * two writers on one laptop: the 15-minute sync tick (collector) and the BLI Memory daemon, which
4
+ * describes a pasted image seconds after the turn ends (BLI-23328).
5
+ *
6
+ * One small file in the collector state directory. A key is the first 32 hex characters of the
7
+ * image's sha256; the file holds keys, failure labels and times only, never a description, a path
8
+ * or a byte. Because two processes now write it, every write is a read-merge-write under a lock
9
+ * file, renamed into place, so neither loses the other's entries. A lost or corrupt file costs at
10
+ * worst a repeat send, which the server answers "known" without a model call.
11
+ */
12
+ import fs from "node:fs/promises";
13
+ import path from "node:path";
14
+ export const IMAGE_DESCRIPTION_STATE_FILENAME = "image-descriptions.json";
15
+ export const IMAGE_DESCRIPTION_STATE_SCHEMA = "cockpit-image-descriptions.v1";
16
+ /** Oldest keys leave first past this many (about 5 MB on disk). */
17
+ export const IMAGE_DESCRIPTION_STATE_MAX_KEYS = 150_000;
18
+ /** Oldest failures leave first past this many. */
19
+ export const IMAGE_FAILED_STATE_MAX_KEYS = 5_000;
20
+ const KEY_CHARS = 32;
21
+ const LOCK_SUFFIX = ".lock";
22
+ /** A lock file older than this belongs to a writer that died. */
23
+ export const IMAGE_STATE_LOCK_STALE_MS = 30_000;
24
+ const LOCK_WAIT_MS = 5_000;
25
+ const LOCK_POLL_MS = 25;
26
+ const TAG = "[image-descriptions]";
27
+ export function imageStateKey(sha256) {
28
+ return sha256.slice(0, KEY_CHARS);
29
+ }
30
+ export function imageDescriptionStatePath(stateDir) {
31
+ return path.join(stateDir, IMAGE_DESCRIPTION_STATE_FILENAME);
32
+ }
33
+ const HOUR_MS = 3_600_000;
34
+ /** A refusal that repeats for the same bytes (a 4xx): a week, then a month. */
35
+ const PERMANENT_BACKOFF_MS = [7 * 24 * HOUR_MS, 30 * 24 * HOUR_MS];
36
+ /** A failure that may pass (the door or the model was down): 1 h, 6 h, 24 h, then 72 h. */
37
+ const TRANSIENT_BACKOFF_MS = [HOUR_MS, 6 * HOUR_MS, 24 * HOUR_MS, 72 * HOUR_MS];
38
+ /** How long to leave an image alone after its Nth failed attempt. */
39
+ export function imageRetryDelayMs(attempts, permanent) {
40
+ const steps = permanent ? PERMANENT_BACKOFF_MS : TRANSIENT_BACKOFF_MS;
41
+ return steps[Math.min(Math.max(attempts, 1), steps.length) - 1];
42
+ }
43
+ function isMissing(error) {
44
+ const code = error?.code;
45
+ return code === "ENOENT" || code === "ENOTDIR";
46
+ }
47
+ /** The state on disk. Missing is empty; unreadable or corrupt is empty and said out loud. */
48
+ export async function readImageDescriptionState(stateDir) {
49
+ let raw;
50
+ try {
51
+ raw = JSON.parse(await fs.readFile(imageDescriptionStatePath(stateDir), "utf8"));
52
+ }
53
+ catch (error) {
54
+ if (!isMissing(error)) {
55
+ console.error(TAG + " state file unreadable, starting from an empty list", JSON.stringify({ reason: "image_state_unreadable" }));
56
+ }
57
+ return { described: [], failed: {} };
58
+ }
59
+ const record = (raw && typeof raw === "object" ? raw : {});
60
+ const described = Array.isArray(record.described)
61
+ ? record.described.filter((key) => typeof key === "string" && key.length === KEY_CHARS)
62
+ : [];
63
+ const failed = {};
64
+ if (record.failed && typeof record.failed === "object" && !Array.isArray(record.failed)) {
65
+ for (const [key, value] of Object.entries(record.failed)) {
66
+ const entry = value;
67
+ if (key.length !== KEY_CHARS || !entry)
68
+ continue;
69
+ if (typeof entry.reason !== "string" || typeof entry.attempts !== "number" || typeof entry.retry_after !== "number")
70
+ continue;
71
+ failed[key] = { reason: entry.reason, attempts: entry.attempts, retry_after: entry.retry_after };
72
+ }
73
+ }
74
+ return { described, failed };
75
+ }
76
+ /**
77
+ * Both writers' entries survive: described keys are the union (the caller's order first, then keys
78
+ * only the disk has), and a failure the disk holds that the caller does not is kept unless that
79
+ * image is described by now. When both hold a failure the one with more attempts wins.
80
+ */
81
+ export function mergeImageDescriptionStates(mine, disk) {
82
+ const described = [...mine.described];
83
+ const known = new Set(described);
84
+ for (const key of disk.described) {
85
+ if (known.has(key))
86
+ continue;
87
+ known.add(key);
88
+ described.push(key);
89
+ }
90
+ const failed = {};
91
+ for (const [key, record] of Object.entries(mine.failed))
92
+ if (!known.has(key))
93
+ failed[key] = record;
94
+ for (const [key, record] of Object.entries(disk.failed)) {
95
+ if (known.has(key))
96
+ continue;
97
+ const have = failed[key];
98
+ if (!have || record.attempts > have.attempts)
99
+ failed[key] = record;
100
+ }
101
+ return { described, failed };
102
+ }
103
+ /**
104
+ * Read the file under the lock, let `next` build the new state from what is really on disk, and
105
+ * write it atomically. A lock that cannot be taken within five seconds is logged and the update
106
+ * still runs: a rare lost update costs a repeat send, a blocked describer would cost every image.
107
+ */
108
+ export async function updateImageDescriptionState(stateDir, next) {
109
+ await fs.mkdir(stateDir, { recursive: true });
110
+ const filePath = imageDescriptionStatePath(stateDir);
111
+ const release = await acquireStateLock(filePath + LOCK_SUFFIX);
112
+ try {
113
+ const built = next(await readImageDescriptionState(stateDir));
114
+ const kept = built.described.length > IMAGE_DESCRIPTION_STATE_MAX_KEYS
115
+ ? built.described.slice(built.described.length - IMAGE_DESCRIPTION_STATE_MAX_KEYS)
116
+ : built.described;
117
+ const failedEntries = Object.entries(built.failed).sort((a, b) => a[1].retry_after - b[1].retry_after);
118
+ const failed = Object.fromEntries(failedEntries.slice(Math.max(0, failedEntries.length - IMAGE_FAILED_STATE_MAX_KEYS)));
119
+ await writeAtomic(filePath, { schema_version: IMAGE_DESCRIPTION_STATE_SCHEMA, described: kept, failed });
120
+ return { described: kept, failed };
121
+ }
122
+ finally {
123
+ await release();
124
+ }
125
+ }
126
+ async function writeAtomic(filePath, value) {
127
+ const temp = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`;
128
+ try {
129
+ await fs.writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
130
+ if (process.platform !== "win32")
131
+ await fs.chmod(temp, 0o600).catch(() => undefined);
132
+ await fs.rename(temp, filePath);
133
+ }
134
+ catch (error) {
135
+ await fs.rm(temp, { force: true }).catch(() => undefined);
136
+ throw error;
137
+ }
138
+ }
139
+ async function acquireStateLock(lockPath) {
140
+ const deadline = Date.now() + LOCK_WAIT_MS;
141
+ for (;;) {
142
+ try {
143
+ const handle = await fs.open(lockPath, "wx", 0o600);
144
+ await handle.close();
145
+ return async () => {
146
+ await fs.rm(lockPath, { force: true }).catch(() => undefined);
147
+ };
148
+ }
149
+ catch (error) {
150
+ const code = error?.code;
151
+ if (code !== "EEXIST" && code !== "EPERM" && code !== "EACCES") {
152
+ console.error(TAG + " state lock unavailable, updating without it", JSON.stringify({ reason: "image_state_lock_error", error_code: typeof code === "string" ? code : "unknown" }));
153
+ return async () => { };
154
+ }
155
+ }
156
+ const age = await fs.stat(lockPath).then((stat) => Date.now() - stat.mtimeMs).catch(() => null);
157
+ if (age !== null && age > IMAGE_STATE_LOCK_STALE_MS) {
158
+ console.error(TAG + " removing a stale state lock", JSON.stringify({ reason: "image_state_lock_stale", age_ms: Math.round(age) }));
159
+ await fs.rm(lockPath, { force: true }).catch(() => undefined);
160
+ continue;
161
+ }
162
+ if (Date.now() >= deadline) {
163
+ console.error(TAG + " state lock busy, updating without it", JSON.stringify({ reason: "image_state_lock_timeout", waited_ms: LOCK_WAIT_MS }));
164
+ return async () => { };
165
+ }
166
+ await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
167
+ }
168
+ }
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export * from "./evidence-rules-fingerprint.js";
11
11
  export * from "./evidence-stubs.js";
12
12
  export * from "./evidence-transcripts.js";
13
13
  export * from "./evidence-upload.js";
14
+ export * from "./image-description-store.js";
14
15
  export * from "./image-descriptions.js";
15
16
  export * from "./image-marker-resolver.js";
16
17
  export * from "./transcript-images.js";
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ export * from "./evidence-rules-fingerprint.js";
11
11
  export * from "./evidence-stubs.js";
12
12
  export * from "./evidence-transcripts.js";
13
13
  export * from "./evidence-upload.js";
14
+ export * from "./image-description-store.js";
14
15
  export * from "./image-descriptions.js";
15
16
  export * from "./image-marker-resolver.js";
16
17
  export * from "./transcript-images.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.84",
3
+ "version": "0.1.86",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",