@yarkivaev/scada 2.6.38 → 2.6.40

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.
@@ -0,0 +1,6 @@
1
+ CREATE TABLE IF NOT EXISTS contiguous_phase_inbox (
2
+ machine text NOT NULL,
3
+ start_time timestamptz NOT NULL,
4
+ phase jsonb NOT NULL,
5
+ PRIMARY KEY (machine, start_time)
6
+ );
@@ -0,0 +1 @@
1
+ GRANT SELECT, INSERT, UPDATE, DELETE ON contiguous_phase_inbox TO supervisor_sink;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.38",
3
+ "version": "2.6.40",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -5,6 +5,7 @@ import measurementStream from '../infrastructure/http/plant/streams/measurementS
5
5
  import alertRoute from '../infrastructure/http/plant/routes/alertRoute.js';
6
6
  import alertStream from '../infrastructure/http/plant/streams/alertStream.js';
7
7
  import timelineRoute from '../infrastructure/http/plant/routes/timelineRoute.js';
8
+ import { phaseAnchors } from '../infrastructure/ingest/sinks/contiguousPhases.js';
8
9
  import timelineStream from '../infrastructure/http/plant/streams/timelineStream.js';
9
10
  import operationRoute from '../infrastructure/http/plant/routes/operationRoute.js';
10
11
  import operationStream from '../infrastructure/http/plant/streams/operationStream.js';
@@ -20,6 +21,22 @@ function pass(_id, rows) {
20
21
  return rows;
21
22
  }
22
23
 
24
+ function currentPhase(watchedPhases, clock) {
25
+ return function project(machine, rows) {
26
+ if (!watchedPhases.has(machine)) {
27
+ return rows;
28
+ }
29
+ const now = clock();
30
+ return rows.map((row) => {
31
+ if ((row.kind ?? 'phase') !== 'phase' || ![0, '0'].includes(row.duration)) {
32
+ return row;
33
+ }
34
+ const start = new Date(row.start_time ?? row.startTime);
35
+ return { ...row, end_time: now > start ? now : start };
36
+ });
37
+ };
38
+ }
39
+
23
40
  /**
24
41
  * Composable plant HTTP API factory.
25
42
  *
@@ -39,6 +56,7 @@ export default function plantApi(basePath, plant, config) {
39
56
  });
40
57
  const extra = opts.extraRoutes || [];
41
58
  const decorate = opts.decorateTimeline || pass;
59
+ const watchedPhases = opts.watchedPhases ?? phaseAnchors(process.env.CONTIGUOUS_PHASE_ANCHORS);
42
60
  const routeList = [
43
61
  ...catalogRoute(basePath, opts.tagCatalog),
44
62
  ...topologyRoute(basePath, plant, time),
@@ -48,8 +66,8 @@ export default function plantApi(basePath, plant, config) {
48
66
  ...measurementRoute(basePath, plant, time),
49
67
  ...alertStream(basePath, plant, time),
50
68
  ...alertRoute(basePath, plant),
51
- ...timelineRoute(basePath, plant, opts.timelineOperator, decorate),
52
- ...timelineStream(basePath, plant, time, decorate),
69
+ ...timelineRoute(basePath, plant, opts.timelineOperator, decorate, currentPhase(watchedPhases, time)),
70
+ ...timelineStream(basePath, plant, time, decorate, watchedPhases),
53
71
  ...operationRoute(basePath, plant, opts.timelineOperator, opts.operationDecisions, opts.owners),
54
72
  ...operationStream(basePath, plant, time),
55
73
  ...heartbeatStream(basePath, time, opts.heartbeat),
@@ -1,3 +1,4 @@
1
+ import { phaseAnchors } from '../infrastructure/ingest/sinks/contiguousPhases.js';
1
2
  import ingestHealth from './ingestHealth.js';
2
3
  import segmentTransactionConfig from './segmentTransactionConfig.js';
3
4
  import segmentBatchStats from './segmentBatchStats.js';
@@ -71,6 +72,7 @@ export function readDeploymentConfig(env) {
71
72
  requestTimeoutMs: parseRequestTimeoutMs(env.REQUEST_TIMEOUT_MS),
72
73
  pipelines: env.COLLECTOR_MODE !== 'external' && env.SINK_PIPELINES !== 'false',
73
74
  pipeline: {
75
+ phaseAnchors: phaseAnchors(env.CONTIGUOUS_PHASE_ANCHORS),
74
76
  repairHistoryOnStart: historyRepair(env.SEGMENT_REPAIR_HISTORY_ON_START),
75
77
  transactions: segmentTransactionConfig(env, dbPoolMax),
76
78
  maxMessageBytes: milliseconds(env, 'STOMP_MAX_MESSAGE_BYTES', 1048576),
@@ -30,7 +30,7 @@ function heartbeatKey(parsed) {
30
30
  * @returns {boolean}
31
31
  */
32
32
  function isHeartbeat(parsed) {
33
- return parsed.type === 'segment' && parsed.duration === 0;
33
+ return parsed.type === 'segment' && parsed.duration === 0 && parsed.properties?.phase_revision === undefined;
34
34
  }
35
35
 
36
36
  /**
@@ -75,7 +75,7 @@ async function respondToRequest(gate, timeline, requestId, req, res) {
75
75
  * @example
76
76
  * timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: 'hmi-kiosk' });
77
77
  */
78
- export default function timelineRoute(basePath, plant, operatorOptions, decorate) {
78
+ export default function timelineRoute(basePath, plant, operatorOptions, decorate, currentPhase) {
79
79
  const gate = timelineOperator(operatorOptions);
80
80
  return [
81
81
  route('GET', `${basePath}/machines/:machineId/segments`, async (req, res, params, query) => {
@@ -96,8 +96,8 @@ export default function timelineRoute(basePath, plant, operatorOptions, decorate
96
96
  return kind.length > 0;
97
97
  });
98
98
  }
99
- const rows = await decorate(params.machineId, await result.machine.timeline.list(options));
100
- jsonResponse({ items: segmentItems(rows) }).send(res);
99
+ const rows = await decorate(params.machineId, await result.machine.timeline.list(options), options);
100
+ jsonResponse({ items: segmentItems(currentPhase ? currentPhase(params.machineId, rows) : rows) }).send(res);
101
101
  }),
102
102
  route('PATCH', `${basePath}/machines/:machineId/segments`, async (req, res, params) => {
103
103
  const result = machineInPlant(plant, params.machineId);
@@ -56,6 +56,32 @@ async function emitRequest(sse, event, decorate, machineId) {
56
56
  }
57
57
  }
58
58
 
59
+ function watchPhase(timeline, sse) {
60
+ const state = { closed: false, version: undefined, timer: undefined };
61
+ async function read() {
62
+ try {
63
+ const rows = await timeline.latest(['phase']);
64
+ const version = JSON.stringify(rows[0] ?? null);
65
+ if (!state.closed && version !== state.version) {
66
+ state.version = version;
67
+ sse.emit('timeline_changed', {});
68
+ }
69
+ } catch {
70
+ // A later read can detect a change after the database reconnects.
71
+ } finally {
72
+ if (!state.closed) {
73
+ state.timer = setTimeout(read, 1000);
74
+ state.timer.unref?.();
75
+ }
76
+ }
77
+ }
78
+ void read();
79
+ return function stop() {
80
+ state.closed = true;
81
+ clearTimeout(state.timer);
82
+ };
83
+ }
84
+
59
85
  /**
60
86
  * Timeline SSE routes for segments and label requests.
61
87
  *
@@ -68,7 +94,7 @@ async function emitRequest(sse, event, decorate, machineId) {
68
94
  * @example
69
95
  * timelineStream('/api/v1', plant, clock);
70
96
  */
71
- export default function timelineStream(basePath, plant, clock, decorate) {
97
+ export default function timelineStream(basePath, plant, clock, decorate, watchedPhases = new Set()) {
72
98
  return [
73
99
  route('GET', `${basePath}/machines/:machineId/segments/stream`, (req, res, params) => {
74
100
  const sse = sseResponse(res, clock);
@@ -78,14 +104,17 @@ export default function timelineStream(basePath, plant, clock, decorate) {
78
104
  sse.close();
79
105
  return;
80
106
  }
107
+ const watched = watchedPhases.has(params.machineId);
108
+ const stop = watched ? watchPhase(result.machine.timeline, sse) : undefined;
81
109
  const subscription = result.machine.timeline.stream((event) => {
82
- return emitSegment(sse, event, decorate, params.machineId);
110
+ return watched && event.type === 'created' && !event.retag ? undefined : emitSegment(sse, event, decorate, params.machineId);
83
111
  });
84
112
  const heartbeat = setInterval(() => {
85
113
  sse.heartbeat();
86
114
  }, 30000);
87
- req.on('close', () => {
115
+ (typeof res.once === 'function' ? res : req).on('close', () => {
88
116
  clearInterval(heartbeat);
117
+ stop?.();
89
118
  subscription.cancel();
90
119
  });
91
120
  }),
@@ -25,11 +25,30 @@ function familyRecord(parsed) {
25
25
  };
26
26
  }
27
27
 
28
+ const maxTransitionPieces = 128;
29
+
30
+ function transitionRecord(parsed) {
31
+ if (typeof parsed.machine !== 'string' || !Array.isArray(parsed.pieces) ||
32
+ parsed.pieces.length < 2 || parsed.pieces.length > maxTransitionPieces) {
33
+ throw new Error('Invalid phase transition envelope');
34
+ }
35
+ const pieces = parsed.pieces.map((piece) => {
36
+ return segmentNormalize({ ...piece, type: 'segment', kind: 'phase', machine: parsed.machine });
37
+ });
38
+ if (pieces.at(-1).duration !== 0 || pieces.slice(0, -1).some((piece, index) => {
39
+ return piece.duration <= 0 || piece.end_time !== pieces[index + 1].start_time;
40
+ })) {
41
+ throw new Error('A phase transition must close adjacent phases and open the next');
42
+ }
43
+ return { type: 'phase-transition', machine: parsed.machine, pieces };
44
+ }
45
+
28
46
  /** Decode once before admission so invalid envelopes never enter a transaction batch. */
29
47
  export function decodeSegment(raw) {
30
48
  try {
31
49
  const parsed = JSON.parse(raw.payload);
32
50
  if (parsed.type === 'split-family') { return familyRecord(parsed); }
51
+ if (parsed.type === 'phase-transition') { return transitionRecord(parsed); }
33
52
  return segmentNormalize(parsed);
34
53
  } catch (error) {
35
54
  error.permanent = true;
@@ -1,3 +1,4 @@
1
+ import contiguousPhases, { validatePhaseAnchors } from '../sinks/contiguousPhases.js';
1
2
  import stompOptions from './stompOptions.js';
2
3
  import segmentTransactions from './segmentTransactions.js';
3
4
  import segmentBatchPolicy from './segmentBatchPolicy.js';
@@ -23,7 +24,7 @@ export const segmentColumns = ['machine', 'kind', 'name', 'start_time', 'end_tim
23
24
  export const segmentConflict = ['machine', 'kind', 'start_time'];
24
25
  export const segmentUpdateColumns = ['name', 'end_time', 'duration', 'options', 'resolved', 'updated_at'];
25
26
  export const splitUpdateColumns = ['name', 'end_time', 'duration', 'tags', 'options', 'properties', 'resolved'];
26
- export const segmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (segments.duration > 0 AND EXCLUDED.duration = 0 AND COALESCE(segments.properties, \'\') LIKE \'%"split_of"%\' AND EXISTS (SELECT 1 FROM segments AS kin WHERE kin.machine = segments.machine AND kin.kind = segments.kind AND kin.start_time > segments.start_time AND COALESCE(kin.properties, \'\') LIKE \'%"split_of"%\')) AND NOT EXISTS (SELECT 1 FROM segments AS later WHERE later.machine = segments.machine AND later.kind = segments.kind AND later.start_time > segments.start_time)';
27
+ export const segmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (segments.duration > 0 AND EXCLUDED.duration = 0 AND COALESCE(segments.properties, \'\') LIKE \'%"split_of"%\' AND EXISTS (SELECT 1 FROM segments AS kin WHERE kin.machine = segments.machine AND kin.kind = segments.kind AND kin.start_time > segments.start_time AND COALESCE(kin.properties, \'\') LIKE \'%"split_of"%\')) AND (NOT EXISTS (SELECT 1 FROM segments AS later WHERE later.machine = segments.machine AND later.kind = segments.kind AND later.start_time > segments.start_time) OR (segments.duration > 0 AND EXCLUDED.duration = segments.duration AND EXCLUDED.name = segments.name AND EXCLUDED.end_time = segments.end_time))';
27
28
  export const segmentsIngestDestination = '/queue/scada.segments.ingest';
28
29
 
29
30
  export { default as segmentDispatch } from '../../../domain/segment/dispatch.js';
@@ -53,16 +54,16 @@ function pipelineSettings(config) {
53
54
  return settings;
54
55
  }
55
56
 
56
- async function repairHistory(pool, budget) {
57
+ async function repairHistory(pool, budget, protectedTracks) {
57
58
  try {
58
- await abutSegments(pool, budget);
59
+ await abutSegments(pool, budget, protectedTracks);
59
60
  } catch (error) {
60
61
  processingErrorLog('abut_segments', error, { budgetSeconds: budget });
61
62
  }
62
63
  }
63
64
 
64
- function repairCasting(pool) {
65
- foldCastingPhases(pool).catch((error) => {
65
+ function repairCasting(pool, protectedTracks) {
66
+ foldCastingPhases(pool, protectedTracks).catch((error) => {
66
67
  processingErrorLog('fold_casting_phases', error, {});
67
68
  });
68
69
  }
@@ -84,7 +85,8 @@ export default function segmentPipeline(stomp, postgres, pool, config) {
84
85
  const budget = silenceBudget(settings.segmentWindow || 15);
85
86
  const { segmentSink, splitSink } = segmentSinks(postgres, pool);
86
87
  const continued = continuedSegments(segmentSink, pool, budget);
87
- const dispatch = segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool);
88
+ const dispatch = contiguousPhases(pool, settings.phaseAnchors,
89
+ segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool));
88
90
  // eslint-disable-next-line prefer-const -- The timer codec closes over the source constructed with that codec.
89
91
  let source;
90
92
  const codec = segmentCodec(dispatch);
@@ -106,20 +108,22 @@ export default function segmentPipeline(stomp, postgres, pool, config) {
106
108
  stompOptions(settings, { serial: false, manualAck: true, deliveryTimeoutMs, onFatal(error) {
107
109
  coalesce.abort?.(error);settings.onFatal?.(error);
108
110
  } }));
109
- const silence = silentOpenWatch(closeSilentOpen(pool), budget, {
111
+ const silence = silentOpenWatch(closeSilentOpen(pool, [...(settings.phaseAnchors?.keys() ?? [])]), budget, {
110
112
  intervalMs: (settings.poll || 5) * 1000
111
113
  });
112
114
  return {
113
115
  health() { return source.health(); },
114
116
  destination,
115
117
  async start() {
118
+ const protectedTracks = [...(settings.phaseAnchors?.keys() ?? [])];
119
+ await validatePhaseAnchors(pool, settings.phaseAnchors);
116
120
  if (settings.repairHistoryOnStart !== false) {
117
- await repairHistory(pool, budget);
121
+ await repairHistory(pool, budget, protectedTracks);
118
122
  }
119
123
  await source.start();
120
124
  await silence.start();
121
125
  if (settings.repairHistoryOnStart !== false) {
122
- repairCasting(pool);
126
+ repairCasting(pool, protectedTracks);
123
127
  }
124
128
  },
125
129
  stop() {
@@ -6,6 +6,7 @@ const GAP_SQL = `UPDATE segments AS left_row
6
6
  lead(start_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_start,
7
7
  lead(name) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_name
8
8
  FROM segments
9
+ WHERE kind <> 'phase' OR NOT (machine = ANY($2::text[]))
9
10
  ) AS next_row
10
11
  WHERE left_row.machine = next_row.machine
11
12
  AND left_row.kind = next_row.kind
@@ -37,6 +38,7 @@ const ABSORB_SQL = `UPDATE segments AS left_row
37
38
  lead(end_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_end,
38
39
  lead(duration) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_duration
39
40
  FROM segments
41
+ WHERE kind <> 'phase' OR NOT (machine = ANY($2::text[]))
40
42
  ) AS next_row
41
43
  WHERE left_row.machine = next_row.machine
42
44
  AND left_row.kind = next_row.kind
@@ -51,6 +53,7 @@ const COLLAPSE_SQL = `DELETE FROM segments AS later
51
53
  lead(start_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_start,
52
54
  lead(name) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_name
53
55
  FROM segments
56
+ WHERE kind <> 'phase' OR NOT (machine = ANY($2::text[]))
54
57
  ) AS pair
55
58
  WHERE later.machine = pair.machine
56
59
  AND later.kind = pair.kind
@@ -65,13 +68,14 @@ const COLLAPSE_SQL = `DELETE FROM segments AS later
65
68
  *
66
69
  * @param {object} pool - pg pool
67
70
  * @param {number} budgetSeconds - maximum gap that still counts as continuous
71
+ * @param {string[]} protectedTracks - machines whose phase boundaries are authoritative
68
72
  * @returns {Promise<void>}
69
73
  *
70
74
  * @example
71
75
  * await abutSegments(pool, 30);
72
76
  */
73
- export default async function abutSegments(pool, budgetSeconds) {
74
- await pool.query(GAP_SQL, [budgetSeconds]);
75
- await pool.query(ABSORB_SQL, [budgetSeconds]);
76
- await pool.query(COLLAPSE_SQL, [budgetSeconds]);
77
+ export default async function abutSegments(pool, budgetSeconds, protectedTracks = []) {
78
+ await pool.query(GAP_SQL, [budgetSeconds, protectedTracks]);
79
+ await pool.query(ABSORB_SQL, [budgetSeconds, protectedTracks]);
80
+ await pool.query(COLLAPSE_SQL, [budgetSeconds, protectedTracks]);
77
81
  }
@@ -13,7 +13,7 @@ import processingErrorLog from '../processingErrorLog.js';
13
13
  * const closer = closeSilentOpen(pool);
14
14
  * await closer.close(30);
15
15
  */
16
- export default function closeSilentOpen(pool) {
16
+ export default function closeSilentOpen(pool, excludedMachines = []) {
17
17
  if (!pool || typeof pool.query !== 'function') {
18
18
  throw new Error('Pool must have a query() method');
19
19
  }
@@ -28,8 +28,9 @@ export default function closeSilentOpen(pool) {
28
28
  )
29
29
  WHERE duration = 0
30
30
  AND end_time > start_time
31
- AND updated_at < NOW() - make_interval(secs => $1)`,
32
- [budgetSeconds]
31
+ AND updated_at < NOW() - make_interval(secs => $1)
32
+ ${excludedMachines.length ? "AND NOT (machine = ANY($2::text[]))" : ""}`,
33
+ excludedMachines.length ? [budgetSeconds, excludedMachines] : [budgetSeconds]
33
34
  );
34
35
  } catch (error) {
35
36
  processingErrorLog('close_silent_open', error, { budgetSeconds });
@@ -0,0 +1,181 @@
1
+ /** An opted-in track advances only from its certified anchor or its current visible tail. */
2
+ export function phaseAnchors(raw) {
3
+ if (raw === undefined) {
4
+ return new Map();
5
+ }
6
+ const values = JSON.parse(raw);
7
+ if (!values || typeof values !== 'object' || Array.isArray(values)) {
8
+ throw new TypeError('CONTIGUOUS_PHASE_ANCHORS must map machine ids to UTC timestamps');
9
+ }
10
+ return new Map(Object.entries(values).map(([machine, value]) => {
11
+ if (!machine || typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT.*Z$/u.test(value) || !Number.isFinite(Date.parse(value))) {
12
+ throw new TypeError('Invalid contiguous phase anchor');
13
+ }
14
+ return [machine, new Date(value).toISOString()];
15
+ }));
16
+ }
17
+
18
+ function revision(properties) {
19
+ // Older property strings need not be valid JSON. The wire revision is a decimal string.
20
+ return `COALESCE(substring((${properties}) from '"phase_revision"[[:space:]]*:[[:space:]]*"([0-9]{1,16})"')::bigint,0)`;
21
+ }
22
+
23
+ function advancesPending(incoming, stored, nondecreasingEnd) {
24
+ return `(${revision(incoming)} > ${revision(stored)}
25
+ OR (${revision(incoming)} = ${revision(stored)} AND ${nondecreasingEnd}))`;
26
+ }
27
+
28
+ const stage = `
29
+ INSERT INTO contiguous_phase_inbox (machine, start_time, phase)
30
+ VALUES ($1,$2,$3)
31
+ ON CONFLICT (machine, start_time) DO UPDATE SET phase=EXCLUDED.phase
32
+ WHERE (contiguous_phase_inbox.phase->>'duration')::numeric = 0
33
+ AND ((EXCLUDED.phase->>'duration')::numeric > 0
34
+ OR ${advancesPending("EXCLUDED.phase->>'properties'", "contiguous_phase_inbox.phase->>'properties'",
35
+ "(EXCLUDED.phase->>'end_time')::timestamptz >= (contiguous_phase_inbox.phase->>'end_time')::timestamptz")})`;
36
+
37
+ const visible = `
38
+ INSERT INTO segments (machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,updated_at)
39
+ VALUES ($1,'phase',$2,$3,$4,$5,$6,$7,$8,$9,now())
40
+ ON CONFLICT (machine,kind,start_time) DO UPDATE SET
41
+ name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
42
+ options=EXCLUDED.options,properties=EXCLUDED.properties,updated_at=EXCLUDED.updated_at
43
+ WHERE segments.duration=0
44
+ AND (EXCLUDED.duration>0 OR
45
+ ((segments.name=EXCLUDED.name OR segments.start_time=segments.end_time)
46
+ AND ${advancesPending('EXCLUDED.properties', 'segments.properties', 'segments.end_time<=EXCLUDED.end_time')}))`;
47
+
48
+ function invalid(message) {
49
+ return Object.assign(new RangeError(message), { permanent: true });
50
+ }
51
+
52
+ function check(row) {
53
+ const span = Date.parse(row.end_time) - Date.parse(row.start_time);
54
+ if (!Number.isSafeInteger(span) || span < 0 ||
55
+ (row.duration !== 0 && (span === 0 || row.duration !== span / 1000))) {
56
+ throw invalid('Invalid phase duration or bounds');
57
+ }
58
+ }
59
+
60
+ function write(runner, row) {
61
+ return runner.query(visible, [row.machine,row.name,row.start_time,row.end_time,row.duration,
62
+ row.options ?? null,row.tags ?? null,row.properties ?? null,row.resolved ?? true]);
63
+ }
64
+
65
+ async function drain(runner, machine, start) {
66
+ let next = start;
67
+ for (;;) {
68
+ // Rows ahead of the tail survive in the inbox until the preceding phase commits.
69
+ // eslint-disable-next-line no-await-in-loop
70
+ const { rows: [item] } = await runner.query(
71
+ 'DELETE FROM contiguous_phase_inbox WHERE machine=$1 AND start_time=$2 RETURNING phase',
72
+ [machine,next]);
73
+ if (!item) {
74
+ return;
75
+ }
76
+ // eslint-disable-next-line no-await-in-loop
77
+ await write(runner, item.phase);
78
+ if (item.phase.duration === 0) {
79
+ return;
80
+ }
81
+ next = item.phase.end_time;
82
+ }
83
+ }
84
+
85
+ async function commit(runner, row, anchor) {
86
+ check(row);
87
+ const { machine } = row;
88
+ await runner.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
89
+ const { rows: [latest] } = await runner.query(`
90
+ SELECT start_time, end_time, duration FROM segments
91
+ WHERE machine=$1 AND kind='phase' AND start_time >= $2
92
+ ORDER BY start_time DESC LIMIT 1`, [machine, anchor]);
93
+ let next = anchor;
94
+ if (latest) {
95
+ next = Number(latest.duration) > 0 ? latest.end_time : latest.start_time;
96
+ }
97
+ if (Date.parse(row.start_time) >= Date.parse(next)) {
98
+ await runner.query(stage, [machine, row.start_time, JSON.stringify(row)]);
99
+ await drain(runner, machine, next);
100
+ }
101
+ }
102
+
103
+ function apply(runner, rows, anchor) {
104
+ return rows.reduce(async (previous, row) => {
105
+ await previous;
106
+ await commit(runner, row, anchor);
107
+ }, Promise.resolve());
108
+ }
109
+
110
+ async function transaction(pool, rows, anchor) {
111
+ const client = await pool.connect();
112
+ try {
113
+ await client.query('BEGIN');
114
+ await apply(client, rows, anchor);
115
+ await client.query('COMMIT');
116
+ } catch (error) {
117
+ await client.query('ROLLBACK');
118
+ throw error;
119
+ } finally {
120
+ client.release();
121
+ }
122
+ }
123
+
124
+ /** Adds durable out-of-order staging for explicitly anchored phase tracks. */
125
+ export default function contiguousPhases(pool, anchors, dispatch) {
126
+ if (!anchors?.size) {
127
+ return dispatch;
128
+ }
129
+ function routed(row) {
130
+ return anchors.has(row.machine) && (row.kind ?? 'phase') === 'phase' &&
131
+ ['segment', 'split', 'split-family', 'phase-transition'].includes(row.type);
132
+ }
133
+ function accept(row, client) {
134
+ if (!routed(row)) {
135
+ return dispatch.accept(row, client);
136
+ }
137
+ if (row.type === 'split-family') {
138
+ throw invalid('An anchored phase track cannot change geometry via split-family');
139
+ }
140
+ if (row.type === 'split') {
141
+ // Casting publishers send a compatibility split before each authoritative segment.
142
+ return Promise.resolve();
143
+ }
144
+ const anchor = anchors.get(row.machine);
145
+ const rows = row.type === 'phase-transition' ? row.pieces : [row];
146
+ return client ? apply(client, rows, anchor) : transaction(pool, rows, anchor);
147
+ }
148
+ return {
149
+ accept,
150
+ acceptMany(records, client) {
151
+ if (!records.some(routed)) {
152
+ return dispatch.acceptMany(records, client);
153
+ }
154
+ return records.reduce(async (pending, row) => {
155
+ await pending;
156
+ return accept(row, client);
157
+ }, Promise.resolve());
158
+ }
159
+ };
160
+ }
161
+
162
+ /** Refuse to adopt an existing noncontiguous suffix as a certified prefix. */
163
+ export async function validatePhaseAnchors(pool, anchors = new Map()) {
164
+ for (const [machine, anchor] of anchors) {
165
+ // eslint-disable-next-line no-await-in-loop
166
+ const { rows: [status] } = await pool.query(`
167
+ WITH suffix AS (
168
+ SELECT start_time,end_time,duration,
169
+ lag(end_time,1,$2::timestamptz) OVER (ORDER BY start_time) AS expected,
170
+ lead(start_time) OVER (ORDER BY start_time) AS next
171
+ FROM segments WHERE machine=$1 AND kind='phase' AND start_time >= $2
172
+ )
173
+ SELECT EXISTS (SELECT 1 FROM suffix WHERE start_time<>expected OR end_time<start_time
174
+ OR (duration=0 AND next IS NOT NULL)) OR EXISTS (
175
+ SELECT 1 FROM segments WHERE machine=$1 AND kind='phase' AND start_time<$2 AND end_time>$2
176
+ ) AS invalid`, [machine,anchor]);
177
+ if (status.invalid) {
178
+ throw new Error(`Cannot adopt noncontiguous phase history for ${machine}`);
179
+ }
180
+ }
181
+ }
@@ -8,7 +8,7 @@ function pointed(record) {
8
8
  }
9
9
 
10
10
  function behind(record, prior) {
11
- return Boolean(prior) && prior.name !== record.name
11
+ return record.duration === 0 && Boolean(prior) && prior.name !== record.name
12
12
  && Date.parse(record.start_time) < Date.parse(prior.start_time);
13
13
  }
14
14
 
@@ -29,7 +29,7 @@ function placed(record, prior, apply) {
29
29
  */
30
30
  async function latest(runner, record) {
31
31
  const result = await runner.query(
32
- `SELECT name, start_time, end_time
32
+ `SELECT name, start_time, end_time, duration
33
33
  FROM segments
34
34
  WHERE machine = $1 AND kind = $2
35
35
  ORDER BY start_time DESC
@@ -39,6 +39,23 @@ async function latest(runner, record) {
39
39
  return result.rows[0];
40
40
  }
41
41
 
42
+ async function reopenContinuation(client, record, prior, next) {
43
+ // The original start proves this heartbeat follows the closed row. A replay
44
+ // at the old start alone cannot reopen it after conversion to a pending point.
45
+ if (client && record.duration === 0 && prior?.duration > 0 &&
46
+ Date.parse(record.start_time) > Date.parse(prior.end_time) &&
47
+ Date.parse(next.start_time) === Date.parse(prior.start_time)) {
48
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${record.machine}`]);
49
+ await client.query(
50
+ `UPDATE segments SET duration=0,end_time=start_time,updated_at=clock_timestamp()
51
+ WHERE machine=$1 AND kind=$2 AND start_time=$3 AND end_time=$4 AND name=$5 AND duration>0
52
+ AND NOT EXISTS (SELECT 1 FROM segments later
53
+ WHERE later.machine=$1 AND later.kind=$2 AND later.start_time>$3)`,
54
+ [record.machine, record.kind || 'phase', prior.start_time, prior.end_time, prior.name]
55
+ );
56
+ }
57
+ }
58
+
42
59
  /**
43
60
  * Segment sink that continues the previous row across a restart
44
61
  * when metric samples never left the continuity budget.
@@ -63,7 +80,9 @@ export default function continuedSegments(inner, pool, budgetSeconds) {
63
80
  if (!seen.has(key)) {
64
81
  seen.set(key, await latest(runner, record));
65
82
  }
66
- const row = placed(record, seen.get(key), apply);
83
+ const previous = seen.get(key);
84
+ const row = placed(record, previous, apply);
85
+ await reopenContinuation(client, record, previous, row);
67
86
  seen.set(key, row);
68
87
  rows.push(row);
69
88
  return { rows, seen };
@@ -124,14 +124,16 @@ async function foldOwnedRetry(pool, machine, attempt) {
124
124
  * Folds overlapping phases on casting machines into a unique timeline.
125
125
  *
126
126
  * @param {object} pool - pg pool
127
+ * @param {string[]} protectedTracks - driver machines with authoritative phases
127
128
  * @returns {Promise<void>}
128
129
  *
129
130
  * @example
130
131
  * await foldCastingPhases(pool);
131
132
  */
132
- export default async function foldCastingPhases(pool) {
133
+ export default async function foldCastingPhases(pool, protectedTracks = []) {
133
134
  const found = await pool.query(
134
- `SELECT DISTINCT machine FROM segments WHERE machine LIKE 'cm%' AND kind='phase'`
135
+ `SELECT DISTINCT machine FROM segments WHERE machine LIKE 'cm%' AND kind='phase' AND NOT (machine = ANY($1::text[]))`,
136
+ [protectedTracks]
135
137
  );
136
138
  await found.rows.reduce(async (prior, row) => {
137
139
  await prior;
@@ -17,6 +17,7 @@ async function prepare(pool, state, token) {
17
17
  token.client.on?.('error', token.onError);
18
18
  await token.runner.query('BEGIN');
19
19
  await token.runner.query("SELECT set_config('statement_timeout', $1, true)", [String(state.timeoutMs)]);
20
+ if (token.cancelled || state.stopped) { throw state.failure ?? new Error('Segment transaction stopped'); }
20
21
  }
21
22
  async function rollback(token) {
22
23
  if (!token.client || token.cancelled) { return false; }
@@ -27,6 +28,7 @@ async function rollback(token) {
27
28
  }
28
29
  }
29
30
  async function apply(dispatch, records, token) {
31
+ token.writing = true;
30
32
  if (typeof dispatch.acceptMany === 'function') {
31
33
  await dispatch.acceptMany(records, token.runner);
32
34
  return;
@@ -37,15 +39,14 @@ async function apply(dispatch, records, token) {
37
39
  }
38
40
  }
39
41
  async function execute(pool, dispatch, records, state, token) {
40
- let phase = 'prepare';
41
42
  try {
42
43
  await prepare(pool, state, token);
43
- phase = 'apply';await apply(dispatch, records, token);
44
- phase = 'commit';await token.runner.query('COMMIT');
44
+ await apply(dispatch, records, token);
45
+ await token.runner.query('COMMIT');
45
46
  return { sqlCalls: token.calls };
46
47
  } catch (error) {
47
48
  const confirmed = await rollback(token);
48
- if (confirmed && phase !== 'prepare' && permanent(error)) { error.permanent = true; }
49
+ if (confirmed && token.writing && permanent(error)) { error.permanent = true; }
49
50
  else if (!state.stopped && !token.cancelled) { state.fail(error); }
50
51
  throw error;
51
52
  } finally {
@@ -67,9 +68,10 @@ export default function segmentTransaction(pool, dispatch, { timeoutMs = 10000,
67
68
  const token = { client: null, released: false, cancelled: false, calls: 0 };
68
69
  token.runner = { query(...args) { token.calls += 1;return token.client.query(...args); } };
69
70
  state.active.add(token);
70
- return deadline(execute(pool, dispatch, records, state, token), timeoutMs, 'Segment transaction', () => {
71
+ return deadline(execute(pool, dispatch, records, state, token), timeoutMs, 'Segment transaction', error => {
71
72
  token.cancelled = true;
72
- release(token, true);
73
+ try { release(token, true); }
74
+ finally { if (token.writing) { state.fail(error); } }
73
75
  });
74
76
  },
75
77
  abort(error = new Error('Segment transaction stopped')) {
@@ -44,13 +44,17 @@ function segmentRow(parsed, startTime, endTime) {
44
44
 
45
45
  function emitPiece(bus, piece) {
46
46
  const times = timestamps(piece);
47
- bus.emit({ type: 'created', segment: segmentRow(piece, times.startTime, times.endTime) });
47
+ const event = { type: 'created', segment: segmentRow(piece, times.startTime, times.endTime) };
48
+ if (piece.type === 'retag') {
49
+ event.retag = true;
50
+ }
51
+ bus.emit(event);
48
52
  }
49
53
 
50
54
  function consume(raw, buses) {
51
55
  const parsed = JSON.parse(raw.payload);
52
56
  const bus = buses[parsed.machine];
53
- if (!bus) {
57
+ if (!bus || parsed.type === 'phase-transition') {
54
58
  return;
55
59
  }
56
60
  if (parsed.type === 'split-family' && Array.isArray(parsed.pieces)) {
@@ -119,7 +119,9 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
119
119
  SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved FROM segments
120
120
  WHERE machine=$1 AND start_time<=$3 AND end_time>=$2
121
121
  ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved`, [machine,new Date((latest?.context.page.from ?? base.from)/timeScale),new Date((latest?.context.page.until ?? base.until)/timeScale)]);
122
- const folded = await historyAbsorb(client, machine, segments);
122
+ // A CAS-validated native page supplies its own phase boundaries and exterior.
123
+ const nativePage = base?.nativeTailMode === nativeTailProtocol;
124
+ const folded = nativePage ? segments : await historyAbsorb(client, machine, segments);
123
125
  for (const item of folded) {
124
126
  // Only computed fields change. User cuts/labels must be applied by caller before commit.
125
127
  // eslint-disable-next-line no-await-in-loop
@@ -134,7 +136,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
134
136
  typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null),
135
137
  typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true, item.consumed ?? true]);
136
138
  }
137
- if (segments.length) { await historyDedupe(client, machine, span(segments)); }
139
+ if (!nativePage && segments.length) { await historyDedupe(client, machine, span(segments)); }
138
140
  const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
139
141
  await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
140
142
  return { applied: true };
@@ -34,6 +34,13 @@ function reads(pool) {
34
34
  if (!Array.isArray(kinds) || kinds.length === 0) {
35
35
  return [];
36
36
  }
37
+ if (kinds.length === 1 && kinds[0] === 'phase') {
38
+ const result = await pool.query(
39
+ `SELECT kind, name, start_time, end_time, duration, options, tags, properties
40
+ FROM segments WHERE machine = $1 AND kind = 'phase' ORDER BY start_time DESC LIMIT 1`,
41
+ [machineId]);
42
+ return result.rows;
43
+ }
37
44
  const result = await pool.query(
38
45
  `SELECT DISTINCT ON (kind) kind, name, start_time, end_time, duration, options, tags, properties
39
46
  FROM segments WHERE machine = $1 AND kind = ANY($2)