@yarkivaev/scada 2.5.7 → 2.6.0

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.
Files changed (107) hide show
  1. package/README.md +136 -2
  2. package/charts/scada/templates/_helpers.tpl +18 -3
  3. package/charts/scada/templates/postgres.yaml +6 -0
  4. package/charts/scada/templates/rabbitmq-config.yaml +5 -1
  5. package/charts/scada/templates/rabbitmq.yaml +12 -1
  6. package/charts/scada/templates/supervisor-sink.yaml +5 -0
  7. package/charts/scada/values.schema.json +46 -1
  8. package/charts/scada/values.yaml +7 -0
  9. package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
  10. package/db/migrations/E0006__historical_telemetry.sql +64 -0
  11. package/db/migrations/E0007__metric_receipts.sql +7 -0
  12. package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
  13. package/db/migrations/E0009__history_continuation.sql +20 -0
  14. package/db/migrations/E0010__history_admissions.sql +8 -0
  15. package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
  16. package/db/migrations/E0012__external_history_grants.sql +4 -0
  17. package/db/migrations/E0013__history_staged_corrections.sql +104 -0
  18. package/db/migrations/E0014__history_correction_grants.sql +5 -0
  19. package/db/migrations/E0015__history_retention_frontier.sql +7 -0
  20. package/db/migrations/E0016__history_retention_grants.sql +1 -0
  21. package/index.js +7 -0
  22. package/package.json +5 -3
  23. package/src/application/control/agent.js +61 -0
  24. package/src/application/control/catalog.js +22 -0
  25. package/src/application/control/controlClient.js +75 -0
  26. package/src/application/control/controlStore.js +55 -0
  27. package/src/application/control/controller.js +22 -0
  28. package/src/application/control/executionSnapshot.js +32 -0
  29. package/src/application/control/index.js +7 -0
  30. package/src/application/control/localAssignment.js +13 -0
  31. package/src/application/control/schedule.js +103 -0
  32. package/src/application/control/snapshotFile.js +24 -0
  33. package/src/application/foldedMetricsSink.js +1 -0
  34. package/src/application/mcp/mcpResources.js +1 -1
  35. package/src/application/mcp/mcpSchema.js +8 -3
  36. package/src/application/runtime/additionalAdapters.js +13 -9
  37. package/src/application/runtime/deliveryQueue.js +62 -0
  38. package/src/application/runtime/deliverySessions.js +28 -0
  39. package/src/application/runtime/modbusDelivery.js +36 -0
  40. package/src/application/runtime/pipelineAdapters.js +12 -8
  41. package/src/application/runtime/queuedDelivery.js +25 -0
  42. package/src/application/runtime/runCollector.js +34 -3
  43. package/src/application/runtime/runtime.js +2 -2
  44. package/src/application/runtime/runtimeHealth.js +1 -1
  45. package/src/application/runtime/runtimeServices.js +6 -2
  46. package/src/application/runtime/streamTask.js +13 -4
  47. package/src/application/runtime/taskContext.js +1 -0
  48. package/src/application/runtime/taskSlot.js +2 -2
  49. package/src/application/runtime/telemetrySink.js +18 -0
  50. package/src/application/siteServer.js +19 -4
  51. package/src/application/siteTelemetry.js +2 -2
  52. package/src/application/supervisorSink.js +32 -12
  53. package/src/application/sync/siteSyncBind.js +2 -2
  54. package/src/bin/controller.js +8 -0
  55. package/src/infrastructure/http/edge/edgeApi.js +2 -0
  56. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
  57. package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
  58. package/src/infrastructure/ingest/db/migrate.js +16 -0
  59. package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
  60. package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
  61. package/src/infrastructure/ingest/db/runRetention.js +2 -0
  62. package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
  63. package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
  64. package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
  65. package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
  66. package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
  67. package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
  68. package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
  69. package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
  70. package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
  71. package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
  72. package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
  73. package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
  74. package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
  75. package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
  76. package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
  77. package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
  78. package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
  79. package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
  80. package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
  81. package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
  82. package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
  83. package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
  84. package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
  85. package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
  86. package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
  87. package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
  88. package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
  89. package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
  90. package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
  91. package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
  92. package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
  93. package/src/infrastructure/persistence/clickhouse/series.js +38 -21
  94. package/src/infrastructure/persistence/pg/history.js +169 -0
  95. package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
  96. package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
  97. package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
  98. package/src/infrastructure/persistence/pg/historyContext.js +65 -0
  99. package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
  100. package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
  101. package/src/infrastructure/persistence/pg/historySeed.js +27 -0
  102. package/src/infrastructure/persistence/pg/metrics.js +5 -4
  103. package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
  104. package/src/infrastructure/persistence/runtime/deliverySpool.js +124 -0
  105. package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
  106. package/src/infrastructure/streams/amqpSink/session.js +6 -0
  107. package/src/infrastructure/streams/amqpSource.js +17 -4
@@ -0,0 +1,70 @@
1
+ import metricsRelation, { annotatedPoints, legacyChartRelation, rawMetricsRelation } from './metricsRelation.js';
2
+
3
+ function missing(error, name) {
4
+ return String(error.code) === '60' && String(error.message).includes(name);
5
+ }
6
+ function missingNative(error) {
7
+ return ['metrics_points_v4','metrics_state_v4'].some((name) => { return missing(error,name); });
8
+ }
9
+ async function query(client, sql, params) {
10
+ const result = await client.query({ query: sql, query_params: params, format: 'JSONEachRow' });
11
+ return result.json();
12
+ }
13
+ function densityChecks(sql) {
14
+ const checks = new Map();
15
+ let cleaned = sql;
16
+ for (const [marker, encoded] of sql.matchAll(/\/\*scada-density-range:(?<encoded>[^*]+)\*\//gu)) {
17
+ cleaned = cleaned.replaceAll(marker,'');
18
+ if (!checks.has(encoded)) {
19
+ const {since,until,gap} = JSON.parse(decodeURIComponent(encoded));
20
+ checks.set(encoded,`SELECT DISTINCT topic FROM (${annotatedPoints(since,until)})
21
+ WHERE (empty({scadaDensityTopics:Array(String)}) OR topic IN {scadaDensityTopics:Array(String)})
22
+ AND (valid_certificate OR (compactable AND island_n>2)) AND first_ts<last_ts
23
+ ${gap === undefined ? '' : `AND max_gap_ms>(${gap})`}
24
+ AND toUnixTimestamp64Milli(first_ts)<=(${until}) AND toUnixTimestamp64Milli(last_ts)>=(${since})`);
25
+ }
26
+ }
27
+ return {cleaned,checks:[...checks.values()]};
28
+ }
29
+ async function density(client, sql, params) {
30
+ const {cleaned,checks} = densityChecks(sql);
31
+ if (!checks.length) { return cleaned; }
32
+ // One bounded request protects all ranges; serial checks could outlive cleanup grace.
33
+ let unavailable;
34
+ try {
35
+ unavailable = await query(client,`/*scada-density-check*/SELECT topic FROM (${checks.join(' UNION ALL ')}) LIMIT 1`,
36
+ {...params,scadaDensityTopics:params.topics ?? (params.topic ? [params.topic] : [])});
37
+ } catch (error) {
38
+ if (!missingNative(error)) { throw error; }
39
+ return cleaned;
40
+ }
41
+ if (unavailable.length) {
42
+ const error = new Error('Exact sample density is unavailable in sealed compacted history; use canonical values or persisted classifications');
43
+ Object.assign(error,{code:'SCADA_HISTORY_DENSITY_UNAVAILABLE',status:409,statusCode:409});
44
+ throw error;
45
+ }
46
+ return cleaned;
47
+ }
48
+ async function legacyCompatible(client) {
49
+ const old = await query(client, "SELECT name FROM system.tables WHERE database='scada' AND name IN ('metrics_points_v3','metrics_state_v3','metrics_rejected_v3','metrics_canonical','metrics_compact_v2')", {});
50
+ if (old.some(row=>{return typeof row.name==='string';})) {
51
+ throw new Error('Previous canonical storage requires an explicit v4 migration; native gap evidence is unavailable');
52
+ }
53
+ }
54
+ /** Read-only upgrades precede writer installation; only absent additive schema falls back. */
55
+ export default async function metricsQuery(client, sql, params) {
56
+ const checked = await density(client,sql.replace(/\bscada\.metrics_raw_read\b/giu,rawMetricsRelation).replace(/\bscada\.metrics_read\b/giu,metricsRelation),params);
57
+ try { return await query(client, checked, params); }
58
+ catch (error) {
59
+ for (const [name, relation] of [['metrics_raw_read',rawMetricsRelation],['metrics_read',metricsRelation]]) {
60
+ const pattern = new RegExp(`\\bscada\\.${name}\\b`, 'giu');
61
+ if (missing(error,name) && pattern.test(checked)) { return metricsQuery(client,checked.replace(pattern,relation),params); }
62
+ }
63
+ if (missingNative(error)) {
64
+ let legacy = checked.replace(/\/\*scada-native-chart-range\*\/[\s\S]*?\/\*end-scada-native-chart-range\*\//gu, legacyChartRelation).replace(/\/\*scada-native-range\*\/[\s\S]*?\/\*end-scada-native-range\*\//gu, 'scada.metrics');
65
+ for (const relation of [rawMetricsRelation, metricsRelation]) { legacy = legacy.replaceAll(relation, 'scada.metrics'); }
66
+ if (legacy !== checked) { await legacyCompatible(client); return query(client, legacy, params); }
67
+ }
68
+ throw error;
69
+ }
70
+ }
@@ -0,0 +1,110 @@
1
+ import { nativeMetricIslandPoints, nativeMetricWindows } from './nativeMetricsCompaction.js';
2
+ import { effectiveNativePoints } from './nativeMetricPoints.js';
3
+
4
+ /** Ordinary native point rows. Never reconstruct or invent deleted observations. */
5
+ export const MAX_COMPACT_WINDOW_MS = 3600000;
6
+ function physical(since, until, expand = false) {
7
+ const bounds = since === undefined ? '' : ` WHERE ts>=fromUnixTimestamp64Milli((${since})-${expand ? MAX_COMPACT_WINDOW_MS : 0}) AND ts<=fromUnixTimestamp64Milli((${until})+${expand ? MAX_COMPACT_WINDOW_MS : 0})`;
8
+ return `SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at FROM scada.metrics_points_v4 FINAL${bounds}`;
9
+ }
10
+ function stored(since,until,expand=false) {
11
+ return effectiveNativePoints(physical(since,until,expand),physical(since,until,true));
12
+ }
13
+ /** Nearest neighbors add at most two complete-window contexts, independently of maxGapMs. */
14
+ function chartStored(since,until) {
15
+ const source=`SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at
16
+ FROM scada.metrics_points_v4 FINAL CROSS JOIN (
17
+ SELECT maxOrNullIf(toUnixTimestamp64Milli(ts),toUnixTimestamp64Milli(ts)<(${since})) AS before_ms,
18
+ minOrNullIf(toUnixTimestamp64Milli(ts),toUnixTimestamp64Milli(ts)>(${until})) AS after_ms
19
+ FROM scada.metrics_points_v4 FINAL WHERE topic={topic:String}
20
+ ) AS neighbors
21
+ WHERE topic={topic:String} AND (
22
+ ts>=fromUnixTimestamp64Milli((${since})-${MAX_COMPACT_WINDOW_MS}) AND ts<=fromUnixTimestamp64Milli((${until})+${MAX_COMPACT_WINDOW_MS})
23
+ OR ts>=fromUnixTimestamp64Milli(before_ms-${MAX_COMPACT_WINDOW_MS}) AND ts<=fromUnixTimestamp64Milli(before_ms+${MAX_COMPACT_WINDOW_MS})
24
+ OR ts>=fromUnixTimestamp64Milli(after_ms-${MAX_COMPACT_WINDOW_MS}) AND ts<=fromUnixTimestamp64Milli(after_ms+${MAX_COMPACT_WINDOW_MS}))`;
25
+ // One FINAL scan with disjunctive bounds returns each physical winner once, even where contexts overlap.
26
+ return effectiveNativePoints(source,source);
27
+ }
28
+ /** Full windows and complete certificates classify continuity before range clipping. */
29
+ export function annotatedPoints(since, until, source=stored(since, until, true)) {
30
+ const fields = ['topic','ts','value','compact_ms','max_gap_ms','window_start','window_ms','point_ms',
31
+ 'island_first_ms','island_last_ms','island_n','valid_certificate','raw_interiors']
32
+ .map(name=>{return `points.${name} AS ${name}`;}).join(',');
33
+ return `SELECT ${fields},
34
+ fromUnixTimestamp64Milli(points.island_first_ms) AS first_ts,fromUnixTimestamp64Milli(points.island_last_ms) AS last_ts,
35
+ w.compact_ms>0 AND w.max_gap_ms>0 AND NOT w.overlap AND ifNull(state.state_exists,0)=1
36
+ AND w.window_start+w.window_ms<=state.closed_before AND w.low=w.high
37
+ AND NOT (legacy.n>0 AND w.window_start<=legacy.last_ms AND w.window_start+w.window_ms>legacy.first_ms) AS compactable
38
+ FROM (${nativeMetricIslandPoints(source)}) AS points
39
+ INNER JOIN (${nativeMetricWindows(source)}) AS w ON points.topic=w.topic AND points.compact_ms=w.compact_ms
40
+ AND points.max_gap_ms=w.max_gap_ms AND points.window_start=w.window_start
41
+ LEFT JOIN (SELECT key,closed_before,1 AS state_exists FROM scada.metrics_state_v4 FINAL WHERE key!='') AS state
42
+ ON state.key=concat('topic:',points.topic)
43
+ LEFT JOIN (SELECT topic,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,count() AS n
44
+ FROM scada.metrics GROUP BY topic) AS legacy ON legacy.topic=points.topic`;
45
+ }
46
+ function relation(points) {
47
+ return `(SELECT topic,ts,argMin(value,priority) AS value FROM (
48
+ SELECT topic,ts,value,0 AS priority FROM scada.metrics
49
+ UNION ALL SELECT topic,ts,value,1 AS priority FROM (${points})
50
+ ) GROUP BY topic,ts)`;
51
+ }
52
+ function adaptive(since, until) {
53
+ return `SELECT topic,ts,value FROM (${annotatedPoints(since, until)}) WHERE NOT compactable OR ts=first_ts OR ts=last_ts`;
54
+ }
55
+ export const rawMetricsRelation = relation(`SELECT topic,ts,value FROM (${stored()})`);
56
+ export default relation(adaptive());
57
+ /** Public point ranges retain their three-column contract. */
58
+ export function metricsRange(since, until) {
59
+ return `/*scada-native-range*/${relation(adaptive(since, until))}/*end-scada-native-range*/`;
60
+ }
61
+ export function rawMetricsRange(since, until) {
62
+ const guard = encodeURIComponent(JSON.stringify({ since, until }));
63
+ return `/*scada-density-range:${guard}*//*scada-native-range*/${relation(`SELECT topic,ts,value FROM (${stored(since, until)})`)}/*end-scada-native-range*/`;
64
+ }
65
+ /** Legacy observations carry no certified coverage or native continuity promise. */
66
+ export const legacyChartRelation = `(SELECT topic,ts,value,toUnixTimestamp64Milli(ts) AS coverage_first_ms,
67
+ toUnixTimestamp64Milli(ts) AS coverage_last_ms,toUInt64(30000) AS max_gap_ms,toUInt8(0) AS native FROM scada.metrics)`;
68
+ /** Adjacent equal observations certify the short bridge across a storage-window boundary. */
69
+ function constantBridges(annotated,since,until,gap) {
70
+ return `SELECT bridge.topic AS topic,fromUnixTimestamp64Milli(arrayJoin(arrayDistinct([
71
+ greatest(prior_ms,toInt64(${since})),least(point_ms,toInt64(${until}))]))) AS ts,
72
+ value,prior_ms AS coverage_first_ms,point_ms AS coverage_last_ms,max_gap_ms,toUInt8(1) AS native
73
+ FROM (SELECT *,lagInFrame(point_ms,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_ms,
74
+ lagInFrame(value,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_value,
75
+ lagInFrame(compact_ms,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_compact_ms,
76
+ lagInFrame(max_gap_ms,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_gap_ms,
77
+ lagInFrame(window_start,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_window_start
78
+ FROM (${annotated})) AS bridge
79
+ LEFT JOIN (SELECT topic,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,count() AS n
80
+ FROM scada.metrics GROUP BY topic) AS legacy ON legacy.topic=bridge.topic
81
+ WHERE max_gap_ms>0 AND max_gap_ms=prior_gap_ms AND compact_ms=prior_compact_ms
82
+ AND window_start!=prior_window_start AND value=prior_value AND point_ms>prior_ms
83
+ AND point_ms-prior_ms<=toInt64(max_gap_ms) AND prior_ms<=(${until}) AND point_ms>=(${since})
84
+ AND NOT (legacy.n>0 AND prior_ms<=legacy.last_ms AND point_ms>=legacy.first_ms)
85
+ ${gap===undefined ? '' : `AND point_ms-prior_ms<=toInt64(${gap})`}`;
86
+ }
87
+ /** Display vertices may clip a constant island, never the silence between islands. */
88
+ export function chartMetricsRange(since,until,gap) {
89
+ const annotated=annotatedPoints(since,until,chartStored(since,until));
90
+ const coverage=gap===undefined ? 'compactable' : `compactable AND max_gap_ms<=(${gap})`;
91
+ const columns=`topic,ts,value,if(${coverage},island_first_ms,point_ms) AS coverage_first_ms,if(${coverage},island_last_ms,point_ms) AS coverage_last_ms,max_gap_ms,toUInt8(1) AS native`;
92
+ const points=`SELECT ${columns} FROM (${annotated}) WHERE NOT compactable OR ts=first_ts OR ts=last_ts
93
+ UNION ALL SELECT topic,fromUnixTimestamp64Milli(arrayJoin(arrayDistinct([
94
+ greatest(island_first_ms,toInt64(${since})),least(island_last_ms,toInt64(${until}))]))) AS ts,
95
+ value,island_first_ms AS coverage_first_ms,island_last_ms AS coverage_last_ms,max_gap_ms,toUInt8(1) AS native
96
+ FROM (${annotated}) AS cover WHERE (${coverage}) AND cover.ts=cover.first_ts AND cover.island_first_ms<=(${until}) AND cover.island_last_ms>=(${since})
97
+ UNION ALL ${constantBridges(annotated,since,until,gap)}`;
98
+ return `/*scada-native-chart-range*/(SELECT topic,ts,
99
+ tupleElement(selected,1) AS value,tupleElement(selected,2) AS coverage_first_ms,
100
+ tupleElement(selected,3) AS coverage_last_ms,tupleElement(selected,4) AS max_gap_ms,tupleElement(selected,5) AS native
101
+ FROM (SELECT topic,ts,argMin(tuple(value,coverage_first_ms,coverage_last_ms,max_gap_ms,native),priority) AS selected FROM (
102
+ SELECT *,0 AS priority FROM ${legacyChartRelation}
103
+ UNION ALL SELECT *,1 AS priority FROM (${points})
104
+ ) GROUP BY topic,ts))/*end-scada-native-chart-range*/`;
105
+ }
106
+ /** Gap-sensitive coverage is valid only at or above the frozen continuity threshold. */
107
+ export function holdsMetricsRange(since,until,gap) {
108
+ const guard=encodeURIComponent(JSON.stringify({since,until,gap}));
109
+ return `/*scada-density-range:${guard}*/${chartMetricsRange(since,until,gap)}`;
110
+ }
@@ -0,0 +1,26 @@
1
+ export const NATIVE_PHYSICAL_POINTS_SQL=`SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at FROM scada.metrics_points_v4 FINAL`;
2
+
3
+ /** Two ordinary endpoint rows certify a previously proven constant immutable span. */
4
+ export function nativeMetricCertificates(sourceSql=NATIVE_PHYSICAL_POINTS_SQL) {
5
+ return `SELECT topic,compact_first AS first_ms,compact_last AS last_ms,value,
6
+ min(revision) AS fence,max(compacted_at) AS certificate_at,min(compact_ms) AS certificate_compact_ms,min(max_gap_ms) AS certificate_max_gap_ms
7
+ FROM (${sourceSql}) WHERE is_compacted=1
8
+ GROUP BY topic,compact_first,compact_last,value
9
+ HAVING first_ms<last_ms AND uniqExact(ts)=2 AND min(toUnixTimestamp64Milli(ts))=first_ms
10
+ AND max(toUnixTimestamp64Milli(ts))=last_ms AND uniqExact(compact_ms)=1 AND uniqExact(max_gap_ms)=1 AND min(max_gap_ms)>0`;
11
+ }
12
+ /** Certified spans never overlap, so one indexed predecessor match is sufficient. */
13
+ export function nativeMetricCertificateMatches(pointSourceSql=NATIVE_PHYSICAL_POINTS_SQL,certificateSourceSql=NATIVE_PHYSICAL_POINTS_SQL) {
14
+ return `SELECT p.topic AS topic,p.ts AS ts,p.value AS value,p.compact_ms AS compact_ms,p.max_gap_ms AS max_gap_ms,p.revision AS revision,
15
+ p.is_compacted AS is_compacted,p.compact_first AS compact_first,p.compact_last AS compact_last,p.compacted_at AS compacted_at,
16
+ p.point_ms AS point_ms,c.first_ms AS certificate_first,c.last_ms AS certificate_last,c.fence AS certificate_fence,c.certificate_at AS certificate_at,c.certificate_compact_ms AS certificate_compact_ms,c.certificate_max_gap_ms AS certificate_max_gap_ms,c.value AS certificate_value
17
+ FROM (SELECT *,toUnixTimestamp64Milli(ts) AS point_ms FROM (${pointSourceSql})) AS p
18
+ ASOF LEFT JOIN (SELECT * FROM (${nativeMetricCertificates(certificateSourceSql)}) ORDER BY topic,first_ms) AS c
19
+ ON p.topic=c.topic AND p.point_ms>=c.first_ms`;
20
+ }
21
+ export const OBSOLETE_NATIVE_POINT_SQL='point_ms>certificate_first AND point_ms<certificate_last AND revision<=certificate_fence';
22
+ /** A delayed older INSERT cannot resurrect a physically deleted interior winner. */
23
+ export function effectiveNativePoints(pointSourceSql=NATIVE_PHYSICAL_POINTS_SQL,certificateSourceSql=NATIVE_PHYSICAL_POINTS_SQL) {
24
+ return `SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at
25
+ FROM (${nativeMetricCertificateMatches(pointSourceSql,certificateSourceSql)}) WHERE NOT(${OBSOLETE_NATIVE_POINT_SQL})`;
26
+ }
@@ -0,0 +1,91 @@
1
+ import nativeMetricsInsert from './nativeMetricsInsert.js';
2
+ import nativeMetricsOwnership from './nativeMetricsOwnership.js';
3
+ import {createHash} from 'node:crypto';
4
+ import nativeMetricsClock from './nativeMetricsClock.js';
5
+ import centralPoint from '../../ingest/telemetry/centralPoint.js';
6
+ import {CENTRAL_RULE_FIELDS,centralRule} from '../../ingest/telemetry/centralPolicy.js';
7
+ const settings={async_insert:0,wait_for_async_insert:1};
8
+
9
+ function normalize(records) {
10
+ return records.map((record,ordinal)=>{
11
+ const policy=centralRule(Object.fromEntries(CENTRAL_RULE_FIELDS.map(key=>{return [key,record[key]];})));
12
+ return {...centralPoint(record),...policy,ordinal};
13
+ });
14
+ }
15
+ function topicStates(points,states,{seq,revision,publishedAt,admittedAt}) {
16
+ const topics=new Map();
17
+ for(const point of points) {
18
+ const old=states.get(`topic:${point.topic}`);
19
+ if(!topics.has(point.topic)){topics.set(point.topic,{key:`topic:${point.topic}`,latest:Number(old?.latest??-2208988800000),closed_before:Number(old?.closed_before??-2208988800000),published_at:Number(old?.published_at??publishedAt),committed_seq:seq.toString(),revision:revision.toString()});}
20
+ const state=topics.get(point.topic);
21
+ if(point.ts<=admittedAt+point.futureSkewMs&&point.ts>=state.closed_before&&point.ts>=admittedAt-point.maxHistoryAgeMs){state.latest=Math.max(state.latest,point.ts);}
22
+ }
23
+ for(const point of points) {
24
+ const state=topics.get(point.topic);
25
+ // Every point's frozen policy participates; never reopen an existing frontier.
26
+ const cutoff=Math.floor(Math.max(state.latest-point.historyWindowMs,admittedAt-point.maxHistoryAgeMs)/(point.compactWindowMs||60000))*(point.compactWindowMs||60000);
27
+ if(cutoff>state.closed_before){state.closed_before=cutoff;state.published_at=null;}
28
+ }
29
+ return topics;
30
+ }
31
+ function admissionRows(points,topics,admittedAt,batchId,seq) {
32
+ const unique=new Map();const rejected=[];
33
+ for(const point of points) {
34
+ let reason=null;
35
+ if(point.ts>admittedAt+point.futureSkewMs){reason='future';}
36
+ else if(point.ts<topics.get(point.topic).closed_before||point.ts<admittedAt-point.maxHistoryAgeMs){reason='too_old';}
37
+ if(reason){rejected.push({batch_id:batchId,ordinal:point.ordinal,topic:point.topic,ts:new Date(point.ts).toISOString().replace('T',' ').slice(0,-1),value:point.value,reason,admitted_at:new Date(admittedAt).toISOString().replace('T',' ').slice(0,-1)});}
38
+ else{unique.set(JSON.stringify([point.topic,point.ts]),{topic:point.topic,ts:new Date(point.ts).toISOString().replace('T',' ').slice(0,-1),value:point.value,compact_ms:point.compactWindowMs,max_gap_ms:point.maxGapMs,revision:((seq*1024n)+BigInt(point.ordinal)).toString()});}
39
+ }
40
+ return {unique,rejected};
41
+ }
42
+
43
+
44
+ async function seedLegacyStates(client,states,points,admittedAt) {
45
+ const topics=[...new Set(points.map(({topic})=>{return topic;}))].filter(topic=>{return !states.has(`topic:${topic}`);});
46
+ if(!topics.length){return;}
47
+ const skews=new Map(points.map(point=>{return [point.topic,point.futureSkewMs];}));
48
+ const futureTimes=topics.map(topic=>{return Math.min(10413791999999,admittedAt+skews.get(topic));});
49
+ const response=await client.query({query:'SELECT topic,max(toUnixTimestamp64Milli(ts)) AS latest FROM scada.metrics WHERE topic IN {topics:Array(String)} AND toUnixTimestamp64Milli(ts)<=arrayElement({futureTimes:Array(Int64)},indexOf({topics:Array(String)},topic)) GROUP BY topic',query_params:{futureTimes,topics},format:'JSONEachRow'});
50
+ for(const row of await response.json()){states.set(`topic:${row.topic}`,{latest:Number(row.latest)});}
51
+ }
52
+ async function committedState(client,points,admittedAt) {
53
+ const response=await client.query({query:'SELECT * FROM scada.metrics_state_v4 FINAL WHERE key IN {keys:Array(String)}',query_params:{keys:['',...new Set(points.map(({topic})=>{return `topic:${topic}`}))]},format:'JSONEachRow'});
54
+ const states=new Map((await response.json()).map(row=>{return [row.key,row]}));
55
+ await seedLegacyStates(client,states,points,admittedAt);
56
+ const seq=BigInt(states.get('')?.committed_seq??0)+1n;
57
+ if(seq>=(2n**64n)){throw new RangeError('Central admission sequence exhausted');}
58
+ return {states,seq};
59
+ }
60
+ async function persist(client,unique,rejected,states,options) {
61
+ nativeMetricsOwnership(options);
62
+ if(unique.size){await nativeMetricsInsert(client,[...unique.values()]);}
63
+ nativeMetricsOwnership(options);
64
+ if(rejected.length){await client.insert({table:'scada.metrics_rejected_v4',values:rejected,format:'JSONEachRow',clickhouse_settings:settings});}
65
+ const publishedAt=await nativeMetricsClock(client,options);
66
+ nativeMetricsOwnership(options);
67
+ for(const state of states){if(state.published_at===null||state.key===''){state.published_at=publishedAt;}}
68
+ await client.insert({table:'scada.metrics_state_v4',values:states,format:'JSONEachRow',clickhouse_settings:settings});
69
+ }
70
+ function admissionContext(points,context,options) {
71
+ const now=options.now??Date.now;
72
+ const admittedAt=context.admittedAt??now();
73
+ const batchId=context.batchId??createHash('sha256').update(JSON.stringify({points,admittedAt})).digest('hex');
74
+ if(!Number.isSafeInteger(admittedAt)||!/^[a-f0-9]{64}$/u.test(batchId)){throw new TypeError('Invalid central admission context');}
75
+ return {now,admittedAt,batchId};
76
+ }
77
+ /** Requires the serialized SAC head and one authoritative read-after-write target. */
78
+ async function nativeMetricsAdmission(client,records,context={},options={}) {
79
+ nativeMetricsOwnership(context);
80
+ if(records.length>1000){throw new TypeError('Central admission head exceeds 1000 points');}
81
+ const points=normalize(records);
82
+ const {now,admittedAt,batchId}=admissionContext(points,context,options);
83
+ if(!points.length){return;}
84
+ const {states,seq}=await committedState(client,points,admittedAt);
85
+ nativeMetricsOwnership(context);
86
+ const topics=topicStates(points,states,{seq,revision:(seq*1024n)+1023n,publishedAt:now(),admittedAt});
87
+ const publishedAt=now();
88
+ const {unique,rejected}=admissionRows(points,topics,admittedAt,batchId,seq);
89
+ await persist(client,unique,rejected,[...topics.values(),{key:'',latest:0,closed_before:0,published_at:publishedAt,committed_seq:seq.toString(),revision:((seq*1024n)+1023n).toString()}],{...options,active:context.active});
90
+ }
91
+ export default nativeMetricsAdmission;
@@ -0,0 +1,9 @@
1
+ /** Publication and standby cleanup share the authoritative target's clock. */
2
+ export default async function nativeMetricsClock(client,options={}) {
3
+ if(options.now){return options.now();}
4
+ const response=await client.query({query:'SELECT toUnixTimestamp64Milli(now64(3)) AS current_ms',format:'JSONEachRow'});
5
+ const [row]=await response.json();
6
+ const value=Number(row?.current_ms);
7
+ if(!Number.isSafeInteger(value)){throw new Error('Invalid authoritative history publication clock');}
8
+ return value;
9
+ }
@@ -0,0 +1,82 @@
1
+ import nativeMetricsInsert from './nativeMetricsInsert.js';
2
+ import nativeMetricsClock from './nativeMetricsClock.js';
3
+ import {effectiveNativePoints,nativeMetricCertificateMatches,OBSOLETE_NATIVE_POINT_SQL} from './nativeMetricPoints.js';
4
+ /** One shared definition of window overlap for reads and physical cleanup. */
5
+ export function nativeMetricWindows(sourceSql=effectiveNativePoints()) {
6
+ return `SELECT *,ifNull(window_start<prior_end,0) OR ifNull(window_start+window_ms>next_start,0) AS overlap
7
+ FROM (SELECT *,maxOrNull(window_start+window_ms) OVER (PARTITION BY topic ORDER BY window_start,window_ms,compact_ms,max_gap_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prior_end,
8
+ minOrNull(window_start) OVER (PARTITION BY topic ORDER BY window_start,window_ms,compact_ms,max_gap_ms ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_start
9
+ FROM (SELECT topic,compact_ms,max_gap_ms,toInt64(floor(toUnixTimestamp64Milli(ts)/toFloat64(if(compact_ms=0,60000,compact_ms))))*toInt64(if(compact_ms=0,60000,compact_ms)) AS window_start,
10
+ toInt64(if(compact_ms=0,60000,compact_ms)) AS window_ms,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,
11
+ min(value) AS low,max(value) AS high,count() AS n
12
+ FROM (${sourceSql}) GROUP BY topic,compact_ms,max_gap_ms,window_start,window_ms))`;
13
+ }
14
+ /** Full certificates are interval atoms, so deleted density cannot create new gaps. */
15
+ export function nativeMetricIslandPoints(sourceSql=effectiveNativePoints()) {
16
+ const policy='topic,compact_ms,max_gap_ms,window_start,window_ms';
17
+ const island=`${policy},island_id`;
18
+ return `SELECT *,countIf(is_compacted=0 AND point_ms>island_first_ms AND point_ms<island_last_ms) OVER (PARTITION BY ${island}) AS raw_interiors
19
+ FROM (SELECT *,min(atom_first) OVER (PARTITION BY ${island}) AS island_first_ms,
20
+ max(atom_last) OVER (PARTITION BY ${island}) AS island_last_ms,count() OVER (PARTITION BY ${island}) AS island_n
21
+ FROM (SELECT *,sum(if(isNull(prior_atom_end),1,atom_first-prior_atom_end>toInt64(max_gap_ms))) OVER
22
+ (PARTITION BY ${policy} ORDER BY atom_first,point_ms ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS island_id
23
+ FROM (SELECT *,maxOrNull(atom_last) OVER (PARTITION BY ${policy} ORDER BY atom_first,point_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prior_atom_end
24
+ FROM (SELECT *,if(valid_certificate,certificate_first,point_ms) AS atom_first,if(valid_certificate,certificate_last,point_ms) AS atom_last,
25
+ toInt64(if(compact_ms=0,60000,compact_ms)) AS window_ms,
26
+ toInt64(floor(point_ms/toFloat64(if(compact_ms=0,60000,compact_ms))))*toInt64(if(compact_ms=0,60000,compact_ms)) AS window_start
27
+ FROM (SELECT *,is_compacted=1 AND certificate_first<certificate_last AND compact_ms=certificate_compact_ms
28
+ AND max_gap_ms=certificate_max_gap_ms AND value=certificate_value
29
+ AND (point_ms=certificate_first OR point_ms=certificate_last) AS valid_certificate
30
+ FROM (${nativeMetricCertificateMatches(sourceSql,sourceSql)}))))))`;
31
+ }
32
+ /** One row per policy/window continuity island, after merging all collectors. */
33
+ export function nativeMetricIslands(sourceSql=effectiveNativePoints()) {
34
+ return `SELECT topic,compact_ms,max_gap_ms,window_start,window_ms,island_first_ms AS first_ms,island_last_ms AS last_ms,
35
+ max(island_n) AS n,max(raw_interiors) AS raw_interiors FROM (${nativeMetricIslandPoints(sourceSql)})
36
+ GROUP BY topic,compact_ms,max_gap_ms,window_start,window_ms,island_first_ms,island_last_ms`;
37
+ }
38
+ /** Only entirely closed, equal windows without policy or legacy overlaps qualify. */
39
+ export const NATIVE_COMPACTION_WINDOWS_SQL=`WITH spans AS (${nativeMetricWindows()}),islands AS (${nativeMetricIslands()}),
40
+ legacy AS (SELECT topic,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,count() AS n FROM scada.metrics GROUP BY topic)
41
+ SELECT a.topic AS topic,a.window_start AS window_start,a.window_ms AS window_ms,i.first_ms AS first_ms,i.last_ms AS last_ms,a.low AS value,a.compact_ms AS compact_ms,a.max_gap_ms AS max_gap_ms,state.committed_seq AS committed_seq,
42
+ state.published_at AS published_at
43
+ FROM spans a INNER JOIN islands i ON a.topic=i.topic AND a.compact_ms=i.compact_ms AND a.max_gap_ms=i.max_gap_ms AND a.window_start=i.window_start AND a.window_ms=i.window_ms
44
+ INNER JOIN (SELECT key,closed_before,published_at,committed_seq FROM scada.metrics_state_v4 FINAL) AS state ON state.key=concat('topic:',a.topic)
45
+ LEFT JOIN legacy l ON l.topic=a.topic
46
+ WHERE a.compact_ms>0 AND a.max_gap_ms>0 AND a.low=a.high AND i.n>2 AND i.raw_interiors>0 AND NOT a.overlap AND a.window_start+a.window_ms<=state.closed_before
47
+ AND NOT(l.n>0 AND a.window_start<=l.last_ms AND a.window_start+a.window_ms>l.first_ms)`;
48
+
49
+ function endpointRows(windows,publishedAt) {
50
+ return windows.flatMap(window=>{
51
+ const common={topic:window.topic,value:window.value,compact_ms:window.compact_ms,max_gap_ms:window.max_gap_ms,
52
+ revision:(BigInt(window.committed_seq)*1024n+1000n).toString(),is_compacted:1,
53
+ compact_first:Number(window.first_ms),compact_last:Number(window.last_ms),compacted_at:publishedAt};
54
+ return [window.first_ms,window.last_ms].map(ts=>{return {...common,ts:new Date(Number(ts)).toISOString().replace('T',' ').slice(0,-1)};});
55
+ });
56
+ }
57
+ async function deleteObsolete(client,windows) {
58
+ if(!windows.length){return;}
59
+ const queryParams={};
60
+ const predicates=windows.map((window,index)=>{
61
+ queryParams[`topic${index}`]=window.topic;queryParams[`first${index}`]=window.certificate_first;queryParams[`last${index}`]=window.certificate_last;queryParams[`fence${index}`]=window.certificate_fence;
62
+ return `(topic={topic${index}:String} AND ts>fromUnixTimestamp64Milli({first${index}:Int64}) AND ts<fromUnixTimestamp64Milli({last${index}:Int64}) AND revision<={fence${index}:UInt128})`;
63
+ });
64
+ await client.command({query:`ALTER TABLE scada.metrics_points_v4 DELETE WHERE ${predicates.join(' OR ')}`,query_params:queryParams,clickhouse_settings:{mutations_sync:1}});
65
+ }
66
+ async function pendingMutations(client) {
67
+ const pending=await client.query({query:"SELECT count() AS n FROM system.mutations WHERE database='scada' AND table='metrics_points_v4' AND NOT is_done",format:'JSONEachRow'});
68
+ return Number((await pending.json())[0]?.n??0);
69
+ }
70
+ /** Certificate publication and physical deletion have separate grace periods. */
71
+ export default async function nativeMetricsCompaction(client,options={}) {
72
+ if(await pendingMutations(client)>=(options.maxPendingMutations??1)){return 0;}
73
+ const now=await nativeMetricsClock(client,options);
74
+ const params={mature:now-(options.compactionGraceMs??120000),limit:options.compactionBatchSize??100};
75
+ const obsolete=await client.query({query:`SELECT DISTINCT topic,certificate_first,certificate_last,certificate_fence FROM (${nativeMetricCertificateMatches()}) WHERE ${OBSOLETE_NATIVE_POINT_SQL} AND certificate_at<={mature:Int64} LIMIT {limit:UInt32}`,query_params:params,format:'JSONEachRow'});
76
+ const stale=await obsolete.json();
77
+ await deleteObsolete(client,stale);
78
+ const candidates=await client.query({query:`SELECT * FROM (${NATIVE_COMPACTION_WINDOWS_SQL}) WHERE published_at<={mature:Int64} LIMIT {limit:UInt32}`,query_params:params,format:'JSONEachRow'});
79
+ const windows=await candidates.json();
80
+ if(windows.length){await nativeMetricsInsert(client,endpointRows(windows,await nativeMetricsClock(client,options)));}
81
+ return stale.length+windows.length;
82
+ }
@@ -0,0 +1,31 @@
1
+ import {Readable} from 'node:stream';
2
+
3
+ function lengthPrefix(length) {
4
+ const bytes=[];let remaining=length;
5
+ do{const digit=remaining%128;remaining=Math.floor(remaining/128);bytes.push(digit+(remaining?128:0));}while(remaining);
6
+ return Buffer.from(bytes);
7
+ }
8
+ function scalar(value,method,size) {
9
+ const buffer=Buffer.alloc(size);buffer[method](value);return buffer;
10
+ }
11
+ function revision(value) {
12
+ const number=BigInt(value);const base=2n**64n;
13
+ return Buffer.concat([scalar(number%base,'writeBigUInt64LE',8),scalar(number/base,'writeBigUInt64LE',8)]);
14
+ }
15
+ function record(row) {
16
+ if(!Number.isFinite(row.value)){throw new TypeError('Finite central telemetry value required');}
17
+ const topic=Buffer.from(row.topic,'utf8');
18
+ return Buffer.concat([lengthPrefix(topic.length),topic,
19
+ scalar(BigInt(Date.parse(`${row.ts.replace(' ','T')}Z`)),'writeBigInt64LE',8),
20
+ scalar(row.value,'writeDoubleLE',8),scalar(BigInt(row.compact_ms),'writeBigUInt64LE',8),revision(row.revision),
21
+ scalar(row.is_compacted??0,'writeUInt8',1),
22
+ ...['compact_first','compact_last','compacted_at'].map(field=>{return scalar(BigInt(row[field]??0),'writeBigInt64LE',8);}),scalar(BigInt(row.max_gap_ms),'writeBigUInt64LE',8)]);
23
+ }
24
+ /** Preserve Float64 bits and UInt128 revisions for admission and endpoint publication. */
25
+ export default async function nativeMetricsInsert(client,rows) {
26
+ if(!rows.length){return;}
27
+ const response=await client.exec({query:'INSERT INTO scada.metrics_points_v4 (topic,ts,value,compact_ms,revision,is_compacted,compact_first,compact_last,compacted_at,max_gap_ms) FORMAT RowBinary',
28
+ values:Readable.from([Buffer.concat(rows.map(record))],{objectMode:false}),
29
+ clickhouse_settings:{async_insert:0,wait_for_async_insert:1,wait_end_of_query:1}});
30
+ for await(const chunk of response.stream){if(chunk.length){throw new Error('Unexpected ClickHouse central insertion response');}}
31
+ }
@@ -0,0 +1,8 @@
1
+ /** A former SAC delivery cannot allocate or publish a newer admission. */
2
+ export default function nativeMetricsOwnership({ active } = {}) {
3
+ if (active !== undefined && (typeof active !== 'function' || active() !== true)) {
4
+ const error = new Error('Central admission ownership lost');
5
+ error.code = 'SCADA_ADMISSION_OWNERSHIP_LOST';
6
+ throw error;
7
+ }
8
+ }
@@ -0,0 +1,44 @@
1
+ export const LEGACY_METRICS_SQL=`CREATE TABLE IF NOT EXISTS scada.metrics (
2
+ topic String, ts DateTime64(3), value Float64
3
+ ) ENGINE=MergeTree ORDER BY(topic,ts)`;
4
+ export const NATIVE_METRICS_SQL=`CREATE TABLE IF NOT EXISTS scada.metrics_points_v4 (
5
+ topic String, ts DateTime64(3), value Float64, compact_ms UInt64, revision UInt128,
6
+ is_compacted UInt8 DEFAULT 0,compact_first Int64 DEFAULT 0,compact_last Int64 DEFAULT 0,compacted_at Int64 DEFAULT 0,max_gap_ms UInt64
7
+ ) ENGINE=ReplacingMergeTree(revision) PARTITION BY toYYYYMM(ts) ORDER BY(topic,ts)`;
8
+ const tables=[
9
+ ['metrics_points_v4',NATIVE_METRICS_SQL,'ReplacingMergeTree','topic,ts','toYYYYMM(ts)','topic:String,ts:DateTime64(3),value:Float64,compact_ms:UInt64,revision:UInt128,is_compacted:UInt8,compact_first:Int64,compact_last:Int64,compacted_at:Int64,max_gap_ms:UInt64'],
10
+ ['metrics_state_v4',`CREATE TABLE IF NOT EXISTS scada.metrics_state_v4 (
11
+ key String, latest Int64, closed_before Int64, published_at Int64, committed_seq UInt64, revision UInt128
12
+ ) ENGINE=ReplacingMergeTree(revision) ORDER BY key`,'ReplacingMergeTree','key','','key:String,latest:Int64,closed_before:Int64,published_at:Int64,committed_seq:UInt64,revision:UInt128'],
13
+ ['metrics_rejected_v4',`CREATE TABLE IF NOT EXISTS scada.metrics_rejected_v4 (
14
+ batch_id String,ordinal UInt16,topic String,ts DateTime64(3),value Float64,reason LowCardinality(String),admitted_at DateTime64(3),recorded_at DateTime64(3) DEFAULT now64(3)
15
+ ) ENGINE=ReplacingMergeTree ORDER BY(batch_id,ordinal) TTL toDateTime(recorded_at)+INTERVAL 30 DAY`,'ReplacingMergeTree','batch_id,ordinal','','batch_id:String,ordinal:UInt16,topic:String,ts:DateTime64(3),value:Float64,reason:LowCardinality(String),admitted_at:DateTime64(3),recorded_at:DateTime64(3)']
16
+ ];
17
+ async function installTable(client,domain,[name,sql,engine,key,partition,columns]) {
18
+ await client.command({query:`${sql} COMMENT 'scada-admission-v4:${domain}'`});
19
+ const response=await client.query({query:'SELECT engine,sorting_key,partition_key,comment,create_table_query FROM system.tables WHERE database=\'scada\' AND name={name:String}',query_params:{name},format:'JSONEachRow'});
20
+ const [table]=await response.json();
21
+ if(table?.comment!==`scada-admission-v4:${domain}`){throw new Error('Central admission domain differs from the existing canonical table');}
22
+ const shape=await client.query({query:"SELECT name,type FROM system.columns WHERE database='scada' AND table={name:String} ORDER BY position",query_params:{name},format:'JSONEachRow'});
23
+ const actual=(await shape.json()).map(column=>{return `${column.name}:${column.type}`}).join(',');
24
+ if(table.engine!==engine||table.sorting_key.replaceAll(' ','')!==key||table.partition_key!==partition||actual!==columns||(name!=='metrics_rejected_v4'&&!table.create_table_query.includes('ReplacingMergeTree(revision)'))){throw new Error('Incompatible central native storage schema');}
25
+ }
26
+
27
+ /** Atomic CREATE comments pin domain before any writer can activate. */
28
+ /* Schema DDL is deliberately ordered: pin and validate each table before views. */
29
+ /* eslint-disable no-await-in-loop */
30
+ export default async function nativeMetricsSchema(client,domain,relation,rawRelation) {
31
+ if(!/^[a-f0-9]{64}$/u.test(domain)){throw new TypeError('Invalid central admission domain');}
32
+ await client.command({query:'CREATE DATABASE IF NOT EXISTS scada'});
33
+ const old=await client.query({query:"SELECT name FROM system.tables WHERE database='scada' AND name IN ('metrics_canonical','metrics_compact_v2','metrics_points_v3','metrics_state_v3','metrics_rejected_v3')",format:'JSONEachRow'});
34
+ if((await old.json()).length){throw new Error('Previous canonical storage requires an explicit v4 migration');}
35
+ await client.command({query:LEGACY_METRICS_SQL});
36
+ for(const table of tables){await installTable(client,domain,table);}
37
+ for(const [name,sql] of [['metrics_read',relation],['metrics_raw_read',rawRelation]]){
38
+ const found=await client.query({query:"SELECT engine,create_table_query FROM system.tables WHERE database='scada' AND name={name:String}",query_params:{name},format:'JSONEachRow'});
39
+ const [view]=await found.json();
40
+ if(view&&(view.engine!=='View'||!view.create_table_query.includes('metrics_points_v4'))){throw new Error('Previous canonical read view requires an explicit v4 migration');}
41
+ await client.command({query:`CREATE VIEW IF NOT EXISTS scada.${name} AS SELECT * FROM ${sql}`});
42
+ }
43
+ }
44
+
@@ -1,3 +1,5 @@
1
+ import { metricsRange } from './metricsRelation.js';
2
+
1
3
  /**
2
4
  * Batched ClickHouse poll for many topic cursors.
3
5
  *
@@ -32,7 +34,7 @@ export default function pollTopicCursors(connection, cursors, until) {
32
34
  }
33
35
  });
34
36
  return connection.query(
35
- `SELECT topic, ts, value FROM scada.metrics
37
+ `SELECT topic, ts, value FROM ${metricsRange('toUnixTimestamp64Milli({since:DateTime64(3)})', 'toUnixTimestamp64Milli({until:DateTime64(3)})')}
36
38
  WHERE topic IN {topics:Array(String)}
37
39
  AND ts > {since:DateTime64(3)}
38
40
  AND ts <= {until:DateTime64(3)}
@@ -1,3 +1,5 @@
1
+ import { metricsRange } from './metricsRelation.js';
2
+
1
3
  /**
2
4
  * Prefix sum of 0→1 edges for one ClickHouse metric topic.
3
5
  *
@@ -16,13 +18,13 @@ function formatDateTime(date) {
16
18
 
17
19
  const RISES_SQL = `WITH prior AS (
18
20
  SELECT ts, value
19
- FROM scada.metrics
21
+ FROM scada.metrics_read
20
22
  WHERE topic = {topic:String} AND ts < {start:DateTime64(3)}
21
23
  ORDER BY ts DESC
22
24
  LIMIT 1
23
25
  ), windowed AS (
24
26
  SELECT ts, value
25
- FROM scada.metrics
27
+ FROM ${metricsRange('toUnixTimestamp64Milli({start:DateTime64(3)})', 'toUnixTimestamp64Milli({end:DateTime64(3)})')}
26
28
  WHERE topic = {topic:String}
27
29
  AND ts >= {start:DateTime64(3)}
28
30
  AND ts < {end:DateTime64(3)}
@@ -0,0 +1,10 @@
1
+ import { rawMetricsRange } from './metricsRelation.js';
2
+
3
+ /** Actual observations for density-sensitive consumers; sealed thinning fails explicitly. */
4
+ export default async function clickhouseSamples(connection,topic,range,unit) {
5
+ const rows=await connection.query(`SELECT ts,value FROM ${rawMetricsRange('{since:Int64}','{until:Int64}')}
6
+ WHERE topic={topic:String} AND ts>=fromUnixTimestamp64Milli({since:Int64})
7
+ AND ts<=fromUnixTimestamp64Milli({until:Int64}) ORDER BY ts`,
8
+ {topic,since:range.start.getTime(),until:range.end.getTime()});
9
+ return rows.map(row=>{return {timestamp:new Date(`${row.ts}Z`),value:row.value,unit};});
10
+ }
@@ -25,6 +25,7 @@ import clickhouseRises from './rises.js';
25
25
  import clickhouseChanges from './changes.js';
26
26
  import clickhouseHolds from './holds.js';
27
27
  import clickhouseSeries from './series.js';
28
+ import clickhouseSamples from './samples.js';
28
29
  import clickhouseLatest from './latest.js';
29
30
 
30
31
  export default function clickhouseSensor(connection, topic, displayName, unit) {
@@ -35,6 +36,9 @@ export default function clickhouseSensor(connection, topic, displayName, unit) {
35
36
  current() {
36
37
  return clickhouseLatest(connection, topic, unit);
37
38
  },
39
+ samples(range) {
40
+ return clickhouseSamples(connection, topic, range, unit);
41
+ },
38
42
  measurements(range, step) {
39
43
  return clickhouseSeries(connection, topic, range, step, unit);
40
44
  },
@@ -1,30 +1,47 @@
1
- /**
2
- * Downsampled ClickHouse metric series for one topic.
3
- *
4
- * @param {object} connection - ClickHouse connection with query method
5
- * @param {string} topic - metric topic
6
- * @param {{start: Date, end: Date}} range - inclusive window
7
- * @param {number} step - downsample step in ms
8
- * @param {string} unit - measurement unit
9
- * @returns {Promise<Array<{timestamp: Date, value: number, unit: string}>>} buckets
10
- */
1
+ import { chartMetricsRange } from './metricsRelation.js';
2
+
3
+ function seriesPoints(rows,unit) {
4
+ const result=[];
5
+ let prior;
6
+ for (const row of rows) {
7
+ const timestamp=new Date(`${row.ts}Z`);
8
+ const separated=prior && row.segment!==undefined && String(row.segment)!==String(prior.segment);
9
+ if(separated && timestamp.getTime()-prior.timestamp.getTime()>1 && prior.value!==null && row.value!==null) {
10
+ result.push({timestamp:new Date(Math.floor((prior.timestamp.getTime()+timestamp.getTime())/2)),value:null,unit});
11
+ }
12
+ const point={timestamp,value:row.value,unit};
13
+ if(Number(row.native)===1) {point.continuous=Boolean(prior && !separated && prior.value!==null && row.value!==null);}
14
+ result.push(point);
15
+ prior={...row,timestamp};
16
+ }
17
+ return result;
18
+ }
19
+
20
+ /** Coarse buckets retain actual island boundaries, including subsecond timestamps. */
11
21
  export default async function clickhouseSeries(connection, topic, range, step, unit) {
12
22
  const seconds = Math.max(1, Math.floor(step / 1000));
13
23
  const start = range.start.toISOString().replace('Z', '').replace('T', ' ');
14
24
  const end = range.end.toISOString().replace('Z', '').replace('T', ' ');
15
25
  const rows = await connection.query(
16
- `SELECT
17
- toStartOfInterval(ts, INTERVAL ${seconds} SECOND) as ts,
18
- anyLast(value) as value
19
- FROM scada.metrics
20
- WHERE topic = {topic:String}
21
- AND ts >= toStartOfInterval({start:DateTime64(3)}, INTERVAL ${seconds} SECOND)
22
- AND ts <= {end:DateTime64(3)}
23
- GROUP BY ts
26
+ `WITH points AS (
27
+ SELECT * FROM ${chartMetricsRange('toUnixTimestamp64Milli({start:DateTime64(3)})','toUnixTimestamp64Milli({end:DateTime64(3)})')}
28
+ WHERE topic={topic:String} AND ts>={start:DateTime64(3)} AND ts<={end:DateTime64(3)}
29
+ ), prior AS (
30
+ SELECT *,row_number() OVER (ORDER BY ts) AS ordinal,
31
+ lagInFrame(coverage_last_ms,1) OVER (ORDER BY ts) AS prior_last,
32
+ lagInFrame(max_gap_ms,1) OVER (ORDER BY ts) AS prior_gap,
33
+ lagInFrame(native,1) OVER (ORDER BY ts) AS prior_native FROM points
34
+ ), segmented AS (
35
+ SELECT *,sum(toUInt8(ordinal=1 OR native!=prior_native OR max_gap_ms!=prior_gap OR max_gap_ms=0
36
+ OR coverage_first_ms>prior_last+toInt64(max_gap_ms))) OVER (ORDER BY ts) AS segment FROM prior
37
+ ), buckets AS (
38
+ SELECT segment,native,toStartOfInterval(ts,INTERVAL ${seconds} SECOND) AS bucket,
39
+ min(ts) AS first_ts,max(ts) AS last_ts,argMin(value,ts) AS first_value,argMax(value,ts) AS last_value
40
+ FROM segmented GROUP BY segment,native,bucket
41
+ ) SELECT tupleElement(vertex,1) AS ts,tupleElement(vertex,2) AS value,segment,native
42
+ FROM (SELECT segment,native,arrayJoin(arrayDistinct([tuple(first_ts,first_value),tuple(last_ts,last_value)])) AS vertex FROM buckets)
24
43
  ORDER BY ts`,
25
44
  { topic, start, end }
26
45
  );
27
- return rows.map((row) => {
28
- return { timestamp: new Date(`${row.ts}Z`), value: row.value, unit };
29
- });
46
+ return seriesPoints(rows,unit);
30
47
  }