@yarkivaev/scada 2.6.2 → 2.6.4

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.
package/README.md CHANGED
@@ -751,6 +751,28 @@ Use `node --expose-gc scripts/measure-delivery-spool.mjs FIXTURE.json 120000` wi
751
751
 
752
752
  No observation is merged, sampled or discarded by batching. An `accept()` promise succeeds only after durable commit. A sparse group flushes on its timer; capacity thresholds, reads and close force earlier flushing. The delay bounds the coalescing window, not disk latency or end-to-end completion. Queue status retains durable `pending`/`bytes` and adds `queuedOperations`, `queuedBytes` and `drainFull` diagnostics.
753
753
 
754
- Receipt admission is reserved before network publication, then queued only after mandatory confirmation. Confirmed receipts accumulate in a bounded window; `drain()` counts them delivered only after their FULL commit. Graceful close rejects new source submissions, flushes existing submissions, waits for the active drain and its receipts, then closes sessions and persistence. The existing crash-after-confirm/before-local-receipt replay contract remains unchanged.
754
+ The positive safe-integer `maxInFlight` option defaults to32. A drain initiates at most that many publications concurrently, in stored order per logical AMQP session. All concurrent writers await the same session opening; one mandatory return does not retire independent confirms. Receipt admission and serialized publication bytes are reserved before network publication, then the receipt is queued only after its individual mandatory confirmation. The retained publication bytes count toward `maxPendingBytes`, separately from receipt mutation bytes counted toward the group byte limit. Confirmed receipts accumulate in a bounded window; `drain()` counts them delivered only after their FULL commit. Graceful close rejects new source submissions, flushes existing submissions, waits for the active drain and its receipts, then closes sessions and persistence. Caller write deadlines abort the actual AMQP writer and retire its session. A caller timeout alone does not release a publication slot or its prospective ACK reservation; late actual success still commits its receipt, and late callbacks from an aborted AMQP generation cannot ACK a retry. A custom factory that ignores both AbortSignal and stop remains fenced and bounded until actual settlement. Close fails after its bounded session wait and retains spool ownership if that work cannot quiesce; retry close after settlement. The existing crash-after-confirm/before-local-receipt replay contract remains unchanged.
755
755
 
756
756
  Healthy full drain pages with durable progress continue on subsequent event-loop turns; after four pages the scheduler pauses 25 ms. Failed, empty or zero-progress pages back off 1s. This removes the former 100-event/s scheduling ceiling without spinning on an offline recipient. Actual append and online catch-up throughput still require qualification on the target filesystem; a serial producer awaiting every individual acceptance cannot benefit from concurrent group formation.
757
+
758
+ ### Bounded native history commits
759
+
760
+ Native history receivers advertise `nativeTailProtocol: preserve-known-suffix-v1`
761
+ on configuration. Workers must negotiate this before starting. A computed
762
+ terminal anchor must not clip an existing segment whose known end lies beyond
763
+ the observed page. An unchanged exterior anchor can be omitted entirely.
764
+
765
+ An exterior row requires `context.nativeTailMode` with that protocol and a
766
+ `preserveSuffix` object identifying a current segment by `kind`, `name`,
767
+ `start_time`, and `end_time`. Under the existing context revision lock, the
768
+ receiver checks its class, extent and current ownership. Archive-only rows
769
+ cannot justify exterior changes. Changing a current segment inside the page
770
+ must retain any unobserved suffix, potentially as a piece starting one
771
+ millisecond after the page end; unseen cut collisions fail atomically.
772
+ Conservative page-boundary cuts remain protected, so a paged transition can
773
+ leave additional adjacent same-class pieces. No new exterior observations or
774
+ classes are inferred. A rejected commit leaves both projection and work intact.
775
+
776
+ Applicable children carry operator metadata and `consumed`; existing rows keep
777
+ their stored consumed state. This native protocol is separate from the staged
778
+ stateful correction protocol used with external raw observation stores.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.2",
3
+ "version": "2.6.4",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@ export default function deliveryOperations(apply, options = {}) {
27
27
  }
28
28
  function release(bytes) { state.operations -= 1; state.bytes -= bytes; notifyIdle(); }
29
29
  function settle(job, result) {
30
- release(job.bytes);
30
+ release(job.reservedBytes ?? job.bytes);
31
31
  if (result.ok) { job.resolve(result.value); } else { job.reject(result.error); }
32
32
  }
33
33
  function group() {
@@ -77,25 +77,27 @@ export default function deliveryOperations(apply, options = {}) {
77
77
  schedule(job.kind === 'barrier' || state.operations >= Math.min(config.maxRecords, config.maxOperations) ? 0 : config.maxDelayMs);
78
78
  });
79
79
  }
80
- function checkBytes(bytes) {
80
+ function checkBytes(bytes, retainedBytes = 0) {
81
81
  positive(bytes, 'Mutation bytes', true);
82
- if (state.bytes + bytes > config.maxPendingBytes) { throw new Error('Delivery pending byte capacity exceeded'); }
82
+ positive(retainedBytes, 'Retained bytes', true);
83
+ if (state.bytes + bytes + retainedBytes > config.maxPendingBytes) { throw new Error('Delivery pending byte capacity exceeded'); }
83
84
  if (bytes > config.maxBytes) { throw new Error('Delivery group byte capacity exceeded'); }
84
85
  }
85
86
  function prepare(build) {
86
87
  reserve();
87
88
  let value;
88
89
  try {
89
- value = build(checkBytes); checkBytes(value.bytes);
90
+ value = build(checkBytes); checkBytes(value.bytes, value.retainedBytes);
90
91
  } catch (error) { release(0); throw error; }
91
- state.bytes += value.bytes;
92
+ const reservedBytes = value.bytes + (value.retainedBytes ?? 0);
93
+ state.bytes += reservedBytes;
92
94
  let settled = false;
93
95
  return {
94
96
  commit() {
95
97
  if (settled) { return Promise.reject(new Error('Delivery reservation already settled')); }
96
- settled = true; return enqueue({ kind: 'mutation', ...value });
98
+ settled = true; return enqueue({ kind: 'mutation', ...value, reservedBytes });
97
99
  },
98
- cancel() { if (!settled) { settled = true; release(value.bytes); } }
100
+ cancel() { if (!settled) { settled = true; release(reservedBytes); } }
99
101
  };
100
102
  }
101
103
  return {
@@ -0,0 +1,31 @@
1
+ /** A slot and its prospective durable receipt stay reserved until the actual writer settles. */
2
+ /* eslint max-lines-per-function: ["error", 80], max-statements: ["error", 25] */
3
+ export default function deliveryPublications(commands, sessions, options) {
4
+ const limit = options.maxInFlight ?? 32;
5
+ if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive safe maxInFlight required'); }
6
+ const active = new Map();
7
+ function publish(record, id) {
8
+ const key = JSON.stringify([record.event.eventId, id]);
9
+ if (active.has(key) || active.size >= limit) { throw new Error('Delivery publication capacity exceeded'); }
10
+ const receipt = commands.prepare((checkBytes) => {
11
+ const operation = { kind: 'ack', eventId: record.event.eventId, recipient: id };
12
+ const bytes = Buffer.byteLength(JSON.stringify(operation));
13
+ const retainedBytes = Buffer.byteLength(JSON.stringify(record.event));
14
+ checkBytes(bytes, retainedBytes); return { operation, bytes, retainedBytes };
15
+ });
16
+ let write;
17
+ try {
18
+ const descriptor = record.event.destinations.find((item) => { return item.id === id; });
19
+ const event = record.event.observation;
20
+ write = sessions.write(descriptor, { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } });
21
+ } catch (error) { receipt.cancel(); throw error; }
22
+ const settled = write.settled.then(() => { return receipt.commit(); }, (error) => { receipt.cancel(); throw error; })
23
+ .finally(() => { active.delete(key); });
24
+ active.set(key, settled);
25
+ void settled.catch(() => {
26
+ // The caller reports failures; late rejection still releases only the actual reservation.
27
+ });
28
+ return write.result.then(() => { return settled; });
29
+ }
30
+ return { publish, limit };
31
+ }
@@ -1,10 +1,8 @@
1
1
  import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
2
2
  import deliverySessions from './deliverySessions.js';
3
3
  import deliveryOperations from './deliveryOperations.js';
4
+ import deliveryPublications from './deliveryPublications.js';
4
5
 
5
- function confirmed(event) {
6
- return { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } };
7
- }
8
6
  function snapshot(operation, checkBytes) {
9
7
  const json = JSON.stringify(operation); checkBytes(Buffer.byteLength(json));
10
8
  const frozen = JSON.parse(json);
@@ -19,43 +17,37 @@ export default function deliveryQueue(directory, options) {
19
17
  const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
20
18
  const batchSize = options.batchSize ?? 100;
21
19
  if (!Number.isSafeInteger(batchSize) || batchSize <= 0) { throw new TypeError('Positive safe batchSize required'); }
22
- const receiptWindow = Math.min(options.groupCommit?.maxRecords ?? 64, options.maxOperations ?? 128);
20
+ const publications = deliveryPublications(commands, sessions, options);
21
+ const receiptWindow = Math.min(publications.limit, options.maxOperations ?? 128);
23
22
  const state = { draining: false, closed: false, full: false };
24
- async function publish(record, id) {
25
- if (state.closed) { throw new Error('Delivery queue closed'); }
26
- // Reserve the eventual receipt BEFORE publication; confirmation can never lose its admission slot.
27
- const receipt = commands.prepare((checkBytes) => { return snapshot({ kind: 'ack', eventId: record.event.eventId, recipient: id }, checkBytes); });
28
- try {
29
- const descriptor = record.event.destinations.find((item) => { return item.id === id; });
30
- await sessions.write(descriptor, confirmed(record.event.observation));
31
- return { receipt: receipt.commit() };
32
- } catch (error) { receipt.cancel(); throw error; }
33
- }
34
23
  async function drain() {
35
24
  state.draining = true;
36
25
  const result = { delivered: 0, failed: 0 };
37
- const receipts = [];
26
+ const receipts = new Set();
38
27
  function failure(error) {
39
28
  result.failed += 1;
40
29
  try { options.onError?.(error); } catch {
41
30
  // Observers cannot prevent independent recipient progress or release.
42
31
  }
43
32
  }
44
- async function flush() { commands.flush(); await Promise.all(receipts.splice(0)); }
45
- async function receive(row, id) {
46
- try {
47
- const sent = await publish(row, id);
48
- receipts.push(sent.receipt.then(() => { result.delivered += 1; }, failure));
49
- } catch (error) { failure(error); }
50
- if (receipts.length >= receiptWindow) { await flush(); }
33
+ async function flush() { commands.flush(); await Promise.all(receipts); }
34
+ function receive(row, id) {
35
+ const receipt = Promise.resolve().then(() => { return publications.publish(row, id); })
36
+ .then(() => { result.delivered += 1; }, failure).finally(() => { receipts.delete(receipt); });
37
+ receipts.add(receipt);
38
+ }
39
+ async function advance(row, id) {
40
+ if (!state.closed) { receive(row, id); }
41
+ if (receipts.size >= receiptWindow) { await Promise.race(receipts); }
51
42
  }
52
43
  try {
53
44
  const rows = await commands.barrier(() => { return spool.pending(batchSize); });
54
45
  Object.assign(state, { full: rows.length === batchSize });
55
46
  for (const row of rows) {
56
47
  for (const id of row.remaining) {
48
+ // Actual timed-out publications retain their global slots across page/caller completion.
57
49
  // eslint-disable-next-line no-await-in-loop
58
- await receive(row, id);
50
+ await advance(row, id);
59
51
  }
60
52
  }
61
53
  return result;
@@ -83,9 +75,10 @@ export default function deliveryQueue(directory, options) {
83
75
  await state.activeDrain?.catch(() => {
84
76
  // Drain caller receives the original error.
85
77
  });
78
+ await sessions.close();
86
79
  await commands.idle();
87
- try { await sessions.close(); } finally { await spool.close(); }
88
- })();
80
+ await spool.close();
81
+ })().catch((error) => { state.closing = null; throw error; });
89
82
  return state.closing;
90
83
  },
91
84
  status() {
@@ -1,28 +1,66 @@
1
1
  import deadline from './deadline.js';
2
2
 
3
- /** Bounded reusable AMQP connections, independent of collector task lifecycles. */
3
+ /** Shared opening and actual settlement outlive caller deadlines; stop fences failed sessions. */
4
+ /* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
4
5
  export default function deliverySessions(factory, timeoutMs = 10000) {
5
6
  const sessions = new Map();
7
+ const state = { closed: false };
8
+ function retire(key, entry) {
9
+ entry.closing ??= (async () => {
10
+ if (!entry.opened) { await entry.sink.stop?.(); }
11
+ await entry.opening.catch(() => {
12
+ // A failed opening must still be stopped; a late successful one may own new resources.
13
+ });
14
+ await entry.sink.stop?.();
15
+ await Promise.allSettled(entry.pending);
16
+ if (sessions.get(key) === entry) { sessions.delete(key); }
17
+ })();
18
+ return entry.closing;
19
+ }
20
+ function session(key, descriptor) {
21
+ let entry = sessions.get(key);
22
+ if (entry?.closing) { throw new Error('Delivery session is closing'); }
23
+ if (!entry) {
24
+ if (sessions.size >= 64) { throw new Error('Delivery session capacity exceeded'); }
25
+ const sink = factory(descriptor);
26
+ entry = { sink, pending: new Set(), opened: false };
27
+ entry.opening = Promise.resolve().then(() => { return sink.start?.(); }).finally(() => { entry.opened = true; });
28
+ sessions.set(key, entry);
29
+ void entry.opening.catch(() => { return retire(key, entry); }).catch(() => {
30
+ // Failed shutdown keeps the failed opening fenced.
31
+ });
32
+ }
33
+ return entry;
34
+ }
6
35
  return {
7
- async write(descriptor, event) {
36
+ write(descriptor, event) {
37
+ if (state.closed) { throw new Error('Delivery sessions closed'); }
8
38
  const key = JSON.stringify(descriptor);
9
- let sink = sessions.get(key);
10
- if (!sink) {
11
- if (sessions.size >= 64) { throw new Error('Delivery session capacity exceeded'); }
12
- sink = factory(descriptor); sessions.set(key, sink);
13
- try { await deadline(() => { return sink.start?.(); }, timeoutMs); } catch (error) {
14
- sessions.delete(key);
15
- await deadline(() => { return sink.stop?.(); }, timeoutMs).catch(() => {
16
- // Original failure propagates.
39
+ const entry = session(key, descriptor);
40
+ const controller = new AbortController();
41
+ const settled = entry.opening.then(() => {
42
+ if (controller.signal.aborted || entry.closing) { throw controller.signal.reason || new Error('Delivery session is closing'); }
43
+ return entry.sink.write([event], { signal: controller.signal });
44
+ });
45
+ entry.pending.add(settled);
46
+ let completed = false;
47
+ void settled.finally(() => { completed = true; entry.pending.delete(settled); }).catch(() => {
48
+ // A publication rejection is independent of other confirms on this session.
49
+ });
50
+ const result = deadline(() => { return settled; }, timeoutMs).catch((error) => {
51
+ if (!completed) {
52
+ controller.abort(error);
53
+ void retire(key, entry).catch(() => {
54
+ // Actual work and ownership remain fenced if stop cannot complete.
17
55
  });
18
- throw error;
19
56
  }
20
- }
21
- await deadline(() => { return sink.write([event]); }, timeoutMs);
57
+ throw error;
58
+ });
59
+ return { result, settled };
22
60
  },
23
- async close() {
24
- await Promise.allSettled(Array.from(sessions.values(), (sink) => { return deadline(() => { return sink.stop?.(); }, timeoutMs); }));
25
- sessions.clear();
61
+ close() {
62
+ state.closed = true;
63
+ return deadline(() => { return Promise.all(Array.from(sessions, ([key, entry]) => { return retire(key, entry); })); }, timeoutMs);
26
64
  }
27
65
  };
28
66
  }
@@ -1,3 +1,4 @@
1
+ import nativeHistoryBounds, {nativeTailProtocol} from './historyNativeBounds.js';
1
2
  import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
2
3
  import historyContext from './historyContext.js';
3
4
  import historyAdmission, {assertHistoryReady} from './historyAdmission.js';
@@ -88,8 +89,12 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
88
89
  if (segments.length && !base?.revision) { throw new TypeError('History context revision required'); }
89
90
  if (observationSource) { await assertHistoryReady(client,machine); }
90
91
  const latest = base?.revision ? await unchanged(client, machine, base, {observationSource,timeScale}) : null;
91
- if (latest && segments.some((item) => { return new Date(item.end_time).getTime()>Math.round(latest.context.page.until/timeScale); })) {
92
- throw new TypeError('Segment extends beyond bounded history page; upgrade history worker');
92
+ const exteriors = nativeHistoryBounds(segments, latest, base, timeScale);
93
+ for (const item of exteriors) {
94
+ // An unseen existing cut must never be overwritten by a new exterior piece.
95
+ // eslint-disable-next-line no-await-in-loop
96
+ const conflict = await client.query('SELECT 1 FROM segments WHERE machine=$1 AND kind=$2 AND start_time=$3', [machine, item.kind ?? 'phase', item.start_time]);
97
+ if (conflict.rowCount) { throw new TypeError('History suffix collides with a cut outside the observed page'); }
93
98
  }
94
99
  if(base?.replace){
95
100
  const next=await historyCorrection(client,machine,work.rows[0],segments,{base,context:latest,timeScale});
@@ -103,8 +108,8 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
103
108
  for (const item of segments) {
104
109
  // Only computed fields change. User cuts/labels must be applied by caller before commit.
105
110
  // eslint-disable-next-line no-await-in-loop
106
- await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved)
107
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT(machine,kind,start_time) DO UPDATE
111
+ await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
112
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT(machine,kind,start_time) DO UPDATE
108
113
  SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,options=EXCLUDED.options,updated_at=clock_timestamp(),
109
114
  tags=CASE WHEN segments.name=EXCLUDED.name THEN segments.tags ELSE EXCLUDED.tags END,
110
115
  properties=CASE WHEN segments.name=EXCLUDED.name THEN segments.properties ELSE EXCLUDED.properties END,
@@ -112,7 +117,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
112
117
  [machine, item.kind ?? 'phase', item.name, item.start_time, item.end_time, item.duration,
113
118
  typeof item.options === 'string' ? item.options : JSON.stringify(item.options ?? null),
114
119
  typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null),
115
- typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true]);
120
+ typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true, item.consumed ?? true]);
116
121
  }
117
122
  const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
118
123
  await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
@@ -134,7 +139,7 @@ export default function historyPg(pool, { retentionDays = 30, now = Date.now, ob
134
139
  const source=observationSource?.(client);
135
140
  const result=await historyConfigure(client,machine,topics,bucketMs*timeScale,{retentionDays,observations:source});
136
141
  await configureClassifier(client,machine,classifierKey,source);
137
- return {...result,...((timeScale!==1 || classifierKey) && {timeScale}),...(classifierKey && {classifierProtocol:historyProtocol})};
142
+ return {...result,...((timeScale!==1 || classifierKey) && {timeScale}),...(!classifierKey && {nativeTailProtocol}),...(classifierKey && {classifierProtocol:historyProtocol})};
138
143
  },true);
139
144
  },
140
145
  async purge() {
@@ -50,7 +50,7 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
50
50
  const annotations = await pool.query(`SELECT a.kind,a.name,a.start_time,a.end_time,a.duration,
51
51
  CASE WHEN s.machine IS NOT NULL THEN s.tags ELSE a.tags END AS tags,
52
52
  CASE WHEN s.machine IS NOT NULL THEN s.properties ELSE a.properties END AS properties,
53
- CASE WHEN s.machine IS NOT NULL THEN s.resolved ELSE a.resolved END AS resolved
53
+ CASE WHEN s.machine IS NOT NULL THEN s.resolved ELSE a.resolved END AS resolved,CASE WHEN s.machine IS NOT NULL THEN s.consumed ELSE NULL END AS consumed
54
54
  FROM history_annotations a LEFT JOIN segments s ON s.machine=a.machine AND s.kind=a.kind AND s.start_time=a.start_time AND s.name=a.name
55
55
  WHERE a.machine=$1 AND a.kind='phase' AND a.start_time<=$3 AND a.end_time>=$2
56
56
  AND (COALESCE(a.tags,'') NOT IN ('','null','[]') OR COALESCE(a.properties,'') NOT IN ('','null','{}')) ORDER BY a.start_time,a.name LIMIT 10001`,
@@ -0,0 +1,43 @@
1
+ export const nativeTailProtocol = 'preserve-known-suffix-v1';
2
+ function instant(value) { return new Date(value).getTime(); }
3
+ function kind(row) { return row.kind ?? 'phase'; }
4
+ function identity(left, right) {
5
+ return kind(left) === kind(right) && left.name === right.name
6
+ && instant(left.start_time) === instant(right.start_time) && instant(left.end_time) === instant(right.end_time);
7
+ }
8
+ function provedOwner(item, latest, base, until) {
9
+ const start = instant(item.start_time); const end = instant(item.end_time);
10
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) { throw new TypeError('Invalid bounded history segment'); }
11
+ if (end <= until) { return null; }
12
+ const owner = base.nativeTailMode === nativeTailProtocol && (latest.segments ?? []).find(row => {
13
+ return item.preserveSuffix && identity(row, item.preserveSuffix)
14
+ && kind(row) === kind(item) && row.name === item.name
15
+ && instant(row.start_time) <= until && instant(row.start_time) <= start
16
+ && start <= until + 1 && instant(row.end_time) === end;
17
+ });
18
+ if (!owner) { throw new TypeError('Segment extends beyond bounded history page without a current suffix proof'); }
19
+ return owner;
20
+ }
21
+ function retainExterior(segments, current, owners, until) {
22
+ for (const owner of current) {
23
+ const change = segments.find(item => { return kind(item) === kind(owner) && instant(item.start_time) === instant(owner.start_time); });
24
+ if (change && instant(owner.end_time) > until
25
+ && (change.name !== owner.name || instant(change.end_time) < instant(owner.end_time))) {
26
+ const retained = [...owners].some(([item, proof]) => {
27
+ return identity(proof, owner) && instant(item.start_time) <= until + 1;
28
+ });
29
+ if (!retained) { throw new TypeError('Known history tail would be truncated; upgrade the history worker'); }
30
+ }
31
+ }
32
+ }
33
+ /** A bounded native correction may carry existing exterior, never classify new exterior. */
34
+ export default function nativeHistoryBounds(segments, latest, base, timeScale) {
35
+ if (!latest) { return []; }
36
+ const until = Math.round(latest.context.page.until / timeScale);
37
+ if (base.nativeTailMode !== undefined && (base.nativeTailMode !== nativeTailProtocol || base.replace)) {
38
+ throw new TypeError('Unsupported native history suffix protocol');
39
+ }
40
+ const owners = new Map(segments.map(item => { return [item, provedOwner(item, latest, base, until)]; }).filter(([, owner]) => { return owner; }));
41
+ if (!base.replace) { retainExterior(segments, latest.segments ?? [], owners, until); }
42
+ return [...owners.keys()].filter(item => { return instant(item.start_time) > until; });
43
+ }