devcontour-harness 0.1.0-alpha.45 → 0.1.0-alpha.47

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 (53) hide show
  1. package/README.md +20 -2
  2. package/docs/architecture.md +8 -0
  3. package/docs/compatibility.md +4 -1
  4. package/docs/contracts.md +25 -5
  5. package/docs/release-notes/0.1.0-alpha.46.md +63 -0
  6. package/docs/release-notes/0.1.0-alpha.47.md +138 -0
  7. package/docs/upgrade.md +119 -19
  8. package/lib/agents/review-probe.js +8 -3
  9. package/lib/contracts/cli.d.ts +11 -0
  10. package/lib/contracts/events.d.ts +13 -1
  11. package/lib/contracts/events.js +2 -0
  12. package/lib/contracts/execution.d.ts +1 -0
  13. package/lib/contracts/execution.js +13 -0
  14. package/lib/contracts/handoff.d.ts +1 -0
  15. package/lib/contracts/handoff.js +6 -1
  16. package/lib/contracts/ports.d.ts +54 -0
  17. package/lib/contracts/published.d.ts +8 -0
  18. package/lib/contracts/report.d.ts +4 -0
  19. package/lib/control/harness.d.ts +1 -1
  20. package/lib/control/workflow.d.ts +5 -1
  21. package/lib/control/workflow.js +18 -3
  22. package/lib/engine/classify.d.ts +6 -0
  23. package/lib/engine/classify.js +26 -0
  24. package/lib/engine/engine.d.ts +25 -2
  25. package/lib/engine/engine.js +76 -7
  26. package/lib/engine/runner.d.ts +11 -6
  27. package/lib/engine/runner.js +107 -34
  28. package/lib/environment/host-load.d.ts +12 -0
  29. package/lib/environment/host-load.js +7 -0
  30. package/lib/environment/lifecycle.d.ts +12 -1
  31. package/lib/environment/lifecycle.js +19 -2
  32. package/lib/environment/process.d.ts +71 -1
  33. package/lib/environment/process.js +149 -31
  34. package/lib/handoff/pack.js +7 -1
  35. package/lib/index.d.ts +5 -1
  36. package/lib/index.js +7 -1
  37. package/lib/report/document.js +2 -0
  38. package/lib/storage/sqlite.d.ts +47 -4
  39. package/lib/storage/sqlite.js +279 -34
  40. package/lib/testing/store-contract.d.ts +9 -0
  41. package/lib/testing/store-contract.js +235 -0
  42. package/lib/verification/applicability.d.ts +25 -2
  43. package/lib/verification/applicability.js +34 -1
  44. package/lib/verification/gates-at.js +15 -1
  45. package/lib/verification/gates.d.ts +3 -10
  46. package/lib/verification/gates.js +136 -15
  47. package/lib/verification/reaped.d.ts +24 -0
  48. package/lib/verification/reaped.js +24 -0
  49. package/package.json +1 -1
  50. package/schemas/execution-document.schema.json +4 -0
  51. package/schemas/handoff-pack.schema.json +4 -0
  52. package/schemas/run-event.schema.json +2 -0
  53. package/schemas/value-report.schema.json +3 -1
@@ -6,7 +6,61 @@ import { StringDecoder } from 'node:string_decoder';
6
6
  import { resolve } from 'node:path';
7
7
  import { assertTrustedCheckout, forgetWorktree, worktreeKey, gitHardening, rememberWorktree, worktreeAddPath, } from "./git-trust.js";
8
8
  import { outputRedactor } from "./redaction.js";
9
+ import { TaskFailure } from "../contracts/index.js";
9
10
  import { activityScope } from "./activity.js";
11
+ import { hostLoad, loadText } from "./host-load.js";
12
+ /**
13
+ * Сдерживаемая команда завершилась, но её потомков не удалось остановить или
14
+ * хотя бы пересчитать (`ps` не ответил под нагрузкой хоста). О коде это
15
+ * ничего не говорит: класс — отказ окружения (`process-reap`), попытка не
16
+ * засчитывается. Сдерживание не ослабляется: результата команды нет, и
17
+ * вызывающий не принимает её исход — потомок, возможно, ещё работает в её
18
+ * каталогах.
19
+ */
20
+ export class ReapFailure extends TaskFailure {
21
+ survivors;
22
+ inventory;
23
+ result;
24
+ constructor(message,
25
+ /** Пережившие остановку PID; пусто, если перечень так и не получен. */
26
+ survivors,
27
+ /** Почему перечень процессов не получен; нет — перечень был. */
28
+ inventory,
29
+ /**
30
+ * Исход самой команды (код, вывод), если она завершилась: провал,
31
+ * который она назвала, — свидетельство о коде и при неостановленных
32
+ * потомках. Принимать его успехом нельзя.
33
+ */
34
+ result) {
35
+ super('environment', message, undefined, 'process-reap');
36
+ this.survivors = survivors;
37
+ this.inventory = inventory;
38
+ this.result = result;
39
+ this.name = 'ReapFailure';
40
+ }
41
+ /** Тот же отказ с дописанной причиной (например, неубранными каталогами). */
42
+ extend(suffix) {
43
+ return new ReapFailure(`${this.message}; ${suffix}`, this.survivors, this.inventory, this.result);
44
+ }
45
+ }
46
+ /**
47
+ * Отказ остановки потомков завершившейся команды — один текст у всех, кто
48
+ * сдерживает команды (и у хоста со своим запуском): команда, её PID и
49
+ * выход, что не остановлено (PID или почему нет перечня), нагрузка хоста.
50
+ */
51
+ export function reapFailure(outcome) {
52
+ const pids = (list) => list.slice(0, 10).join(', ') + (list.length > 10 ? ` и ещё ${list.length - 10}` : '');
53
+ const what = outcome.inventory
54
+ ? `перечень процессов не получен (${outcome.inventory})` +
55
+ (outcome.survivors.length
56
+ ? `; последние замеченные потомки: PID ${pids(outcome.survivors)}`
57
+ : '')
58
+ : `живы после остановки PID ${pids(outcome.survivors)}`;
59
+ const exit = outcome.signal ? `сигнал ${outcome.signal}` : `код выхода ${outcome.code ?? -1}`;
60
+ const text = `Не удалось завершить процессы команды «${outcome.label}» (PID ${outcome.pid ?? '?'}, ${exit}): ${what}. ` +
61
+ `Ресурсы не освобождены: потомки команды могут ещё работать; ${loadText(hostLoad.read())}`;
62
+ return new ReapFailure(outcome.redact ? outcome.redact(text) : text, outcome.survivors, outcome.inventory, outcome.result);
63
+ }
10
64
  export async function command(argv, cwd, options = {}) {
11
65
  const [file, ...args] = argv;
12
66
  if (!file)
@@ -158,11 +212,13 @@ export async function command(argv, cwd, options = {}) {
158
212
  if (child.pid && mark)
159
213
  for (const [pid, start] of await descendants(child.pid, seen))
160
214
  seen.set(pid, start);
161
- const survivors = mark ? await sweep(mark, seen, dirs, Date.parse(startedAt)) : [];
162
- if (survivors.length) {
163
- reject(new Error(`Не удалось завершить процессы проверки: ${survivors.join(', ')}. Ресурсы не освобождены`));
164
- return;
165
- }
215
+ const swept = mark
216
+ ? await sweep(mark, seen, dirs, Date.parse(startedAt))
217
+ : { survivors: [] };
218
+ // Потомков не удалось остановить или пересчитать: исход команды
219
+ // собирается как обычно (ожидание pipes ограничено — их может держать
220
+ // переживший потомок) и уходит вместе с отказом, а не результатом.
221
+ const reaped = swept.survivors.length > 0 || swept.inventory !== undefined;
166
222
  if (mark) {
167
223
  let pipeTimer;
168
224
  try {
@@ -187,11 +243,13 @@ export async function command(argv, cwd, options = {}) {
187
243
  append('stdout', maskOut(rest, true));
188
244
  const restErr = stderrDecoder.end();
189
245
  append('stderr', maskErr(options.rawStderr ? options.rawStderr(restErr, true) : restErr, true));
190
- if (outputError) {
246
+ // Неостановленные потомки важнее отказа обработчика вывода: иначе
247
+ // отказ терял бы причину `process-reap`, и дерево сочли бы свободным.
248
+ if (outputError && !reaped) {
191
249
  reject(outputError);
192
250
  return;
193
251
  }
194
- resolve({
252
+ const result = {
195
253
  code: code ?? -1,
196
254
  stdout,
197
255
  stderr,
@@ -208,7 +266,19 @@ export async function command(argv, cwd, options = {}) {
208
266
  stderrTail: stderr.slice(-4000),
209
267
  processTree,
210
268
  },
211
- });
269
+ };
270
+ if (reaped)
271
+ reject(reapFailure({
272
+ label: options.activity?.label ?? file.split('/').at(-1) ?? file,
273
+ pid: child.pid,
274
+ code,
275
+ signal,
276
+ ...swept,
277
+ ...(options.redact ? { redact: options.redact } : {}),
278
+ result,
279
+ }));
280
+ else
281
+ resolve(result);
212
282
  };
213
283
  child.stdin.on('error', () => { });
214
284
  child.stdin.end(options.input ?? '');
@@ -345,14 +415,21 @@ export async function git(cwd, ...args) {
345
415
  return result.stdout.trim();
346
416
  }
347
417
  /**
348
- * Вывод системной утилиты или null, если она не выполнилась. Не блокирует
418
+ * Вывод системной утилиты или причина, по которой его нет. Не блокирует
349
419
  * event loop. Локаль фиксирована (`osToolEnv`): вывод разбирается.
350
420
  */
351
- function output(command, args, timeout,
352
- /** Код выхода, при котором вывод остаётся верным (lsof: часть процессов уже завершилась). */
353
- partial) {
421
+ function outcome(command, args, timeout, partial) {
354
422
  return new Promise((resolve) => {
355
- execFile(command, args, { encoding: 'utf8', env: osToolEnv(), timeout, maxBuffer: 64_000_000 }, (error, stdout) => resolve(error && (!partial || error.code !== partial) ? null : stdout));
423
+ execFile(command, args, { encoding: 'utf8', env: osToolEnv(), timeout, maxBuffer: 64_000_000 }, (error, stdout) => {
424
+ if (!error || (partial && error.code === partial))
425
+ return resolve({ stdout });
426
+ const name = command.split('/').at(-1) ?? command;
427
+ resolve({
428
+ error: error.killed
429
+ ? `${name} не ответил за ${Math.round(timeout / 1000)} с`
430
+ : `${name}: ${typeof error.code === 'number' ? `код выхода ${error.code}` : (error.code ?? error.message)}`,
431
+ });
432
+ });
356
433
  });
357
434
  }
358
435
  /** Процессы пользователя, в окружении которых есть метка. */
@@ -373,20 +450,28 @@ async function marked(mark) {
373
450
  });
374
451
  }
375
452
  // macOS: -E добавляет окружение к команде для процессов своего пользователя.
376
- const stdout = await output(osTool('ps'), ['-Eww', '-ax', '-o', 'pid=,command='], 10000);
377
- if (stdout === null)
378
- throw new Error('Не удалось перечислить процессы проверки');
379
- return stdout.split('\n').flatMap((line) => {
453
+ const listed = await processInventory.tool(osTool('ps'), ['-Eww', '-ax', '-o', 'pid=,command='], 10000);
454
+ if ('error' in listed)
455
+ throw new Error(listed.error);
456
+ return listed.stdout.split('\n').flatMap((line) => {
380
457
  const m = /^\s*(\d+)\s+(.*)$/.exec(line);
381
458
  return m && m[2].includes(needle) && Number(m[1]) !== process.pid ? [Number(m[1])] : [];
382
459
  });
383
460
  }
384
- /** Живые процессы: PID, родитель, время старта. */
385
- async function processTable() {
386
- const stdout = await output(osTool('ps'), ['-axo', 'pid=,ppid=,lstart='], 10000);
387
- if (stdout === null)
461
+ /**
462
+ * Живые процессы: PID, родитель, время старта. `strict` — для остановки
463
+ * потомков: неполученная таблица там не «процессов нет», а отказ перечня
464
+ * (`sweep` повторяет его и сдаётся с `ReapFailure`). Опрос во время команды
465
+ * пустую таблицу переживает.
466
+ */
467
+ async function processTable(strict = false) {
468
+ const listed = await processInventory.tool(osTool('ps'), ['-axo', 'pid=,ppid=,lstart='], 10000);
469
+ if ('error' in listed) {
470
+ if (strict)
471
+ throw new Error(listed.error);
388
472
  return [];
389
- return stdout.split('\n').flatMap((line) => {
473
+ }
474
+ return listed.stdout.split('\n').flatMap((line) => {
390
475
  const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
391
476
  return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), start: m[3].trim() }] : [];
392
477
  });
@@ -455,10 +540,13 @@ async function inside(dirs, since, table) {
455
540
  const candidates = [...started.keys()].filter((pid) => pid !== process.pid && fresh(pid));
456
541
  if (!candidates.length)
457
542
  return [];
458
- const stdout = await output(osTool('lsof'), ['-a', '-d', 'cwd', '-Fpn', '-u', String(process.getuid?.()), '-p', candidates.join(',')], 15000, 1);
543
+ // Отказ lsof — неполученный перечень, а не «в каталогах никого нет».
544
+ const listed = await processInventory.tool(osTool('lsof'), ['-a', '-d', 'cwd', '-Fpn', '-u', String(process.getuid?.()), '-p', candidates.join(',')], 15000, 1);
545
+ if ('error' in listed)
546
+ throw new Error(listed.error);
459
547
  const pids = [];
460
548
  let pid = 0;
461
- for (const line of (stdout ?? '').split('\n')) {
549
+ for (const line of listed.stdout.split('\n')) {
462
550
  if (line.startsWith('p'))
463
551
  pid = Number(line.slice(1));
464
552
  else if (line.startsWith('n') &&
@@ -469,16 +557,32 @@ async function inside(dirs, since, table) {
469
557
  }
470
558
  return pids;
471
559
  }
472
- /** Остановить всех потомков команды; вернуть тех, кто пережил попытки. */
560
+ /**
561
+ * Перечень процессов для остановки потомков; объект — чтобы тест мог
562
+ * подменить его отказ.
563
+ */
564
+ export const processInventory = {
565
+ marked,
566
+ /** Запуск системной утилиты перечня (`ps`, `lsof`). */
567
+ tool: outcome,
568
+ };
569
+ /** Сколько раз перечень может не получиться за одну остановку, прежде чем она сдаётся. */
570
+ const INVENTORY_TRIES = 3;
571
+ /**
572
+ * Остановить всех потомков команды; вернуть тех, кто пережил попытки, и —
573
+ * если перечень так и не получен — почему. Перечень не получен — не «живых
574
+ * нет»: команда тогда не считается завершённой.
575
+ */
473
576
  async function sweep(mark, seen, dirs, since) {
474
577
  let left = [];
578
+ let failures = 0;
475
579
  for (let attempt = 0; attempt < 20; attempt++) {
476
580
  try {
477
- const rows = await processTable();
581
+ const rows = await processTable(true);
478
582
  const table = new Map(rows.map((r) => [r.pid, r.start]));
479
583
  left = [
480
584
  ...new Set([
481
- ...(await marked(mark)),
585
+ ...(await processInventory.marked(mark)),
482
586
  // Замеченный опросом потомок — только если это тот же процесс, а
483
587
  // не новый, получивший освободившийся PID.
484
588
  ...[...seen].filter(([pid, start]) => table.get(pid) === start).map(([pid]) => pid),
@@ -486,11 +590,25 @@ async function sweep(mark, seen, dirs, since) {
486
590
  ]),
487
591
  ];
488
592
  }
489
- catch {
490
- return [-1];
593
+ catch (error) {
594
+ // Под нагрузкой хоста `ps` не укладывается в свой предел: перечень
595
+ // повторяется, а не объявляется отказом с первого раза. Уже известные
596
+ // потомки останавливаются и между попытками.
597
+ const reason = error instanceof Error ? error.message : String(error);
598
+ if (++failures >= INVENTORY_TRIES)
599
+ return { survivors: left, inventory: reason };
600
+ for (const pid of left)
601
+ try {
602
+ process.kill(pid, 'SIGKILL');
603
+ }
604
+ catch {
605
+ /* Already gone. */
606
+ }
607
+ await new Promise((r) => setTimeout(r, 500 * failures));
608
+ continue;
491
609
  }
492
610
  if (!left.length)
493
- return [];
611
+ return { survivors: [] };
494
612
  for (const pid of left)
495
613
  try {
496
614
  process.kill(pid, 'SIGKILL');
@@ -500,5 +618,5 @@ async function sweep(mark, seen, dirs, since) {
500
618
  }
501
619
  await new Promise((r) => setTimeout(r, 100));
502
620
  }
503
- return left;
621
+ return { survivors: left };
504
622
  }
@@ -374,7 +374,13 @@ function build(h, options, maxBytes, measure) {
374
374
  const repairsAll = h.workflows
375
375
  .list()
376
376
  .filter((j) => j.kind === 'graph' && graphIds.has(j.id) && j.status !== 'completed')
377
- .map((j) => ({ graphId: j.id, status: j.status, used: j.repairs ?? 0, budget: repairBudget }));
377
+ .map((j) => ({
378
+ graphId: j.id,
379
+ key: j.key,
380
+ status: j.status,
381
+ used: j.repairs ?? 0,
382
+ budget: repairBudget,
383
+ }));
378
384
  const repairs = repairsAll.slice(0, HANDOFF_LIMITS.repairs);
379
385
  const controller = status.controller
380
386
  ? {
package/lib/index.d.ts CHANGED
@@ -69,7 +69,7 @@ export { runGatesAt, type GatesAtContext, type GatesAtInput, type GatesAtResult,
69
69
  export { dependencyStoreRoot, materializeStore, type StoreContext, type StoreReceipt, } from './verification/dependency-store.ts';
70
70
  export { explicitPrerequisites, gatePrerequisites, orderedScope, standaloneScope, } from './verification/gate-scope.ts';
71
71
  export { requirementProof, uncoveredGates, unprovenReason } from './verification/proof.ts';
72
- export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, type ChangedPaths, type GateDecision, type PathDecision, } from './verification/applicability.ts';
72
+ export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, providerMovement, type ChangedPaths, type GateDecision, type PathDecision, type ProviderSnapshot, } from './verification/applicability.ts';
73
73
  export { ReviewProbes, probeLimits, observeReproductions } from './agents/review-probe.ts';
74
74
  export { composeRedactors, outputRedactor,
75
75
  /**
@@ -80,6 +80,10 @@ export { composeRedactors, outputRedactor,
80
80
  */
81
81
  policySecrets, redactDeep, redactError, redactor, type Redactor, } from './environment/redaction.ts';
82
82
  export { hostGitArgs } from './environment/process.ts';
83
+ export { ReapFailure, reapFailure } from './environment/process.ts';
84
+ export { hostLoad, loadText, type HostLoad } from './environment/host-load.ts';
85
+ export { CleanupFailure } from './environment/lifecycle.ts';
86
+ export { failureOrigin } from './engine/classify.ts';
83
87
  export { UntrustedCheckoutError, assertTrustedCheckout, forgetWorktree, gitHardening, rememberWorktree, resetGitTrust, worktreeAddPath, worktreeKey, } from './environment/git-trust.ts';
84
88
  /**
85
89
  * Корень рабочих деревьев попыток: хост выбирает его сам (`checkoutRoot`)
package/lib/index.js CHANGED
@@ -69,7 +69,7 @@ export { runGatesAt, } from "./verification/gates-at.js";
69
69
  export { dependencyStoreRoot, materializeStore, } from "./verification/dependency-store.js";
70
70
  export { explicitPrerequisites, gatePrerequisites, orderedScope, standaloneScope, } from "./verification/gate-scope.js";
71
71
  export { requirementProof, uncoveredGates, unprovenReason } from "./verification/proof.js";
72
- export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, } from "./verification/applicability.js";
72
+ export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, providerMovement, } from "./verification/applicability.js";
73
73
  export { ReviewProbes, probeLimits, observeReproductions } from "./agents/review-probe.js";
74
74
  export { composeRedactors, outputRedactor,
75
75
  /**
@@ -82,6 +82,12 @@ policySecrets, redactDeep, redactError, redactor, } from "./environment/redactio
82
82
  // Git хоста над checkout, где исполнялся чужой код: хост, запускающий свой
83
83
  // git над теми же деревьями, сверяет репозиторий теми же правилами.
84
84
  export { hostGitArgs } from "./environment/process.js";
85
+ // Отказ остановки потомков сдерживаемой команды: хост со своим запуском
86
+ // команд называет и классифицирует его так же (`environment`/`process-reap`).
87
+ export { ReapFailure, reapFailure } from "./environment/process.js";
88
+ export { hostLoad, loadText } from "./environment/host-load.js";
89
+ export { CleanupFailure } from "./environment/lifecycle.js";
90
+ export { failureOrigin } from "./engine/classify.js";
85
91
  export { UntrustedCheckoutError, assertTrustedCheckout, forgetWorktree, gitHardening, rememberWorktree, resetGitTrust, worktreeAddPath, worktreeKey, } from "./environment/git-trust.js";
86
92
  /**
87
93
  * Корень рабочих деревьев попыток: хост выбирает его сам (`checkoutRoot`)
@@ -43,6 +43,8 @@ const causeLabels = {
43
43
  'lease-expired': 'lease expired',
44
44
  stalled: 'stalled process',
45
45
  shutdown: 'controller shutdown',
46
+ 'process-reap': 'command processes not stopped or not listed',
47
+ cleanup: 'attempt resources not released (check folders, environment teardown)',
46
48
  other: 'other',
47
49
  none: 'not an environment cause',
48
50
  };
@@ -2,10 +2,14 @@ import { type ExecutionStore, type ExecutionTransaction, type ExecutionView, typ
2
2
  /**
3
3
  * Standalone ExecutionStore: нейтральный документ, события и локальные
4
4
  * записи в одной SQLite. Транзакция — `BEGIN IMMEDIATE` (вложенная —
5
- * SAVEPOINT); документ читается один раз на внешнюю транзакцию, вложенные
6
- * работают с ним же и при отказе восстанавливают его снимок и свой буфер
7
- * событий. Документ проверяется схемой при каждой фиксации: состояние вне
8
- * договора не записывается.
5
+ * SAVEPOINT); документ читается не больше раза на внешнюю транзакцию — при
6
+ * первом обращении к записям модели, — вложенные работают с ним же и при
7
+ * отказе восстанавливают его снимок и свой буфер событий. Документ пишется,
8
+ * только если транзакция изменила записи модели, и проверяется схемой при
9
+ * каждой такой фиксации: состояние вне договора не записывается.
10
+ *
11
+ * Аренда попыток (D53) — строки таблицы `leases` в той же базе: продление
12
+ * (`renewLease`) меняет одну строку, не читая и не переписывая документ.
9
13
  *
10
14
  * Версия: в `meta` записаны версия формата и версия писателя. Неизвестная
11
15
  * версия формата отклоняется при открытии, до любой записи.
@@ -46,7 +50,46 @@ export declare class SqliteExecutionStore implements ExecutionStore {
46
50
  static readOnce<T>(file: string, writer: string, fn: (store: SqliteExecutionStore) => T): T;
47
51
  /** Проверка существующего файла без единой записи; отказ — HarnessError. */
48
52
  private static preflight;
53
+ /**
54
+ * Документ с наложенными сроками аренды: при метке срок активной попытки —
55
+ * из её строки, пока token строки равен token попытки; без такой строки
56
+ * аренды нет (0). Без метки (документ прежней версии) источник — документ.
57
+ */
49
58
  private load;
59
+ private hasLeases;
60
+ /** Есть ли таблица строк аренды (её создаёт первая строка). */
61
+ private leaseTable;
62
+ private leaseRows;
63
+ private putLeaseRow;
64
+ private deleteLeaseRow;
65
+ /** Метка D53 и строки всех активных попыток документа — в открытой транзакции. */
66
+ private markLeaseRows;
67
+ /** Документ проверяется схемой и пишется; растёт `sequence`. */
68
+ private writeDocument;
69
+ /** `PRAGMA data_version` на момент последней проверки документа этим соединением. */
70
+ private validatedAt?;
71
+ /**
72
+ * Проверка формата в начале транзакции без разбора документа на каждой.
73
+ * Документ разбирается строгой схемой, если его могло изменить другое
74
+ * соединение (`PRAGMA data_version` сменился) с прошлой проверки: документ
75
+ * вне договора (например, более новой версии) — отказ до любой записи и в
76
+ * транзакции, которая только продлевает аренду строкой. Свои фиксации
77
+ * `data_version` этого соединения не меняют: продления одного процесса
78
+ * документ не разбирают. Возвращает разобранный документ или `undefined`.
79
+ */
80
+ private validate;
81
+ /** Версия данных (`ExecutionView.dataVersion`): продление строкой её не меняет. */
82
+ private dataVersion;
83
+ private bumpDataVersion;
84
+ /**
85
+ * Шаг вниз перед откатом на версию без строк аренды (D53): срок строки
86
+ * копируется в документ, метка и строки снимаются одной транзакцией. Без
87
+ * него прежняя версия отказывала бы навсегда. Выполняется после остановки
88
+ * очереди; следующее открытие этой версией с активными попытками снова
89
+ * перенесёт сроки в строки. Возвращает число активных попыток, чей срок
90
+ * перенесён в документ.
91
+ */
92
+ stepDownLeases(): number;
50
93
  read<T>(fn: (view: ExecutionView) => NotPromise<T>): T;
51
94
  transact<T>(kind: TransactionKind, fn: (tx: ExecutionTransaction) => NotPromise<T>): T;
52
95
  private writeEvents;