simetra 0.3.0-next.1 → 0.3.0-next.11

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: {
@@ -4048,7 +4139,7 @@ const FLIGHT_KIND_RULES = {
4048
4139
  ],
4049
4140
  confirms: "view-with-composition",
4050
4141
  successMovesDeadline: true,
4051
- failureCounts: "if-loaded",
4142
+ failureCounts: "always",
4052
4143
  liftsBanners: true,
4053
4144
  setsBanners: false,
4054
4145
  discarded: "pause-then-retry"
@@ -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
  };
@@ -4441,7 +4555,7 @@ function settleFlight(state, input) {
4441
4555
  failures: 0,
4442
4556
  failedAt: void 0
4443
4557
  };
4444
- if (input.outcome === "failed" && input.applyFailed !== true && (rules.failureCounts === "always" || rules.failureCounts === "if-loaded" && input.loaded)) next = {
4558
+ if (input.outcome === "failed" && input.applyFailed !== true && rules.failureCounts === "always") next = {
4445
4559
  ...next,
4446
4560
  failures: next.failures + 1,
4447
4561
  failedAt: input.startedAt
@@ -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,43 @@ 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 counts = (applied) => applied ? rules.successMovesDeadline : context.readFailed && rules.failureCounts === "always";
5442
+ const sentAt = "part" in s && s.part === "rights" ? s.targetState.refreshedAt : void 0;
5293
5443
  const settle = (applied) => ({
5294
5444
  outcome: applied ? "applied" : "failed",
5295
5445
  flight: required(flight.kind, "its kind"),
5296
5446
  evidence: applied ? {
5297
- kind: "session-start",
5447
+ kind: flight.kind === "service" ? "service-sent" : "session-start",
5298
5448
  epoch: required(flight.epoch, "its start epoch")
5299
5449
  } : void 0,
5300
5450
  own: true,
5301
- startedAt: counts(applied) ? required(flight.startedAt, "its start time") : flight.startedAt ?? 0,
5302
- loaded: s.loaded,
5451
+ epoch: required(flight.epoch, "its start epoch"),
5452
+ ...flight.kind === "load" && s.targetState.flightRevision !== void 0 ? { headerRevision: s.targetState.flightRevision } : {},
5453
+ startedAt: sentAt ?? (counts(applied) ? required(flight.startedAt, "its start time") : flight.startedAt ?? 0),
5303
5454
  applyFailed: !context.readFailed,
5304
- ...context.report?.sectionRead === void 0 ? {} : { sectionRead: context.report.sectionRead }
5455
+ ...context.report?.sectionRead === void 0 ? {} : { sectionRead: context.report.sectionRead },
5456
+ ...context.report?.carriedHeader === true ? { carriedHeader: true } : {}
5305
5457
  });
5458
+ if ("part" in s) {
5459
+ if (outcome === "applied" || outcome === "failed") s.targetState = settleFlight(s.targetState, settle(outcome === "applied"));
5460
+ return false;
5461
+ }
5306
5462
  if (outcome === "applied") {
5307
5463
  if (rules.successMovesDeadline && rules.confirms === "view-with-composition") s.loaded = true;
5308
5464
  s.targetState = settleFlight(s.targetState, settle(true));
5465
+ for (const { target, complete } of context.covered ?? []) target.targetState = settleFlight(target.targetState, {
5466
+ ...settle(true),
5467
+ own: false,
5468
+ coversHeader: true,
5469
+ complete
5470
+ });
5309
5471
  if (rules.confirms === "view-with-composition" || s.status === "error") {
5310
5472
  s.status = "ready";
5311
5473
  s.error = void 0;
@@ -5323,6 +5485,10 @@ function settleTarget(s, flight, outcome, failure, context) {
5323
5485
  s.status = "error";
5324
5486
  s.error = errorOf(failure.error);
5325
5487
  }
5488
+ if (outcome === "discarded-by-epoch") s.targetState = settleFlight(s.targetState, {
5489
+ ...settle(false),
5490
+ outcome: "discarded-by-epoch"
5491
+ });
5326
5492
  return false;
5327
5493
  }
5328
5494
  const CHECK_ON_MOUNT = {
@@ -5411,7 +5577,8 @@ function createRegistry(ctx) {
5411
5577
  const again = settleTarget(s, f, outcome, failure, {
5412
5578
  readFailed: entry.failure !== void 0,
5413
5579
  tabHidden: ctx.tabHidden,
5414
- ...entry.report === void 0 ? {} : { report: entry.report }
5580
+ ...entry.report === void 0 ? {} : { report: entry.report },
5581
+ ...outcome === "applied" ? { covered: coveredBy(s) } : {}
5415
5582
  });
5416
5583
  if (outcome === "applied") verdict.again = again;
5417
5584
  },
@@ -5481,7 +5648,6 @@ function createRegistry(ctx) {
5481
5648
  cause: why,
5482
5649
  epoch: readEpoch,
5483
5650
  retry: true,
5484
- proofAtStart: true,
5485
5651
  ...header === void 0 ? {} : { headerRevision: rowViews.revision(s.form.object.name, header) }
5486
5652
  });
5487
5653
  const verdict = {
@@ -5728,11 +5894,10 @@ function createRegistry(ctx) {
5728
5894
  * been one) came after the start of its last read: the read cannot have
5729
5895
  * seen it, so the re-read is not a repeat of a discarded answer.
5730
5896
  */
5731
- function hiddenSinceRead(s) {
5897
+ function hiddenSinceRead(s, start = s.targetState.readStart ?? -1) {
5732
5898
  const spec = s.form.spec;
5733
5899
  if (spec.kind !== "section") return false;
5734
5900
  const o = s.form.object;
5735
- const start = s.targetState.readStart ?? -1;
5736
5901
  return hiddenAfter(o, spec.owner, start) || session.epochs.evictedSince(keyId(o.name, spec.owner), start);
5737
5902
  }
5738
5903
  /**
@@ -5752,19 +5917,103 @@ function createRegistry(ctx) {
5752
5917
  });
5753
5918
  return;
5754
5919
  }
5755
- if (behindHeader(s)) load(s, why);
5920
+ placeBehindHeader(s);
5921
+ placeOwnerHeader(s);
5922
+ if (readsBehindHeader(s)) load(s, why);
5923
+ else if (readsOwnerHeader(s)) load(s, why.reason === "requirement" ? {
5924
+ ...why,
5925
+ requirement: "owner-header"
5926
+ } : why);
5756
5927
  }
5757
5928
  /**
5758
- * Картка чи ТЧ відстала від шапки (вимога «ціль відстала від шапки»): одне
5759
- * означення для перевірки й для діагностики `sync()`.
5929
+ * Картка чи ТЧ відстала від шапки — умова постановки вимоги «ціль відстала
5930
+ * від шапки» (рядок 20, Р-SK3-11): ціль неповна за `cardStale`/`sectionStale`,
5931
+ * а шапка змінилась (ревізія), чи `hide` власника новіший за застосоване
5932
+ * завантаження. Дешеві перевірки — першими: умова питається на кожен `commit`.
5760
5933
  */
5761
- function behindHeader(s) {
5934
+ function headerChanged(s) {
5762
5935
  const header = headerKey(s);
5763
5936
  if (header === void 0) return false;
5764
- if (!(s.form.spec.kind === "card" ? cardStale(s) : sectionStale(s))) return false;
5765
5937
  return rowViews.revision(s.form.object.name, header) !== s.targetState.readRevision || hiddenSinceRead(s);
5766
5938
  }
5767
5939
  /**
5940
+ * Ставить вимогу «ціль відстала від шапки» (збережена, знімає її лише
5941
+ * осідання з доказом). Стоячу вимогу не зсуває: читання, що вже летить зі
5942
+ * стартом після неї, її знімає, а нова зміна шапки після його старту ставить
5943
+ * вимогу наново (доказ шапки — ревізія на старті, див. `headerChanged`).
5944
+ */
5945
+ function placeBehindHeader(s) {
5946
+ if (!s.alive || s.purged || headerKey(s) === void 0) return;
5947
+ if (requirementOf(s.targetState, "target-behind-header") !== void 0) return;
5948
+ if (!headerChanged(s)) return;
5949
+ if (!(s.form.spec.kind === "card" ? cardStale(s) : sectionStale(s))) return;
5950
+ s.targetState = addRequirement(s.targetState, {
5951
+ kind: "target-behind-header",
5952
+ since: session.epochs.now(),
5953
+ barrier: false,
5954
+ tried: void 0
5955
+ });
5956
+ }
5957
+ /**
5958
+ * Стоїть вимога шапки, і її є що читати: спроби ще не було, або шапка (ревізія
5959
+ * чи `hide` власника) змінилась після старту спроби, що збилась. Власний `commit` збою чи відкинутого
5960
+ * завантаження повтору не дає (ревізія та сама), як на `main`.
5961
+ */
5962
+ function readsBehindHeader(s) {
5963
+ const stands = requirementOf(s.targetState, "target-behind-header");
5964
+ if (stands === void 0) return false;
5965
+ const header = headerKey(s);
5966
+ return stands.tried === void 0 || header !== void 0 && rowViews.revision(s.form.object.name, header) !== stands.tried.revision || hiddenSinceRead(s, stands.tried.start);
5967
+ }
5968
+ /**
5969
+ * Ставить вимогу «шапка власника» (рядок 22, Р-SK3-12): власник ТЧ `removed`
5970
+ * позначкою, яку не покриває доказ запису цілі. Позначку покриває читання ТЧ
5971
+ * з шапкою, що стартувало не раніше читання, яке її поставило (власна
5972
+ * позначка завантаження покрита ним самим); `since` — епоха позначки, тож
5973
+ * доказ — читання після неї. Повторна позначка того самого ідентифікатора
5974
+ * зсуває лише `since`.
5975
+ */
5976
+ function placeOwnerHeader(s) {
5977
+ const spec = s.form.spec;
5978
+ if (!s.alive || s.purged || spec.kind !== "section") return;
5979
+ const mark = s.form.object.rows.get(spec.owner)?.removed;
5980
+ if (mark === void 0) return;
5981
+ const proved = s.targetState.ownerHeaderRead;
5982
+ if (proved !== void 0 && proved >= mark.proof) return;
5983
+ const stands = requirementOf(s.targetState, "owner-header");
5984
+ if (stands !== void 0 && stands.mark === mark.id && stands.since >= mark.epoch) return;
5985
+ s.targetState = addRequirement(s.targetState, {
5986
+ kind: "owner-header",
5987
+ since: mark.epoch,
5988
+ mark: mark.id,
5989
+ tried: void 0
5990
+ });
5991
+ }
5992
+ /**
5993
+ * Вимога шапки власника стоїть, і її є що читати: спроби ще не було, або
5994
+ * позначка повторена після старту спроби, що збилась. Власний `commit` збою
5995
+ * чи відкинутого завантаження повтору не дає.
5996
+ */
5997
+ function readsOwnerHeader(s) {
5998
+ const stands = requirementOf(s.targetState, "owner-header");
5999
+ return stands !== void 0 && (stands.tried === void 0 || stands.since > stands.tried);
6000
+ }
6001
+ /** Див. `SubsetRegistry.covered`. */
6002
+ function coveredBy(by) {
6003
+ const found = [];
6004
+ for (const t of subsets.values()) {
6005
+ if (t === by || !t.alive || t.purged || t.form.object !== by.form.object) continue;
6006
+ const header = headerKey(t);
6007
+ if (header === void 0 || !by.owned.has(header)) continue;
6008
+ if (requirementOf(t.targetState, "target-behind-header") === void 0) continue;
6009
+ found.push({
6010
+ target: t,
6011
+ complete: !(t.form.spec.kind === "card" ? cardStale(t) : sectionStale(t))
6012
+ });
6013
+ }
6014
+ return found;
6015
+ }
6016
+ /**
5768
6017
  * The first hold starts the subset; a card with a stored row shows it
5769
6018
  * without a read. A held subset is checked on mount, and a section on
5770
6019
  * `preload` too: a stale section (`sectionStale`) is re-read once observed.
@@ -6077,7 +6326,6 @@ function createRegistry(ctx) {
6077
6326
  };
6078
6327
  }
6079
6328
  return {
6080
- behindHeader: (s) => s.alive && !s.purged && behindHeader(s),
6081
6329
  view(spec) {
6082
6330
  if (isClosed()) return closedHandle();
6083
6331
  const form = formOf(ctx, spec);
@@ -6125,7 +6373,11 @@ function createRegistry(ctx) {
6125
6373
  const s = acquire(form);
6126
6374
  const o = form.object;
6127
6375
  const spec = form.spec;
6128
- s.owned = diffOwn(ops, scope, o, /* @__PURE__ */ new Set(), [...state.layout, ...state.unshown]);
6376
+ s.owned = diffOwn(ops, scope, o, /* @__PURE__ */ new Set(), [
6377
+ ...state.layout,
6378
+ ...state.unshown,
6379
+ ...spec.kind === "section" ? [spec.owner] : []
6380
+ ]);
6129
6381
  if (spec.kind !== "card" && spec.kind !== "section") {
6130
6382
  s.layout = state.layout.filter((key) => s.owned.has(key));
6131
6383
  s.layoutSet = new Set(s.layout);
@@ -6165,9 +6417,19 @@ function createRegistry(ctx) {
6165
6417
  if (idle(s)) scheduleRelease(s);
6166
6418
  }
6167
6419
  },
6420
+ covered: coveredBy,
6421
+ readsByCheck(s) {
6422
+ if (!s.alive || s.purged || s.listeners.size === 0) return false;
6423
+ if (s.targetState.flight !== void 0) return false;
6424
+ placeBehindHeader(s);
6425
+ placeOwnerHeader(s);
6426
+ return readsBehindHeader(s) || readsOwnerHeader(s);
6427
+ },
6168
6428
  afterCommit(closing) {
6169
6429
  const notify = [];
6170
6430
  for (const s of subsets.values()) {
6431
+ placeBehindHeader(s);
6432
+ placeOwnerHeader(s);
6171
6433
  if (!closing && snapshotFresh(s) && !affected(s)) continue;
6172
6434
  if (snapshotFresh(s)) s.targetState = derivedInputChanged(s.targetState, "affected");
6173
6435
  if (s.listeners.size === 0) continue;
@@ -6480,9 +6742,13 @@ function applyKeys(ctx, s, requested, rows, startEpoch, marksNew) {
6480
6742
  let fresh = false;
6481
6743
  for (const row of rows) {
6482
6744
  got.add(row.key);
6483
- if (s.owned.has(row.key)) ctx.ops.put(scope, o, row, startEpoch, false);
6745
+ if (s.owned.has(row.key) || ownsDeclaredKeys(s) && s.form.keys.includes(row.key)) ctx.ops.put(scope, o, row, startEpoch, false);
6484
6746
  else if (!lostSince(ctx, o, row, startEpoch)) fresh = true;
6485
6747
  }
6748
+ if (ownsDeclaredKeys(s)) {
6749
+ const brought = rows.map((r) => r.key).filter((k) => s.form.keys.includes(k) && !s.owned.has(k));
6750
+ if (brought.length > 0) ownDeclaredKeys(ctx.ops, scope, s, [...s.owned, ...brought]);
6751
+ }
6486
6752
  for (const key of requested) if (!got.has(key) && s.owned.has(key)) ctx.ops.remove(scope, o, key, startEpoch);
6487
6753
  if (fresh && marksNew) s.hasNewRows = true;
6488
6754
  if (s.form.spec.kind === "keys") rebuildLayout(ctx, s);
@@ -6767,6 +7033,23 @@ function eligible(ctx, s, options) {
6767
7033
  return s.alive && !s.purged && s.loaded && (!options.visibleOnly || isVisible(s) || options.alsoViews?.has(s) === true) && (minAgeMs === void 0 || ctx.defects.has("min-age-ignored") || ctx.defects.has("min-age-ignored-sections") && s.form.spec.kind === "section" || (s.targetState.refreshedAt !== void 0 && ctx.defects.has("min-age-all-young") ? false : ctx.now() >= dueOf(ctx, s, minAgeMs))) && (s.form.spec.kind !== "section" || s.listeners.size > 0 || options.alsoViews?.has(s) === true);
6768
7034
  }
6769
7035
  /**
7036
+ * A view whose first load failed and stands idle (row 18): no row, so it is
7037
+ * not {@link eligible} for `revalidate` — its read is a load, not a re-read.
7038
+ * The failure pause (`viewDue`) is its only due time.
7039
+ */
7040
+ const failedFirstLoad = (s) => s.alive && !s.purged && !s.loaded && s.status === "error" && s.targetState.failures > 0 && s.targetState.flight === void 0;
7041
+ /**
7042
+ * The failed first loads whose pause ended: the tick loads them again
7043
+ * without a user action (row 18). The gate judges the read itself (M7).
7044
+ */
7045
+ function dueFirstLoads(ctx, object) {
7046
+ return [...ctx.registry.subsets()].filter((s) => {
7047
+ if (s.form.object.name !== object || !failedFirstLoad(s)) return false;
7048
+ const at = viewDue(ctx, s);
7049
+ return at !== void 0 && ctx.now() >= at;
7050
+ });
7051
+ }
7052
+ /**
6770
7053
  * The earliest due time of the object's views the interval tick would read
6771
7054
  * (P4-B spec §6.7): visible, loaded, not in flight, not out of the discard
6772
7055
  * limit — the same filter `revalidate` applies with `minAgeMs`, so the timer
@@ -6785,6 +7068,7 @@ function nextViewDue(ctx, object) {
6785
7068
  * reads it then); `undefined` — the tick does not read it.
6786
7069
  */
6787
7070
  function viewDue(ctx, s) {
7071
+ if (failedFirstLoad(s)) return isVisible(s) && !unavailable(s) ? dueOf(ctx, s) : void 0;
6788
7072
  if (!eligible(ctx, s, { visibleOnly: true })) return void 0;
6789
7073
  if (inFlight(s) || unavailable(s) && !ctx.defects.has("scheduler-reads-unavailable")) return void 0;
6790
7074
  const at = dueOf(ctx, s);
@@ -6863,14 +7147,15 @@ async function revalidateHydrated(ctx, s, why) {
6863
7147
  * row or an `include` target, invisible views included: the
6864
7148
  * values return only with a read that started after the `hide`. A failed
6865
7149
  * 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.
7150
+ * object is re-read as its own object's view. A tabular section holds the
7151
+ * header of its owner (row 22), so it is re-read here like any holder, unless
7152
+ * the check of the view already reads it for a requirement.
6868
7153
  */
6869
7154
  async function revalidateHolders(ctx, object, keys, why) {
6870
7155
  const groups = /* @__PURE__ */ new Map();
6871
7156
  for (const s of ctx.registry.subsets()) {
6872
7157
  if (!s.alive || s.purged || !s.loaded) continue;
6873
- if (s.form.spec.kind === "section") continue;
7158
+ if (s.form.spec.kind === "section" && ctx.registry.readsByCheck(s)) continue;
6874
7159
  const included = s.included.get(object);
6875
7160
  if (!(s.form.object.name === object && [...keys].some((k) => s.owned.has(k)) || included !== void 0 && [...keys].some((k) => included.has(k)))) continue;
6876
7161
  const read = admitViews(ctx, [s], why);
@@ -7012,7 +7297,8 @@ async function revalidateViews(ctx, o, reads) {
7012
7297
  const entry = entryOf.get(flight);
7013
7298
  const again = settleTarget(entry.s, flight, outcome, failure, {
7014
7299
  readFailed: entry.failure !== void 0,
7015
- ...entry.report === void 0 ? {} : { report: entry.report }
7300
+ ...entry.report === void 0 ? {} : { report: entry.report },
7301
+ ...outcome === "applied" ? { covered: ctx.registry.covered(entry.s) } : {}
7016
7302
  });
7017
7303
  if (outcome === "applied" && again) entry.verdict.again = repeatOf(flight, "R18");
7018
7304
  },
@@ -7070,7 +7356,6 @@ async function rereadKey(ctx, object, key, options) {
7070
7356
  }, "K4");
7071
7357
  if (!isPermit(admitted)) return;
7072
7358
  const o = ctx.objectOf(object);
7073
- const token = session.token();
7074
7359
  const limit = new AbortController();
7075
7360
  const requester = (outcome, scope) => {
7076
7361
  if (outcome.kind !== "read" && unconfirmed !== void 0) {
@@ -7083,6 +7368,7 @@ async function rereadKey(ctx, object, key, options) {
7083
7368
  const flight = admitted.flight({
7084
7369
  lease,
7085
7370
  kind: "keys",
7371
+ token: session.token(),
7086
7372
  requester,
7087
7373
  deadlineMs: REREAD_TIMEOUT_MS,
7088
7374
  done: { fired: false }
@@ -7095,6 +7381,7 @@ async function rereadKey(ctx, object, key, options) {
7095
7381
  required(flight.requester, "its requester")(outcome, scope);
7096
7382
  };
7097
7383
  session.sleep(required(flight.deadlineMs, "its deadline"), limit.signal).then(() => {
7384
+ const token = required(flight.token, "its token");
7098
7385
  if (required(flight.done, "its reply mark").fired || !token.valid) return;
7099
7386
  session.commit((scope) => reply({ kind: "failed" }, scope), token, "reread timeout");
7100
7387
  });
@@ -7110,9 +7397,9 @@ async function rereadKey(ctx, object, key, options) {
7110
7397
  flight,
7111
7398
  ...rows === void 0 ? { failure: { error: void 0 } } : {}
7112
7399
  }], {
7113
- token,
7400
+ token: required(flight.token, "its token"),
7114
7401
  what: `reread ${o.name}`,
7115
- quiet: () => !token.valid,
7402
+ quiet: () => !required(flight.token, "its token").valid,
7116
7403
  gate: () => {
7117
7404
  const epochs = new Set(read.epochs);
7118
7405
  for (const row of required(rows, "its answer")) epochs.add(row.versionEpoch ?? null);
@@ -7763,9 +8050,10 @@ function createReceiver(ctx) {
7763
8050
  token,
7764
8051
  what: "writer",
7765
8052
  quiet: () => stopped,
7766
- readFailed: ({ flight, job: { object } }, scope) => {
7767
- if (rulesOf(flight).keysFailure === "composition-unconfirmed") createWriter(writer, scope).markViews(object, {
7768
- needsRefresh: true,
8053
+ settleTarget: (flight, outcome, _evidence, failure) => {
8054
+ if (entry.failure === void 0 || failure === void 0 || rulesOf(flight).keysFailure !== "composition-unconfirmed") return;
8055
+ for (const s of subsetsOf(writer, entry.job.o)) settleTarget(s, flight, outcome, failure, {
8056
+ readFailed: true,
7769
8057
  unconfirmedSince: since
7770
8058
  });
7771
8059
  },
@@ -7962,6 +8250,20 @@ const RIGHTS_UNCONFIRMED = {
7962
8250
  reason: "requirement",
7963
8251
  requirement: "rights-unconfirmed"
7964
8252
  };
8253
+ const VERSION_UNCONFIRMED = {
8254
+ reason: "requirement",
8255
+ requirement: "version-unconfirmed"
8256
+ };
8257
+ /**
8258
+ * Причина читання з даних польоту: політ — це причина плюс запис шлюзу, тож
8259
+ * копії причини службова ціль не тримає.
8260
+ */
8261
+ function causeOfFlight(flight) {
8262
+ return flight.reason === "requirement" ? {
8263
+ reason: "requirement",
8264
+ requirement: flight.requirement
8265
+ } : { reason: flight.reason };
8266
+ }
7965
8267
  const HYDRATION_TRUST = {
7966
8268
  reason: "requirement",
7967
8269
  requirement: "hydration-trust",
@@ -8023,12 +8325,29 @@ function createCore(options) {
8023
8325
  now,
8024
8326
  defects
8025
8327
  });
8328
+ const services = {
8329
+ rights: {
8330
+ part: "rights",
8331
+ targetState: createTargetState()
8332
+ },
8333
+ version: {
8334
+ part: "version",
8335
+ targetState: createTargetState()
8336
+ }
8337
+ };
8026
8338
  const batcher = createBatcher(options.source, {
8027
8339
  ownFlight: gate.issued,
8028
8340
  staleObject: gate.staleObject,
8029
8341
  sleep: session.sleep,
8030
8342
  onRightsSent: () => {
8031
- rightsSentAt = now();
8343
+ const state = services.rights.targetState;
8344
+ services.rights.targetState = startFlight(state, {
8345
+ kind: "service",
8346
+ cause: state.flightCause ?? RIGHTS_UNCONFIRMED,
8347
+ retry: true,
8348
+ epoch: state.flightEpoch,
8349
+ sentAt: now()
8350
+ });
8032
8351
  },
8033
8352
  onRead: (event) => {
8034
8353
  for (const listener of [...readListeners]) try {
@@ -8038,7 +8357,10 @@ function createCore(options) {
8038
8357
  onVersion(version) {
8039
8358
  if (session.token().valid) applyVersion(version.objects);
8040
8359
  },
8041
- onRights: (item) => acceptRights(item)
8360
+ onRights: (item) => {
8361
+ const outcome = acceptRights(item);
8362
+ if (rightsFlight !== void 0) settleService("rights", rightsFlight, outcome);
8363
+ }
8042
8364
  });
8043
8365
  const pendingWrites = /* @__PURE__ */ new Map();
8044
8366
  const source = {
@@ -8143,38 +8465,42 @@ function createCore(options) {
8143
8465
  const origins = forward.map(() => flight);
8144
8466
  if (injected) {
8145
8467
  forward.unshift({ type: "rights" });
8146
- origins.unshift(rightsFirst.flight());
8468
+ origins.unshift(rightsFirst.flight({ kind: "service" }));
8147
8469
  }
8148
8470
  const rightsAt = forward.findIndex((part) => part.type === "rights");
8149
8471
  let answered = { items: [] };
8150
8472
  if (rightsAt < 0) {
8151
8473
  if (forward.length > 0) answered = await batcher.read(forward, origins);
8152
8474
  } 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" } : {
8475
+ const sentEpoch = session.epochs.next();
8476
+ const flying = origins[rightsAt];
8477
+ rightsFlight = flying;
8478
+ rightsKnown = rights?.rightsVersion;
8479
+ forward[rightsAt] = rightsKnown === void 0 ? { type: "rights" } : {
8159
8480
  type: "rights",
8160
- known: sentRights.known
8481
+ known: rightsKnown
8161
8482
  };
8162
8483
  rightsFirstSent = true;
8163
- rightsFlying = true;
8164
- rightsSent = sentRights;
8484
+ services.rights.targetState = startFlight(services.rights.targetState, {
8485
+ kind: "service",
8486
+ epoch: sentEpoch,
8487
+ cause: causeOfFlight(flying)
8488
+ });
8165
8489
  try {
8166
8490
  answered = await batcher.read(forward, origins);
8167
8491
  } catch (error) {
8168
- if (sentRights.token.valid) log({ kind: "rights-failed" });
8492
+ if (session.token().valid) log({ kind: "rights-failed" });
8493
+ if (services.rights.targetState.answerPending) settleService("rights", flying, "failed");
8169
8494
  throw error;
8170
8495
  } finally {
8171
- rightsFlying = false;
8496
+ rightsFlight = void 0;
8497
+ const tail = services.rights.targetState.trailing;
8498
+ services.rights.targetState = slotChanged(services.rights.targetState, {
8499
+ kind: "freed",
8500
+ alive: true
8501
+ });
8172
8502
  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
- }
8503
+ if (tail !== void 0) requestRightsFor(tail);
8178
8504
  }
8179
8505
  if (injected) answered = { items: answered.items.slice(1) };
8180
8506
  }
@@ -8190,10 +8516,8 @@ function createCore(options) {
8190
8516
  const rightsEnabled = options.rightsSnapshot === true;
8191
8517
  let rights;
8192
8518
  let rightsFirstSent = false;
8193
- let rightsFlying = false;
8194
- let rightsTail;
8195
- let rightsSentAt;
8196
- let rightsSent;
8519
+ let rightsKnown;
8520
+ let rightsFlight;
8197
8521
  let firstRights;
8198
8522
  const beforeFirst = {
8199
8523
  views: /* @__PURE__ */ new Set(),
@@ -8260,34 +8584,34 @@ function createCore(options) {
8260
8584
  if (session.token().valid) core.close("session-changed");
8261
8585
  }
8262
8586
  function acceptRights(item) {
8263
- const sentRights = rightsSent;
8264
- if (sentRights === void 0 || !sentRights.token.valid) return;
8587
+ const sentEpoch = services.rights.targetState.flightEpoch;
8588
+ if (sentEpoch === void 0 || !session.token().valid) return "closed";
8265
8589
  if (!item.ok || !("type" in item) || item.type !== "rights") {
8266
8590
  log({ kind: "rights-failed" });
8267
- return;
8591
+ return "failed";
8268
8592
  }
8269
8593
  const { rightsVersion, snapshot } = item.value;
8270
8594
  const current = rights;
8271
8595
  if (snapshot === void 0) {
8272
- if (current === void 0 || sentRights.known !== current.rightsVersion || rightsVersion !== current.rightsVersion) {
8596
+ if (current === void 0 || rightsKnown !== current.rightsVersion || rightsVersion !== current.rightsVersion) {
8273
8597
  log({ kind: "rights-failed" });
8274
- return;
8598
+ return "failed";
8275
8599
  }
8276
8600
  rights = {
8277
8601
  ...current,
8278
8602
  rightsVersion
8279
8603
  };
8280
- return;
8604
+ return "applied";
8281
8605
  }
8282
8606
  if (current !== void 0 && current.snapshot.userId !== null && snapshot.userId !== null && current.snapshot.userId !== snapshot.userId) {
8283
8607
  rightsSessionChanged();
8284
- return;
8608
+ return "closed";
8285
8609
  }
8286
- if (current !== void 0 && sentRights.epoch <= current.rightsEpoch) return;
8610
+ if (current !== void 0 && sentEpoch <= current.rightsEpoch) return "discarded-by-epoch";
8287
8611
  const next = {
8288
8612
  snapshot,
8289
8613
  rightsVersion,
8290
- rightsEpoch: sentRights.epoch,
8614
+ rightsEpoch: sentEpoch,
8291
8615
  appliedEpoch: session.epochs.next()
8292
8616
  };
8293
8617
  rights = next;
@@ -8302,6 +8626,7 @@ function createCore(options) {
8302
8626
  });
8303
8627
  }
8304
8628
  receiver?.snapshotReplaced();
8629
+ return "applied";
8305
8630
  }
8306
8631
  function replaceRights(prev, next, item) {
8307
8632
  rightsPassListener?.();
@@ -8369,7 +8694,8 @@ function createCore(options) {
8369
8694
  object: name,
8370
8695
  session,
8371
8696
  rows
8372
- })
8697
+ }),
8698
+ keyQueue: void 0
8373
8699
  });
8374
8700
  }
8375
8701
  const objectOf = (name) => {
@@ -8414,8 +8740,9 @@ function createCore(options) {
8414
8740
  },
8415
8741
  own: (scope, o, key) => o.rows.own(scope, key),
8416
8742
  disown(scope, o, key) {
8743
+ const before = o.rows.get(key);
8417
8744
  o.rows.disown(scope, key);
8418
- rowViews.touch(o.name, key);
8745
+ if (before !== void 0 && o.rows.get(key) !== before) rowViews.touch(o.name, key);
8419
8746
  },
8420
8747
  putSection(scope, o, owner, section, lines, ownerVersion, versionEpoch, readEpoch, ownerScope) {
8421
8748
  if (staleObjects.has(o.name)) return void 0;
@@ -8482,10 +8809,9 @@ function createCore(options) {
8482
8809
  let hydration = "none";
8483
8810
  let visible = options.visible ?? true;
8484
8811
  let lastResumeAt;
8485
- const tails = /* @__PURE__ */ new Map();
8486
8812
  function runTail(o) {
8487
- const tail = tails.get(o);
8488
- if (tail === void 0 || tail.flying !== void 0) return;
8813
+ const queue = o.keyQueue;
8814
+ if (queue === void 0 || queue.flying !== void 0) return;
8489
8815
  const tailCause = {
8490
8816
  reason: "requirement",
8491
8817
  requirement: "row-unfinished"
@@ -8496,12 +8822,11 @@ function createCore(options) {
8496
8822
  };
8497
8823
  const admitted = source.admit(tailCause, tailTarget, "K3");
8498
8824
  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);
8825
+ o.keyQueue = keysTaken(queue);
8826
+ const keys = o.keyQueue.flying;
8827
+ if (keys === void 0) return;
8828
+ const gen = o.keyQueue.gen;
8829
+ const token = session.childToken(() => o.keyQueue?.gen === gen);
8505
8830
  const extras = {
8506
8831
  lease: source.lease(),
8507
8832
  kind: "keys",
@@ -8545,25 +8870,23 @@ function createCore(options) {
8545
8870
  flight.lease?.release();
8546
8871
  }
8547
8872
  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;
8873
+ if (o.keyQueue !== void 0) o.keyQueue = flightSettled(o.keyQueue);
8549
8874
  runTail(o);
8550
8875
  });
8551
8876
  }
8877
+ function headerReadBySections(o, key) {
8878
+ const holders = [...registry.subsets()].filter((s) => s.form.object === o && s.owned.has(key));
8879
+ return holders.length > 0 && holders.every((s) => s.form.spec.kind === "section" && registry.readsByCheck(s));
8880
+ }
8552
8881
  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);
8882
+ o.keyQueue = keysQueued(o.keyQueue ?? createKeyQueue(), keys);
8560
8883
  runTail(o);
8561
8884
  }
8562
8885
  session.onFlush(() => {
8563
8886
  written.length = 0;
8564
8887
  const closing = closed !== void 0;
8565
8888
  for (const o of objects.values()) {
8566
- const keys = o.rows.drainTail();
8889
+ const keys = o.rows.drainTail().filter((key) => !headerReadBySections(o, key));
8567
8890
  if (keys.length > 0) scheduleTail(o, keys);
8568
8891
  }
8569
8892
  const barredNow = [...barredSections];
@@ -8606,7 +8929,7 @@ function createCore(options) {
8606
8929
  rowViews.clear();
8607
8930
  dirtySections.clear();
8608
8931
  dirtyObjects.clear();
8609
- tails.clear();
8932
+ for (const o of objects.values()) o.keyQueue = void 0;
8610
8933
  purges.clear();
8611
8934
  scheduled.clear();
8612
8935
  wave = void 0;
@@ -8615,10 +8938,7 @@ function createCore(options) {
8615
8938
  receiver?.stop();
8616
8939
  });
8617
8940
  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);
8941
+ if (o.keyQueue !== void 0) o.keyQueue = flightInvalidated(o.keyQueue);
8622
8942
  }
8623
8943
  const purges = /* @__PURE__ */ new Map();
8624
8944
  const hiddenKeys = /* @__PURE__ */ new Map();
@@ -8873,10 +9193,11 @@ function createCore(options) {
8873
9193
  return due;
8874
9194
  }
8875
9195
  function rightsDueAt() {
8876
- if (!rightsEnabled || gate.tabHidden() || rightsFlying) return void 0;
8877
- if (rightsSentAt === void 0) return void 0;
9196
+ const state = services.rights.targetState;
9197
+ if (!rightsEnabled || gate.tabHidden() || inFlight$1(state)) return void 0;
9198
+ if (state.refreshedAt === void 0) return void 0;
8878
9199
  if (![...objects.values()].some((o) => o.rows.size > 0)) return void 0;
8879
- return rightsSentAt + limits.revalidateIntervalMs;
9200
+ return state.refreshedAt + limits.revalidateIntervalMs;
8880
9201
  }
8881
9202
  let lastTickAt;
8882
9203
  const scheduler = createScheduler({
@@ -8891,7 +9212,14 @@ function createCore(options) {
8891
9212
  }
8892
9213
  const minAgeMs = .9 * limits.revalidateIntervalMs;
8893
9214
  let read = false;
8894
- for (const o of objects.values()) if (!gate.staleObject(o.name) && hasDueViews(writerContext, o.name, minAgeMs)) read = true;
9215
+ for (const o of objects.values()) {
9216
+ if (gate.staleObject(o.name)) continue;
9217
+ if (hasDueViews(writerContext, o.name, minAgeMs)) read = true;
9218
+ for (const s of dueFirstLoads(writerContext, o.name)) registry.load(s, {
9219
+ reason: "retry",
9220
+ site: "M7"
9221
+ });
9222
+ }
8895
9223
  if (runDue()) read = true;
8896
9224
  if (wave !== void 0 && wave.at <= now()) fireWave();
8897
9225
  receiver?.tick();
@@ -8984,20 +9312,46 @@ function createCore(options) {
8984
9312
  }, token, "version");
8985
9313
  for (const object of turned) notifyStaleClient(object);
8986
9314
  }
8987
- let versionFlying = false;
8988
- let versionTail = false;
9315
+ function settleService(part, flight, outcome) {
9316
+ const target = services[part];
9317
+ settlePass(session, [{
9318
+ flight,
9319
+ outcome,
9320
+ ...outcome === "failed" ? { failure: { error: void 0 } } : {}
9321
+ }], {
9322
+ token: session.token(),
9323
+ what: `service ${part}`,
9324
+ writeless: true,
9325
+ quiet: (entry) => entry.outcome === "closed",
9326
+ gate: (entry) => entry.outcome === "discarded-by-epoch" ? "discard" : "apply",
9327
+ settleTarget: (settled, result, _evidence, failure) => {
9328
+ settleTarget(target, settled, result, failure, { readFailed: false });
9329
+ }
9330
+ });
9331
+ target.targetState = slotChanged(target.targetState, { kind: "answered" });
9332
+ }
8989
9333
  function startVersion(permit) {
8990
- versionFlying = true;
9334
+ services.version.targetState = startFlight(services.version.targetState, {
9335
+ kind: "service",
9336
+ cause: VERSION_UNCONFIRMED
9337
+ });
8991
9338
  const token = session.token();
8992
- source.read([{ type: "version" }], permit.flight()).then(() => {}, (error) => {
9339
+ const flight = permit.flight({ kind: "service" });
9340
+ source.read([{ type: "version" }], flight).then(({ items }) => {
9341
+ settleService("version", flight, items[0]?.ok === true ? "applied" : "failed");
9342
+ }, (error) => {
8993
9343
  if (token.valid) log({
8994
9344
  kind: "listener-failed",
8995
9345
  error
8996
9346
  });
9347
+ settleService("version", flight, "failed");
8997
9348
  }).finally(() => {
8998
- versionFlying = false;
8999
- if (!versionTail) return;
9000
- versionTail = false;
9349
+ const tail = services.version.targetState.trailing;
9350
+ services.version.targetState = slotChanged(services.version.targetState, {
9351
+ kind: "freed",
9352
+ alive: true
9353
+ });
9354
+ if (tail === void 0) return;
9001
9355
  core.requestVersion();
9002
9356
  });
9003
9357
  }
@@ -9008,8 +9362,11 @@ function createCore(options) {
9008
9362
  service: "rights"
9009
9363
  }, "S2");
9010
9364
  if (!isPermit(admitted)) return;
9011
- if (!rightsFlying) source.read([{ type: "rights" }], admitted.flight()).catch(() => {});
9012
- else if (!batcher.hasQueuedRights()) rightsTail ??= cause;
9365
+ if (!inFlight$1(services.rights.targetState)) source.read([{ type: "rights" }], admitted.flight({ kind: "service" })).catch(() => {});
9366
+ else if (!batcher.hasQueuedRights()) services.rights.targetState = startFlight(services.rights.targetState, {
9367
+ kind: "service",
9368
+ cause
9369
+ });
9013
9370
  }
9014
9371
  function reconcile(why, reconcileOptions = {}, snapshotViews, services = ["version", "rights"], rightsCause = RIGHTS_UNCONFIRMED) {
9015
9372
  if (services.includes("version")) core.requestVersion();
@@ -9056,16 +9413,16 @@ function createCore(options) {
9056
9413
  }, token, "writer");
9057
9414
  },
9058
9415
  requestVersion() {
9059
- const admitted = source.admit({
9060
- reason: "requirement",
9061
- requirement: "version-unconfirmed"
9062
- }, {
9416
+ const admitted = source.admit(VERSION_UNCONFIRMED, {
9063
9417
  kind: "service",
9064
9418
  service: "version"
9065
9419
  }, "S1");
9066
9420
  if (!isPermit(admitted)) return;
9067
- if (!versionFlying) startVersion(admitted);
9068
- else if (!batcher.hasQueuedVersion()) versionTail = true;
9421
+ if (!inFlight$1(services.version.targetState)) startVersion(admitted);
9422
+ else if (!batcher.hasQueuedVersion()) services.version.targetState = startFlight(services.version.targetState, {
9423
+ kind: "service",
9424
+ cause: VERSION_UNCONFIRMED
9425
+ });
9069
9426
  },
9070
9427
  requestRights: () => requestRightsFor(RIGHTS_UNCONFIRMED),
9071
9428
  rights: () => rights,
@@ -9193,7 +9550,6 @@ function createCore(options) {
9193
9550
  log,
9194
9551
  defects
9195
9552
  });
9196
- const TAB_GATED = /* @__PURE__ */ new Set(["channel-rejoin"]);
9197
9553
  const VISIBILITY_GATED = /* @__PURE__ */ new Set(["channel-rejoin", "hydration-trust"]);
9198
9554
  const causeOf = (why) => {
9199
9555
  const { site, ...cause } = why;
@@ -9253,7 +9609,8 @@ function createCore(options) {
9253
9609
  epoch: hydrationEpoch
9254
9610
  });
9255
9611
  if (narrowing.has(s) || beforeFirstViews.has(s)) requirements.push({ kind: "access-narrowed" });
9256
- if (registry.behindHeader(s)) requirements.push({ kind: "target-behind-header" });
9612
+ if (requirementOf(state, "target-behind-header") !== void 0) requirements.push({ kind: "target-behind-header" });
9613
+ if (requirementOf(state, "owner-header") !== void 0) requirements.push({ kind: "owner-header" });
9257
9614
  const flights = [];
9258
9615
  if (state.flight !== void 0 && state.retryAt === void 0) flights.push({
9259
9616
  kind: "load",
@@ -9281,7 +9638,7 @@ function createCore(options) {
9281
9638
  const conditionOf = (r) => {
9282
9639
  if (r.kind === "composition-unconfirmed") return hold === "absent" ? void 0 : gate.tabHidden() ? "tab-hidden" : hold;
9283
9640
  if (r.kind === "hydration-trust" && hydration === "hydrated") return "hydrating";
9284
- if (gate.tabHidden() && (TAB_GATED.has(r.kind) || inRetry)) return "tab-hidden";
9641
+ if (gate.tabHidden() && (HIDDEN_TAB[r.kind] === "defer" || inRetry)) return "tab-hidden";
9285
9642
  if (!readable && VISIBILITY_GATED.has(r.kind)) return "target-invisible";
9286
9643
  if (promised([r], flights, queued)) return "promised";
9287
9644
  return inRetry ? "paused" : void 0;
@@ -9305,13 +9662,13 @@ function createCore(options) {
9305
9662
  const waitingKeys = new Set((receiver?.waitingKeys() ?? []).map((w) => `${w.object}\u0000${w.key.toLowerCase()}`));
9306
9663
  const retries = new Map((receiver?.minVersionRetries() ?? []).map((r) => [`${r.object}\u0000${r.key.toLowerCase()}`, r]));
9307
9664
  for (const o of objects.values()) {
9308
- const tail = tails.get(o);
9309
- const flying = new Set(tail?.flying ?? []);
9665
+ const queue = o.keyQueue;
9666
+ const flying = new Set(queue?.flying ?? []);
9310
9667
  const holders = [...registry.subsets()].filter((s) => s.alive && !s.purged && s.form.object === o);
9311
9668
  for (const key of o.rows.keys()) {
9312
9669
  const e = o.rows.get(key);
9313
9670
  const retry = retries.get(`${o.name}\u0000${key.toLowerCase()}`);
9314
- const inTail = tail?.pending.has(key) === true || flying.has(key);
9671
+ const inTail = isKeyQueued(queue, key);
9315
9672
  const requirements = [];
9316
9673
  const { minVersion, hidden, epoch } = e.stale;
9317
9674
  if (minVersion !== void 0) requirements.push({
@@ -9329,7 +9686,7 @@ function createCore(options) {
9329
9686
  if (requirements.length === 0) continue;
9330
9687
  const tabGated = (r) => r.kind === "version-epoch-switched" || r.kind === "min-version" && retry !== void 0;
9331
9688
  const flights = flying.has(key) ? [{ kind: "keys" }] : [];
9332
- const queued = tail?.pending.has(key) === true ? [{
9689
+ const queued = queue?.pending.includes(key) === true ? [{
9333
9690
  kind: "keys",
9334
9691
  cause: {
9335
9692
  reason: "requirement",
@@ -9352,9 +9709,10 @@ function createCore(options) {
9352
9709
  }
9353
9710
  }
9354
9711
  {
9355
- const requirements = versionTail ? [{ kind: "version-unconfirmed" }] : [];
9356
- const flights = versionFlying ? [{ kind: "service" }] : [];
9357
- const queued = versionTail ? [{ kind: "service" }] : [];
9712
+ const state = services.version.targetState;
9713
+ const requirements = state.trailing === void 0 ? [] : [{ kind: "version-unconfirmed" }];
9714
+ const flights = inFlight$1(state) ? [{ kind: "service" }] : [];
9715
+ const queued = state.trailing === void 0 ? [] : [{ kind: "service" }];
9358
9716
  record({
9359
9717
  target: {
9360
9718
  kind: "service",
@@ -9368,13 +9726,14 @@ function createCore(options) {
9368
9726
  if (rightsEnabled) {
9369
9727
  const requirements = [];
9370
9728
  if (rights === void 0) requirements.push({ kind: "rights-unconfirmed" });
9371
- const flights = rightsFlying ? [rightsSent === void 0 ? { kind: "service" } : {
9729
+ const state = services.rights.targetState;
9730
+ const flights = inFlight$1(state) ? [state.flightEpoch === void 0 ? { kind: "service" } : {
9372
9731
  kind: "service",
9373
- epoch: rightsSent.epoch
9732
+ epoch: state.flightEpoch
9374
9733
  }] : [];
9375
- const queued = rightsTail === void 0 ? [] : [{
9734
+ const queued = state.trailing === void 0 ? [] : [{
9376
9735
  kind: "service",
9377
- cause: rightsTail
9736
+ cause: state.trailing
9378
9737
  }];
9379
9738
  record(withOptional({
9380
9739
  target: {
@@ -9441,7 +9800,7 @@ function createCore(options) {
9441
9800
  ...session.epochs.sizes(),
9442
9801
  revisions: views.revisions,
9443
9802
  rowViews: views.views,
9444
- tails: [...tails.values()].reduce((n, t) => n + t.pending.size + (t.flying?.length ?? 0), 0),
9803
+ tails: [...objects.values()].reduce((n, o) => n + queuedKeyCount(o.keyQueue), 0),
9445
9804
  purges: purges.size,
9446
9805
  releaseTimers: subs.filter((s) => s.releaseTimer !== void 0).length,
9447
9806
  preloadTimers: subs.reduce((n, s) => n + s.preloadTimers.size, 0),