simetra 0.3.0-next.1 → 0.3.0-next.10

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.
@@ -834,6 +834,7 @@ function createObjectStore(options) {
834
834
  const rowChannel = channelOf(entry);
835
835
  const rows = /* @__PURE__ */ new Map();
836
836
  const tail = /* @__PURE__ */ new Set();
837
+ let nextMark = 0;
837
838
  let restored = 0;
838
839
  let hidden = 0;
839
840
  session.onFlush(() => {
@@ -1127,6 +1128,7 @@ function createObjectStore(options) {
1127
1128
  e.removed.divergent = divergent;
1128
1129
  if (!divergent && readEpoch >= e.removed.epoch) {
1129
1130
  onRemark?.(key);
1131
+ e.removed.proof = readEpoch;
1130
1132
  if (!defects.has("repeated-remove-keeps-epoch")) e.removed.epoch = epochs.next();
1131
1133
  }
1132
1134
  return;
@@ -1136,7 +1138,9 @@ function createObjectStore(options) {
1136
1138
  e.lazyEpochs.clear();
1137
1139
  e.removed = {
1138
1140
  epoch: epochs.next(),
1139
- divergent
1141
+ divergent,
1142
+ id: nextMark++,
1143
+ proof: readEpoch
1140
1144
  };
1141
1145
  },
1142
1146
  purgeKeys(scope, keys) {
@@ -1262,7 +1266,9 @@ function createObjectStore(options) {
1262
1266
  for (const [field, epoch] of init.lazyIn) e.lazyEpochs.set(field, effectiveEpoch(epoch, e.versionEpoch));
1263
1267
  if (init.state === "removed") e.removed = {
1264
1268
  epoch: at,
1265
- divergent: false
1269
+ divergent: false,
1270
+ id: nextMark++,
1271
+ proof: at
1266
1272
  };
1267
1273
  if (init.state === "hidden") {
1268
1274
  e.stale.hidden = { epoch: at };
@@ -2145,6 +2151,7 @@ const HIDDEN_TAB = {
2145
2151
  "hydration-trust": "defer",
2146
2152
  "access-narrowed": "admit",
2147
2153
  "target-behind-header": "defer",
2154
+ "owner-header": "defer",
2148
2155
  "min-version": "defer",
2149
2156
  "value-hidden": "defer",
2150
2157
  "row-unfinished": "defer",
@@ -2747,21 +2754,6 @@ function tracked(source, flight) {
2747
2754
  };
2748
2755
  }
2749
2756
  /**
2750
- * Reads one part and returns its rows; a failed part is `CommandFailure` of
2751
- * its error. For the callers that read one query at a time.
2752
- */
2753
- async function readOne(source, query) {
2754
- const [item] = (await source.read([{
2755
- type: "query",
2756
- query
2757
- }])).items;
2758
- if (item === void 0 || !item.ok || !("rows" in item)) throw new CommandFailure(item !== void 0 && !item.ok ? item.error : { code: "command.internal" });
2759
- return {
2760
- ...item.rows,
2761
- epoch: item.epoch
2762
- };
2763
- }
2764
- /**
2765
2757
  * The row a partial marker stands for (P4-B spec §4.1): the held row with the
2766
2758
  * values of the `copy` attributes the marker carries. Only those attributes
2767
2759
  * are taken — key, version and the rest of `copies` are ignored, because a
@@ -2834,6 +2826,35 @@ async function readRows$1(source, entry, query, snapshot) {
2834
2826
  };
2835
2827
  }
2836
2828
  /**
2829
+ * Reads the lines of a tabular section and the header of its owner (card
2830
+ * form) in one call: the batcher sends both parts as one request (row 22,
2831
+ * sync kernel spec §5.14). The first failed part, in the order of the parts,
2832
+ * is the failure of the read.
2833
+ */
2834
+ async function readSectionWithHeader(source, entry, query, header, snapshot) {
2835
+ const { items } = await source.read([{
2836
+ type: "query",
2837
+ query
2838
+ }, {
2839
+ type: "query",
2840
+ query: header,
2841
+ ...snapshot === void 0 ? {} : { known: snapshot.known }
2842
+ }]);
2843
+ const rowsPart = (item) => {
2844
+ if (item === void 0 || !item.ok || !("rows" in item)) throw new CommandFailure(item !== void 0 && !item.ok ? item.error : { code: "command.internal" });
2845
+ return item;
2846
+ };
2847
+ const lines = rowsPart(items[0]);
2848
+ const head = rowsPart(items[1]);
2849
+ return {
2850
+ section: {
2851
+ ...lines.rows,
2852
+ epoch: lines.epoch
2853
+ },
2854
+ header: rowsOf(entry, head.rows.rows, head.epoch, snapshot)
2855
+ };
2856
+ }
2857
+ /**
2837
2858
  * Reads rows of the object of `entry` by keys (P4-B spec §6.1, form `keys`) — the single
2838
2859
  * path of every re-read by key. The list form goes by `keysPerRequest` keys
2839
2860
  * per request; on `response-too-large` a chunk is halved down to one key,
@@ -3926,6 +3947,11 @@ function createBatcher(source, options) {
3926
3947
  // src/data/store/rights.ts
3927
3948
  const readRows = (snapshot, entry) => snapshot.rights.filter((r) => r.action === "read" && r.object === entry.kindLabel);
3928
3949
  /**
3950
+ * Контейнери мітки об'єкта з `heldContainers` (спека прав контейнера §1):
3951
+ * неявне читання рядка контейнера — не грант, тож рядків `read` воно не дає.
3952
+ */
3953
+ const heldRows = (snapshot, entry) => snapshot.heldContainers.filter((h) => h.object === entry.kindLabel);
3954
+ /**
3929
3955
  * Рядок діє в скоупі так само, як множини політики (`rights_any/own/dim` і
3930
3956
  * `rights_container`): рядок рівня `scope` чи `container` свого скоупу.
3931
3957
  * Рядки `global` і `everyUser` не мають скоупу й скоупленого об'єкта не
@@ -3944,16 +3970,19 @@ const publicReadCovers = (snapshot, entry) => entry.publicRead === "anon" || ent
3944
3970
  * покриває роль знімка, — так.
3945
3971
  * Скоуплений — скоуп у `scopeSets` свого виду й рядок `read`, що діє в
3946
3972
  * скоупі, будь-якого обсягу, зокрема контейнерний. Нескоуплений — будь-який
3947
- * рядок `read` мітки об'єкта.
3973
+ * рядок `read` мітки об'єкта. Пару контейнерного об'єкта відкриває й запис
3974
+ * `heldContainers` цього об'єкта й скоупу (спека прав контейнера §1) — у
3975
+ * межі тенанта, як політику `read_as_container`.
3948
3976
  */
3949
3977
  function readAllowed(snapshot, pair, entry) {
3950
3978
  if (entry.rights === void 0) return true;
3951
3979
  if (publicReadCovers(snapshot, entry)) return true;
3952
3980
  const rows = readRows(snapshot, entry);
3953
- if (entry.scopeKindId === void 0) return rows.length > 0;
3981
+ const held = heldRows(snapshot, entry);
3982
+ if (entry.scopeKindId === void 0) return rows.length > 0 || held.length > 0;
3954
3983
  const scope = pair.scope;
3955
3984
  const kind = entry.scopeKindId;
3956
- return scope !== null && snapshot.scopeSets.some((s) => s.scopeKind === kind && s.scope === scope) && rows.some((r) => actsInScope(r, scope));
3985
+ return scope !== null && snapshot.scopeSets.some((s) => s.scopeKind === kind && s.scope === scope) && (rows.some((r) => actsInScope(r, scope)) || held.some((h) => h.scope === scope));
3957
3986
  }
3958
3987
  /**
3959
3988
  * Чи може користувач підписатися на канал: дзеркало режиму підписки
@@ -3997,13 +4026,19 @@ const tupleOf = (r) => JSON.stringify([
3997
4026
  * Чи звузив новий знімок читання об'єкта до B6 (P4-B spec §6.2 правило 4):
3998
4027
  * зник кортеж рядка `read` мітки об'єкта, а його пара лишилась дозволеною; для нескоупленого об'єкта — ще й
3999
4028
  * змінились `scopeSets` (межа читання «Користувачів» залежить від членства).
4029
+ * Зниклий запис `heldContainers` при дозволеній парі — теж звуження: рядок
4030
+ * того контейнера база більше не дає, хоч пара лишається.
4000
4031
  * Об'єкт без контракту `rights` знімок не описує — ні.
4001
4032
  */
4002
4033
  function readNarrowed(prev, next, entry) {
4003
4034
  if (entry.rights === void 0) return false;
4004
4035
  const kept = new Set(readRows(next, entry).map(tupleOf));
4005
- const narrowed = (r) => !kept.has(tupleOf(r)) && (entry.scopeKindId === void 0 || readAllowed(next, { scope: r.scope }, entry));
4036
+ const pairAllowed = (scope) => entry.scopeKindId === void 0 || readAllowed(next, { scope }, entry);
4037
+ const narrowed = (r) => !kept.has(tupleOf(r)) && pairAllowed(r.scope);
4006
4038
  if (readRows(prev, entry).some(narrowed)) return true;
4039
+ const heldOf = (h) => JSON.stringify([h.container, h.scope]);
4040
+ const keptHeld = new Set(heldRows(next, entry).map(heldOf));
4041
+ if (heldRows(prev, entry).some((h) => !keptHeld.has(heldOf(h)) && pairAllowed(h.scope))) return true;
4007
4042
  if (entry.scopeKindId !== void 0) return false;
4008
4043
  const scopes = (s) => new Set(s.scopeSets.map((x) => `${x.scopeKind}\u0000${x.scope}`));
4009
4044
  const before = scopes(prev);
@@ -4037,6 +4072,62 @@ function reopenedPairs(prev, next, entry) {
4037
4072
  const kind = entry.scopeKindId;
4038
4073
  return [...new Set(next.scopeSets.filter((s) => s.scopeKind === kind).map((s) => s.scope))].filter(reopened);
4039
4074
  }
4075
+ // src/data/store/sync/key-queue.ts
4076
+ function frozen$1(queue) {
4077
+ Object.freeze(queue.pending);
4078
+ if (queue.flying !== void 0) Object.freeze(queue.flying);
4079
+ return Object.freeze(queue);
4080
+ }
4081
+ /** Порожня черга: перший запис об'єкта. */
4082
+ function createKeyQueue() {
4083
+ return frozen$1({
4084
+ pending: [],
4085
+ flying: void 0,
4086
+ gen: 0
4087
+ });
4088
+ }
4089
+ /** Ключі стали в чергу; ключ, що вже чекає, не зсувається. */
4090
+ function keysQueued(queue, keys) {
4091
+ return frozen$1({
4092
+ ...queue,
4093
+ pending: [.../* @__PURE__ */ new Set([...queue.pending, ...keys])]
4094
+ });
4095
+ }
4096
+ /** Політ забирає все, що чекало; порожня черга лишається як є. */
4097
+ function keysTaken(queue) {
4098
+ if (queue.pending.length === 0) return queue;
4099
+ return frozen$1({
4100
+ ...queue,
4101
+ pending: [],
4102
+ flying: queue.pending
4103
+ });
4104
+ }
4105
+ /** Політ осів: місце вільне, покоління лишається. */
4106
+ function flightSettled(queue) {
4107
+ return frozen$1({
4108
+ ...queue,
4109
+ flying: void 0
4110
+ });
4111
+ }
4112
+ /**
4113
+ * Відповідь у польоті могла не нести рядка, якого на мить `purge` у сховищі не
4114
+ * було (П12): покоління зростає, ключі польоту повертаються в чергу.
4115
+ */
4116
+ function flightInvalidated(queue) {
4117
+ return frozen$1({
4118
+ ...queue,
4119
+ gen: queue.gen + 1,
4120
+ pending: [.../* @__PURE__ */ new Set([...queue.pending, ...queue.flying ?? []])]
4121
+ });
4122
+ }
4123
+ /** Ключ чекає польоту чи в польоті. */
4124
+ function isKeyQueued(queue, key) {
4125
+ return queue !== void 0 && (queue.pending.includes(key) || queue.flying?.includes(key) === true);
4126
+ }
4127
+ /** Число ключів у черзі й польоті (діагностика розмірів). */
4128
+ function queuedKeyCount(queue) {
4129
+ return (queue?.pending.length ?? 0) + (queue?.flying?.length ?? 0);
4130
+ }
4040
4131
  // src/data/store/sync/flight-kinds.ts
4041
4132
  const FLIGHT_KIND_RULES = {
4042
4133
  load: {
@@ -4166,6 +4257,9 @@ function evidenceOf(flight) {
4166
4257
  epoch: flight.epoch
4167
4258
  };
4168
4259
  }
4260
+ const WRITELESS_SCOPE = { assert() {
4261
+ throw new Error("a writeless pass has no write scope");
4262
+ } };
4169
4263
  /**
4170
4264
  * Один прохід: синхронний, коли жоден політ не чекає залежності. Оренда
4171
4265
  * кожного польоту знімається рівно раз — і тоді, коли гачок кидає.
@@ -4180,7 +4274,10 @@ function settlePass(session, entries, hooks) {
4180
4274
  if (hooks.quiet?.(entry) === true || entry.failure !== void 0 && hooks.refused?.(entry.failure.error)) outcomes[i] = "closed";
4181
4275
  else live.push(i);
4182
4276
  });
4183
- if (live.length > 0) {
4277
+ if (live.length > 0 && hooks.writeless === true) {
4278
+ if (hooks.token.valid) region(WRITELESS_SCOPE, live);
4279
+ else for (const i of live) outcomes[i] = hooks.lost?.(entries[i]) ?? "closed";
4280
+ } else if (live.length > 0) {
4184
4281
  if (!session.commit((scope) => region(scope, live), hooks.token, hooks.what)) for (const i of live) outcomes[i] = hooks.lost?.(entries[i]) ?? "closed";
4185
4282
  }
4186
4283
  entries.forEach((entry, i) => hooks.settled?.(entry, outcomes[i], details[i]));
@@ -4331,6 +4428,7 @@ function startFlight(state, start) {
4331
4428
  return frozen(startedFlight(state, start));
4332
4429
  }
4333
4430
  function startedFlight(state, start) {
4431
+ if (start.sentAt !== void 0 && (start.kind !== "service" || start.retry !== true)) throw new Error("only an attempt of a service flight is sent with a deadline");
4334
4432
  switch (start.kind) {
4335
4433
  case "page": return state;
4336
4434
  case "reread":
@@ -4353,10 +4451,7 @@ function startedFlight(state, start) {
4353
4451
  flightRevision: start.headerRevision,
4354
4452
  retryAt: void 0,
4355
4453
  answerPending: true,
4356
- ...start.proofAtStart === true && start.headerRevision !== void 0 ? {
4357
- readRevision: start.headerRevision,
4358
- readStart: start.epoch
4359
- } : {}
4454
+ ...start.sentAt === void 0 ? {} : { refreshedAt: start.sentAt }
4360
4455
  };
4361
4456
  if (state.flight !== void 0) return {
4362
4457
  ...state,
@@ -4396,10 +4491,29 @@ function lifts(requirement, input) {
4396
4491
  const other = !input.own && input.coversHeader === true && input.complete === true;
4397
4492
  return own || other;
4398
4493
  }
4399
- case "owner-header": return input.own && input.flight === "load" && input.carriedHeader === true;
4494
+ case "owner-header": return input.own && (input.flight === "load" || input.flight === "reread") && input.carriedHeader === true;
4400
4495
  }
4401
4496
  }
4402
4497
  /**
4498
+ * Власна спроба завантаження, що не зняла вимоги шапки (збій чи відкинуте за
4499
+ * епохою): запис пам'ятає ревізію шапки й епоху її старту, як це робив `main`,
4500
+ * але вимога лишається.
4501
+ */
4502
+ function withTried(requirement, input) {
4503
+ if (requirement.kind === "owner-header" && input.own && (input.flight === "load" || input.flight === "reread") && (input.outcome === "failed" || input.outcome === "discarded-by-epoch") && input.epoch !== void 0) return {
4504
+ ...requirement,
4505
+ tried: input.epoch
4506
+ };
4507
+ if (requirement.kind !== "target-behind-header" || !input.own || input.flight !== "load" || requirement.barrier || input.outcome !== "failed" && input.outcome !== "discarded-by-epoch" || input.headerRevision === void 0 || input.epoch === void 0) return requirement;
4508
+ return {
4509
+ ...requirement,
4510
+ tried: {
4511
+ revision: input.headerRevision,
4512
+ start: input.epoch
4513
+ }
4514
+ };
4515
+ }
4516
+ /**
4403
4517
  * Політ осів. Вимоги знімає лише застосоване читання з доказом потрібного
4404
4518
  * виду польоту й старту (`lifts`); збій, відкинуте за епохою, `evicted`,
4405
4519
  * `after-purge` і `closed` вимог не знімають і доказу не пишуть. Місця
@@ -4413,7 +4527,7 @@ function settleFlight(state, input) {
4413
4527
  const start = startOf(input.evidence);
4414
4528
  let next = {
4415
4529
  ...state,
4416
- requirements: state.requirements.filter((r) => !lifts(r, input))
4530
+ requirements: state.requirements.filter((r) => !lifts(r, input)).map((r) => withTried(r, input))
4417
4531
  };
4418
4532
  if (!input.own) return withRevision(state, next);
4419
4533
  if (input.sectionRead !== void 0) next = {
@@ -4430,7 +4544,7 @@ function settleFlight(state, input) {
4430
4544
  readStart: start,
4431
4545
  readRevision: input.headerRevision
4432
4546
  };
4433
- if (input.flight === "load" && input.carriedHeader === true) next = {
4547
+ if ((input.flight === "load" || input.flight === "reread") && input.carriedHeader === true) next = {
4434
4548
  ...next,
4435
4549
  ownerHeaderRead: Math.max(next.ownerHeaderRead ?? -1, start)
4436
4550
  };
@@ -4528,12 +4642,15 @@ function addRequirement(state, requirement) {
4528
4642
  let merged = requirement;
4529
4643
  if (stands !== void 0) {
4530
4644
  const since = Math.max(stands.since, requirement.since);
4531
- if (stands.kind === "target-behind-header") merged = {
4532
- ...stands,
4533
- since,
4534
- barrier: stands.barrier || requirement.barrier
4535
- };
4536
- else if (stands.kind === "owner-header" && requirement.kind === "owner-header" && stands.mark === requirement.mark) merged = {
4645
+ if (stands.kind === "target-behind-header") {
4646
+ const placed = requirement;
4647
+ merged = {
4648
+ ...stands,
4649
+ since,
4650
+ barrier: stands.barrier || placed.barrier,
4651
+ tried: stands.tried
4652
+ };
4653
+ } else if (stands.kind === "owner-header" && requirement.kind === "owner-header" && stands.mark === requirement.mark) merged = {
4537
4654
  ...stands,
4538
4655
  since
4539
4656
  };
@@ -4731,6 +4848,18 @@ function diffOwn(ops, scope, o, prev, wanted) {
4731
4848
  for (const key of prev) if (!next.has(key)) ops.disown(scope, o, key);
4732
4849
  return next;
4733
4850
  }
4851
+ /**
4852
+ * Правило складу картки: вона бере ключ у власність, коли відповідь
4853
+ * (завантаження чи системне перечитування) несе рядок оголошеного ключа — одне
4854
+ * правило для обох шляхів (рядок 20). `keys` має інше правило стабільності
4855
+ * складу (§6.5): нові ключі лише ставлять `hasNewRows`.
4856
+ */
4857
+ function ownsDeclaredKeys(s) {
4858
+ return s.form.spec.kind === "card";
4859
+ }
4860
+ function ownDeclaredKeys(ops, scope, s, keys = s.form.keys) {
4861
+ s.owned = diffOwn(ops, scope, s.form.object, s.owned, keys);
4862
+ }
4734
4863
  function setLayout(s, layout) {
4735
4864
  s.layout = layout;
4736
4865
  s.layoutSet = new Set(layout);
@@ -5157,7 +5286,7 @@ async function readKeysForm(ctx, s, readEpoch) {
5157
5286
  got.add(row.key);
5158
5287
  }
5159
5288
  for (const key of form.keys) if (!got.has(key)) missed(ops, scope, o, key, readEpoch);
5160
- s.owned = diffOwn(ops, scope, o, s.owned, form.keys);
5289
+ ownDeclaredKeys(ops, scope, s, form.keys);
5161
5290
  setLayout(s, form.keys.filter((k) => s.owned.has(k)));
5162
5291
  };
5163
5292
  }
@@ -5179,7 +5308,7 @@ async function readCard(ctx, s, readEpoch) {
5179
5308
  return (scope) => {
5180
5309
  if (row !== void 0) ops.put(scope, o, row, readEpoch, true);
5181
5310
  else missed(ops, scope, o, key, readEpoch);
5182
- s.owned = diffOwn(ops, scope, o, s.owned, [key]);
5311
+ ownDeclaredKeys(ops, scope, s, [key]);
5183
5312
  if (form.include.length === 0) return;
5184
5313
  const alive = o.rows.get(key)?.removed === void 0 && row !== void 0;
5185
5314
  applyIncluded(ctx, scope, s, aliveIncluded(included, includeKeys(form.include, alive ? [row.values] : [])), readEpoch);
@@ -5190,21 +5319,35 @@ async function readSection(ctx, s, readEpoch) {
5190
5319
  const o = s.form.object;
5191
5320
  const spec = s.form.spec;
5192
5321
  const section = o.entry.tabularSections.find((t) => t.name === spec.section);
5193
- const result = await readOne(ctx.source, {
5322
+ const answer = await readSectionWithHeader(ctx.source, o.entry, {
5194
5323
  object: o.ref,
5195
5324
  tabularSection: spec.section,
5196
5325
  owner: spec.owner
5197
- });
5326
+ }, {
5327
+ object: o.ref,
5328
+ id: spec.owner
5329
+ }, o.rows.knownFor([spec.owner], {
5330
+ owned: s.owned,
5331
+ form: "card"
5332
+ }));
5333
+ const result = answer.section;
5334
+ const header = answer.header.find((r) => r.key === spec.owner);
5198
5335
  const lines = result.rows.map((values) => lineOf(section, values));
5199
5336
  return (scope, report) => {
5200
- if (report !== void 0) report.sectionRead = readEpoch;
5337
+ if (report !== void 0) {
5338
+ report.sectionRead = readEpoch;
5339
+ report.carriedHeader = true;
5340
+ }
5201
5341
  s.headerState = void 0;
5342
+ if (header !== void 0) ops.put(scope, o, header, readEpoch, true);
5343
+ else missed(ops, scope, o, spec.owner, readEpoch);
5344
+ s.owned = diffOwn(ops, scope, o, s.owned, [spec.owner]);
5202
5345
  if (result.ownerVersion === void 0) {
5203
5346
  ops.clearOwner(scope, o, spec.owner);
5204
5347
  return;
5205
5348
  }
5206
- const header = o.rows.get(spec.owner);
5207
- if (ops.putSection(scope, o, spec.owner, spec.section, lines, result.ownerVersion, result.epoch, readEpoch, o.entry.scopeColumn === void 0 ? null : header === void 0 || differentEpochs(result.epoch, header.versionEpoch) || header.version !== result.ownerVersion ? "unknown" : header.scope) === "barred" && report !== void 0) report.sectionRead = void 0;
5349
+ const held = o.rows.get(spec.owner);
5350
+ if (ops.putSection(scope, o, spec.owner, spec.section, lines, result.ownerVersion, result.epoch, readEpoch, o.entry.scopeColumn === void 0 ? null : held === void 0 || differentEpochs(result.epoch, held.versionEpoch) || held.version !== result.ownerVersion ? "unknown" : held.scope) === "barred" && report !== void 0) report.sectionRead = void 0;
5208
5351
  };
5209
5352
  }
5210
5353
  /**
@@ -5288,24 +5431,45 @@ function requirementHold(s) {
5288
5431
  * Збій читання тут не повторює: його повторює пауза збоїв.
5289
5432
  */
5290
5433
  function settleTarget(s, flight, outcome, failure, context) {
5434
+ if (context.unconfirmedSince !== void 0 && !("part" in s)) {
5435
+ s.needsRefresh = true;
5436
+ requireConfirmation(s, context.unconfirmedSince);
5437
+ s.targetState = derivedInputChanged(s.targetState, "registry-flag");
5438
+ return false;
5439
+ }
5291
5440
  const rules = rulesOf(flight);
5292
- const counts = (applied) => applied ? rules.successMovesDeadline : context.readFailed && (rules.failureCounts === "always" || rules.failureCounts === "if-loaded" && s.loaded);
5441
+ const loadedBefore = "part" in s ? true : s.loaded;
5442
+ const counts = (applied) => applied ? rules.successMovesDeadline : context.readFailed && (rules.failureCounts === "always" || rules.failureCounts === "if-loaded" && loadedBefore);
5443
+ const sentAt = "part" in s && s.part === "rights" ? s.targetState.refreshedAt : void 0;
5293
5444
  const settle = (applied) => ({
5294
5445
  outcome: applied ? "applied" : "failed",
5295
5446
  flight: required(flight.kind, "its kind"),
5296
5447
  evidence: applied ? {
5297
- kind: "session-start",
5448
+ kind: flight.kind === "service" ? "service-sent" : "session-start",
5298
5449
  epoch: required(flight.epoch, "its start epoch")
5299
5450
  } : void 0,
5300
5451
  own: true,
5301
- startedAt: counts(applied) ? required(flight.startedAt, "its start time") : flight.startedAt ?? 0,
5302
- loaded: s.loaded,
5452
+ epoch: required(flight.epoch, "its start epoch"),
5453
+ ...flight.kind === "load" && s.targetState.flightRevision !== void 0 ? { headerRevision: s.targetState.flightRevision } : {},
5454
+ startedAt: sentAt ?? (counts(applied) ? required(flight.startedAt, "its start time") : flight.startedAt ?? 0),
5455
+ loaded: loadedBefore,
5303
5456
  applyFailed: !context.readFailed,
5304
- ...context.report?.sectionRead === void 0 ? {} : { sectionRead: context.report.sectionRead }
5457
+ ...context.report?.sectionRead === void 0 ? {} : { sectionRead: context.report.sectionRead },
5458
+ ...context.report?.carriedHeader === true ? { carriedHeader: true } : {}
5305
5459
  });
5460
+ if ("part" in s) {
5461
+ if (outcome === "applied" || outcome === "failed") s.targetState = settleFlight(s.targetState, settle(outcome === "applied"));
5462
+ return false;
5463
+ }
5306
5464
  if (outcome === "applied") {
5307
5465
  if (rules.successMovesDeadline && rules.confirms === "view-with-composition") s.loaded = true;
5308
5466
  s.targetState = settleFlight(s.targetState, settle(true));
5467
+ for (const { target, complete } of context.covered ?? []) target.targetState = settleFlight(target.targetState, {
5468
+ ...settle(true),
5469
+ own: false,
5470
+ coversHeader: true,
5471
+ complete
5472
+ });
5309
5473
  if (rules.confirms === "view-with-composition" || s.status === "error") {
5310
5474
  s.status = "ready";
5311
5475
  s.error = void 0;
@@ -5323,6 +5487,10 @@ function settleTarget(s, flight, outcome, failure, context) {
5323
5487
  s.status = "error";
5324
5488
  s.error = errorOf(failure.error);
5325
5489
  }
5490
+ if (outcome === "discarded-by-epoch") s.targetState = settleFlight(s.targetState, {
5491
+ ...settle(false),
5492
+ outcome: "discarded-by-epoch"
5493
+ });
5326
5494
  return false;
5327
5495
  }
5328
5496
  const CHECK_ON_MOUNT = {
@@ -5411,7 +5579,8 @@ function createRegistry(ctx) {
5411
5579
  const again = settleTarget(s, f, outcome, failure, {
5412
5580
  readFailed: entry.failure !== void 0,
5413
5581
  tabHidden: ctx.tabHidden,
5414
- ...entry.report === void 0 ? {} : { report: entry.report }
5582
+ ...entry.report === void 0 ? {} : { report: entry.report },
5583
+ ...outcome === "applied" ? { covered: coveredBy(s) } : {}
5415
5584
  });
5416
5585
  if (outcome === "applied") verdict.again = again;
5417
5586
  },
@@ -5481,7 +5650,6 @@ function createRegistry(ctx) {
5481
5650
  cause: why,
5482
5651
  epoch: readEpoch,
5483
5652
  retry: true,
5484
- proofAtStart: true,
5485
5653
  ...header === void 0 ? {} : { headerRevision: rowViews.revision(s.form.object.name, header) }
5486
5654
  });
5487
5655
  const verdict = {
@@ -5728,11 +5896,10 @@ function createRegistry(ctx) {
5728
5896
  * been one) came after the start of its last read: the read cannot have
5729
5897
  * seen it, so the re-read is not a repeat of a discarded answer.
5730
5898
  */
5731
- function hiddenSinceRead(s) {
5899
+ function hiddenSinceRead(s, start = s.targetState.readStart ?? -1) {
5732
5900
  const spec = s.form.spec;
5733
5901
  if (spec.kind !== "section") return false;
5734
5902
  const o = s.form.object;
5735
- const start = s.targetState.readStart ?? -1;
5736
5903
  return hiddenAfter(o, spec.owner, start) || session.epochs.evictedSince(keyId(o.name, spec.owner), start);
5737
5904
  }
5738
5905
  /**
@@ -5752,19 +5919,103 @@ function createRegistry(ctx) {
5752
5919
  });
5753
5920
  return;
5754
5921
  }
5755
- if (behindHeader(s)) load(s, why);
5922
+ placeBehindHeader(s);
5923
+ placeOwnerHeader(s);
5924
+ if (readsBehindHeader(s)) load(s, why);
5925
+ else if (readsOwnerHeader(s)) load(s, why.reason === "requirement" ? {
5926
+ ...why,
5927
+ requirement: "owner-header"
5928
+ } : why);
5756
5929
  }
5757
5930
  /**
5758
- * Картка чи ТЧ відстала від шапки (вимога «ціль відстала від шапки»): одне
5759
- * означення для перевірки й для діагностики `sync()`.
5931
+ * Картка чи ТЧ відстала від шапки — умова постановки вимоги «ціль відстала
5932
+ * від шапки» (рядок 20, Р-SK3-11): ціль неповна за `cardStale`/`sectionStale`,
5933
+ * а шапка змінилась (ревізія), чи `hide` власника новіший за застосоване
5934
+ * завантаження. Дешеві перевірки — першими: умова питається на кожен `commit`.
5760
5935
  */
5761
- function behindHeader(s) {
5936
+ function headerChanged(s) {
5762
5937
  const header = headerKey(s);
5763
5938
  if (header === void 0) return false;
5764
- if (!(s.form.spec.kind === "card" ? cardStale(s) : sectionStale(s))) return false;
5765
5939
  return rowViews.revision(s.form.object.name, header) !== s.targetState.readRevision || hiddenSinceRead(s);
5766
5940
  }
5767
5941
  /**
5942
+ * Ставить вимогу «ціль відстала від шапки» (збережена, знімає її лише
5943
+ * осідання з доказом). Стоячу вимогу не зсуває: читання, що вже летить зі
5944
+ * стартом після неї, її знімає, а нова зміна шапки після його старту ставить
5945
+ * вимогу наново (доказ шапки — ревізія на старті, див. `headerChanged`).
5946
+ */
5947
+ function placeBehindHeader(s) {
5948
+ if (!s.alive || s.purged || headerKey(s) === void 0) return;
5949
+ if (requirementOf(s.targetState, "target-behind-header") !== void 0) return;
5950
+ if (!headerChanged(s)) return;
5951
+ if (!(s.form.spec.kind === "card" ? cardStale(s) : sectionStale(s))) return;
5952
+ s.targetState = addRequirement(s.targetState, {
5953
+ kind: "target-behind-header",
5954
+ since: session.epochs.now(),
5955
+ barrier: false,
5956
+ tried: void 0
5957
+ });
5958
+ }
5959
+ /**
5960
+ * Стоїть вимога шапки, і її є що читати: спроби ще не було, або шапка (ревізія
5961
+ * чи `hide` власника) змінилась після старту спроби, що збилась. Власний `commit` збою чи відкинутого
5962
+ * завантаження повтору не дає (ревізія та сама), як на `main`.
5963
+ */
5964
+ function readsBehindHeader(s) {
5965
+ const stands = requirementOf(s.targetState, "target-behind-header");
5966
+ if (stands === void 0) return false;
5967
+ const header = headerKey(s);
5968
+ return stands.tried === void 0 || header !== void 0 && rowViews.revision(s.form.object.name, header) !== stands.tried.revision || hiddenSinceRead(s, stands.tried.start);
5969
+ }
5970
+ /**
5971
+ * Ставить вимогу «шапка власника» (рядок 22, Р-SK3-12): власник ТЧ `removed`
5972
+ * позначкою, яку не покриває доказ запису цілі. Позначку покриває читання ТЧ
5973
+ * з шапкою, що стартувало не раніше читання, яке її поставило (власна
5974
+ * позначка завантаження покрита ним самим); `since` — епоха позначки, тож
5975
+ * доказ — читання після неї. Повторна позначка того самого ідентифікатора
5976
+ * зсуває лише `since`.
5977
+ */
5978
+ function placeOwnerHeader(s) {
5979
+ const spec = s.form.spec;
5980
+ if (!s.alive || s.purged || spec.kind !== "section") return;
5981
+ const mark = s.form.object.rows.get(spec.owner)?.removed;
5982
+ if (mark === void 0) return;
5983
+ const proved = s.targetState.ownerHeaderRead;
5984
+ if (proved !== void 0 && proved >= mark.proof) return;
5985
+ const stands = requirementOf(s.targetState, "owner-header");
5986
+ if (stands !== void 0 && stands.mark === mark.id && stands.since >= mark.epoch) return;
5987
+ s.targetState = addRequirement(s.targetState, {
5988
+ kind: "owner-header",
5989
+ since: mark.epoch,
5990
+ mark: mark.id,
5991
+ tried: void 0
5992
+ });
5993
+ }
5994
+ /**
5995
+ * Вимога шапки власника стоїть, і її є що читати: спроби ще не було, або
5996
+ * позначка повторена після старту спроби, що збилась. Власний `commit` збою
5997
+ * чи відкинутого завантаження повтору не дає.
5998
+ */
5999
+ function readsOwnerHeader(s) {
6000
+ const stands = requirementOf(s.targetState, "owner-header");
6001
+ return stands !== void 0 && (stands.tried === void 0 || stands.since > stands.tried);
6002
+ }
6003
+ /** Див. `SubsetRegistry.covered`. */
6004
+ function coveredBy(by) {
6005
+ const found = [];
6006
+ for (const t of subsets.values()) {
6007
+ if (t === by || !t.alive || t.purged || t.form.object !== by.form.object) continue;
6008
+ const header = headerKey(t);
6009
+ if (header === void 0 || !by.owned.has(header)) continue;
6010
+ if (requirementOf(t.targetState, "target-behind-header") === void 0) continue;
6011
+ found.push({
6012
+ target: t,
6013
+ complete: !(t.form.spec.kind === "card" ? cardStale(t) : sectionStale(t))
6014
+ });
6015
+ }
6016
+ return found;
6017
+ }
6018
+ /**
5768
6019
  * The first hold starts the subset; a card with a stored row shows it
5769
6020
  * without a read. A held subset is checked on mount, and a section on
5770
6021
  * `preload` too: a stale section (`sectionStale`) is re-read once observed.
@@ -6077,7 +6328,6 @@ function createRegistry(ctx) {
6077
6328
  };
6078
6329
  }
6079
6330
  return {
6080
- behindHeader: (s) => s.alive && !s.purged && behindHeader(s),
6081
6331
  view(spec) {
6082
6332
  if (isClosed()) return closedHandle();
6083
6333
  const form = formOf(ctx, spec);
@@ -6125,7 +6375,11 @@ function createRegistry(ctx) {
6125
6375
  const s = acquire(form);
6126
6376
  const o = form.object;
6127
6377
  const spec = form.spec;
6128
- s.owned = diffOwn(ops, scope, o, /* @__PURE__ */ new Set(), [...state.layout, ...state.unshown]);
6378
+ s.owned = diffOwn(ops, scope, o, /* @__PURE__ */ new Set(), [
6379
+ ...state.layout,
6380
+ ...state.unshown,
6381
+ ...spec.kind === "section" ? [spec.owner] : []
6382
+ ]);
6129
6383
  if (spec.kind !== "card" && spec.kind !== "section") {
6130
6384
  s.layout = state.layout.filter((key) => s.owned.has(key));
6131
6385
  s.layoutSet = new Set(s.layout);
@@ -6165,9 +6419,19 @@ function createRegistry(ctx) {
6165
6419
  if (idle(s)) scheduleRelease(s);
6166
6420
  }
6167
6421
  },
6422
+ covered: coveredBy,
6423
+ readsByCheck(s) {
6424
+ if (!s.alive || s.purged || s.listeners.size === 0) return false;
6425
+ if (s.targetState.flight !== void 0) return false;
6426
+ placeBehindHeader(s);
6427
+ placeOwnerHeader(s);
6428
+ return readsBehindHeader(s) || readsOwnerHeader(s);
6429
+ },
6168
6430
  afterCommit(closing) {
6169
6431
  const notify = [];
6170
6432
  for (const s of subsets.values()) {
6433
+ placeBehindHeader(s);
6434
+ placeOwnerHeader(s);
6171
6435
  if (!closing && snapshotFresh(s) && !affected(s)) continue;
6172
6436
  if (snapshotFresh(s)) s.targetState = derivedInputChanged(s.targetState, "affected");
6173
6437
  if (s.listeners.size === 0) continue;
@@ -6480,9 +6744,13 @@ function applyKeys(ctx, s, requested, rows, startEpoch, marksNew) {
6480
6744
  let fresh = false;
6481
6745
  for (const row of rows) {
6482
6746
  got.add(row.key);
6483
- if (s.owned.has(row.key)) ctx.ops.put(scope, o, row, startEpoch, false);
6747
+ if (s.owned.has(row.key) || ownsDeclaredKeys(s) && s.form.keys.includes(row.key)) ctx.ops.put(scope, o, row, startEpoch, false);
6484
6748
  else if (!lostSince(ctx, o, row, startEpoch)) fresh = true;
6485
6749
  }
6750
+ if (ownsDeclaredKeys(s)) {
6751
+ const brought = rows.map((r) => r.key).filter((k) => s.form.keys.includes(k) && !s.owned.has(k));
6752
+ if (brought.length > 0) ownDeclaredKeys(ctx.ops, scope, s, [...s.owned, ...brought]);
6753
+ }
6486
6754
  for (const key of requested) if (!got.has(key) && s.owned.has(key)) ctx.ops.remove(scope, o, key, startEpoch);
6487
6755
  if (fresh && marksNew) s.hasNewRows = true;
6488
6756
  if (s.form.spec.kind === "keys") rebuildLayout(ctx, s);
@@ -6863,14 +7131,15 @@ async function revalidateHydrated(ctx, s, why) {
6863
7131
  * row or an `include` target, invisible views included: the
6864
7132
  * values return only with a read that started after the `hide`. A failed
6865
7133
  * read leaves them hidden. A view of another object that includes the
6866
- * object is re-read as its own object's view. Tabular section subsets are
6867
- * not re-read here: they go stale by the hide epoch of their owner.
7134
+ * object is re-read as its own object's view. A tabular section holds the
7135
+ * header of its owner (row 22), so it is re-read here like any holder, unless
7136
+ * the check of the view already reads it for a requirement.
6868
7137
  */
6869
7138
  async function revalidateHolders(ctx, object, keys, why) {
6870
7139
  const groups = /* @__PURE__ */ new Map();
6871
7140
  for (const s of ctx.registry.subsets()) {
6872
7141
  if (!s.alive || s.purged || !s.loaded) continue;
6873
- if (s.form.spec.kind === "section") continue;
7142
+ if (s.form.spec.kind === "section" && ctx.registry.readsByCheck(s)) continue;
6874
7143
  const included = s.included.get(object);
6875
7144
  if (!(s.form.object.name === object && [...keys].some((k) => s.owned.has(k)) || included !== void 0 && [...keys].some((k) => included.has(k)))) continue;
6876
7145
  const read = admitViews(ctx, [s], why);
@@ -7012,7 +7281,8 @@ async function revalidateViews(ctx, o, reads) {
7012
7281
  const entry = entryOf.get(flight);
7013
7282
  const again = settleTarget(entry.s, flight, outcome, failure, {
7014
7283
  readFailed: entry.failure !== void 0,
7015
- ...entry.report === void 0 ? {} : { report: entry.report }
7284
+ ...entry.report === void 0 ? {} : { report: entry.report },
7285
+ ...outcome === "applied" ? { covered: ctx.registry.covered(entry.s) } : {}
7016
7286
  });
7017
7287
  if (outcome === "applied" && again) entry.verdict.again = repeatOf(flight, "R18");
7018
7288
  },
@@ -7070,7 +7340,6 @@ async function rereadKey(ctx, object, key, options) {
7070
7340
  }, "K4");
7071
7341
  if (!isPermit(admitted)) return;
7072
7342
  const o = ctx.objectOf(object);
7073
- const token = session.token();
7074
7343
  const limit = new AbortController();
7075
7344
  const requester = (outcome, scope) => {
7076
7345
  if (outcome.kind !== "read" && unconfirmed !== void 0) {
@@ -7083,6 +7352,7 @@ async function rereadKey(ctx, object, key, options) {
7083
7352
  const flight = admitted.flight({
7084
7353
  lease,
7085
7354
  kind: "keys",
7355
+ token: session.token(),
7086
7356
  requester,
7087
7357
  deadlineMs: REREAD_TIMEOUT_MS,
7088
7358
  done: { fired: false }
@@ -7095,6 +7365,7 @@ async function rereadKey(ctx, object, key, options) {
7095
7365
  required(flight.requester, "its requester")(outcome, scope);
7096
7366
  };
7097
7367
  session.sleep(required(flight.deadlineMs, "its deadline"), limit.signal).then(() => {
7368
+ const token = required(flight.token, "its token");
7098
7369
  if (required(flight.done, "its reply mark").fired || !token.valid) return;
7099
7370
  session.commit((scope) => reply({ kind: "failed" }, scope), token, "reread timeout");
7100
7371
  });
@@ -7110,9 +7381,9 @@ async function rereadKey(ctx, object, key, options) {
7110
7381
  flight,
7111
7382
  ...rows === void 0 ? { failure: { error: void 0 } } : {}
7112
7383
  }], {
7113
- token,
7384
+ token: required(flight.token, "its token"),
7114
7385
  what: `reread ${o.name}`,
7115
- quiet: () => !token.valid,
7386
+ quiet: () => !required(flight.token, "its token").valid,
7116
7387
  gate: () => {
7117
7388
  const epochs = new Set(read.epochs);
7118
7389
  for (const row of required(rows, "its answer")) epochs.add(row.versionEpoch ?? null);
@@ -7763,9 +8034,10 @@ function createReceiver(ctx) {
7763
8034
  token,
7764
8035
  what: "writer",
7765
8036
  quiet: () => stopped,
7766
- readFailed: ({ flight, job: { object } }, scope) => {
7767
- if (rulesOf(flight).keysFailure === "composition-unconfirmed") createWriter(writer, scope).markViews(object, {
7768
- needsRefresh: true,
8037
+ settleTarget: (flight, outcome, _evidence, failure) => {
8038
+ if (entry.failure === void 0 || failure === void 0 || rulesOf(flight).keysFailure !== "composition-unconfirmed") return;
8039
+ for (const s of subsetsOf(writer, entry.job.o)) settleTarget(s, flight, outcome, failure, {
8040
+ readFailed: true,
7769
8041
  unconfirmedSince: since
7770
8042
  });
7771
8043
  },
@@ -7962,6 +8234,20 @@ const RIGHTS_UNCONFIRMED = {
7962
8234
  reason: "requirement",
7963
8235
  requirement: "rights-unconfirmed"
7964
8236
  };
8237
+ const VERSION_UNCONFIRMED = {
8238
+ reason: "requirement",
8239
+ requirement: "version-unconfirmed"
8240
+ };
8241
+ /**
8242
+ * Причина читання з даних польоту: політ — це причина плюс запис шлюзу, тож
8243
+ * копії причини службова ціль не тримає.
8244
+ */
8245
+ function causeOfFlight(flight) {
8246
+ return flight.reason === "requirement" ? {
8247
+ reason: "requirement",
8248
+ requirement: flight.requirement
8249
+ } : { reason: flight.reason };
8250
+ }
7965
8251
  const HYDRATION_TRUST = {
7966
8252
  reason: "requirement",
7967
8253
  requirement: "hydration-trust",
@@ -8023,12 +8309,29 @@ function createCore(options) {
8023
8309
  now,
8024
8310
  defects
8025
8311
  });
8312
+ const services = {
8313
+ rights: {
8314
+ part: "rights",
8315
+ targetState: createTargetState()
8316
+ },
8317
+ version: {
8318
+ part: "version",
8319
+ targetState: createTargetState()
8320
+ }
8321
+ };
8026
8322
  const batcher = createBatcher(options.source, {
8027
8323
  ownFlight: gate.issued,
8028
8324
  staleObject: gate.staleObject,
8029
8325
  sleep: session.sleep,
8030
8326
  onRightsSent: () => {
8031
- rightsSentAt = now();
8327
+ const state = services.rights.targetState;
8328
+ services.rights.targetState = startFlight(state, {
8329
+ kind: "service",
8330
+ cause: state.flightCause ?? RIGHTS_UNCONFIRMED,
8331
+ retry: true,
8332
+ epoch: state.flightEpoch,
8333
+ sentAt: now()
8334
+ });
8032
8335
  },
8033
8336
  onRead: (event) => {
8034
8337
  for (const listener of [...readListeners]) try {
@@ -8038,7 +8341,10 @@ function createCore(options) {
8038
8341
  onVersion(version) {
8039
8342
  if (session.token().valid) applyVersion(version.objects);
8040
8343
  },
8041
- onRights: (item) => acceptRights(item)
8344
+ onRights: (item) => {
8345
+ const outcome = acceptRights(item);
8346
+ if (rightsFlight !== void 0) settleService("rights", rightsFlight, outcome);
8347
+ }
8042
8348
  });
8043
8349
  const pendingWrites = /* @__PURE__ */ new Map();
8044
8350
  const source = {
@@ -8143,38 +8449,42 @@ function createCore(options) {
8143
8449
  const origins = forward.map(() => flight);
8144
8450
  if (injected) {
8145
8451
  forward.unshift({ type: "rights" });
8146
- origins.unshift(rightsFirst.flight());
8452
+ origins.unshift(rightsFirst.flight({ kind: "service" }));
8147
8453
  }
8148
8454
  const rightsAt = forward.findIndex((part) => part.type === "rights");
8149
8455
  let answered = { items: [] };
8150
8456
  if (rightsAt < 0) {
8151
8457
  if (forward.length > 0) answered = await batcher.read(forward, origins);
8152
8458
  } else {
8153
- const sentRights = {
8154
- token: session.token(),
8155
- epoch: session.epochs.next(),
8156
- known: rights?.rightsVersion
8157
- };
8158
- forward[rightsAt] = sentRights.known === void 0 ? { type: "rights" } : {
8459
+ const sentEpoch = session.epochs.next();
8460
+ const flying = origins[rightsAt];
8461
+ rightsFlight = flying;
8462
+ rightsKnown = rights?.rightsVersion;
8463
+ forward[rightsAt] = rightsKnown === void 0 ? { type: "rights" } : {
8159
8464
  type: "rights",
8160
- known: sentRights.known
8465
+ known: rightsKnown
8161
8466
  };
8162
8467
  rightsFirstSent = true;
8163
- rightsFlying = true;
8164
- rightsSent = sentRights;
8468
+ services.rights.targetState = startFlight(services.rights.targetState, {
8469
+ kind: "service",
8470
+ epoch: sentEpoch,
8471
+ cause: causeOfFlight(flying)
8472
+ });
8165
8473
  try {
8166
8474
  answered = await batcher.read(forward, origins);
8167
8475
  } catch (error) {
8168
- if (sentRights.token.valid) log({ kind: "rights-failed" });
8476
+ if (session.token().valid) log({ kind: "rights-failed" });
8477
+ if (services.rights.targetState.answerPending) settleService("rights", flying, "failed");
8169
8478
  throw error;
8170
8479
  } finally {
8171
- rightsFlying = false;
8480
+ rightsFlight = void 0;
8481
+ const tail = services.rights.targetState.trailing;
8482
+ services.rights.targetState = slotChanged(services.rights.targetState, {
8483
+ kind: "freed",
8484
+ alive: true
8485
+ });
8172
8486
  if (!defects.has("scheduler-no-reschedule")) scheduler.request();
8173
- const tail = rightsTail;
8174
- if (tail !== void 0) {
8175
- rightsTail = void 0;
8176
- requestRightsFor(tail);
8177
- }
8487
+ if (tail !== void 0) requestRightsFor(tail);
8178
8488
  }
8179
8489
  if (injected) answered = { items: answered.items.slice(1) };
8180
8490
  }
@@ -8190,10 +8500,8 @@ function createCore(options) {
8190
8500
  const rightsEnabled = options.rightsSnapshot === true;
8191
8501
  let rights;
8192
8502
  let rightsFirstSent = false;
8193
- let rightsFlying = false;
8194
- let rightsTail;
8195
- let rightsSentAt;
8196
- let rightsSent;
8503
+ let rightsKnown;
8504
+ let rightsFlight;
8197
8505
  let firstRights;
8198
8506
  const beforeFirst = {
8199
8507
  views: /* @__PURE__ */ new Set(),
@@ -8260,34 +8568,34 @@ function createCore(options) {
8260
8568
  if (session.token().valid) core.close("session-changed");
8261
8569
  }
8262
8570
  function acceptRights(item) {
8263
- const sentRights = rightsSent;
8264
- if (sentRights === void 0 || !sentRights.token.valid) return;
8571
+ const sentEpoch = services.rights.targetState.flightEpoch;
8572
+ if (sentEpoch === void 0 || !session.token().valid) return "closed";
8265
8573
  if (!item.ok || !("type" in item) || item.type !== "rights") {
8266
8574
  log({ kind: "rights-failed" });
8267
- return;
8575
+ return "failed";
8268
8576
  }
8269
8577
  const { rightsVersion, snapshot } = item.value;
8270
8578
  const current = rights;
8271
8579
  if (snapshot === void 0) {
8272
- if (current === void 0 || sentRights.known !== current.rightsVersion || rightsVersion !== current.rightsVersion) {
8580
+ if (current === void 0 || rightsKnown !== current.rightsVersion || rightsVersion !== current.rightsVersion) {
8273
8581
  log({ kind: "rights-failed" });
8274
- return;
8582
+ return "failed";
8275
8583
  }
8276
8584
  rights = {
8277
8585
  ...current,
8278
8586
  rightsVersion
8279
8587
  };
8280
- return;
8588
+ return "applied";
8281
8589
  }
8282
8590
  if (current !== void 0 && current.snapshot.userId !== null && snapshot.userId !== null && current.snapshot.userId !== snapshot.userId) {
8283
8591
  rightsSessionChanged();
8284
- return;
8592
+ return "closed";
8285
8593
  }
8286
- if (current !== void 0 && sentRights.epoch <= current.rightsEpoch) return;
8594
+ if (current !== void 0 && sentEpoch <= current.rightsEpoch) return "discarded-by-epoch";
8287
8595
  const next = {
8288
8596
  snapshot,
8289
8597
  rightsVersion,
8290
- rightsEpoch: sentRights.epoch,
8598
+ rightsEpoch: sentEpoch,
8291
8599
  appliedEpoch: session.epochs.next()
8292
8600
  };
8293
8601
  rights = next;
@@ -8302,6 +8610,7 @@ function createCore(options) {
8302
8610
  });
8303
8611
  }
8304
8612
  receiver?.snapshotReplaced();
8613
+ return "applied";
8305
8614
  }
8306
8615
  function replaceRights(prev, next, item) {
8307
8616
  rightsPassListener?.();
@@ -8369,7 +8678,8 @@ function createCore(options) {
8369
8678
  object: name,
8370
8679
  session,
8371
8680
  rows
8372
- })
8681
+ }),
8682
+ keyQueue: void 0
8373
8683
  });
8374
8684
  }
8375
8685
  const objectOf = (name) => {
@@ -8414,8 +8724,9 @@ function createCore(options) {
8414
8724
  },
8415
8725
  own: (scope, o, key) => o.rows.own(scope, key),
8416
8726
  disown(scope, o, key) {
8727
+ const before = o.rows.get(key);
8417
8728
  o.rows.disown(scope, key);
8418
- rowViews.touch(o.name, key);
8729
+ if (before !== void 0 && o.rows.get(key) !== before) rowViews.touch(o.name, key);
8419
8730
  },
8420
8731
  putSection(scope, o, owner, section, lines, ownerVersion, versionEpoch, readEpoch, ownerScope) {
8421
8732
  if (staleObjects.has(o.name)) return void 0;
@@ -8482,10 +8793,9 @@ function createCore(options) {
8482
8793
  let hydration = "none";
8483
8794
  let visible = options.visible ?? true;
8484
8795
  let lastResumeAt;
8485
- const tails = /* @__PURE__ */ new Map();
8486
8796
  function runTail(o) {
8487
- const tail = tails.get(o);
8488
- if (tail === void 0 || tail.flying !== void 0) return;
8797
+ const queue = o.keyQueue;
8798
+ if (queue === void 0 || queue.flying !== void 0) return;
8489
8799
  const tailCause = {
8490
8800
  reason: "requirement",
8491
8801
  requirement: "row-unfinished"
@@ -8496,12 +8806,11 @@ function createCore(options) {
8496
8806
  };
8497
8807
  const admitted = source.admit(tailCause, tailTarget, "K3");
8498
8808
  if (!isPermit(admitted)) return;
8499
- const keys = [...tail.pending];
8500
- tail.pending.clear();
8501
- if (keys.length === 0) return;
8502
- tail.flying = keys;
8503
- const gen = tail.gen;
8504
- const token = session.childToken(() => tail.gen === gen);
8809
+ o.keyQueue = keysTaken(queue);
8810
+ const keys = o.keyQueue.flying;
8811
+ if (keys === void 0) return;
8812
+ const gen = o.keyQueue.gen;
8813
+ const token = session.childToken(() => o.keyQueue?.gen === gen);
8505
8814
  const extras = {
8506
8815
  lease: source.lease(),
8507
8816
  kind: "keys",
@@ -8545,25 +8854,23 @@ function createCore(options) {
8545
8854
  flight.lease?.release();
8546
8855
  }
8547
8856
  readKeys(read.source, o.entry, keys, { keysPerRequest: limits.keysPerRequest }).then((rows) => defects.has("settle-bypasses-pass") ? settleBypassingPass(rows) : settleTail(rows), () => settleTail(void 0)).finally(() => {
8548
- tail.flying = void 0;
8857
+ if (o.keyQueue !== void 0) o.keyQueue = flightSettled(o.keyQueue);
8549
8858
  runTail(o);
8550
8859
  });
8551
8860
  }
8861
+ function headerReadBySections(o, key) {
8862
+ const holders = [...registry.subsets()].filter((s) => s.form.object === o && s.owned.has(key));
8863
+ return holders.length > 0 && holders.every((s) => s.form.spec.kind === "section" && registry.readsByCheck(s));
8864
+ }
8552
8865
  function scheduleTail(o, keys) {
8553
- const tail = tails.get(o) ?? {
8554
- pending: /* @__PURE__ */ new Set(),
8555
- flying: void 0,
8556
- gen: 0
8557
- };
8558
- tails.set(o, tail);
8559
- for (const key of keys) tail.pending.add(key);
8866
+ o.keyQueue = keysQueued(o.keyQueue ?? createKeyQueue(), keys);
8560
8867
  runTail(o);
8561
8868
  }
8562
8869
  session.onFlush(() => {
8563
8870
  written.length = 0;
8564
8871
  const closing = closed !== void 0;
8565
8872
  for (const o of objects.values()) {
8566
- const keys = o.rows.drainTail();
8873
+ const keys = o.rows.drainTail().filter((key) => !headerReadBySections(o, key));
8567
8874
  if (keys.length > 0) scheduleTail(o, keys);
8568
8875
  }
8569
8876
  const barredNow = [...barredSections];
@@ -8606,7 +8913,7 @@ function createCore(options) {
8606
8913
  rowViews.clear();
8607
8914
  dirtySections.clear();
8608
8915
  dirtyObjects.clear();
8609
- tails.clear();
8916
+ for (const o of objects.values()) o.keyQueue = void 0;
8610
8917
  purges.clear();
8611
8918
  scheduled.clear();
8612
8919
  wave = void 0;
@@ -8615,10 +8922,7 @@ function createCore(options) {
8615
8922
  receiver?.stop();
8616
8923
  });
8617
8924
  function invalidateTail(o) {
8618
- const tail = tails.get(o);
8619
- if (tail === void 0) return;
8620
- tail.gen++;
8621
- for (const key of tail.flying ?? []) tail.pending.add(key);
8925
+ if (o.keyQueue !== void 0) o.keyQueue = flightInvalidated(o.keyQueue);
8622
8926
  }
8623
8927
  const purges = /* @__PURE__ */ new Map();
8624
8928
  const hiddenKeys = /* @__PURE__ */ new Map();
@@ -8873,10 +9177,11 @@ function createCore(options) {
8873
9177
  return due;
8874
9178
  }
8875
9179
  function rightsDueAt() {
8876
- if (!rightsEnabled || gate.tabHidden() || rightsFlying) return void 0;
8877
- if (rightsSentAt === void 0) return void 0;
9180
+ const state = services.rights.targetState;
9181
+ if (!rightsEnabled || gate.tabHidden() || inFlight$1(state)) return void 0;
9182
+ if (state.refreshedAt === void 0) return void 0;
8878
9183
  if (![...objects.values()].some((o) => o.rows.size > 0)) return void 0;
8879
- return rightsSentAt + limits.revalidateIntervalMs;
9184
+ return state.refreshedAt + limits.revalidateIntervalMs;
8880
9185
  }
8881
9186
  let lastTickAt;
8882
9187
  const scheduler = createScheduler({
@@ -8984,20 +9289,46 @@ function createCore(options) {
8984
9289
  }, token, "version");
8985
9290
  for (const object of turned) notifyStaleClient(object);
8986
9291
  }
8987
- let versionFlying = false;
8988
- let versionTail = false;
9292
+ function settleService(part, flight, outcome) {
9293
+ const target = services[part];
9294
+ settlePass(session, [{
9295
+ flight,
9296
+ outcome,
9297
+ ...outcome === "failed" ? { failure: { error: void 0 } } : {}
9298
+ }], {
9299
+ token: session.token(),
9300
+ what: `service ${part}`,
9301
+ writeless: true,
9302
+ quiet: (entry) => entry.outcome === "closed",
9303
+ gate: (entry) => entry.outcome === "discarded-by-epoch" ? "discard" : "apply",
9304
+ settleTarget: (settled, result, _evidence, failure) => {
9305
+ settleTarget(target, settled, result, failure, { readFailed: false });
9306
+ }
9307
+ });
9308
+ target.targetState = slotChanged(target.targetState, { kind: "answered" });
9309
+ }
8989
9310
  function startVersion(permit) {
8990
- versionFlying = true;
9311
+ services.version.targetState = startFlight(services.version.targetState, {
9312
+ kind: "service",
9313
+ cause: VERSION_UNCONFIRMED
9314
+ });
8991
9315
  const token = session.token();
8992
- source.read([{ type: "version" }], permit.flight()).then(() => {}, (error) => {
9316
+ const flight = permit.flight({ kind: "service" });
9317
+ source.read([{ type: "version" }], flight).then(({ items }) => {
9318
+ settleService("version", flight, items[0]?.ok === true ? "applied" : "failed");
9319
+ }, (error) => {
8993
9320
  if (token.valid) log({
8994
9321
  kind: "listener-failed",
8995
9322
  error
8996
9323
  });
9324
+ settleService("version", flight, "failed");
8997
9325
  }).finally(() => {
8998
- versionFlying = false;
8999
- if (!versionTail) return;
9000
- versionTail = false;
9326
+ const tail = services.version.targetState.trailing;
9327
+ services.version.targetState = slotChanged(services.version.targetState, {
9328
+ kind: "freed",
9329
+ alive: true
9330
+ });
9331
+ if (tail === void 0) return;
9001
9332
  core.requestVersion();
9002
9333
  });
9003
9334
  }
@@ -9008,8 +9339,11 @@ function createCore(options) {
9008
9339
  service: "rights"
9009
9340
  }, "S2");
9010
9341
  if (!isPermit(admitted)) return;
9011
- if (!rightsFlying) source.read([{ type: "rights" }], admitted.flight()).catch(() => {});
9012
- else if (!batcher.hasQueuedRights()) rightsTail ??= cause;
9342
+ if (!inFlight$1(services.rights.targetState)) source.read([{ type: "rights" }], admitted.flight({ kind: "service" })).catch(() => {});
9343
+ else if (!batcher.hasQueuedRights()) services.rights.targetState = startFlight(services.rights.targetState, {
9344
+ kind: "service",
9345
+ cause
9346
+ });
9013
9347
  }
9014
9348
  function reconcile(why, reconcileOptions = {}, snapshotViews, services = ["version", "rights"], rightsCause = RIGHTS_UNCONFIRMED) {
9015
9349
  if (services.includes("version")) core.requestVersion();
@@ -9056,16 +9390,16 @@ function createCore(options) {
9056
9390
  }, token, "writer");
9057
9391
  },
9058
9392
  requestVersion() {
9059
- const admitted = source.admit({
9060
- reason: "requirement",
9061
- requirement: "version-unconfirmed"
9062
- }, {
9393
+ const admitted = source.admit(VERSION_UNCONFIRMED, {
9063
9394
  kind: "service",
9064
9395
  service: "version"
9065
9396
  }, "S1");
9066
9397
  if (!isPermit(admitted)) return;
9067
- if (!versionFlying) startVersion(admitted);
9068
- else if (!batcher.hasQueuedVersion()) versionTail = true;
9398
+ if (!inFlight$1(services.version.targetState)) startVersion(admitted);
9399
+ else if (!batcher.hasQueuedVersion()) services.version.targetState = startFlight(services.version.targetState, {
9400
+ kind: "service",
9401
+ cause: VERSION_UNCONFIRMED
9402
+ });
9069
9403
  },
9070
9404
  requestRights: () => requestRightsFor(RIGHTS_UNCONFIRMED),
9071
9405
  rights: () => rights,
@@ -9193,7 +9527,6 @@ function createCore(options) {
9193
9527
  log,
9194
9528
  defects
9195
9529
  });
9196
- const TAB_GATED = /* @__PURE__ */ new Set(["channel-rejoin"]);
9197
9530
  const VISIBILITY_GATED = /* @__PURE__ */ new Set(["channel-rejoin", "hydration-trust"]);
9198
9531
  const causeOf = (why) => {
9199
9532
  const { site, ...cause } = why;
@@ -9253,7 +9586,8 @@ function createCore(options) {
9253
9586
  epoch: hydrationEpoch
9254
9587
  });
9255
9588
  if (narrowing.has(s) || beforeFirstViews.has(s)) requirements.push({ kind: "access-narrowed" });
9256
- if (registry.behindHeader(s)) requirements.push({ kind: "target-behind-header" });
9589
+ if (requirementOf(state, "target-behind-header") !== void 0) requirements.push({ kind: "target-behind-header" });
9590
+ if (requirementOf(state, "owner-header") !== void 0) requirements.push({ kind: "owner-header" });
9257
9591
  const flights = [];
9258
9592
  if (state.flight !== void 0 && state.retryAt === void 0) flights.push({
9259
9593
  kind: "load",
@@ -9281,7 +9615,7 @@ function createCore(options) {
9281
9615
  const conditionOf = (r) => {
9282
9616
  if (r.kind === "composition-unconfirmed") return hold === "absent" ? void 0 : gate.tabHidden() ? "tab-hidden" : hold;
9283
9617
  if (r.kind === "hydration-trust" && hydration === "hydrated") return "hydrating";
9284
- if (gate.tabHidden() && (TAB_GATED.has(r.kind) || inRetry)) return "tab-hidden";
9618
+ if (gate.tabHidden() && (HIDDEN_TAB[r.kind] === "defer" || inRetry)) return "tab-hidden";
9285
9619
  if (!readable && VISIBILITY_GATED.has(r.kind)) return "target-invisible";
9286
9620
  if (promised([r], flights, queued)) return "promised";
9287
9621
  return inRetry ? "paused" : void 0;
@@ -9305,13 +9639,13 @@ function createCore(options) {
9305
9639
  const waitingKeys = new Set((receiver?.waitingKeys() ?? []).map((w) => `${w.object}\u0000${w.key.toLowerCase()}`));
9306
9640
  const retries = new Map((receiver?.minVersionRetries() ?? []).map((r) => [`${r.object}\u0000${r.key.toLowerCase()}`, r]));
9307
9641
  for (const o of objects.values()) {
9308
- const tail = tails.get(o);
9309
- const flying = new Set(tail?.flying ?? []);
9642
+ const queue = o.keyQueue;
9643
+ const flying = new Set(queue?.flying ?? []);
9310
9644
  const holders = [...registry.subsets()].filter((s) => s.alive && !s.purged && s.form.object === o);
9311
9645
  for (const key of o.rows.keys()) {
9312
9646
  const e = o.rows.get(key);
9313
9647
  const retry = retries.get(`${o.name}\u0000${key.toLowerCase()}`);
9314
- const inTail = tail?.pending.has(key) === true || flying.has(key);
9648
+ const inTail = isKeyQueued(queue, key);
9315
9649
  const requirements = [];
9316
9650
  const { minVersion, hidden, epoch } = e.stale;
9317
9651
  if (minVersion !== void 0) requirements.push({
@@ -9329,7 +9663,7 @@ function createCore(options) {
9329
9663
  if (requirements.length === 0) continue;
9330
9664
  const tabGated = (r) => r.kind === "version-epoch-switched" || r.kind === "min-version" && retry !== void 0;
9331
9665
  const flights = flying.has(key) ? [{ kind: "keys" }] : [];
9332
- const queued = tail?.pending.has(key) === true ? [{
9666
+ const queued = queue?.pending.includes(key) === true ? [{
9333
9667
  kind: "keys",
9334
9668
  cause: {
9335
9669
  reason: "requirement",
@@ -9352,9 +9686,10 @@ function createCore(options) {
9352
9686
  }
9353
9687
  }
9354
9688
  {
9355
- const requirements = versionTail ? [{ kind: "version-unconfirmed" }] : [];
9356
- const flights = versionFlying ? [{ kind: "service" }] : [];
9357
- const queued = versionTail ? [{ kind: "service" }] : [];
9689
+ const state = services.version.targetState;
9690
+ const requirements = state.trailing === void 0 ? [] : [{ kind: "version-unconfirmed" }];
9691
+ const flights = inFlight$1(state) ? [{ kind: "service" }] : [];
9692
+ const queued = state.trailing === void 0 ? [] : [{ kind: "service" }];
9358
9693
  record({
9359
9694
  target: {
9360
9695
  kind: "service",
@@ -9368,13 +9703,14 @@ function createCore(options) {
9368
9703
  if (rightsEnabled) {
9369
9704
  const requirements = [];
9370
9705
  if (rights === void 0) requirements.push({ kind: "rights-unconfirmed" });
9371
- const flights = rightsFlying ? [rightsSent === void 0 ? { kind: "service" } : {
9706
+ const state = services.rights.targetState;
9707
+ const flights = inFlight$1(state) ? [state.flightEpoch === void 0 ? { kind: "service" } : {
9372
9708
  kind: "service",
9373
- epoch: rightsSent.epoch
9709
+ epoch: state.flightEpoch
9374
9710
  }] : [];
9375
- const queued = rightsTail === void 0 ? [] : [{
9711
+ const queued = state.trailing === void 0 ? [] : [{
9376
9712
  kind: "service",
9377
- cause: rightsTail
9713
+ cause: state.trailing
9378
9714
  }];
9379
9715
  record(withOptional({
9380
9716
  target: {
@@ -9441,7 +9777,7 @@ function createCore(options) {
9441
9777
  ...session.epochs.sizes(),
9442
9778
  revisions: views.revisions,
9443
9779
  rowViews: views.views,
9444
- tails: [...tails.values()].reduce((n, t) => n + t.pending.size + (t.flying?.length ?? 0), 0),
9780
+ tails: [...objects.values()].reduce((n, o) => n + queuedKeyCount(o.keyQueue), 0),
9445
9781
  purges: purges.size,
9446
9782
  releaseTimers: subs.filter((s) => s.releaseTimer !== void 0).length,
9447
9783
  preloadTimers: subs.reduce((n, s) => n + s.preloadTimers.size, 0),