@powerhousedao/reactor 6.2.2-dev.6 → 6.2.2-dev.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { A as parsePagingOptions, C as DuplicateManifestError, D as DocumentDeletedError, E as ModuleNotFoundError, O as DocumentNotFoundError, S as CollectionMembershipCache, T as InvalidModuleError, _ as KyselyWriteCache, a as createForwardingPoolInstrumentation, b as createConsistencyToken, c as DuplicateOperationError, d as KyselyKeyframeStore, f as DocumentModelRegistry, g as EventBus, h as KyselyExecutionScope, i as runMigrations, j as throwIfAborted, k as matchesScope, l as OptimisticLockError, m as DriveCollectionId, n as REACTOR_SCHEMA, o as instrumentPgPool, p as SimpleJobExecutor, r as getMigrationStatus, s as KyselyOperationStore, t as DEFAULT_DRIVE_CONTAINER_TYPES, u as RevisionMismatchError, v as KyselyOperationIndex, w as DuplicateModuleError, x as createEmptyConsistencyToken, y as DocumentMetaCache } from "./drive-container-types-DpJp2AmE.js";
1
+ import { A as GATED_DOCUMENT_ACTIONS, B as AuthTimestampNotMonotonicError, C as DuplicateOperationError, D as DuplicateModuleError, E as DuplicateManifestError, F as selectDecisionModel, G as InvalidOperationTimestampError, H as DocumentDeletedError, I as documentDecisionModel, J as parsePagingOptions, K as UpgradePreconditionFailedError, L as authDecisionModel, M as createEmptyConsistencyToken, N as targetDocumentId, O as InvalidModuleError, P as decideAtHead, R as buildDecisionModel, S as AppendConditionFailedError, T as RevisionMismatchError, U as DocumentNotFoundError, V as AuthorizationDeniedError, W as ExcessiveReshuffleError, Y as throwIfAborted, _ as DocumentMetaCache, a as createForwardingPoolInstrumentation, b as JobExecutorEventTypes, c as KyselyKeyframeStore, d as DriveCollectionId, f as KyselyExecutionScope, g as KyselyOperationIndex, h as KyselyWriteCache, i as runMigrations, j as createConsistencyToken, k as ModuleNotFoundError, l as DocumentModelRegistry, m as EventBus, n as REACTOR_SCHEMA, o as instrumentPgPool, p as resolveFeatureFlags, q as matchesScope, r as getMigrationStatus, s as KyselyOperationStore, t as DEFAULT_DRIVE_CONTAINER_TYPES, u as SimpleJobExecutor, v as CollectionMembershipCache, w as OptimisticLockError, x as APPEND_CONDITION_FAILED_PREFIX, y as DEFAULT_DEFERRED_JOB_TTL_MS, z as AuthEnforcementDisabledError } from "./drive-container-types-bVQ_8YwX.js";
2
2
  import { n as ReactorEventTypes, t as EventBusAggregateError } from "./types-DMKLa0Ok.js";
3
3
  import { i as WorkerInitFailedError, r as WorkerExitedError, t as WorkerAbortTimeoutError } from "./errors-D3S6Eysd.js";
4
- import { a as ReadModelCoordinator, i as KyselyDocumentView, n as ConsistencyTracker, o as BaseReadModel, r as makeConsistencyKey, t as KyselyDocumentIndexer } from "./document-indexer-FGJmRAdX.js";
4
+ import { a as ReadModelCoordinator, i as KyselyDocumentView, n as ConsistencyTracker, o as BaseReadModel, r as makeConsistencyKey, t as KyselyDocumentIndexer } from "./document-indexer-DlpJB8AK.js";
5
5
  import { n as errorToInfo, r as sanitizeArg, t as createForwardingLogger } from "./forwarding-logger-BBkMSxuJ.js";
6
- import { t as workerEntryPath } from "./worker-DBJOv8Gp.js";
7
- import { actions, actions as documentActions, createPresignedHeader, generateId, hashDocumentStateForScope, replayDocument } from "@powerhousedao/shared/document-model";
6
+ import { t as workerEntryPath } from "./worker-DXJpyHLW.js";
7
+ import { DowngradeNotSupportedError, MAX_AUTH_GRANTS, UnsupportedDocumentModelVersionError, actions, actions as documentActions, createPresignedHeader, decide, deserializeSignature, garbageCollect, generateId, groupDocumentType, groupMembershipActionTypes, hashDocumentStateForScope, normalizeDocumentModelVersion, sortOperations, toTransportAction } from "@powerhousedao/shared/document-model";
8
8
  import { addFile, addFolder, copyNode, deleteNode, driveCreateDocument, generateNodesCopy, getDescendants, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
9
9
  import { v4 } from "uuid";
10
10
  import { ConsoleLogger, childLogger } from "document-model";
@@ -190,10 +190,12 @@ function topologicalSort(jobs) {
190
190
  */
191
191
  function toErrorInfo$1(error) {
192
192
  if (error instanceof Error) return {
193
+ name: error.name,
193
194
  message: error.message,
194
195
  stack: error.stack || (/* @__PURE__ */ new Error()).stack || ""
195
196
  };
196
197
  return {
198
+ name: "Error",
197
199
  message: error,
198
200
  stack: (/* @__PURE__ */ new Error()).stack || ""
199
201
  };
@@ -363,7 +365,7 @@ var DriveClient = class {
363
365
  documentId: document.header.id,
364
366
  model: document.header.documentType,
365
367
  fromVersion: 0,
366
- toVersion: 1,
368
+ toVersion: normalizeDocumentModelVersion(document.state.document?.version),
367
369
  initialState: document.state
368
370
  }),
369
371
  addRelationshipAction(driveIdentifier, documentId, "child")
@@ -391,7 +393,7 @@ var DriveClient = class {
391
393
  }] }, signal);
392
394
  const completedJobs = await Promise.all(Object.values(batchResult.jobs).map((job) => this.client.waitForJob(job, signal)));
393
395
  for (const job of completedJobs) if (job.status === JobStatus.FAILED) throw new Error(job.error?.message);
394
- return this.reactor.get(documentId);
396
+ return this.client.get(documentId, void 0, signal);
395
397
  }
396
398
  async addFolder(driveIdentifier, name, parentFolder, signal) {
397
399
  this.logger.verbose("drives.addFolder(@driveIdentifier, @name, @parentFolder)", driveIdentifier, name, parentFolder);
@@ -400,7 +402,7 @@ var DriveClient = class {
400
402
  id: folderId,
401
403
  name,
402
404
  parentFolder
403
- })], signal)).state.global.nodes.find((n) => n.id === folderId);
405
+ })], signal)).state.global?.nodes.find((n) => n.id === folderId);
404
406
  if (!node || !isFolderNode(node)) throw new Error("Folder creation failed");
405
407
  return node;
406
408
  }
@@ -427,7 +429,7 @@ var DriveClient = class {
427
429
  const node = (await this.client.execute(driveIdentifier, "main", [updateNode({
428
430
  id: nodeId,
429
431
  name
430
- })], signal)).state.global.nodes.find((n) => n.id === nodeId);
432
+ })], signal)).state.global?.nodes.find((n) => n.id === nodeId);
431
433
  if (!node) throw new Error("Node missing from drive after rename");
432
434
  return node;
433
435
  }
@@ -468,8 +470,12 @@ var DriveClient = class {
468
470
  const node = drive.state.global.nodes.find((n) => n.id === entry.srcId);
469
471
  if (!node || !isFileNode(node)) continue;
470
472
  const srcDoc = await this.client.get(entry.srcId, void 0, signal);
471
- const module = await this.client.getDocumentModelModule(srcDoc.header.documentType);
472
- const duplicated = replayDocument(srcDoc.initialState, srcDoc.operations, module.reducer, createPresignedHeader(entry.targetId, srcDoc.header.documentType));
473
+ const duplicated = {
474
+ ...srcDoc,
475
+ header: createPresignedHeader(entry.targetId, srcDoc.header.documentType),
476
+ initialState: srcDoc.state,
477
+ operations: {}
478
+ };
473
479
  const resolvedName = resolvedNamesByTargetId.get(entry.targetId);
474
480
  if (resolvedName) duplicated.header.name = resolvedName;
475
481
  await this.addFile(driveIdentifier, duplicated, entry.targetParentFolder ?? void 0, signal);
@@ -680,8 +686,335 @@ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
680
686
  return DocumentChangeType;
681
687
  }({});
682
688
  //#endregion
689
+ //#region src/decision/read-gate.ts
690
+ /**
691
+ * Scopes every holder of a document may read, whatever the grants say. Denying
692
+ * the policy itself would let a replica sync a document without it, read the
693
+ * auth scope as uninitialized, and allow every operation it holds, so replicas
694
+ * would diverge permanently. The document scope carries the metadata the same
695
+ * argument covers. Grants gate domain-scope reads only.
696
+ */
697
+ const ALWAYS_READABLE_SCOPES = new Set(["auth", "document"]);
698
+ /** What a gate does with an uninitialized policy when told nothing. */
699
+ const OPEN_BY_DEFAULT = { withholdUninitialized: false };
700
+ /**
701
+ * The branch a group is read on. A group's member list lives on its main
702
+ * branch whatever branch the document naming it is on, and the reference
703
+ * relation records no branch of its own.
704
+ */
705
+ const GROUP_BRANCH = "main";
706
+ /**
707
+ * The scope of a group document that holds its member list. It is the only
708
+ * scope group serving reaches, because it is the only one the audience must
709
+ * fold in order to evaluate auth with the group.
710
+ */
711
+ const GROUP_MEMBERSHIP_SCOPE = "global";
712
+ /**
713
+ * How many of a group's referencing documents are examined before a read of
714
+ * that group gives up and withholds. Each one costs a model build, and the
715
+ * relation is append-only, so an old and briefly-held reference still counts.
716
+ * Truncating denies, which is the direction that withholds. It is the cap a
717
+ * version-1 policy carries on its own grant list, taken from there rather than
718
+ * restated: raising that cap raises the read fan-out here.
719
+ */
720
+ const MAX_EXAMINED_REFERENCERS = MAX_AUTH_GRANTS;
721
+ /**
722
+ * How many referencers are probed at once. The reactor's Postgres pool size is
723
+ * optional and defaults to ten, and a listing resolves one gate per result, so
724
+ * per-gate fan-out multiplies: a handful keeps one group read from claiming the
725
+ * whole pool while still cutting the walk several times over. On PGlite the
726
+ * queries serialize regardless, so a larger number buys nothing in a browser.
727
+ */
728
+ const REFERENCER_PROBE_CONCURRENCY = 4;
729
+ /**
730
+ * The policy carried on a document, if it carries one. A document handed to the
731
+ * gate with no state at all is not policied, so it is not gated.
732
+ */
733
+ function authOf(document) {
734
+ return document.state?.auth;
735
+ }
736
+ /**
737
+ * The model reads enforce. Below `authEnforcement` there is no model to
738
+ * enforce: the document-only model ignores the auth scope entirely, so reading
739
+ * through it would serve every domain scope of a policied document to anyone.
740
+ * Undefined therefore means "evaluate the policy alone", which is what the read
741
+ * surface did before the model existed.
742
+ */
743
+ function readDecisionModel(flags, registry) {
744
+ return flags.authEnforcement ? selectDecisionModel(flags, registry) : void 0;
745
+ }
746
+ /**
747
+ * Evaluates the policy on its own, with no groups map and no condition context.
748
+ * A `{ group }` or conditional grant therefore never applies: an allow that
749
+ * does not apply withholds access, so this cannot widen a policy, but a policy
750
+ * relying on a conditional deny is weaker here than it is written.
751
+ */
752
+ var BareReadGate = class {
753
+ scopePredicate(document, subject) {
754
+ const auth = authOf(document);
755
+ return Promise.resolve((scope) => ALWAYS_READABLE_SCOPES.has(scope) || decide(auth, subject, {
756
+ verb: "read",
757
+ scope
758
+ }) === "allow");
759
+ }
760
+ };
761
+ /**
762
+ * Answers a stream read from the document already fetched, and anything else
763
+ * through the read side.
764
+ *
765
+ * The seed is why routing reads through a decision model costs no extra I/O for
766
+ * the document being read: its `document` and `auth` scopes are the two static
767
+ * projections, and the caller has both in hand. Only a group stream the grant
768
+ * list names is fetched.
769
+ */
770
+ var SeededStateReader = class {
771
+ constructor(documentView, seed, branch) {
772
+ this.documentView = documentView;
773
+ this.seed = seed;
774
+ this.branch = branch;
775
+ }
776
+ /**
777
+ * A stream this replica does not hold has to reach buildDecisionModel as the
778
+ * absence it recognises, or the whole read fails instead of leaving the group
779
+ * out of the model, where its principal does not match and the policy fails
780
+ * closed. The read side reports absence as a plain Error, so the absence is
781
+ * confirmed rather than inferred from the message: a transient failure must
782
+ * surface, not silently deny.
783
+ */
784
+ async getState(documentId, scope, branch, targetRevision, signal) {
785
+ if (targetRevision === void 0 && documentId === this.seed.header.id && branch === this.branch && scope in this.seed.state) return this.seed;
786
+ try {
787
+ return await this.documentView.get(documentId, {
788
+ branch,
789
+ scopes: [scope]
790
+ }, void 0, signal);
791
+ } catch (error) {
792
+ await this.assertAbsent(documentId, error, signal);
793
+ throw new DocumentNotFoundError(documentId);
794
+ }
795
+ }
796
+ async assertAbsent(documentId, error, signal) {
797
+ if (DocumentNotFoundError.isError(error)) return;
798
+ let exists;
799
+ try {
800
+ exists = await this.documentView.exists([documentId], void 0, signal);
801
+ } catch {
802
+ throw error;
803
+ }
804
+ if (exists[0]) throw error;
805
+ }
806
+ };
807
+ /**
808
+ * Evaluates a read against the registered decision model, built at the stream
809
+ * heads. This is what makes `{ group }` principals and conditional grants apply
810
+ * to a read: the model supplies the groups map and the scope's own state, the
811
+ * same two things admission supplies.
812
+ *
813
+ * A read has no action, so a condition on `action.input.*` never holds for one.
814
+ *
815
+ * State is read through the read side rather than the write cache. The write
816
+ * cache is invalidated by whichever process runs the executor, so a reactor
817
+ * running its executors in worker processes would answer reads in the parent
818
+ * from state no commit ever invalidates.
819
+ */
820
+ var ModelReadGate = class {
821
+ constructor(model, documentView, servesGroups, operationIndex, logger, options = OPEN_BY_DEFAULT) {
822
+ this.model = model;
823
+ this.documentView = documentView;
824
+ this.servesGroups = servesGroups;
825
+ this.operationIndex = operationIndex;
826
+ this.logger = logger;
827
+ this.options = options;
828
+ }
829
+ /**
830
+ * A served group yields its member list and nothing else. What the audience
831
+ * is owed is the state it must fold to evaluate auth with the group; a
832
+ * group's other scopes are its own business and stay behind its own grants.
833
+ */
834
+ async scopePredicate(document, subject, branch, signal) {
835
+ const own = await this.ownPolicyPredicate(document, subject, branch, signal);
836
+ if (!this.servesGroup(document) || own(GROUP_MEMBERSHIP_SCOPE)) return own;
837
+ const audience = await this.servesGroupTo(document.header.id, subject, signal);
838
+ return (scope) => own(scope) || audience && scope === GROUP_MEMBERSHIP_SCOPE;
839
+ }
840
+ /**
841
+ * Whether the subject is served this group because a policy names it.
842
+ *
843
+ * A replica must fold a group's membership to evaluate auth with it, so a
844
+ * group a grant names is served to the audience of the document that names
845
+ * it, whatever the group's own read grants say. Naming a group in a policy
846
+ * publishes its roster to that policy's audience; a group whose membership
847
+ * must stay confidential does not belong in a grant.
848
+ *
849
+ * The referencing document's own domain scopes are the test. Its `auth` and
850
+ * `document` scopes are readable by every holder, so testing those would
851
+ * serve every referenced group to everybody.
852
+ *
853
+ * One level only. A referencer that is itself a group is skipped, and a
854
+ * referencer's own readability is decided from its policy alone, so a
855
+ * reference cycle terminates. Cycles are reachable: the reference relation
856
+ * is recorded from an operation's input, including one later stored denied,
857
+ * so a refused grant naming a group from inside another group leaves a row
858
+ * behind that validation never saw.
859
+ *
860
+ * The referencers are probed a few at a time and the walk stops at the first
861
+ * that serves, because a subject outside the audience is the case that runs to
862
+ * the bound, and it is the common one. A probe that failed decides only when
863
+ * nothing served: serving rests on a real allow, so this cannot widen, and it
864
+ * stops one unreachable referencer from turning an allow already in hand into
865
+ * a denial. A read records no operation, so replicas differing over a
866
+ * transient failure has no consensus consequence.
867
+ *
868
+ * The probes are awaited together rather than raced, so none is ever left
869
+ * running with nobody awaiting it, which is where unhandled rejections come
870
+ * from.
871
+ */
872
+ async servesGroupTo(groupId, subject, signal) {
873
+ if (!this.operationIndex) return false;
874
+ const referencers = await this.operationIndex.getGroupReferencers(groupId, signal);
875
+ const examined = referencers.slice(0, MAX_EXAMINED_REFERENCERS);
876
+ if (examined.length < referencers.length) this.logger?.warn(`Group ${groupId} is referenced by ${referencers.length} documents; only the first ${MAX_EXAMINED_REFERENCERS} decide whether it is served`);
877
+ const walk = {
878
+ next: 0,
879
+ served: false,
880
+ failure: void 0
881
+ };
882
+ const probe = async () => {
883
+ while (!walk.served && walk.next < examined.length) {
884
+ const referencerId = examined[walk.next++];
885
+ let serves = false;
886
+ try {
887
+ serves = await this.servesThrough(referencerId, subject, signal);
888
+ } catch (error) {
889
+ walk.failure ??= Error.isError(error) ? error : /* @__PURE__ */ new Error(`Probing referencer ${referencerId} failed`);
890
+ }
891
+ if (serves) walk.served = true;
892
+ }
893
+ };
894
+ await Promise.all(Array.from({ length: Math.min(REFERENCER_PROBE_CONCURRENCY, examined.length) }, probe));
895
+ if (!walk.served && walk.failure) throw walk.failure;
896
+ return walk.served;
897
+ }
898
+ /**
899
+ * Whether one referencing document serves the subject any domain scope. A
900
+ * referencer this replica does not hold serves nothing, which fails closed
901
+ * the same way a group it does not hold does.
902
+ */
903
+ async servesThrough(referencerId, subject, signal) {
904
+ let referencer;
905
+ try {
906
+ referencer = await this.documentView.get(referencerId, { branch: GROUP_BRANCH }, void 0, signal);
907
+ } catch {
908
+ return false;
909
+ }
910
+ if (this.servesGroup(referencer)) return false;
911
+ const readable = await this.ownPolicyPredicate(referencer, subject, GROUP_BRANCH, signal);
912
+ return Object.keys(referencer.state ?? {}).filter((scope) => !ALWAYS_READABLE_SCOPES.has(scope)).some((scope) => readable(scope));
913
+ }
914
+ servesGroup(document) {
915
+ return this.servesGroups && this.operationIndex !== void 0 && document.header.documentType === groupDocumentType;
916
+ }
917
+ /**
918
+ * What this document's own policy says, with no group serving applied.
919
+ *
920
+ * An unpoliced document is readable in full unless the host closes by default,
921
+ * and either way it is the common case and the one worth answering without
922
+ * building anything. The test is the one `evaluate` makes: a legacy `{}` auth
923
+ * scope and version 0 both mean uninitialized, and "no grants" does not,
924
+ * because a policy with a version and an empty grant list denies everything.
925
+ *
926
+ * Closing here rather than around the gate is what keeps a policy able to
927
+ * publish an unpoliced group it names: the referencer walk asks this question
928
+ * of the referencing document, whose real policy answers it.
929
+ */
930
+ async ownPolicyPredicate(document, subject, branch, signal) {
931
+ const auth = authOf(document);
932
+ if (!auth || !auth.version) return this.options.withholdUninitialized ? (scope) => ALWAYS_READABLE_SCOPES.has(scope) : () => true;
933
+ const target = {
934
+ documentId: document.header.id,
935
+ branch
936
+ };
937
+ const built = await buildDecisionModel(new SeededStateReader(this.documentView, document, branch), this.model, target, signal);
938
+ const definition = this.model(target);
939
+ const scopeStates = document.state ?? {};
940
+ return (scope) => ALWAYS_READABLE_SCOPES.has(scope) || definition.decide(built.model, subject, {
941
+ verb: "read",
942
+ scope
943
+ }, {
944
+ scopeState: scopeStates[scope],
945
+ actionInput: void 0
946
+ }).decision === "allow";
947
+ }
948
+ };
949
+ //#endregion
950
+ //#region src/client/util.ts
951
+ function authSubjectFromSigner(signer) {
952
+ return {
953
+ address: signer.user?.address,
954
+ key: signer.app?.key
955
+ };
956
+ }
957
+ function withAuthScope(view) {
958
+ if (view?.scopes && view.scopes.length > 0) return {
959
+ ...view,
960
+ scopes: [...new Set([...view.scopes, "auth"])]
961
+ };
962
+ return view;
963
+ }
964
+ /**
965
+ * Drops the scopes the predicate refuses. The predicate is resolved by the read
966
+ * gate, which decides against the whole policy once per document; this only
967
+ * applies the answer, so it stays synchronous.
968
+ */
969
+ function filterReadableScopes(document, readable) {
970
+ const state = document.state;
971
+ if (!state) return document;
972
+ return {
973
+ ...document,
974
+ state: keepReadableScopes(state, readable),
975
+ initialState: keepReadableScopes(document.initialState, readable)
976
+ };
977
+ }
978
+ function keepReadableScopes(scopes, readable) {
979
+ if (!scopes) return scopes;
980
+ const kept = {};
981
+ for (const scope of Object.keys(scopes)) if (readable(scope)) kept[scope] = scopes[scope];
982
+ return kept;
983
+ }
984
+ //#endregion
683
985
  //#region src/client/reactor-client.ts
684
986
  /**
987
+ * The document a candidate is decided against. Routed on the action type alone,
988
+ * which is what the executor routes on: every action the reactor reduces onto
989
+ * the document scope carries that scope already, and the gate follows the
990
+ * action's own target rather than the document the request named.
991
+ */
992
+ function evaluationTargetId(candidate, fallback) {
993
+ return GATED_DOCUMENT_ACTIONS.has(candidate.type) ? targetDocumentId({
994
+ type: candidate.type,
995
+ input: candidate.input
996
+ }, fallback) : fallback;
997
+ }
998
+ /**
999
+ * One candidate's verdict, decided exactly as admission decides it: the same
1000
+ * request, and a condition context populated only while authConditions is on,
1001
+ * so a conditional grant applies here precisely when it would apply there.
1002
+ * Groups need nothing added, because the selected model carries them.
1003
+ */
1004
+ function decideCandidate(config, target, subject, candidate) {
1005
+ return target.definition.decide(target.model, subject, {
1006
+ verb: "execute",
1007
+ scope: candidate.scope,
1008
+ operation: candidate.type
1009
+ }, config.flags.authConditions ? {
1010
+ scopeState: target.scopeStates[candidate.scope],
1011
+ actionInput: candidate.input
1012
+ } : {
1013
+ scopeState: void 0,
1014
+ actionInput: void 0
1015
+ });
1016
+ }
1017
+ /**
685
1018
  * ReactorClient implementation that wraps lower-level APIs to provide
686
1019
  * a simpler interface for document operations.
687
1020
  *
@@ -699,8 +1032,10 @@ var ReactorClient = class {
699
1032
  jobAwaiter;
700
1033
  documentIndexer;
701
1034
  documentView;
1035
+ readGate;
1036
+ actionEvaluation;
702
1037
  drives;
703
- constructor(logger, reactor, signer, subscriptionManager, jobAwaiter, documentIndexer, documentView) {
1038
+ constructor(logger, reactor, signer, subscriptionManager, jobAwaiter, documentIndexer, documentView, readGate = new BareReadGate(), actionEvaluation) {
704
1039
  this.logger = logger;
705
1040
  this.reactor = reactor;
706
1041
  this.signer = signer;
@@ -708,9 +1043,33 @@ var ReactorClient = class {
708
1043
  this.jobAwaiter = jobAwaiter;
709
1044
  this.documentIndexer = documentIndexer;
710
1045
  this.documentView = documentView;
1046
+ this.readGate = readGate;
1047
+ this.actionEvaluation = actionEvaluation;
711
1048
  this.drives = new DriveClient(this, logger, reactor, signer);
712
1049
  this.logger.verbose("ReactorClient initialized");
713
1050
  }
1051
+ readSubject(subject) {
1052
+ return subject ?? authSubjectFromSigner(this.signer);
1053
+ }
1054
+ /**
1055
+ * Which scopes of one document the subject may read. Resolved once per
1056
+ * document, so the gate builds its model once however many scopes are then
1057
+ * tested, and the filtering itself stays synchronous.
1058
+ */
1059
+ readableScopes(document, view, signal) {
1060
+ return this.readGate.scopePredicate(document, this.readSubject(view?.subject), view?.branch ?? "main", signal);
1061
+ }
1062
+ /**
1063
+ * One document, filtered to the scopes the subject may read. Every method
1064
+ * that hands a document back goes through here, including the ones that
1065
+ * follow a write: a document returned from a mutation is a read like any
1066
+ * other, and returning it whole served scopes the same subject would be
1067
+ * refused by `get`. Its author still sees what it wrote, because an allow on
1068
+ * execute confers read of that scope.
1069
+ */
1070
+ async gateDocument(document, view, signal) {
1071
+ return filterReadableScopes(document, await this.readableScopes(document, view, signal));
1072
+ }
714
1073
  /**
715
1074
  * Retrieves a list of document model modules.
716
1075
  */
@@ -725,24 +1084,53 @@ var ReactorClient = class {
725
1084
  * @returns The document model module
726
1085
  */
727
1086
  async getDocumentModelModule(documentType) {
728
- const module = (await this.reactor.getDocumentModels()).results.find((m) => m.documentModel.global.id === documentType);
729
- if (!module) throw new Error(`Document model module not found for type: ${documentType}`);
730
- return module;
1087
+ const modules = await this.reactor.getDocumentModels();
1088
+ let latestModule;
1089
+ let latestVersion = -1;
1090
+ for (const module of modules.results) {
1091
+ if (module.documentModel.global.id !== documentType) continue;
1092
+ const version = module.version ?? 1;
1093
+ if (version > latestVersion) {
1094
+ latestVersion = version;
1095
+ latestModule = module;
1096
+ }
1097
+ }
1098
+ if (!latestModule) throw new Error(`Document model module not found for type: ${documentType}`);
1099
+ return latestModule;
1100
+ }
1101
+ /**
1102
+ * Retrieves the document model module matching the version the document is
1103
+ * stamped with, so not-yet-upgraded documents get the reducer their
1104
+ * history was written with rather than the latest.
1105
+ */
1106
+ async getDocumentModelModuleForDocument(document) {
1107
+ const documentType = document.header.documentType;
1108
+ const version = normalizeDocumentModelVersion(document.state.document?.version);
1109
+ const modules = await this.reactor.getDocumentModels();
1110
+ const availableVersions = [];
1111
+ for (const module of modules.results) {
1112
+ if (module.documentModel.global.id !== documentType) continue;
1113
+ const moduleVersion = normalizeDocumentModelVersion(module.version);
1114
+ if (moduleVersion === version) return module;
1115
+ availableVersions.push(moduleVersion);
1116
+ }
1117
+ throw new UnsupportedDocumentModelVersionError(documentType, version, availableVersions.sort((a, b) => a - b));
731
1118
  }
732
1119
  /**
733
1120
  * Retrieves a specific PHDocument
734
1121
  */
735
1122
  async get(identifier, view, signal) {
736
1123
  this.logger.verbose("get(@identifier, @view)", identifier, view);
737
- return await this.reactor.getByIdOrSlug(identifier, view, void 0, signal);
1124
+ const document = await this.reactor.getByIdOrSlug(identifier, withAuthScope(view), void 0, signal);
1125
+ return this.gateDocument(document, view, signal);
738
1126
  }
739
1127
  /**
740
1128
  * Resolves an identifier (id or slug) to the canonical document id, using the
741
1129
  * same lookup as the data path. Resolves against the "main" branch. Throws if
742
1130
  * the identifier cannot be resolved or is ambiguous.
743
1131
  */
744
- async resolveIdOrSlug(identifier, signal) {
745
- return this.documentView.resolveIdOrSlug(identifier, void 0, void 0, signal);
1132
+ async resolveIdOrSlug(identifier, view, signal) {
1133
+ return this.documentView.resolveIdOrSlug(identifier, view, void 0, signal);
746
1134
  }
747
1135
  /**
748
1136
  * Retrieves operations for a document
@@ -750,8 +1138,11 @@ var ReactorClient = class {
750
1138
  async getOperations(documentIdentifier, view, filter, paging, signal) {
751
1139
  this.logger.verbose("getOperations(@documentIdentifier, @view, @filter, @paging)", documentIdentifier, view, filter, paging);
752
1140
  const documentId = await this.documentView.resolveIdOrSlug(documentIdentifier, view, void 0, signal);
753
- if (paging?.cursor && isCompositeCursor(paging.cursor)) return this.getOperationsWithCompositeCursor(documentId, view, filter, paging, signal);
1141
+ const gated = await this.reactor.getByIdOrSlug(documentId, withAuthScope(view), void 0, signal);
1142
+ const canRead = await this.readableScopes(gated, view, signal);
1143
+ if (paging?.cursor && isCompositeCursor(paging.cursor)) return this.getOperationsWithCompositeCursor(documentId, view, filter, paging, signal, canRead);
754
1144
  const operationsByScope = await this.reactor.getOperations(documentId, view, filter, paging, void 0, signal);
1145
+ for (const scope of Object.keys(operationsByScope)) if (!canRead(scope)) delete operationsByScope[scope];
755
1146
  const scopeEntries = Object.entries(operationsByScope);
756
1147
  const effectivePaging = paging || {
757
1148
  cursor: "0",
@@ -779,11 +1170,12 @@ var ReactorClient = class {
779
1170
  nextCursor: Object.keys(activeCursors).length > 0 ? encodeCompositeCursor(activeCursors) : void 0
780
1171
  };
781
1172
  }
782
- async getOperationsWithCompositeCursor(documentId, view, filter, paging, signal) {
1173
+ async getOperationsWithCompositeCursor(documentId, view, filter, paging, signal, canRead) {
783
1174
  const scopeCursors = decodeCompositeCursor(paging.cursor);
784
1175
  const allOperations = [];
785
1176
  const activeCursors = {};
786
1177
  for (const [scopeName, cursor] of Object.entries(scopeCursors)) {
1178
+ if (!canRead(scopeName)) continue;
787
1179
  const scopeView = {
788
1180
  ...view,
789
1181
  scopes: [scopeName]
@@ -817,7 +1209,7 @@ var ReactorClient = class {
817
1209
  limit: 0
818
1210
  }
819
1211
  };
820
- return this.reactor.find({ ids: targetIds }, view, paging, void 0, signal);
1212
+ return this.find({ ids: targetIds }, view, paging, signal);
821
1213
  }
822
1214
  /**
823
1215
  * Retrieves incoming relationships of a given type to a target document.
@@ -833,14 +1225,90 @@ var ReactorClient = class {
833
1225
  limit: 0
834
1226
  }
835
1227
  };
836
- return this.reactor.find({ ids: sourceIds }, view, paging, void 0, signal);
1228
+ return this.find({ ids: sourceIds }, view, paging, signal);
837
1229
  }
838
1230
  /**
839
1231
  * Filters documents by criteria and returns a list of them
840
1232
  */
841
1233
  async find(search, view, paging, signal) {
842
1234
  this.logger.verbose("find(@search, @view, @paging)", search, view, paging);
843
- return this.reactor.find(search, view, paging, void 0, signal);
1235
+ const results = await this.reactor.find(search, withAuthScope(view), paging, void 0, signal);
1236
+ return {
1237
+ ...results,
1238
+ results: await Promise.all(results.results.map(async (doc) => filterReadableScopes(doc, await this.readableScopes(doc, view, signal))))
1239
+ };
1240
+ }
1241
+ /**
1242
+ * Predicts the admission verdict for each candidate. See
1243
+ * {@link IReactorClient.evaluateActions} for the contract and its caveats.
1244
+ *
1245
+ * Read-only throughout, and never through the write cache: that cache is
1246
+ * invalidated by whichever process runs the executor, so a reactor running
1247
+ * its executors in worker processes would answer here from state no commit
1248
+ * ever invalidates.
1249
+ */
1250
+ async evaluateActions(documentIdentifier, branch, candidates, subject, signal) {
1251
+ this.logger.verbose("evaluateActions(@documentIdentifier, @branch, @count candidates)", documentIdentifier, branch, candidates.length);
1252
+ const config = this.actionEvaluation;
1253
+ if (config === void 0) throw new AuthEnforcementDisabledError();
1254
+ const decidedSubject = this.readSubject(subject);
1255
+ const resolvedId = await this.documentView.resolveIdOrSlug(documentIdentifier, { branch }, void 0, signal);
1256
+ const targets = /* @__PURE__ */ new Map();
1257
+ const evaluations = [];
1258
+ for (const candidate of candidates) {
1259
+ if (candidate.type === "CREATE_DOCUMENT") {
1260
+ evaluations.push({ decision: "allow" });
1261
+ continue;
1262
+ }
1263
+ const targetId = evaluationTargetId(candidate, resolvedId);
1264
+ let target = targets.get(targetId);
1265
+ if (target === void 0) {
1266
+ target = await this.buildEvaluationTarget(config, targetId, branch, signal);
1267
+ targets.set(targetId, target);
1268
+ }
1269
+ evaluations.push(decideCandidate(config, target, decidedSubject, candidate));
1270
+ }
1271
+ const allowed = evaluations.filter((evaluation) => evaluation.decision === "allow").length;
1272
+ return {
1273
+ evaluations,
1274
+ allAllowed: candidates.length > 0 && allowed === candidates.length,
1275
+ anyAllowed: allowed > 0,
1276
+ allDenied: candidates.length > 0 && allowed === 0,
1277
+ anyDenied: allowed < candidates.length
1278
+ };
1279
+ }
1280
+ /**
1281
+ * The decision model for one target document, built at its stream heads.
1282
+ *
1283
+ * The document is fetched unfiltered, because the policy is what decides:
1284
+ * reading it through the read gate would withhold the very scopes the
1285
+ * decision is about. A deleted document is served at its deletion boundary,
1286
+ * which is what lets the model refuse an execute against it -- authEnforcement
1287
+ * requires documentDecisions, so that read is available whenever this runs.
1288
+ *
1289
+ * Reading past the gate discloses nothing a submit does not. The `auth` and
1290
+ * `document` scopes are readable by every holder, so a verdict resting on the
1291
+ * policy alone is one the caller could compute unaided; and a verdict resting
1292
+ * on a conditional grant reads the executing scope's state exactly as
1293
+ * admission reads it, so the answer here is what submitting and being refused
1294
+ * would have revealed anyway.
1295
+ *
1296
+ * The append condition the build records is dropped. It guards a write, and
1297
+ * this makes none; reproducing it is also what the preflight cannot do, which
1298
+ * is why the answer is a prediction.
1299
+ */
1300
+ async buildEvaluationTarget(config, documentId, branch, signal) {
1301
+ const document = await this.documentView.get(documentId, { branch }, void 0, signal);
1302
+ const target = {
1303
+ documentId,
1304
+ branch
1305
+ };
1306
+ const built = await buildDecisionModel(new SeededStateReader(this.documentView, document, branch), config.model, target, signal);
1307
+ return {
1308
+ definition: config.model(target),
1309
+ model: built.model,
1310
+ scopeStates: document.state ?? {}
1311
+ };
844
1312
  }
845
1313
  /**
846
1314
  * Creates a document and waits for completion
@@ -868,7 +1336,7 @@ var ReactorClient = class {
868
1336
  documentId,
869
1337
  model: document.header.documentType,
870
1338
  fromVersion: 0,
871
- toVersion: document.state.document.version,
1339
+ toVersion: normalizeDocumentModelVersion(document.state.document?.version),
872
1340
  initialState: document.state
873
1341
  })], this.signer, signal);
874
1342
  const jobs = [{
@@ -893,7 +1361,8 @@ var ReactorClient = class {
893
1361
  const batchResult = await this.reactor.executeBatch({ jobs }, signal);
894
1362
  const completedJobs = await Promise.all(Object.values(batchResult.jobs).map((job) => this.waitForJob(job, signal)));
895
1363
  for (const job of completedJobs) if (job.status === JobStatus.FAILED) throw new Error(job.error?.message);
896
- return await this.reactor.get(documentId);
1364
+ const created = await this.reactor.get(documentId);
1365
+ return this.gateDocument(created, void 0, signal);
897
1366
  }
898
1367
  /**
899
1368
  * Creates an empty document and waits for completion
@@ -903,20 +1372,64 @@ var ReactorClient = class {
903
1372
  const matchingModules = (await this.reactor.getDocumentModels(void 0, void 0, signal)).results.filter((m) => m.documentModel.global.id === documentModelType);
904
1373
  let module;
905
1374
  if (options?.documentModelVersion !== void 0) {
906
- module = matchingModules.find((m) => m.version === options.documentModelVersion);
1375
+ const requestedVersion = normalizeDocumentModelVersion(options.documentModelVersion);
1376
+ module = matchingModules.find((m) => normalizeDocumentModelVersion(m.version) === requestedVersion);
907
1377
  if (!module) throw new Error(`Document model not found for type: ${documentModelType} with version: ${options.documentModelVersion}`);
908
1378
  } else {
909
1379
  module = matchingModules.reduce((latest, current) => {
910
1380
  if (latest === void 0) return current;
911
- return (current.version ?? 0) > (latest.version ?? 0) ? current : latest;
1381
+ return normalizeDocumentModelVersion(current.version) > normalizeDocumentModelVersion(latest.version) ? current : latest;
912
1382
  }, void 0);
913
1383
  if (!module) throw new Error(`Document model not found for type: ${documentModelType}`);
914
1384
  }
915
1385
  const document = module.utils.createDocument();
916
- document.state.document.version = module.version ?? 1;
1386
+ document.state.document.version = normalizeDocumentModelVersion(module.version);
917
1387
  return this.create(document, options?.parentIdentifier, signal);
918
1388
  }
919
1389
  /**
1390
+ * Upgrades a document to a newer document model version by dispatching an
1391
+ * UPGRADE_DOCUMENT action. When toVersion is omitted, upgrades to the
1392
+ * latest registered module version for the document's type. Returns the
1393
+ * document unchanged when it is already at the target version.
1394
+ *
1395
+ * The executor validates the action's version and revision snapshot against
1396
+ * the state the migration actually runs on. When a concurrent edit
1397
+ * invalidates the snapshot, the upgrade is rebuilt from a fresh read and
1398
+ * retried up to maxConflictRetries times before the conflict is surfaced.
1399
+ */
1400
+ async upgradeDocument(documentIdentifier, toVersion, options, signal) {
1401
+ this.logger.verbose("upgradeDocument(@documentIdentifier, @toVersion)", documentIdentifier, toVersion);
1402
+ const maxConflictRetries = options?.maxConflictRetries ?? 3;
1403
+ let lastConflictMessage = "";
1404
+ for (let attempt = 0; attempt <= maxConflictRetries; attempt++) {
1405
+ const document = await this.reactor.getByIdOrSlug(documentIdentifier, void 0, void 0, signal);
1406
+ const documentId = document.header.id;
1407
+ const documentType = document.header.documentType;
1408
+ const branch = document.header.branch || "main";
1409
+ const fromVersion = normalizeDocumentModelVersion(document.state.document?.version);
1410
+ let targetVersion = toVersion;
1411
+ if (targetVersion === void 0) targetVersion = normalizeDocumentModelVersion((await this.getDocumentModelModule(documentType)).version);
1412
+ if (targetVersion === fromVersion) return this.gateDocument(document, { branch }, signal);
1413
+ if (targetVersion < fromVersion) throw new DowngradeNotSupportedError(documentType, fromVersion, targetVersion);
1414
+ const signedActions = await signActions([upgradeDocumentAction({
1415
+ documentId,
1416
+ model: documentType,
1417
+ fromVersion,
1418
+ toVersion: targetVersion,
1419
+ revision: { ...document.header.revision }
1420
+ })], this.signer, signal);
1421
+ const jobInfo = await this.reactor.execute(documentId, branch, signedActions, signal);
1422
+ const completedJob = await this.waitForJob(jobInfo, signal);
1423
+ if (completedJob.status !== JobStatus.FAILED) {
1424
+ const upgraded = await this.reactor.getByIdOrSlug(documentId, { branch }, completedJob.consistencyToken, signal);
1425
+ return this.gateDocument(upgraded, { branch }, signal);
1426
+ }
1427
+ if (completedJob.error?.name !== "UpgradePreconditionFailedError") throw new Error(completedJob.error?.message);
1428
+ lastConflictMessage = completedJob.error.message;
1429
+ }
1430
+ throw new Error(`Upgrade of document ${documentIdentifier} conflicted with concurrent edits after ${maxConflictRetries + 1} attempts: ${lastConflictMessage}`);
1431
+ }
1432
+ /**
920
1433
  * Creates an empty document in a drive as a single batched operation.
921
1434
  * Delegates to {@link IDriveClient.addFile}.
922
1435
  *
@@ -936,7 +1449,8 @@ var ReactorClient = class {
936
1449
  const completedJob = await this.waitForJob(jobInfo, signal);
937
1450
  if (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);
938
1451
  const view = { branch };
939
- return await this.reactor.getByIdOrSlug(documentIdentifier, view, completedJob.consistencyToken, signal);
1452
+ const result = await this.reactor.getByIdOrSlug(documentIdentifier, view, completedJob.consistencyToken, signal);
1453
+ return this.gateDocument(result, view, signal);
940
1454
  }
941
1455
  /**
942
1456
  * Submits a list of actions to a document
@@ -980,7 +1494,8 @@ var ReactorClient = class {
980
1494
  const jobInfo = await this.reactor.addRelationship(sourceIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);
981
1495
  const completedJob = await this.waitForJob(jobInfo, signal);
982
1496
  if (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);
983
- return await this.reactor.getByIdOrSlug(sourceIdentifier, { branch }, completedJob.consistencyToken, signal);
1497
+ const result = await this.reactor.getByIdOrSlug(sourceIdentifier, { branch }, completedJob.consistencyToken, signal);
1498
+ return this.gateDocument(result, { branch }, signal);
984
1499
  }
985
1500
  /**
986
1501
  * Removes a relationship between two documents and waits for completion.
@@ -990,7 +1505,8 @@ var ReactorClient = class {
990
1505
  const jobInfo = await this.reactor.removeRelationship(sourceIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);
991
1506
  const completedJob = await this.waitForJob(jobInfo, signal);
992
1507
  if (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);
993
- return await this.reactor.getByIdOrSlug(sourceIdentifier, { branch }, completedJob.consistencyToken, signal);
1508
+ const result = await this.reactor.getByIdOrSlug(sourceIdentifier, { branch }, completedJob.consistencyToken, signal);
1509
+ return this.gateDocument(result, { branch }, signal);
994
1510
  }
995
1511
  /**
996
1512
  * Moves a relationship from one source document to another and waits for completion.
@@ -1003,9 +1519,11 @@ var ReactorClient = class {
1003
1519
  const addJobInfo = await this.reactor.addRelationship(targetParentIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);
1004
1520
  const addCompletedJob = await this.waitForJob(addJobInfo, signal);
1005
1521
  if (addCompletedJob.status === JobStatus.FAILED) throw new Error(addCompletedJob.error?.message);
1522
+ const sourceResult = await this.reactor.getByIdOrSlug(sourceParentIdentifier, { branch }, removeCompletedJob.consistencyToken, signal);
1523
+ const targetResult = await this.reactor.getByIdOrSlug(targetParentIdentifier, { branch }, addCompletedJob.consistencyToken, signal);
1006
1524
  return {
1007
- source: await this.reactor.getByIdOrSlug(sourceParentIdentifier, { branch }, removeCompletedJob.consistencyToken, signal),
1008
- target: await this.reactor.getByIdOrSlug(targetParentIdentifier, { branch }, addCompletedJob.consistencyToken, signal)
1525
+ source: await this.gateDocument(sourceResult, { branch }, signal),
1526
+ target: await this.gateDocument(targetResult, { branch }, signal)
1009
1527
  };
1010
1528
  }
1011
1529
  async loadBatch(request, signal) {
@@ -1078,32 +1596,56 @@ var ReactorClient = class {
1078
1596
  */
1079
1597
  subscribe(search, callback, view) {
1080
1598
  this.logger.verbose("subscribe(@search, @view)", search, view);
1599
+ const readable = async (document) => filterReadableScopes(document, await this.readableScopes(document, view));
1600
+ let disposed = false;
1601
+ let delivering = Promise.resolve();
1602
+ /**
1603
+ * Queues one event behind those already queued. Gating an event resolves
1604
+ * asynchronously, so an event needing a group fetch would otherwise be
1605
+ * overtaken by the one behind it, and one still in flight would reach a
1606
+ * subscriber that has already unsubscribed. Only delivery is ordered, not
1607
+ * the gating: a single subscription can cover every document in the
1608
+ * reactor, so serializing that work would make its delivery rate the sum
1609
+ * of every gate build rather than the slowest. An event that cannot be
1610
+ * gated is withheld, because serving it unfiltered would leak the scopes
1611
+ * the gate did not clear -- but it is logged rather than swallowed, since
1612
+ * the gate rethrows a transient failure precisely so it is not read as a
1613
+ * denial.
1614
+ */
1615
+ const deliver = (event) => {
1616
+ Promise.resolve(event).catch(() => void 0);
1617
+ delivering = delivering.then(async () => {
1618
+ const built = await event;
1619
+ if (disposed) return;
1620
+ callback(built);
1621
+ }).catch((error) => {
1622
+ this.logger.error("Subscription delivery failed for @search: @Error", { search }, error);
1623
+ });
1624
+ };
1081
1625
  const unsubscribeCreated = this.subscriptionManager.onDocumentCreated((result) => {
1082
- (async () => {
1083
- try {
1084
- const documents = await Promise.all(result.results.map((id) => this.reactor.get(id, view, void 0, void 0)));
1085
- callback({
1086
- type: DocumentChangeType.Created,
1087
- documents
1088
- });
1089
- } catch {}
1090
- })();
1626
+ deliver((async () => {
1627
+ const documents = await Promise.all(result.results.map((id) => this.reactor.get(id, withAuthScope(view), void 0, void 0)));
1628
+ return {
1629
+ type: DocumentChangeType.Created,
1630
+ documents: await Promise.all(documents.map(readable))
1631
+ };
1632
+ })());
1091
1633
  }, search);
1092
1634
  const unsubscribeDeleted = this.subscriptionManager.onDocumentDeleted((documentIds) => {
1093
- callback({
1635
+ deliver({
1094
1636
  type: DocumentChangeType.Deleted,
1095
1637
  documents: [],
1096
1638
  context: { childId: documentIds[0] }
1097
1639
  });
1098
1640
  }, search);
1099
1641
  const unsubscribeUpdated = this.subscriptionManager.onDocumentStateUpdated((result) => {
1100
- callback({
1642
+ deliver((async () => ({
1101
1643
  type: DocumentChangeType.Updated,
1102
- documents: result.results
1103
- });
1644
+ documents: await Promise.all(result.results.map(readable))
1645
+ }))());
1104
1646
  }, search, view);
1105
1647
  const unsubscribeRelationship = this.subscriptionManager.onRelationshipChanged((parentId, childId, changeType) => {
1106
- callback({
1648
+ deliver({
1107
1649
  type: changeType === RelationshipChangeType.Added ? DocumentChangeType.ChildAdded : DocumentChangeType.ChildRemoved,
1108
1650
  documents: [],
1109
1651
  context: {
@@ -1113,6 +1655,7 @@ var ReactorClient = class {
1113
1655
  });
1114
1656
  }, search);
1115
1657
  return () => {
1658
+ disposed = true;
1116
1659
  unsubscribeCreated();
1117
1660
  unsubscribeDeleted();
1118
1661
  unsubscribeUpdated();
@@ -1144,17 +1687,33 @@ let JobQueueState = /* @__PURE__ */ function(JobQueueState) {
1144
1687
  return JobQueueState;
1145
1688
  }({});
1146
1689
  /**
1690
+ * How a retry is accounted against the job's retry limit.
1691
+ * - `CountAgainstLimit` (default): a fault; the job eventually exhausts its
1692
+ * retries and fails terminally.
1693
+ * - `ExemptFromLimit`: not a fault, so the attempt is not charged to the job.
1694
+ * Used for concurrency conflicts, where the retry does new work.
1695
+ */
1696
+ let RetryAccounting = /* @__PURE__ */ function(RetryAccounting) {
1697
+ RetryAccounting["CountAgainstLimit"] = "count-against-limit";
1698
+ RetryAccounting["ExemptFromLimit"] = "exempt-from-limit";
1699
+ return RetryAccounting;
1700
+ }({});
1701
+ /**
1147
1702
  * Event types for the queue system
1148
1703
  */
1149
1704
  const QueueEventTypes = { JOB_AVAILABLE: 1e4 };
1150
1705
  //#endregion
1151
1706
  //#region src/executor/job-result-handler.ts
1707
+ /** Conflict retries a job may take without charging its retry limit. */
1708
+ const MAX_EXEMPT_CONFLICT_RETRIES = 20;
1152
1709
  function toErrorInfo(error) {
1153
1710
  if (error instanceof Error) return {
1711
+ name: error.name,
1154
1712
  message: error.message,
1155
1713
  stack: error.stack || (/* @__PURE__ */ new Error()).stack || ""
1156
1714
  };
1157
1715
  return {
1716
+ name: "Error",
1158
1717
  message: error,
1159
1718
  stack: (/* @__PURE__ */ new Error()).stack || ""
1160
1719
  };
@@ -1187,12 +1746,19 @@ var JobResultHandler = class {
1187
1746
  } catch {}
1188
1747
  }
1189
1748
  }
1190
- if (result.error && DocumentNotFoundError.isError(result.error)) {
1749
+ if (result.error && AppendConditionFailedError.isError(result.error) && this.countConflicts(handle.job) < MAX_EXEMPT_CONFLICT_RETRIES) {
1750
+ const errorInfo = toErrorInfo(result.error);
1751
+ try {
1752
+ await this.queue.retryJob(handle.job.id, errorInfo, RetryAccounting.ExemptFromLimit);
1753
+ return;
1754
+ } catch {}
1755
+ }
1756
+ if (result.error && DocumentNotFoundError.isError(result.error) && handle.job.kind === "load") {
1191
1757
  handle.defer();
1192
- callbacks.deferJob(handle.job.documentId, handle.job);
1758
+ callbacks.deferJob(result.error.documentId, handle.job);
1193
1759
  return;
1194
1760
  }
1195
- if (result.error && DocumentDeletedError.isError(result.error)) {
1761
+ if (result.error && (DocumentDeletedError.isError(result.error) || DocumentNotFoundError.isError(result.error) || AuthorizationDeniedError.isError(result.error) || AuthTimestampNotMonotonicError.isError(result.error) || InvalidOperationTimestampError.isError(result.error) || ExcessiveReshuffleError.isError(result.error) || UpgradePreconditionFailedError.isError(result.error))) {
1196
1762
  const errorInfo = toErrorInfo(result.error);
1197
1763
  this.jobTracker.markFailed(handle.job.id, errorInfo, handle.job);
1198
1764
  this.eventBus.emit(ReactorEventTypes.JOB_FAILED, {
@@ -1230,6 +1796,12 @@ var JobResultHandler = class {
1230
1796
  handle.fail(fullErrorInfo);
1231
1797
  }
1232
1798
  }
1799
+ /** How many times this job has already lost an append-condition race. */
1800
+ countConflicts(job) {
1801
+ let conflicts = 0;
1802
+ for (const error of job.errorHistory) if (AppendConditionFailedError.isFailureMessage(error.message)) conflicts++;
1803
+ return conflicts;
1804
+ }
1233
1805
  hasCreateDocumentAction(job) {
1234
1806
  for (const action of job.actions) if (action.type === "CREATE_DOCUMENT") return true;
1235
1807
  for (const operation of job.operations) if (operation.action.type === "CREATE_DOCUMENT") return true;
@@ -1245,22 +1817,134 @@ var JobResultHandler = class {
1245
1817
  stackLines.push(`[Attempt ${index + 1}] Stack trace:\n${error.stack}`);
1246
1818
  });
1247
1819
  return {
1820
+ name: currentError.name,
1248
1821
  message: messageLines.join("\n"),
1249
1822
  stack: stackLines.join("\n\n")
1250
1823
  };
1251
1824
  }
1252
1825
  };
1253
1826
  //#endregion
1254
- //#region src/executor/types.ts
1827
+ //#region src/executor/deferred-jobs.ts
1255
1828
  /**
1256
- * Event types for the job executor
1829
+ * The jobs held back because the document they write to was not there yet.
1830
+ *
1831
+ * A job whose document is missing is deferred rather than failed, because the
1832
+ * operations that create that document may still be on their way - out of order
1833
+ * from a peer, or a sibling job in the same batch. Deferring emits no event and
1834
+ * moves no job status, which is what makes it cheap: a job that gets flushed
1835
+ * runs as if it had merely waited its turn.
1836
+ *
1837
+ * That silence is also why the wait has to be bounded. A deferred job is only
1838
+ * released when a job carrying CREATE_DOCUMENT for that exact document id
1839
+ * completes, so a job deferred against an id nothing will ever create is
1840
+ * released by nothing. Its status stays RUNNING, which is not terminal, so a
1841
+ * caller awaiting it waits forever - there is no timeout on that side. The TTL
1842
+ * converts that silence into the failure the caller can act on.
1843
+ *
1844
+ * Failing through the queue rather than only the tracker matters: the queue
1845
+ * records the job as resolved, which is what unblocks anything that declared a
1846
+ * dependency on it. Deferring alone does not, so a dependent of a deferred job
1847
+ * is stranded at PENDING for as long as the deferral lasts.
1257
1848
  */
1258
- const JobExecutorEventTypes = {
1259
- JOB_STARTED: 2e4,
1260
- JOB_COMPLETED: 20001,
1261
- JOB_FAILED: 20002,
1262
- EXECUTOR_STARTED: 20003,
1263
- EXECUTOR_STOPPED: 20004
1849
+ var DeferredJobs = class {
1850
+ #byDocumentId = /* @__PURE__ */ new Map();
1851
+ #timers = /* @__PURE__ */ new Map();
1852
+ constructor(queue, jobTracker, eventBus, logger, ttlMs = DEFAULT_DEFERRED_JOB_TTL_MS, onReleased = () => Promise.resolve()) {
1853
+ this.queue = queue;
1854
+ this.jobTracker = jobTracker;
1855
+ this.eventBus = eventBus;
1856
+ this.logger = logger;
1857
+ this.ttlMs = ttlMs;
1858
+ this.onReleased = onReleased;
1859
+ }
1860
+ /**
1861
+ * Holds a job until its document arrives, or until the TTL elapses.
1862
+ *
1863
+ * A job deferred again after a flush replaces its own timer rather than
1864
+ * accumulating one, so the wait is measured from the most recent attempt.
1865
+ */
1866
+ add(documentId, job) {
1867
+ const existing = this.#byDocumentId.get(documentId) ?? [];
1868
+ existing.push(job);
1869
+ this.#byDocumentId.set(documentId, existing);
1870
+ this.#clearTimer(job.id);
1871
+ const timer = setTimeout(() => {
1872
+ this.#expire(documentId, job);
1873
+ }, this.ttlMs);
1874
+ if (typeof timer === "object" && "unref" in timer) timer.unref();
1875
+ this.#timers.set(job.id, timer);
1876
+ }
1877
+ /** Re-enqueues everything waiting on a document that has now arrived. */
1878
+ async flush(documentId) {
1879
+ const jobs = this.#byDocumentId.get(documentId);
1880
+ if (!jobs || jobs.length === 0) return;
1881
+ this.#byDocumentId.delete(documentId);
1882
+ for (const job of jobs) {
1883
+ this.#clearTimer(job.id);
1884
+ try {
1885
+ await this.queue.enqueue(job);
1886
+ } catch (error) {
1887
+ this.logger.error("Error re-enqueuing deferred job: @Error", error);
1888
+ }
1889
+ }
1890
+ }
1891
+ /**
1892
+ * Fails everything still deferred, for a reactor that is shutting down.
1893
+ *
1894
+ * The queue is deliberately not told: it is going away too, and nothing is
1895
+ * left to unblock.
1896
+ */
1897
+ failAll() {
1898
+ for (const [, jobs] of this.#byDocumentId) for (const job of jobs) {
1899
+ this.#clearTimer(job.id);
1900
+ this.#markFailed(job);
1901
+ }
1902
+ this.#byDocumentId.clear();
1903
+ }
1904
+ /** The jobs still waiting on a document. Exposed for assertions. */
1905
+ waitingOn(documentId) {
1906
+ return this.#byDocumentId.get(documentId) ?? [];
1907
+ }
1908
+ async #expire(documentId, job) {
1909
+ const jobs = this.#byDocumentId.get(documentId);
1910
+ if (!jobs?.includes(job)) return;
1911
+ const remaining = jobs.filter((held) => held !== job);
1912
+ if (remaining.length === 0) this.#byDocumentId.delete(documentId);
1913
+ else this.#byDocumentId.set(documentId, remaining);
1914
+ this.#timers.delete(job.id);
1915
+ this.logger.error("Deferred job @jobId gave up waiting for document @documentId after @ttlMs ms", job.id, documentId, this.ttlMs);
1916
+ const errorInfo = this.#markFailed(job);
1917
+ try {
1918
+ await this.queue.failJob(job.id, errorInfo);
1919
+ } catch (error) {
1920
+ this.logger.error("Error failing an expired deferred job: @Error", error);
1921
+ return;
1922
+ }
1923
+ this.jobTracker.markFailed(job.id, errorInfo, job);
1924
+ try {
1925
+ await this.onReleased();
1926
+ } catch (error) {
1927
+ this.logger.error("Error dispatching after a deferred job expired: @Error", error);
1928
+ }
1929
+ }
1930
+ #markFailed(job) {
1931
+ const error = new DocumentNotFoundError(job.documentId);
1932
+ const errorInfo = toErrorInfo(error);
1933
+ this.jobTracker.markFailed(job.id, errorInfo, job);
1934
+ this.eventBus.emit(ReactorEventTypes.JOB_FAILED, {
1935
+ jobId: job.id,
1936
+ error,
1937
+ job
1938
+ }).catch(() => {});
1939
+ return errorInfo;
1940
+ }
1941
+ #clearTimer(jobId) {
1942
+ const timer = this.#timers.get(jobId);
1943
+ if (timer !== void 0) {
1944
+ clearTimeout(timer);
1945
+ this.#timers.delete(jobId);
1946
+ }
1947
+ }
1264
1948
  };
1265
1949
  //#endregion
1266
1950
  //#region src/executor/worker-pool-router.ts
@@ -1332,10 +2016,10 @@ var WorkerPoolJobExecutorManager = class {
1332
2016
  activeJobs = 0;
1333
2017
  totalJobsProcessed = 0;
1334
2018
  unsubscribe;
1335
- deferredJobs = /* @__PURE__ */ new Map();
2019
+ deferredJobs;
1336
2020
  resultHandler;
1337
2021
  jobTimeoutMs;
1338
- constructor(workerFactory, eventBus, queue, jobTracker, logger, resolver, collectionMembershipCache, jobTimeoutMs = 3e4) {
2022
+ constructor(workerFactory, eventBus, queue, jobTracker, logger, resolver, collectionMembershipCache, jobTimeoutMs = 3e4, deferredJobTtlMs = DEFAULT_DEFERRED_JOB_TTL_MS) {
1339
2023
  this.workerFactory = workerFactory;
1340
2024
  this.eventBus = eventBus;
1341
2025
  this.queue = queue;
@@ -1344,6 +2028,7 @@ var WorkerPoolJobExecutorManager = class {
1344
2028
  this.resolver = resolver;
1345
2029
  this.collectionMembershipCache = collectionMembershipCache;
1346
2030
  this.jobTimeoutMs = jobTimeoutMs;
2031
+ this.deferredJobs = new DeferredJobs(queue, jobTracker, eventBus, logger, deferredJobTtlMs, () => this.tryDispatchAll());
1347
2032
  this.resultHandler = new JobResultHandler(queue, jobTracker, eventBus, resolver, logger);
1348
2033
  }
1349
2034
  async start(numWorkers) {
@@ -1364,16 +2049,7 @@ var WorkerPoolJobExecutorManager = class {
1364
2049
  this.unsubscribe = void 0;
1365
2050
  }
1366
2051
  if (graceful) while (this.activeJobs > 0) await new Promise((resolve) => setTimeout(resolve, 10));
1367
- for (const [, jobs] of this.deferredJobs) for (const job of jobs) {
1368
- const errorInfo = toErrorInfo(new DocumentNotFoundError(job.documentId));
1369
- this.jobTracker.markFailed(job.id, errorInfo, job);
1370
- this.eventBus.emit(ReactorEventTypes.JOB_FAILED, {
1371
- jobId: job.id,
1372
- error: new DocumentNotFoundError(job.documentId),
1373
- job
1374
- }).catch(() => {});
1375
- }
1376
- this.deferredJobs.clear();
2052
+ this.deferredJobs.failAll();
1377
2053
  await Promise.all(this.workers.map((w) => w.shutdown(graceful).catch((err) => {
1378
2054
  this.logger.warn("worker shutdown failed: @Error", err);
1379
2055
  })));
@@ -1495,12 +2171,8 @@ var WorkerPoolJobExecutorManager = class {
1495
2171
  this.logger.error("emitWriteReady failed for job @jobId: @Error", { jobId: handle.job.id }, error);
1496
2172
  });
1497
2173
  await this.resultHandler.handleResult(handle, outcome.result, {
1498
- deferJob: (documentId, job) => {
1499
- const existing = this.deferredJobs.get(documentId) ?? [];
1500
- existing.push(job);
1501
- this.deferredJobs.set(documentId, existing);
1502
- },
1503
- flushDeferredFor: (documentId) => this.flushDeferredJobs(documentId)
2174
+ deferJob: (documentId, job) => this.deferredJobs.add(documentId, job),
2175
+ flushDeferredFor: (documentId) => this.deferredJobs.flush(documentId)
1504
2176
  });
1505
2177
  this.activeJobs--;
1506
2178
  await this.tryDispatchFor(worker);
@@ -1582,16 +2254,6 @@ var WorkerPoolJobExecutorManager = class {
1582
2254
  this.workers[deadIndex] = fresh;
1583
2255
  await this.tryDispatchFor(fresh);
1584
2256
  }
1585
- async flushDeferredJobs(documentId) {
1586
- const jobs = this.deferredJobs.get(documentId);
1587
- if (!jobs || jobs.length === 0) return;
1588
- this.deferredJobs.delete(documentId);
1589
- for (const job of jobs) try {
1590
- await this.queue.enqueue(job);
1591
- } catch (error) {
1592
- this.logger.error("Error re-enqueuing deferred job: @Error", error);
1593
- }
1594
- }
1595
2257
  };
1596
2258
  function isWorkerTransportError(error) {
1597
2259
  return error instanceof WorkerExitedError || error instanceof WorkerInitFailedError || error instanceof WorkerAbortTimeoutError;
@@ -1620,10 +2282,10 @@ var SimpleJobExecutorManager = class {
1620
2282
  activeJobs = 0;
1621
2283
  totalJobsProcessed = 0;
1622
2284
  unsubscribe;
1623
- deferredJobs = /* @__PURE__ */ new Map();
2285
+ deferredJobs;
1624
2286
  resultHandler;
1625
2287
  jobTimeoutMs;
1626
- constructor(executorFactory, eventBus, queue, jobTracker, logger, resolver, jobTimeoutMs = 3e4) {
2288
+ constructor(executorFactory, eventBus, queue, jobTracker, logger, resolver, jobTimeoutMs = 3e4, deferredJobTtlMs = DEFAULT_DEFERRED_JOB_TTL_MS) {
1627
2289
  this.executorFactory = executorFactory;
1628
2290
  this.eventBus = eventBus;
1629
2291
  this.queue = queue;
@@ -1631,6 +2293,7 @@ var SimpleJobExecutorManager = class {
1631
2293
  this.logger = logger;
1632
2294
  this.resolver = resolver;
1633
2295
  this.jobTimeoutMs = jobTimeoutMs;
2296
+ this.deferredJobs = new DeferredJobs(queue, jobTracker, eventBus, logger, deferredJobTtlMs, () => this.checkForMoreJobs());
1634
2297
  this.resultHandler = new JobResultHandler(queue, jobTracker, eventBus, resolver, logger);
1635
2298
  }
1636
2299
  async start(numExecutors) {
@@ -1651,16 +2314,7 @@ var SimpleJobExecutorManager = class {
1651
2314
  this.unsubscribe = void 0;
1652
2315
  }
1653
2316
  if (graceful) while (this.activeJobs > 0) await new Promise((resolve) => setTimeout(resolve, 100));
1654
- for (const [, jobs] of this.deferredJobs) for (const job of jobs) {
1655
- const errorInfo = toErrorInfo(new DocumentNotFoundError(job.documentId));
1656
- this.jobTracker.markFailed(job.id, errorInfo, job);
1657
- this.eventBus.emit(ReactorEventTypes.JOB_FAILED, {
1658
- jobId: job.id,
1659
- error: new DocumentNotFoundError(job.documentId),
1660
- job
1661
- }).catch(() => {});
1662
- }
1663
- this.deferredJobs.clear();
2317
+ this.deferredJobs.failAll();
1664
2318
  this.executors = [];
1665
2319
  this.isRunning = false;
1666
2320
  }
@@ -1753,12 +2407,8 @@ var SimpleJobExecutorManager = class {
1753
2407
  this.eventBus.emit(JobExecutorEventTypes.JOB_FAILED, failedEvent).catch(() => {});
1754
2408
  }
1755
2409
  await this.resultHandler.handleResult(handle, result, {
1756
- deferJob: (documentId, job) => {
1757
- const existing = this.deferredJobs.get(documentId) ?? [];
1758
- existing.push(job);
1759
- this.deferredJobs.set(documentId, existing);
1760
- },
1761
- flushDeferredFor: (documentId) => this.flushDeferredJobs(documentId)
2410
+ deferJob: (documentId, job) => this.deferredJobs.add(documentId, job),
2411
+ flushDeferredFor: (documentId) => this.deferredJobs.flush(documentId)
1762
2412
  });
1763
2413
  this.activeJobs--;
1764
2414
  await this.checkForMoreJobs();
@@ -1792,16 +2442,6 @@ var SimpleJobExecutorManager = class {
1792
2442
  }
1793
2443
  }
1794
2444
  }
1795
- async flushDeferredJobs(documentId) {
1796
- const jobs = this.deferredJobs.get(documentId);
1797
- if (!jobs || jobs.length === 0) return;
1798
- this.deferredJobs.delete(documentId);
1799
- for (const job of jobs) try {
1800
- await this.queue.enqueue(job);
1801
- } catch (error) {
1802
- this.logger.error("Error re-enqueuing deferred job: @Error", error);
1803
- }
1804
- }
1805
2445
  };
1806
2446
  //#endregion
1807
2447
  //#region src/job-tracker/in-memory-job-tracker.ts
@@ -1850,6 +2490,7 @@ var InMemoryJobTracker = class {
1850
2490
  }
1851
2491
  handleJobFailed(event) {
1852
2492
  this.markFailed(event.jobId, {
2493
+ name: event.error.name,
1853
2494
  message: event.error.message,
1854
2495
  stack: event.error.stack || ""
1855
2496
  }, event.job);
@@ -1958,6 +2599,26 @@ function matchesFilter(op, filter) {
1958
2599
  }
1959
2600
  return true;
1960
2601
  }
2602
+ function nonEmpty(value) {
2603
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2604
+ }
2605
+ function namespaceOf(processor) {
2606
+ return nonEmpty(processor.namespace);
2607
+ }
2608
+ function classNameOf(processor) {
2609
+ const name = processor.constructor.name;
2610
+ return name && name !== "Object" ? name : void 0;
2611
+ }
2612
+ function resolveProcessorSlots(records, legacy) {
2613
+ if (legacy) return records.map((_, i) => String(i));
2614
+ const seen = /* @__PURE__ */ new Map();
2615
+ return records.map((record, i) => {
2616
+ const base = nonEmpty(record.id) ?? namespaceOf(record.processor) ?? classNameOf(record.processor) ?? String(i);
2617
+ const count = seen.get(base) ?? 0;
2618
+ seen.set(base, count + 1);
2619
+ return count === 0 ? base : `${base}#${count}`;
2620
+ });
2621
+ }
1961
2622
  //#endregion
1962
2623
  //#region src/processors/processor-manager.ts
1963
2624
  /**
@@ -1979,13 +2640,15 @@ var ProcessorManager = class extends BaseReadModel {
1979
2640
  cursorCache = /* @__PURE__ */ new Map();
1980
2641
  logger;
1981
2642
  driveContainerTypes;
1982
- constructor(db, operationIndex, writeCache, consistencyTracker, logger, driveContainerTypes) {
2643
+ legacyProcessorIds;
2644
+ constructor(db, operationIndex, writeCache, consistencyTracker, logger, driveContainerTypes, options = {}) {
1983
2645
  super(db, operationIndex, writeCache, consistencyTracker, {
1984
2646
  readModelId: "processor-manager",
1985
2647
  rebuildStateOnInit: true
1986
2648
  });
1987
2649
  this.logger = logger;
1988
2650
  this.driveContainerTypes = driveContainerTypes;
2651
+ this.legacyProcessorIds = options.legacyProcessorIds ?? true;
1989
2652
  }
1990
2653
  async init() {
1991
2654
  await super.init();
@@ -2072,9 +2735,10 @@ var ProcessorManager = class extends BaseReadModel {
2072
2735
  }
2073
2736
  if (records.length === 0) return;
2074
2737
  const trackedList = [];
2738
+ const slots = resolveProcessorSlots(records, this.legacyProcessorIds);
2075
2739
  for (let i = 0; i < records.length; i++) {
2076
2740
  const record = records[i];
2077
- const processorId = `${identifier}:${driveId}:${i}`;
2741
+ const processorId = `${identifier}:${driveId}:${slots[i]}`;
2078
2742
  const cached = this.cursorCache.get(processorId);
2079
2743
  let lastOrdinal;
2080
2744
  let status;
@@ -2106,8 +2770,9 @@ var ProcessorManager = class extends BaseReadModel {
2106
2770
  trackedList.push(tracked);
2107
2771
  await this.saveProcessorCursor(tracked);
2108
2772
  }
2109
- await this.db.deleteFrom("ProcessorCursor").where("factoryId", "=", identifier).where("driveId", "=", driveId).where("processorIndex", ">=", records.length).execute();
2110
- for (const [id, row] of this.cursorCache) if (row.factoryId === identifier && row.driveId === driveId && row.processorIndex >= records.length) this.cursorCache.delete(id);
2773
+ const liveIds = new Set(trackedList.map((t) => t.processorId));
2774
+ await this.db.deleteFrom("ProcessorCursor").where("factoryId", "=", identifier).where("driveId", "=", driveId).where("processorId", "not in", [...liveIds]).execute();
2775
+ for (const [id, row] of this.cursorCache) if (row.factoryId === identifier && row.driveId === driveId && !liveIds.has(id)) this.cursorCache.delete(id);
2111
2776
  const factoryProcessors = this.factoryToProcessors.get(identifier);
2112
2777
  if (factoryProcessors) factoryProcessors.set(driveId, trackedList);
2113
2778
  const existingDriveProcessors = this.processorsByDrive.get(driveId) ?? [];
@@ -2311,10 +2976,12 @@ var InMemoryQueue = class {
2311
2976
  }
2312
2977
  toErrorInfo(error) {
2313
2978
  if (error instanceof Error) return {
2979
+ name: error.name,
2314
2980
  message: error.message,
2315
2981
  stack: error.stack || (/* @__PURE__ */ new Error()).stack || ""
2316
2982
  };
2317
2983
  return {
2984
+ name: "Error",
2318
2985
  message: error,
2319
2986
  stack: (/* @__PURE__ */ new Error()).stack || ""
2320
2987
  };
@@ -2402,6 +3069,7 @@ var InMemoryQueue = class {
2402
3069
  await this.resolver.ensureModelLoaded(documentType);
2403
3070
  } catch {
2404
3071
  await this.failJob(job.id, {
3072
+ name: "Error",
2405
3073
  message: `Failed to load document model for type: ${documentType}`,
2406
3074
  stack: (/* @__PURE__ */ new Error()).stack || ""
2407
3075
  });
@@ -2575,9 +3243,11 @@ var InMemoryQueue = class {
2575
3243
  this.jobIndex.delete(jobId);
2576
3244
  this.completedJobs.add(jobId);
2577
3245
  await this.remove(jobId);
3246
+ const emittedError = new Error(error?.message ?? "Job failed");
3247
+ if (error?.name) emittedError.name = error.name;
2578
3248
  this.eventBus.emit(ReactorEventTypes.JOB_FAILED, {
2579
3249
  jobId,
2580
- error: new Error(error?.message ?? "Job failed"),
3250
+ error: emittedError,
2581
3251
  job
2582
3252
  }).catch(() => {});
2583
3253
  this.checkDrained();
@@ -2587,7 +3257,7 @@ var InMemoryQueue = class {
2587
3257
  if (documentId) this.markJobComplete(jobId, documentId);
2588
3258
  this.jobIndex.delete(jobId);
2589
3259
  }
2590
- async retryJob(jobId, error) {
3260
+ async retryJob(jobId, error, accounting = RetryAccounting.CountAgainstLimit) {
2591
3261
  const job = this.jobIndex.get(jobId);
2592
3262
  if (!job) return;
2593
3263
  job.lastError = error;
@@ -2596,9 +3266,10 @@ var InMemoryQueue = class {
2596
3266
  this.jobIndex.delete(jobId);
2597
3267
  this.jobIdToQueueKey.delete(jobId);
2598
3268
  if (error) job.errorHistory.push(error);
3269
+ const retryCount = job.retryCount || 0;
2599
3270
  const updatedJob = {
2600
3271
  ...job,
2601
- retryCount: (job.retryCount || 0) + 1,
3272
+ retryCount: accounting === RetryAccounting.CountAgainstLimit ? retryCount + 1 : retryCount,
2602
3273
  lastError: error
2603
3274
  };
2604
3275
  await this.enqueue(updatedJob);
@@ -3116,6 +3787,83 @@ var SubscriptionNotificationReadModel = class {
3116
3787
  }
3117
3788
  };
3118
3789
  //#endregion
3790
+ //#region src/core/group-reevaluation-trigger.ts
3791
+ /**
3792
+ * Watches committed writes for group membership changes and enqueues a
3793
+ * re-evaluation job for every document whose auth history references the
3794
+ * changed group, found through the reverse direction of the group-reference
3795
+ * relation. Each affected document is re-judged in its own job, so the work
3796
+ * runs under that document's execution slot rather than the group's.
3797
+ *
3798
+ * The job carries the earliest changed membership timestamp; the executor
3799
+ * skips the pass when everything the document holds sorts before it, which
3800
+ * keeps the common case (a membership write later than all history) free.
3801
+ */
3802
+ var GroupReevaluationTrigger = class {
3803
+ unsubscribe;
3804
+ constructor(logger, eventBus, queue, operationIndex) {
3805
+ this.logger = logger;
3806
+ this.eventBus = eventBus;
3807
+ this.queue = queue;
3808
+ this.operationIndex = operationIndex;
3809
+ }
3810
+ startup() {
3811
+ this.unsubscribe = this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY, async (_type, event) => this.onWriteReady(event));
3812
+ }
3813
+ shutdown() {
3814
+ this.unsubscribe?.();
3815
+ this.unsubscribe = void 0;
3816
+ }
3817
+ async onWriteReady(event) {
3818
+ const changed = /* @__PURE__ */ new Map();
3819
+ for (const { operation, context } of event.operations) {
3820
+ if (context.documentType !== groupDocumentType || context.scope !== "global" || !groupMembershipActionTypes.includes(operation.action.type)) continue;
3821
+ const existing = changed.get(context.documentId);
3822
+ if (existing === void 0 || Date.parse(operation.timestampUtcMs) < Date.parse(existing)) changed.set(context.documentId, operation.timestampUtcMs);
3823
+ }
3824
+ if (changed.size === 0) return;
3825
+ const affected = /* @__PURE__ */ new Map();
3826
+ for (const [groupId, timestamp] of changed) {
3827
+ let referencers;
3828
+ try {
3829
+ referencers = await this.operationIndex.getGroupReferencers(groupId);
3830
+ } catch (error) {
3831
+ this.logger.error("Failed to resolve referencers of group @groupId: @error", groupId, error);
3832
+ continue;
3833
+ }
3834
+ for (const documentId of referencers) {
3835
+ const existing = affected.get(documentId);
3836
+ if (existing === void 0 || Date.parse(timestamp) < Date.parse(existing)) affected.set(documentId, timestamp);
3837
+ }
3838
+ }
3839
+ for (const [documentId, timestamp] of affected) {
3840
+ const jobId = v4();
3841
+ const job = {
3842
+ id: jobId,
3843
+ kind: "reevaluation",
3844
+ documentId,
3845
+ scope: "global",
3846
+ branch: "main",
3847
+ actions: [],
3848
+ operations: [],
3849
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3850
+ queueHint: [],
3851
+ maxRetries: 3,
3852
+ errorHistory: [],
3853
+ meta: {
3854
+ ...buildSingleJobMeta(jobId),
3855
+ triggerTimestampUtcMs: timestamp
3856
+ }
3857
+ };
3858
+ try {
3859
+ await this.queue.enqueue(job);
3860
+ } catch (error) {
3861
+ this.logger.error("Failed to enqueue re-evaluation of @documentId: @error", documentId, error);
3862
+ }
3863
+ }
3864
+ }
3865
+ };
3866
+ //#endregion
3119
3867
  //#region src/sync/types.ts
3120
3868
  let ChannelScheme = /* @__PURE__ */ function(ChannelScheme) {
3121
3869
  ChannelScheme["CONNECT"] = "connect";
@@ -3407,13 +4155,42 @@ var BufferedMailbox = class {
3407
4155
  var GraphQLRequestError = class extends Error {
3408
4156
  statusCode;
3409
4157
  category;
3410
- constructor(message, category, statusCode) {
4158
+ /**
4159
+ * One entry per error the response carried, in order, holding its
4160
+ * `extensions.code` - undefined where it declared none. Kept per error rather
4161
+ * than as a set, because a response that mixes a classified error with an
4162
+ * unclassified one must not be read as if only the classified one arrived.
4163
+ */
4164
+ codes;
4165
+ constructor(message, category, statusCode, codes = []) {
3411
4166
  super(message);
3412
4167
  this.name = "GraphQLRequestError";
3413
4168
  this.category = category;
3414
4169
  this.statusCode = statusCode;
4170
+ this.codes = codes;
3415
4171
  }
3416
4172
  };
4173
+ /**
4174
+ * Extension codes a remote uses to say a failure is worth polling through.
4175
+ *
4176
+ * Shared with reactor-api so the server throws what this check reads and the two
4177
+ * cannot drift. A `graphql` category error is otherwise permanent: it stops the
4178
+ * poll timer, and nothing restarts it, so a code that lands here is the
4179
+ * difference between a channel that recovers and one that is dead for the
4180
+ * process lifetime.
4181
+ */
4182
+ const RECOVERABLE_GRAPHQL_ERROR_CODES = { malformedStoredOperation: "MALFORMED_STORED_OPERATION" };
4183
+ const RECOVERABLE_CODES = new Set(Object.values(RECOVERABLE_GRAPHQL_ERROR_CODES));
4184
+ /**
4185
+ * True when every error the response carried named a recoverable code.
4186
+ *
4187
+ * Unanimity is the requirement: one unclassified error alongside a recoverable
4188
+ * one means something else also went wrong, and polling through that would be
4189
+ * guessing.
4190
+ */
4191
+ function isRecoverableGraphQLError(error) {
4192
+ return error.codes.length > 0 && error.codes.every((code) => code !== void 0 && RECOVERABLE_CODES.has(code));
4193
+ }
3417
4194
  /** Auth-rejection message fragments the switchboard emits. Shared with
3418
4195
  * reactor-api so server throws and this client check can't drift. */
3419
4196
  const DRIVE_AUTH_ERROR_MESSAGES = {
@@ -3437,11 +4214,18 @@ var PollingChannelError = class extends Error {
3437
4214
  var ChannelError = class extends Error {
3438
4215
  source;
3439
4216
  error;
3440
- constructor(source, error) {
4217
+ /**
4218
+ * The classification when something other than the error carries it. Absent
4219
+ * means derive it from `error.name`; a dead letter mirrored from a peer sets it,
4220
+ * because only the message crosses the wire.
4221
+ */
4222
+ errorType;
4223
+ constructor(source, error, errorType) {
3441
4224
  super(`ChannelError[${source}]: ${error.message}`);
3442
4225
  this.name = "ChannelError";
3443
4226
  this.source = source;
3444
4227
  this.error = error;
4228
+ this.errorType = errorType;
3445
4229
  }
3446
4230
  };
3447
4231
  //#endregion
@@ -3646,6 +4430,7 @@ function toOperationWithContext(entry) {
3646
4430
  skip: entry.skip,
3647
4431
  hash: entry.hash,
3648
4432
  timestampUtcMs: entry.timestampUtcMs,
4433
+ deniedReason: entry.deniedReason,
3649
4434
  action: entry.action
3650
4435
  },
3651
4436
  context: {
@@ -3662,29 +4447,35 @@ function toOperationWithContext(entry) {
3662
4447
  * a single SyncOperation per group. Within each group, operations are sorted
3663
4448
  * by context.ordinal. The merged SyncOperation keeps the first group member's
3664
4449
  * jobId; all other jobIds are remapped so external dependencies still resolve.
4450
+ *
4451
+ * Only CONTIGUOUS runs merge. A document whose scopes interleave arrives as an
4452
+ * alternating chain (document -> auth -> document -> auth) where each entry
4453
+ * depends on the one before it. Merging every occurrence of a
4454
+ * (documentId, scope, branch) collapses that chain into two nodes that each
4455
+ * depend on the other, which validateBatchStructure rejects as a dependency
4456
+ * cycle. Merging only adjacent entries keeps the chain linear.
3665
4457
  */
3666
4458
  function consolidateSyncOperations(syncOps) {
3667
4459
  if (syncOps.length <= 1) return syncOps;
3668
- const groups = /* @__PURE__ */ new Map();
4460
+ const groups = [];
3669
4461
  const jobIdRemap = /* @__PURE__ */ new Map();
3670
- const insertionOrder = [];
4462
+ let prevKey = null;
3671
4463
  for (const syncOp of syncOps) {
3672
4464
  const key = `${syncOp.documentId}|${syncOp.scopes.slice().sort().join(",")}|${syncOp.branch}`;
3673
- const existing = groups.get(key);
3674
- if (existing) {
3675
- existing.ops.push(syncOp);
3676
- if (syncOp.jobId && syncOp.jobId !== existing.canonicalJobId) jobIdRemap.set(syncOp.jobId, existing.canonicalJobId);
4465
+ const current = key === prevKey ? groups[groups.length - 1] : void 0;
4466
+ if (current) {
4467
+ current.ops.push(syncOp);
4468
+ if (syncOp.jobId && syncOp.jobId !== current.canonicalJobId) jobIdRemap.set(syncOp.jobId, current.canonicalJobId);
3677
4469
  } else {
3678
- groups.set(key, {
4470
+ groups.push({
3679
4471
  ops: [syncOp],
3680
4472
  canonicalJobId: syncOp.jobId
3681
4473
  });
3682
- insertionOrder.push(key);
4474
+ prevKey = key;
3683
4475
  }
3684
4476
  }
3685
4477
  const result = [];
3686
- for (const key of insertionOrder) {
3687
- const group = groups.get(key);
4478
+ for (const group of groups) {
3688
4479
  const allOperations = group.ops.flatMap((op) => op.operations).sort((a, b) => a.context.ordinal - b.context.ordinal);
3689
4480
  const allDeps = /* @__PURE__ */ new Set();
3690
4481
  for (const op of group.ops) for (const dep of op.jobDependencies) allDeps.add(dep);
@@ -3811,6 +4602,33 @@ function splitComponent(items, maxSize) {
3811
4602
  for (let i = 0; i < sorted.length; i += maxSize) chunks.push(sorted.slice(i, i + maxSize));
3812
4603
  return chunks;
3813
4604
  }
4605
+ /**
4606
+ * Classifies a failure by error name rather than `instanceof`, because a failure
4607
+ * that crossed the pooled-worker boundary arrives as plain data.
4608
+ */
4609
+ function classifyJobFailure(errorName) {
4610
+ switch (errorName) {
4611
+ case "AuthTimestampNotMonotonicError": return "AUTH_TIMESTAMP_NOT_MONOTONIC";
4612
+ case "InvalidOperationTimestampError": return "INVALID_TIMESTAMP";
4613
+ case "ExcessiveReshuffleError": return "EXCESSIVE_SHUFFLE";
4614
+ case "InvalidSignatureError": return "SIGNATURE_INVALID";
4615
+ case "HashMismatchError": return "HASH_MISMATCH";
4616
+ default: return "UNCLASSIFIED";
4617
+ }
4618
+ }
4619
+ /** The explicit type when something else carried it, else derived by name. */
4620
+ function syncOperationErrorType(error) {
4621
+ return error?.errorType ?? classifyJobFailure(error?.error?.name ?? "Error");
4622
+ }
4623
+ /** Dead-letter types that must not stop the document syncing. */
4624
+ const NON_QUARANTINING_ERROR_TYPES = new Set(["AUTH_TIMESTAMP_NOT_MONOTONIC"]);
4625
+ /**
4626
+ * A held auth operation must not quarantine: reconciling the two policies needs
4627
+ * the traffic a quarantine would stop.
4628
+ */
4629
+ function quarantinesDocument(errorType) {
4630
+ return !NON_QUARANTINING_ERROR_TYPES.has(errorType);
4631
+ }
3814
4632
  //#endregion
3815
4633
  //#region src/sync/channels/interval-poll-timer.ts
3816
4634
  const DEFAULT_CONFIG = {
@@ -3924,36 +4742,15 @@ var IntervalPollTimer = class {
3924
4742
  //#region src/sync/channels/utils.ts
3925
4743
  let syncOpCounter = 0;
3926
4744
  /**
3927
- * Serializes an action for GraphQL transport, converting signature tuples to strings.
4745
+ * Serializes an action for GraphQL transport.
3928
4746
  *
3929
- * Only the fields declared by the GraphQL `ActionInput` type are forwarded. This
3930
- * guards against stale runtime-only fields (e.g. a legacy `attachments` array on
3931
- * operations persisted before the attachment-system removal) leaking into the
3932
- * mutation variables, where the tightened schema would reject them.
4747
+ * Projects onto exactly the fields `ActionInput` declares, which is what keeps a
4748
+ * stale runtime-only field - a legacy `attachments` array, say - from riding
4749
+ * along into the mutation variables, where the schema would reject the whole
4750
+ * request rather than the field.
3933
4751
  */
3934
4752
  function serializeAction(action) {
3935
- const base = {
3936
- id: action.id,
3937
- type: action.type,
3938
- timestampUtcMs: action.timestampUtcMs,
3939
- input: action.input,
3940
- scope: action.scope
3941
- };
3942
- const signer = action.context?.signer;
3943
- if (!signer?.signatures) return action.context ? {
3944
- ...base,
3945
- context: action.context
3946
- } : base;
3947
- return {
3948
- ...base,
3949
- context: {
3950
- ...action.context,
3951
- signer: {
3952
- ...signer,
3953
- signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
3954
- }
3955
- }
3956
- };
4753
+ return toTransportAction(action);
3957
4754
  }
3958
4755
  /**
3959
4756
  * Serializes a SyncEnvelope for GraphQL transport.
@@ -3973,6 +4770,7 @@ function serializeEnvelope(envelope) {
3973
4770
  hash: opWithContext.operation.hash,
3974
4771
  skip: opWithContext.operation.skip,
3975
4772
  error: opWithContext.operation.error,
4773
+ ...opWithContext.operation.deniedReason !== void 0 ? { deniedReason: opWithContext.operation.deniedReason } : {},
3976
4774
  id: opWithContext.operation.id,
3977
4775
  action: serializeAction(opWithContext.operation.action)
3978
4776
  },
@@ -3990,31 +4788,33 @@ function serializeEnvelope(envelope) {
3990
4788
  };
3991
4789
  }
3992
4790
  /**
3993
- * Deserializes a signature from a comma-separated string back to a tuple.
3994
- *
3995
- * GraphQL serializes Signature tuples as comma-separated strings for transport.
3996
- * This function converts them back to the expected [string, string, string, string, string] format.
4791
+ * `isDenied` tests strictly against undefined, so a null left in place would mark
4792
+ * every synced operation denied. The key is removed rather than set to undefined,
4793
+ * so an operation that arrived without it stays identical to the one sent.
3997
4794
  */
3998
- function deserializeSignature(sig) {
3999
- if (Array.isArray(sig)) return sig;
4000
- return sig.split(", ");
4795
+ function normalizeAbsentFields(operation) {
4796
+ const wire = operation;
4797
+ if (wire.error !== null && wire.deniedReason !== null) return operation;
4798
+ const normalized = { ...operation };
4799
+ if (wire.error === null) delete normalized.error;
4800
+ if (wire.deniedReason === null) delete normalized.deniedReason;
4801
+ return normalized;
4001
4802
  }
4002
- /**
4003
- * Deserializes signatures in an operation's signer context from strings back to tuples.
4004
- *
4005
- * When operations are transported via GraphQL, signatures are serialized as comma-separated
4006
- * strings. This function restores them to the Signature tuple format required for verification.
4007
- */
4008
- function deserializeOperationSignatures(opWithContext) {
4009
- const signer = opWithContext.operation.action.context?.signer;
4010
- if (!signer?.signatures || signer.signatures.length === 0) return opWithContext;
4803
+ /** Restores signature tuples and null-valued optional fields to undefined. */
4804
+ function deserializeOperation(opWithContext) {
4805
+ const operation = normalizeAbsentFields(opWithContext.operation);
4806
+ const signer = operation.action.context?.signer;
4807
+ if (!signer?.signatures || signer.signatures.length === 0) return {
4808
+ ...opWithContext,
4809
+ operation
4810
+ };
4011
4811
  const deserializedSignatures = signer.signatures.map(deserializeSignature);
4012
4812
  const deserializedOperation = {
4013
- ...opWithContext.operation,
4813
+ ...operation,
4014
4814
  action: {
4015
- ...opWithContext.operation.action,
4815
+ ...operation.action,
4016
4816
  context: {
4017
- ...opWithContext.operation.action.context,
4817
+ ...operation.action.context,
4018
4818
  signer: {
4019
4819
  ...signer,
4020
4820
  signatures: deserializedSignatures
@@ -4041,7 +4841,7 @@ function deserializeOperationSignatures(opWithContext) {
4041
4841
  */
4042
4842
  function envelopesToSyncOperations(envelope, remoteName) {
4043
4843
  if (!envelope.operations || envelope.operations.length === 0) return [];
4044
- return batchOperationsByDocument(envelope.operations.map(deserializeOperationSignatures)).map((batch) => {
4844
+ return batchOperationsByDocument(envelope.operations.map(deserializeOperation)).map((batch) => {
4045
4845
  return new SyncOperation(`syncop-${envelope.channelMeta.id}-${Date.now()}-${syncOpCounter++}`, envelope.key ?? "", (envelope.dependsOn ?? []).filter(Boolean), remoteName, batch.documentId, [batch.scope], batch.branch, batch.operations);
4046
4846
  });
4047
4847
  }
@@ -4053,6 +4853,12 @@ const getLatestAppliedOrdinal = (syncOps) => {
4053
4853
  //#endregion
4054
4854
  //#region src/sync/channels/gql-req-channel.ts
4055
4855
  /**
4856
+ * Fields the auth projection added to the sync schema. A remote that predates
4857
+ * them rejects the whole query for naming one, so they are selected only while
4858
+ * the remote is known to serve them.
4859
+ */
4860
+ const DECISION_FIELDS = ["deniedReason", "errorType"];
4861
+ /**
4056
4862
  * GraphQL-based synchronization channel for network communication between reactors.
4057
4863
  */
4058
4864
  var GqlRequestChannel = class {
@@ -4079,6 +4885,8 @@ var GqlRequestChannel = class {
4079
4885
  isPushing = false;
4080
4886
  pendingDrain = false;
4081
4887
  receivingPages = false;
4888
+ /** Cleared for good the first time the remote rejects {@link DECISION_FIELDS}. */
4889
+ peerServesDecisionFields = true;
4082
4890
  isRecovering = false;
4083
4891
  connectionState = "connecting";
4084
4892
  /** Latest unrecoverable error was an auth rejection; cleared on connect. */
@@ -4257,7 +5065,7 @@ var GqlRequestChannel = class {
4257
5065
  const syncOps = [];
4258
5066
  for (const dl of deadLetters) {
4259
5067
  const syncOp = new SyncOperation(crypto.randomUUID(), dl.jobId, [], this.remoteName, dl.documentId, dl.scopes, dl.branch, []);
4260
- syncOp.failed(new ChannelError(ChannelErrorSource.Outbox, new Error(dl.error)));
5068
+ syncOp.failed(new ChannelError(ChannelErrorSource.Outbox, new Error(dl.error), dl.errorType ?? void 0));
4261
5069
  syncOps.push(syncOp);
4262
5070
  }
4263
5071
  this.deadLetter.add(...syncOps);
@@ -4349,7 +5157,44 @@ var GqlRequestChannel = class {
4349
5157
  * Queries the remote GraphQL endpoint for sync envelopes.
4350
5158
  */
4351
5159
  async pollSyncEnvelopes(ackOrdinal, latestOrdinal) {
4352
- const query = `
5160
+ const variables = {
5161
+ channelId: this.channelId,
5162
+ outboxAck: ackOrdinal,
5163
+ outboxLatest: latestOrdinal
5164
+ };
5165
+ let response;
5166
+ try {
5167
+ response = await this.executeGraphQL(this.pollQuery(this.peerServesDecisionFields), variables);
5168
+ } catch (error) {
5169
+ if (!this.rejectsDecisionFields(error)) throw error;
5170
+ this.logger.warn("Remote @channelId does not serve deniedReason/errorType; polling without them. The remote is on an older schema, so it has neither to report.", this.channelId);
5171
+ this.peerServesDecisionFields = false;
5172
+ response = await this.executeGraphQL(this.pollQuery(false), variables);
5173
+ }
5174
+ return {
5175
+ envelopes: response.pollSyncEnvelopes.envelopes,
5176
+ ackOrdinal: response.pollSyncEnvelopes.ackOrdinal,
5177
+ deadLetters: response.pollSyncEnvelopes.deadLetters ?? [],
5178
+ hasMore: response.pollSyncEnvelopes.hasMore
5179
+ };
5180
+ }
5181
+ /**
5182
+ * True when the remote rejected the query for naming a field it does not
5183
+ * have. Selecting an unknown field fails validation for the whole query, so
5184
+ * an unhandled one takes the channel's polling down until the process
5185
+ * restarts rather than degrading.
5186
+ */
5187
+ rejectsDecisionFields(error) {
5188
+ if (!this.peerServesDecisionFields) return false;
5189
+ if (!(error instanceof GraphQLRequestError) || error.category !== "graphql") return false;
5190
+ return DECISION_FIELDS.some((field) => error.message.includes(field));
5191
+ }
5192
+ /**
5193
+ * The poll query. `withDecisionFields` selects the two fields added with the
5194
+ * auth projection; a remote on the previous schema is polled without them.
5195
+ */
5196
+ pollQuery(withDecisionFields) {
5197
+ return `
4353
5198
  query PollSyncEnvelopes($channelId: String!, $outboxAck: Int!, $outboxLatest: Int!) {
4354
5199
  pollSyncEnvelopes(channelId: $channelId, outboxAck: $outboxAck, outboxLatest: $outboxLatest) {
4355
5200
  envelopes {
@@ -4364,6 +5209,7 @@ var GqlRequestChannel = class {
4364
5209
  hash
4365
5210
  skip
4366
5211
  error
5212
+ ${withDecisionFields ? "deniedReason" : ""}
4367
5213
  id
4368
5214
  action {
4369
5215
  id
@@ -4407,6 +5253,7 @@ var GqlRequestChannel = class {
4407
5253
  deadLetters {
4408
5254
  documentId
4409
5255
  error
5256
+ ${withDecisionFields ? "errorType" : ""}
4410
5257
  jobId
4411
5258
  branch
4412
5259
  scopes
@@ -4416,18 +5263,6 @@ var GqlRequestChannel = class {
4416
5263
  }
4417
5264
  }
4418
5265
  `;
4419
- const variables = {
4420
- channelId: this.channelId,
4421
- outboxAck: ackOrdinal,
4422
- outboxLatest: latestOrdinal
4423
- };
4424
- const response = await this.executeGraphQL(query, variables);
4425
- return {
4426
- envelopes: response.pollSyncEnvelopes.envelopes,
4427
- ackOrdinal: response.pollSyncEnvelopes.ackOrdinal,
4428
- deadLetters: response.pollSyncEnvelopes.deadLetters ?? [],
4429
- hasMore: response.pollSyncEnvelopes.hasMore
4430
- };
4431
5266
  }
4432
5267
  /**
4433
5268
  * Registers or updates this channel on the remote server via GraphQL mutation.
@@ -4546,7 +5381,7 @@ var GqlRequestChannel = class {
4546
5381
  if (error.statusCode !== void 0 && error.statusCode >= 500) return "recoverable";
4547
5382
  return "unrecoverable";
4548
5383
  case "parse": return "recoverable";
4549
- case "graphql": return "unrecoverable";
5384
+ case "graphql": return isRecoverableGraphQLError(error) ? "recoverable" : "unrecoverable";
4550
5385
  case "missing-data": return "unrecoverable";
4551
5386
  }
4552
5387
  }
@@ -4631,7 +5466,7 @@ var GqlRequestChannel = class {
4631
5466
  throw new GraphQLRequestError(`Failed to parse GraphQL response: ${error instanceof Error ? error.message : String(error)}`, "parse");
4632
5467
  }
4633
5468
  this.logger.verbose("GQL response @channelId @operation status=@status data=@data errors=@errors", this.channelId, operationName, response.status, JSON.stringify(result.data), result.errors ? JSON.stringify(result.errors) : "none");
4634
- if (result.errors) throw new GraphQLRequestError(`GraphQL errors: ${JSON.stringify(result.errors, null, 2)}`, "graphql");
5469
+ if (result.errors) throw new GraphQLRequestError(`GraphQL errors: ${JSON.stringify(result.errors, null, 2)}`, "graphql", void 0, result.errors.map((error) => error.extensions?.code));
4635
5470
  if (!result.data) throw new GraphQLRequestError("GraphQL response missing data field", "missing-data");
4636
5471
  return result.data;
4637
5472
  }
@@ -4723,6 +5558,10 @@ var GqlRequestChannelFactory = class {
4723
5558
  };
4724
5559
  //#endregion
4725
5560
  //#region src/sync/channels/gql-res-channel.ts
5561
+ /** Where a sync operation's run of ordinals begins. */
5562
+ function firstOrdinalOf$1(syncOp) {
5563
+ return syncOp.operations.length > 0 ? syncOp.operations[0].context.ordinal : 0;
5564
+ }
4726
5565
  /**
4727
5566
  * This class is used server-side to accumulate inbox + outbox operations.
4728
5567
  *
@@ -4738,6 +5577,8 @@ var GqlResponseChannel = class {
4738
5577
  isShutdown;
4739
5578
  lastPersistedInboxOrdinal = 0;
4740
5579
  lastPersistedOutboxOrdinal = 0;
5580
+ evictedOutboxFloor = Number.POSITIVE_INFINITY;
5581
+ appliedOutboxOrdinal = 0;
4741
5582
  connectionState = "connecting";
4742
5583
  connectionStateCallbacks = /* @__PURE__ */ new Set();
4743
5584
  constructor(logger, channelId, remoteName, cursorStorage) {
@@ -4750,18 +5591,11 @@ var GqlResponseChannel = class {
4750
5591
  this.outbox = new Mailbox();
4751
5592
  this.deadLetter = new Mailbox();
4752
5593
  this.outbox.onRemoved((syncOps) => {
4753
- const maxOrdinal = getLatestAppliedOrdinal(syncOps);
4754
- if (maxOrdinal > this.lastPersistedOutboxOrdinal) {
4755
- this.lastPersistedOutboxOrdinal = maxOrdinal;
4756
- this.cursorStorage.upsert({
4757
- remoteName: this.remoteName,
4758
- cursorType: "outbox",
4759
- cursorOrdinal: maxOrdinal,
4760
- lastSyncedAtUtcMs: Date.now()
4761
- }).catch((error) => {
4762
- this.logger.error("Failed to update outbox cursor for @ChannelId! This means that future application runs may resend duplicate operations. This is recoverable (with deduplication protection), but not-optimal: @Error", this.channelId, error);
4763
- });
4764
- }
5594
+ this.rememberUnserved(syncOps);
5595
+ this.persistOutboxCursor(getLatestAppliedOrdinal(syncOps));
5596
+ });
5597
+ this.outbox.onAdded((syncOps) => {
5598
+ this.forgetEvictedBelow(syncOps);
4765
5599
  });
4766
5600
  this.inbox.onRemoved((syncOps) => {
4767
5601
  const maxOrdinal = getLatestAppliedOrdinal(syncOps);
@@ -4803,6 +5637,17 @@ var GqlResponseChannel = class {
4803
5637
  }
4804
5638
  /** Response channels are push-driven; resolvers populate mailboxes directly. */
4805
5639
  triggerPull() {}
5640
+ async init() {
5641
+ const cursors = await this.cursorStorage.list(this.remoteName);
5642
+ const inboxOrdinal = cursors.find((c) => c.cursorType === "inbox")?.cursorOrdinal ?? 0;
5643
+ const outboxOrdinal = cursors.find((c) => c.cursorType === "outbox")?.cursorOrdinal ?? 0;
5644
+ this.inbox.init(inboxOrdinal);
5645
+ this.outbox.init(outboxOrdinal);
5646
+ this.lastPersistedInboxOrdinal = inboxOrdinal;
5647
+ this.lastPersistedOutboxOrdinal = outboxOrdinal;
5648
+ this.appliedOutboxOrdinal = outboxOrdinal;
5649
+ this.transitionConnectionState("connected");
5650
+ }
4806
5651
  transitionConnectionState(next) {
4807
5652
  if (this.connectionState === next) return;
4808
5653
  this.connectionState = next;
@@ -4813,15 +5658,68 @@ var GqlResponseChannel = class {
4813
5658
  this.logger.error("Connection state change callback error: @Error", error);
4814
5659
  }
4815
5660
  }
4816
- async init() {
4817
- const cursors = await this.cursorStorage.list(this.remoteName);
4818
- const inboxOrdinal = cursors.find((c) => c.cursorType === "inbox")?.cursorOrdinal ?? 0;
4819
- const outboxOrdinal = cursors.find((c) => c.cursorType === "outbox")?.cursorOrdinal ?? 0;
4820
- this.inbox.init(inboxOrdinal);
4821
- this.outbox.init(outboxOrdinal);
4822
- this.lastPersistedInboxOrdinal = inboxOrdinal;
4823
- this.lastPersistedOutboxOrdinal = outboxOrdinal;
4824
- this.transitionConnectionState("connected");
5661
+ /**
5662
+ * Records the ordinals of entries that left the outbox without being served,
5663
+ * so the cursor cannot advance past them.
5664
+ *
5665
+ * An entry can leave unserved because a bound evicted it, and an evicted entry
5666
+ * is exactly one this channel intends to re-derive: it is still owed to the
5667
+ * remote. Remembering the floor across the whole run rather than only while
5668
+ * the entry is present is what makes that true after a later ack would
5669
+ * otherwise have swept the cursor past it.
5670
+ */
5671
+ rememberUnserved(syncOps) {
5672
+ for (const syncOp of syncOps) {
5673
+ if (syncOp.status === SyncOperationStatus.Applied) continue;
5674
+ const first = firstOrdinalOf$1(syncOp);
5675
+ if (first > 0 && first < this.evictedOutboxFloor) this.evictedOutboxFloor = first;
5676
+ }
5677
+ }
5678
+ /**
5679
+ * Persists the outbox cursor, never past an operation this remote has not
5680
+ * been served.
5681
+ *
5682
+ * The cursor is where a restart resumes deriving the outbox from, so an
5683
+ * ordinal persisted past an unserved entry loses that entry for good: the
5684
+ * rebuild starts beyond it and nothing else remembers it was owed. Acks
5685
+ * arrive out of order with respect to what is withheld -- a later entry can
5686
+ * be acknowledged while an earlier one is still being withheld from this
5687
+ * subject -- so the applied high-water mark alone is not a safe cursor.
5688
+ */
5689
+ persistOutboxCursor(appliedOrdinal) {
5690
+ this.appliedOutboxOrdinal = Math.max(this.appliedOutboxOrdinal, appliedOrdinal);
5691
+ const ordinal = Math.min(this.appliedOutboxOrdinal, this.unservedFloor() - 1);
5692
+ if (ordinal <= this.lastPersistedOutboxOrdinal) return;
5693
+ this.lastPersistedOutboxOrdinal = ordinal;
5694
+ this.cursorStorage.upsert({
5695
+ remoteName: this.remoteName,
5696
+ cursorType: "outbox",
5697
+ cursorOrdinal: ordinal,
5698
+ lastSyncedAtUtcMs: Date.now()
5699
+ }).catch((error) => {
5700
+ this.logger.error("Failed to update outbox cursor for @ChannelId! This means that future application runs may resend duplicate operations. This is recoverable (with deduplication protection), but not-optimal: @Error", this.channelId, error);
5701
+ });
5702
+ }
5703
+ /** Drops the evicted floor once the entries it stood for are queued again. */
5704
+ forgetEvictedBelow(syncOps) {
5705
+ if (this.evictedOutboxFloor === Number.POSITIVE_INFINITY) return;
5706
+ for (const syncOp of syncOps) {
5707
+ const first = firstOrdinalOf$1(syncOp);
5708
+ if (first > 0 && first <= this.evictedOutboxFloor) {
5709
+ this.evictedOutboxFloor = Number.POSITIVE_INFINITY;
5710
+ return;
5711
+ }
5712
+ }
5713
+ }
5714
+ /** The lowest ordinal still owed to this remote, evicted or still queued. */
5715
+ unservedFloor() {
5716
+ let floor = this.evictedOutboxFloor;
5717
+ for (const syncOp of this.outbox.items) {
5718
+ if (syncOp.status === SyncOperationStatus.Applied) continue;
5719
+ const first = firstOrdinalOf$1(syncOp);
5720
+ if (first > 0 && first < floor) floor = first;
5721
+ }
5722
+ return floor;
4825
5723
  }
4826
5724
  };
4827
5725
  //#endregion
@@ -4909,7 +5807,8 @@ function rowToDeadLetterRecord(row) {
4909
5807
  branch: row.branch,
4910
5808
  operations: row.operations,
4911
5809
  errorSource: row.error_source,
4912
- errorMessage: row.error_message
5810
+ errorMessage: row.error_message,
5811
+ errorType: row.error_type ?? "UNCLASSIFIED"
4913
5812
  };
4914
5813
  }
4915
5814
  function deadLetterRecordToRow(record) {
@@ -4923,7 +5822,8 @@ function deadLetterRecordToRow(record) {
4923
5822
  branch: record.branch,
4924
5823
  operations: JSON.stringify(record.operations),
4925
5824
  error_source: record.errorSource,
4926
- error_message: record.errorMessage
5825
+ error_message: record.errorMessage,
5826
+ error_type: record.errorType
4927
5827
  };
4928
5828
  }
4929
5829
  /**
@@ -4980,9 +5880,11 @@ var KyselySyncDeadLetterStorage = class {
4980
5880
  }
4981
5881
  async listQuarantinedDocumentIds(signal) {
4982
5882
  if (signal?.aborted) throw new Error("Operation aborted");
4983
- const rows = await this.db.selectFrom("sync_dead_letters").select("document_id").distinct().execute();
5883
+ const rows = await this.db.selectFrom("sync_dead_letters").select(["document_id", "error_type"]).distinct().execute();
4984
5884
  if (signal?.aborted) throw new Error("Operation aborted");
4985
- return rows.map((row) => row.document_id);
5885
+ const quarantined = /* @__PURE__ */ new Set();
5886
+ for (const row of rows) if (quarantinesDocument(row.error_type ?? "UNCLASSIFIED")) quarantined.add(row.document_id);
5887
+ return [...quarantined];
4986
5888
  }
4987
5889
  };
4988
5890
  //#endregion
@@ -5001,7 +5903,10 @@ function rowToRemoteRecord(row) {
5001
5903
  scope: row.filter_scopes ?? [],
5002
5904
  branch: row.filter_branch
5003
5905
  },
5004
- options: { sinceTimestampUtcMs: "0" },
5906
+ options: {
5907
+ sinceTimestampUtcMs: "0",
5908
+ boundAddress: row.bound_address ?? void 0
5909
+ },
5005
5910
  status: {
5006
5911
  push: {
5007
5912
  state: row.push_state,
@@ -5041,7 +5946,8 @@ function remoteRecordToRow(remote) {
5041
5946
  pull_state: remote.status.pull.state,
5042
5947
  pull_last_success_utc_ms: remote.status.pull.lastSuccessUtcMs ? new Date(remote.status.pull.lastSuccessUtcMs).toISOString() : null,
5043
5948
  pull_last_failure_utc_ms: remote.status.pull.lastFailureUtcMs ? new Date(remote.status.pull.lastFailureUtcMs).toISOString() : null,
5044
- pull_failure_count: remote.status.pull.failureCount
5949
+ pull_failure_count: remote.status.pull.failureCount,
5950
+ bound_address: remote.options.boundAddress ?? null
5045
5951
  };
5046
5952
  }
5047
5953
  var KyselySyncRemoteStorage = class {
@@ -5409,9 +6315,14 @@ var OutboxMode = /* @__PURE__ */ function(OutboxMode) {
5409
6315
  }(OutboxMode || {});
5410
6316
  const defaultSyncManagerConfig = {
5411
6317
  maxDeadLettersPerRemote: 100,
5412
- maxInboxBatchSize: 32
6318
+ maxInboxBatchSize: 32,
6319
+ maxHeldOperationsPerRemote: 1e4
5413
6320
  };
5414
6321
  const PLAN_KEY_TO_JOB_UUID_CAP = 1e4;
6322
+ /** Where a sync operation's run of ordinals begins. */
6323
+ function firstOrdinalOf(syncOp) {
6324
+ return syncOp.operations.length > 0 ? syncOp.operations[0].context.ordinal : 0;
6325
+ }
5415
6326
  var SyncManager = class {
5416
6327
  logger;
5417
6328
  remoteStorage;
@@ -5435,6 +6346,7 @@ var SyncManager = class {
5435
6346
  quarantinedDocumentIds = /* @__PURE__ */ new Set();
5436
6347
  backfillAbortControllers = /* @__PURE__ */ new Map();
5437
6348
  planKeyToJobUuid = /* @__PURE__ */ new Map();
6349
+ evictedOutboxFloors = /* @__PURE__ */ new Map();
5438
6350
  lastEnqueuedJobIdByKey = /* @__PURE__ */ new Map();
5439
6351
  inboxChunkChain = Promise.resolve();
5440
6352
  constructor(logger, remoteStorage, cursorStorage, deadLetterStorage, channelFactory, operationIndex, reactor, eventBus, driveContainerTypes, config = {}) {
@@ -5542,6 +6454,28 @@ var SyncManager = class {
5542
6454
  for (const remote of this.remotes.values()) if (remote.meta.id === id) return remote;
5543
6455
  throw new Error(`Remote with id '${id}' does not exist`);
5544
6456
  }
6457
+ async bindRemote(id, boundAddress) {
6458
+ const remote = this.getById(id);
6459
+ const bound = remote.meta.options.boundAddress;
6460
+ if (bound === boundAddress) return;
6461
+ if (bound !== void 0) throw new Error(`Remote with id '${id}' is already bound to another address`);
6462
+ remote.meta.options = {
6463
+ ...remote.meta.options,
6464
+ boundAddress
6465
+ };
6466
+ await this.remoteStorage.upsert({
6467
+ id: remote.meta.id,
6468
+ name: remote.meta.name,
6469
+ collectionId: remote.meta.collectionId,
6470
+ channelConfig: remote.meta.channelConfig,
6471
+ filter: remote.meta.filter,
6472
+ options: remote.meta.options,
6473
+ status: {
6474
+ push: createIdleHealth(),
6475
+ pull: createIdleHealth()
6476
+ }
6477
+ });
6478
+ }
5545
6479
  async add(name, collectionId, channelConfig, filter = {
5546
6480
  documentId: [],
5547
6481
  scope: [],
@@ -5655,7 +6589,8 @@ var SyncManager = class {
5655
6589
  remote.channel.deadLetter.onAdded((syncOps) => {
5656
6590
  for (const syncOp of syncOps) {
5657
6591
  this.logger.error("Dead letter (@remote, @documentId, @jobId, @error, @dependencies)", remote.meta.name, syncOp.documentId, syncOp.jobId, syncOp.error?.message ?? "unknown", syncOp.jobDependencies);
5658
- this.quarantinedDocumentIds.add(syncOp.documentId);
6592
+ const errorType = syncOperationErrorType(syncOp.error);
6593
+ if (quarantinesDocument(errorType)) this.quarantinedDocumentIds.add(syncOp.documentId);
5659
6594
  const record = {
5660
6595
  id: syncOp.id,
5661
6596
  jobId: syncOp.jobId,
@@ -5666,7 +6601,8 @@ var SyncManager = class {
5666
6601
  branch: syncOp.branch,
5667
6602
  operations: syncOp.operations,
5668
6603
  errorSource: syncOp.error?.source ?? ChannelErrorSource.None,
5669
- errorMessage: syncOp.error?.error.message ?? "unknown"
6604
+ errorMessage: syncOp.error?.error.message ?? "unknown",
6605
+ errorType
5670
6606
  };
5671
6607
  this.deadLetterStorage.add(record).catch((err) => {
5672
6608
  this.logger.error("Failed to persist dead letter (@id, @error)", record.id, err instanceof Error ? err.message : String(err));
@@ -5676,7 +6612,8 @@ var SyncManager = class {
5676
6612
  jobId: record.jobId,
5677
6613
  remoteName: record.remoteName,
5678
6614
  documentId: record.documentId,
5679
- errorSource: record.errorSource
6615
+ errorSource: record.errorSource,
6616
+ errorType: record.errorType
5680
6617
  }).catch(() => {});
5681
6618
  }
5682
6619
  const items = remote.channel.deadLetter.items;
@@ -5703,7 +6640,7 @@ var SyncManager = class {
5703
6640
  const syncOps = [];
5704
6641
  for (const record of records) {
5705
6642
  const syncOp = new SyncOperation(record.id, record.jobId, record.jobDependencies, record.remoteName, record.documentId, record.scopes, record.branch, record.operations);
5706
- syncOp.failed(new ChannelError(record.errorSource, new Error(record.errorMessage)));
6643
+ syncOp.failed(new ChannelError(record.errorSource, new Error(record.errorMessage), record.errorType));
5707
6644
  syncOps.push(syncOp);
5708
6645
  }
5709
6646
  remote.channel.deadLetter.add(...syncOps);
@@ -5784,8 +6721,7 @@ var SyncManager = class {
5784
6721
  if (completedJobInfo.status === JobStatus.FAILED) {
5785
6722
  const errorMessage = completedJobInfo.error?.message || "Unknown error";
5786
6723
  this.logger.error("Failed to apply operations from inbox (@remote, @documentId, @jobId, @error)", remote.meta.name, syncOp.documentId, completedJobInfo.id, errorMessage);
5787
- const error = new ChannelError(ChannelErrorSource.Inbox, /* @__PURE__ */ new Error(`Failed to apply operations: ${errorMessage}`));
5788
- syncOp.failed(error);
6724
+ syncOp.failed(this.inboxFailure(completedJobInfo.error));
5789
6725
  remote.channel.deadLetter.add(syncOp);
5790
6726
  } else syncOp.executed();
5791
6727
  remote.channel.inbox.remove(syncOp);
@@ -5862,17 +6798,79 @@ var SyncManager = class {
5862
6798
  }
5863
6799
  if (this.isShutdown) return;
5864
6800
  if (completedJobInfo.status === JobStatus.FAILED) {
5865
- const errorMessage = completedJobInfo.error?.message || "Unknown error";
5866
- const channelError = new ChannelError(ChannelErrorSource.Inbox, /* @__PURE__ */ new Error(`Failed to apply operations: ${errorMessage}`));
5867
- syncOp.failed(channelError);
6801
+ syncOp.failed(this.inboxFailure(completedJobInfo.error));
5868
6802
  remote.channel.deadLetter.add(syncOp);
5869
6803
  } else syncOp.executed();
5870
6804
  remote.channel.inbox.remove(syncOp);
5871
6805
  }
5872
6806
  }
6807
+ /**
6808
+ * The dead letter for a load job the executor failed.
6809
+ *
6810
+ * The classification is passed explicitly because it cannot be recovered
6811
+ * downstream: the wrapper carries the failure's message, not the failure, so
6812
+ * deriving it from the wrapper's own name would classify every one of these
6813
+ * as unclassified and quarantine the document. A held auth operation must
6814
+ * keep syncing, because reconciling the two policies needs the traffic a
6815
+ * quarantine would stop.
6816
+ */
6817
+ inboxFailure(error) {
6818
+ const message = error?.message || "Unknown error";
6819
+ return new ChannelError(ChannelErrorSource.Inbox, /* @__PURE__ */ new Error(`Failed to apply operations: ${message}`), classifyJobFailure(error?.name ?? "Error"));
6820
+ }
6821
+ /**
6822
+ * Where the next outbox derivation starts: at the evicted floor when there is
6823
+ * room to take those entries back, and at the caller's cursor otherwise.
6824
+ *
6825
+ * The floor is forgotten as it is folded in. If the refill overflows again the
6826
+ * eviction records a new one, and if it does not, the entries are queued and
6827
+ * the outbox itself holds the cursor down.
6828
+ */
6829
+ refillOrdinal(remote, ackOrdinal) {
6830
+ const floor = this.evictedOutboxFloors.get(remote.meta.name);
6831
+ if (floor === void 0) return ackOrdinal;
6832
+ if (this.outboxOperationCount(remote) >= this.config.maxHeldOperationsPerRemote) return ackOrdinal;
6833
+ this.evictedOutboxFloors.delete(remote.meta.name);
6834
+ return Math.min(ackOrdinal, floor - 1);
6835
+ }
6836
+ /**
6837
+ * Evicts the newest entries of an outbox that has grown past its bound.
6838
+ *
6839
+ * Only entries that have never been taken up for transport are eligible, which
6840
+ * is what makes this a bound on withheld work rather than a way to drop
6841
+ * something already in flight. One entry is always kept, so an outbox whose
6842
+ * first entry is larger than the whole cap still makes progress.
6843
+ */
6844
+ evictPastOutboxBound(remote) {
6845
+ const cap = this.config.maxHeldOperationsPerRemote;
6846
+ const queued = remote.channel.outbox.items.filter((syncOp) => syncOp.status === SyncOperationStatus.Unknown).sort((a, b) => firstOrdinalOf(a) - firstOrdinalOf(b));
6847
+ let kept = 0;
6848
+ let cut = queued.length;
6849
+ for (let i = 0; i < queued.length; i++) {
6850
+ const size = queued[i].operations.length;
6851
+ if (i > 0 && kept + size > cap) {
6852
+ cut = i;
6853
+ break;
6854
+ }
6855
+ kept += size;
6856
+ }
6857
+ const evicted = queued.slice(cut);
6858
+ if (evicted.length === 0) return;
6859
+ const floor = firstOrdinalOf(evicted[0]);
6860
+ const known = this.evictedOutboxFloors.get(remote.meta.name);
6861
+ this.evictedOutboxFloors.set(remote.meta.name, known === void 0 ? floor : Math.min(known, floor));
6862
+ this.logger.warn("Outbox for @RemoteName is past its bound of @Cap operations; evicting @Count entries from ordinal @Floor, to be derived again once it drains", remote.meta.name, cap, evicted.length, floor);
6863
+ remote.channel.outbox.remove(...evicted);
6864
+ }
6865
+ outboxOperationCount(remote) {
6866
+ let count = 0;
6867
+ for (const syncOp of remote.channel.outbox.items) count += syncOp.operations.length;
6868
+ return count;
6869
+ }
5873
6870
  async updateOutbox(remote, ackOrdinal, mode = OutboxMode.Backfill, signal) {
5874
6871
  const composedSignal = signal ? AbortSignal.any([signal, this.abortController.signal]) : this.abortController.signal;
5875
- let maxOrdinal = ackOrdinal;
6872
+ const startOrdinal = this.refillOrdinal(remote, ackOrdinal);
6873
+ let maxOrdinal = startOrdinal;
5876
6874
  const lastJobByDoc = /* @__PURE__ */ new Map();
5877
6875
  let prevChainJobId;
5878
6876
  const sinceTimestamp = remote.meta.options.sinceTimestampUtcMs;
@@ -5892,8 +6890,9 @@ var SyncManager = class {
5892
6890
  if (mode === OutboxMode.BatchTriggered) prevChainJobId = jobId;
5893
6891
  }
5894
6892
  remote.channel.outbox.add(...syncOps);
6893
+ this.evictPastOutboxBound(remote);
5895
6894
  };
5896
- let page = await this.operationIndex.find(remote.meta.collectionId.key, ackOrdinal, { excludeSourceRemote: remote.meta.name }, void 0, composedSignal);
6895
+ let page = await this.operationIndex.find(remote.meta.collectionId.key, startOrdinal, { excludeSourceRemote: remote.meta.name }, void 0, composedSignal);
5897
6896
  let carry = [];
5898
6897
  let hasMore;
5899
6898
  do {
@@ -5909,9 +6908,17 @@ var SyncManager = class {
5909
6908
  operations = operations.filter((op) => !this.quarantinedDocumentIds.has(op.context.documentId));
5910
6909
  hasMore = !!page.next;
5911
6910
  if (operations.length > 0) {
6911
+ const created = /* @__PURE__ */ new Set();
6912
+ for (const entry of operations) if (entry.operation.action.type === "CREATE_DOCUMENT") created.add(entry.context.documentId);
5912
6913
  operations.sort((a, b) => {
5913
6914
  if (a.context.documentId !== b.context.documentId) return a.context.documentId < b.context.documentId ? -1 : 1;
5914
- if (a.context.scope !== b.context.scope) return a.context.scope < b.context.scope ? -1 : 1;
6915
+ if (a.context.scope !== b.context.scope) {
6916
+ if (created.has(a.context.documentId)) {
6917
+ if (a.context.scope === "document") return -1;
6918
+ if (b.context.scope === "document") return 1;
6919
+ }
6920
+ return a.context.scope < b.context.scope ? -1 : 1;
6921
+ }
5915
6922
  return a.context.ordinal - b.context.ordinal;
5916
6923
  });
5917
6924
  if (hasMore) {
@@ -5958,6 +6965,10 @@ var SyncBuilder = class {
5958
6965
  this.config.maxInboxBatchSize = limit;
5959
6966
  return this;
5960
6967
  }
6968
+ withMaxHeldOperationsPerRemote(limit) {
6969
+ this.config.maxHeldOperationsPerRemote = limit;
6970
+ return this;
6971
+ }
5961
6972
  build(reactor, logger, operationIndex, eventBus, db, driveContainerTypes) {
5962
6973
  return this.buildModule(reactor, logger, operationIndex, eventBus, db, driveContainerTypes).syncManager;
5963
6974
  }
@@ -6190,7 +7201,7 @@ var Reactor = class {
6190
7201
  documentId: document.header.id,
6191
7202
  model: document.header.documentType,
6192
7203
  fromVersion: 0,
6193
- toVersion: document.state.document.version,
7204
+ toVersion: normalizeDocumentModelVersion(document.state.document?.version),
6194
7205
  initialState: document.state
6195
7206
  })];
6196
7207
  if (signer) actions = await signActions(actions, signer, signal);
@@ -6572,7 +7583,10 @@ var ReactorBuilder = class {
6572
7583
  logger;
6573
7584
  documentModelSources = [];
6574
7585
  upgradeManifests = [];
6575
- features = { legacyStorageEnabled: false };
7586
+ features = {
7587
+ legacyStorageEnabled: false,
7588
+ legacyProcessorIds: true
7589
+ };
6576
7590
  readModels = [];
6577
7591
  readModelFactories = [];
6578
7592
  executorManager;
@@ -6769,6 +7783,8 @@ var ReactorBuilder = class {
6769
7783
  }
6770
7784
  async buildModule() {
6771
7785
  if (!this.logger) this.logger = new ConsoleLogger(["reactor"]);
7786
+ const featureFlags = resolveFeatureFlags(this.executorConfig.featureFlags);
7787
+ if (this.projectionShardConfig !== void 0 && this.readModelFactories.length > 0) throw new Error("withProjectionShards does not support read models registered through withReadModelFactory; projection workers cannot receive host-only factory dependencies");
6772
7788
  const resolvedSources = await resolveModelSources(this.documentModelSources);
6773
7789
  if (this.workerPool) {
6774
7790
  if (resolvedSources.manifest.length === 0) throw new Error("withWorkerPool requires at least one worker-importable document-model source ({ filePath } or { packageName }).");
@@ -6818,15 +7834,15 @@ var ReactorBuilder = class {
6818
7834
  if (pool.db === void 0) throw new Error("unreachable: worker pool configured without db or factory");
6819
7835
  factory = await this.createDefaultWorkerFactory(pool.numWorkers, pool.db, pool.verifier);
6820
7836
  }
6821
- const poolManager = new WorkerPoolJobExecutorManager(factory, eventBus, queue, jobTracker, this.logger, resolver, collectionMembershipCache, this.executorConfig.jobTimeoutMs);
7837
+ const poolManager = new WorkerPoolJobExecutorManager(factory, eventBus, queue, jobTracker, this.logger, resolver, collectionMembershipCache, this.executorConfig.jobTimeoutMs, this.executorConfig.deferredJobTtlMs);
6822
7838
  executorManager = poolManager;
6823
7839
  executorStartCount = pool.numWorkers;
6824
7840
  if (resolver instanceof DocumentModelResolver) resolver.setBroadcastHook((entry) => poolManager.loadModel(entry));
6825
- } else executorManager = new SimpleJobExecutorManager(() => new SimpleJobExecutor(this.logger, documentModelRegistry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, this.driveContainerTypes, this.executorConfig, this.signatureVerifier, executionScope), eventBus, queue, jobTracker, this.logger, resolver, this.executorConfig.jobTimeoutMs);
7841
+ } else executorManager = new SimpleJobExecutorManager(() => new SimpleJobExecutor(this.logger, documentModelRegistry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, this.driveContainerTypes, this.executorConfig, this.signatureVerifier, executionScope), eventBus, queue, jobTracker, this.logger, resolver, this.executorConfig.jobTimeoutMs, this.executorConfig.deferredJobTtlMs);
6826
7842
  await executorManager.start(executorStartCount);
6827
7843
  const readModelInstances = Array.from(new Set([...this.readModels]));
6828
7844
  const documentViewConsistencyTracker = new ConsistencyTracker();
6829
- const documentView = new KyselyDocumentView(database, operationStore, operationIndex, writeCache, documentViewConsistencyTracker);
7845
+ const documentView = new KyselyDocumentView(database, operationStore, operationIndex, writeCache, documentViewConsistencyTracker, featureFlags.documentDecisions);
6830
7846
  try {
6831
7847
  await documentView.init();
6832
7848
  } catch (error) {
@@ -6844,7 +7860,7 @@ var ReactorBuilder = class {
6844
7860
  const subscriptionManager = new ReactorSubscriptionManager(new DefaultSubscriptionErrorHandler());
6845
7861
  const subscriptionNotificationReadModel = new SubscriptionNotificationReadModel(subscriptionManager, documentView);
6846
7862
  const processorManagerConsistencyTracker = new ConsistencyTracker();
6847
- const processorManager = new ProcessorManager(database, operationIndex, writeCache, processorManagerConsistencyTracker, this.logger, this.driveContainerTypes);
7863
+ const processorManager = new ProcessorManager(database, operationIndex, writeCache, processorManagerConsistencyTracker, this.logger, this.driveContainerTypes, { legacyProcessorIds: this.features.legacyProcessorIds !== false });
6848
7864
  try {
6849
7865
  await processorManager.init();
6850
7866
  } catch (error) {
@@ -6852,6 +7868,7 @@ var ReactorBuilder = class {
6852
7868
  }
6853
7869
  for (const factory of this.readModelFactories) {
6854
7870
  const readModel = await factory({
7871
+ documentModelRegistry,
6855
7872
  operationIndex,
6856
7873
  writeCache,
6857
7874
  processorManagerConsistencyTracker
@@ -6869,9 +7886,15 @@ var ReactorBuilder = class {
6869
7886
  syncModule = this.syncBuilder.buildModule(reactor, this.logger, operationIndex, eventBus, database, this.driveContainerTypes);
6870
7887
  await syncModule.syncManager.startup();
6871
7888
  }
7889
+ let groupReevaluationTrigger;
7890
+ if (featureFlags.authGroups) {
7891
+ groupReevaluationTrigger = new GroupReevaluationTrigger(this.logger, eventBus, queue, operationIndex);
7892
+ groupReevaluationTrigger.startup();
7893
+ }
6872
7894
  const module = {
6873
7895
  eventBus,
6874
7896
  documentModelRegistry,
7897
+ featureFlags,
6875
7898
  queue,
6876
7899
  jobTracker,
6877
7900
  executorManager,
@@ -6890,6 +7913,7 @@ var ReactorBuilder = class {
6890
7913
  processorManagerConsistencyTracker,
6891
7914
  syncModule,
6892
7915
  reactor,
7916
+ groupReevaluationTrigger,
6893
7917
  pools: this.instrumentedPools
6894
7918
  };
6895
7919
  if (this.signalHandlersEnabled) this.attachSignalHandlers(module);
@@ -6962,9 +7986,9 @@ var ReactorBuilder = class {
6962
7986
  */
6963
7987
  async createDefaultWorkerFactory(numWorkers, db, signatureVerifier) {
6964
7988
  const [{ WorkerHandle }, { createThreadTransport }, { workerEntryPath }] = await Promise.all([
6965
- import("./worker-handle-B1w03nRA.js"),
7989
+ import("./worker-handle-CrERzl8s.js"),
6966
7990
  import("./transport-ByGviWdZ.js"),
6967
- import("./worker-DBJOv8Gp.js").then((n) => n.n)
7991
+ import("./worker-DXJpyHLW.js").then((n) => n.n)
6968
7992
  ]);
6969
7993
  const poolConfig = {
6970
7994
  enabled: true,
@@ -6985,7 +8009,8 @@ var ReactorBuilder = class {
6985
8009
  poolConfig,
6986
8010
  db,
6987
8011
  signatureVerifier,
6988
- models
8012
+ models,
8013
+ executorConfig: this.executorConfig
6989
8014
  },
6990
8015
  logger,
6991
8016
  poolInstrumentation
@@ -7106,6 +8131,7 @@ var ReactorClientBuilder = class {
7106
8131
  subscriptionManager;
7107
8132
  jobAwaiter;
7108
8133
  documentModelLoader;
8134
+ readGate;
7109
8135
  /**
7110
8136
  * Sets the logger for the ReactorClient.
7111
8137
  * @param logger - The logger to use.
@@ -7158,6 +8184,47 @@ var ReactorClientBuilder = class {
7158
8184
  this.documentModelLoader = loader;
7159
8185
  return this;
7160
8186
  }
8187
+ /**
8188
+ * Overrides how reads are gated. A client built from a ReactorBuilder derives
8189
+ * this from that reactor's flags; one built from `withReactor` cannot, because
8190
+ * it is handed no flags and no registry, so it gates on the policy alone
8191
+ * unless a gate is supplied here.
8192
+ */
8193
+ withReadGate(readGate) {
8194
+ this.readGate = readGate;
8195
+ return this;
8196
+ }
8197
+ /**
8198
+ * The gate the resolved model calls for. Below authEnforcement there is no
8199
+ * model to enforce -- the registered one ignores the auth scope -- so the
8200
+ * policy is evaluated on its own, which is what reads did before the model
8201
+ * existed. Group serving turns on with authGroups, because below it a
8202
+ * `{ group }` grant does not match, so a served roster is one no grant can
8203
+ * use.
8204
+ */
8205
+ resolveReadGate(reactorModule, documentView, model) {
8206
+ if (!reactorModule || model === void 0) return new BareReadGate();
8207
+ return new ModelReadGate(model, documentView, reactorModule.featureFlags.authGroups, reactorModule.operationIndex, this.logger);
8208
+ }
8209
+ /**
8210
+ * What the client answers an authorization preflight from, or undefined when
8211
+ * it answers none.
8212
+ *
8213
+ * Resolved from the same model reads enforce, so a preflight and a read can
8214
+ * never decide against different models. Undefined below authEnforcement, and
8215
+ * undefined on the `withReactor` path, where there are no flags and no
8216
+ * registry to select a model with -- a client with no model refuses the
8217
+ * preflight rather than answering it from the legacy host-side permission
8218
+ * tables. Deliberately not derived from the read gate: `withReadGate`
8219
+ * overrides that, so sniffing the gate's type would report enforcement from a
8220
+ * caller's substitution.
8221
+ */
8222
+ resolveActionEvaluation(reactorModule, model) {
8223
+ return reactorModule && model ? {
8224
+ model,
8225
+ flags: reactorModule.featureFlags
8226
+ } : void 0;
8227
+ }
7161
8228
  async build() {
7162
8229
  return (await this.buildModule()).client;
7163
8230
  }
@@ -7186,8 +8253,9 @@ var ReactorClientBuilder = class {
7186
8253
  const signer = this.signer ?? new PassthroughSigner();
7187
8254
  const subscriptionManager = this.subscriptionManager ?? reactorModule?.subscriptionManager ?? new ReactorSubscriptionManager(new DefaultSubscriptionErrorHandler());
7188
8255
  const jobAwaiter = this.jobAwaiter ?? new JobAwaiter(eventBus, (jobId, signal) => reactor.getJobStatus(jobId, signal));
8256
+ const decisionModel = reactorModule ? readDecisionModel(reactorModule.featureFlags, reactorModule.documentModelRegistry) : void 0;
7189
8257
  return {
7190
- client: new ReactorClient(this.logger, reactor, signer, subscriptionManager, jobAwaiter, documentIndexer, documentView),
8258
+ client: new ReactorClient(this.logger, reactor, signer, subscriptionManager, jobAwaiter, documentIndexer, documentView, this.readGate ?? this.resolveReadGate(reactorModule, documentView, decisionModel), this.resolveActionEvaluation(reactorModule, decisionModel)),
7191
8259
  reactor,
7192
8260
  eventBus,
7193
8261
  documentIndexer,
@@ -7225,6 +8293,85 @@ function driveIdFromUrl(url) {
7225
8293
  return url.split("/").pop() ?? "";
7226
8294
  }
7227
8295
  //#endregion
8296
+ //#region src/decision/sync-scope-gate.ts
8297
+ /** What a subject may read of a document that is not there to be read. */
8298
+ const META_ONLY = (scope) => ALWAYS_READABLE_SCOPES.has(scope);
8299
+ /**
8300
+ * A read gate asked by document id rather than by document.
8301
+ *
8302
+ * Serving works from an id: an outbox entry names a document, a branch and a
8303
+ * scope, and carries no state. Fetching the document is therefore the serving
8304
+ * path's own job, and it is the only thing this adds to the gate it wraps.
8305
+ */
8306
+ var SyncScopeGate = class {
8307
+ constructor(gate, documentView, logger) {
8308
+ this.gate = gate;
8309
+ this.documentView = documentView;
8310
+ this.logger = logger;
8311
+ }
8312
+ /**
8313
+ * Which scopes of one document the subject may be served.
8314
+ *
8315
+ * A document this replica cannot produce yields the metadata scopes and
8316
+ * nothing else. That is the fail-closed direction, and it is safe to fail
8317
+ * closed here precisely because serving withholds rather than consumes: the
8318
+ * entry stays in the outbox and the next poll asks again, so a document that
8319
+ * is merely not indexed yet is delayed rather than lost.
8320
+ *
8321
+ * Any other failure is rethrown. A read side that is down must not read as a
8322
+ * silent, universal denial, because a denial that looks like a policy is one
8323
+ * nobody investigates.
8324
+ */
8325
+ async scopePredicateById(documentId, subject, branch, signal) {
8326
+ let document;
8327
+ try {
8328
+ document = await this.documentView.get(documentId, { branch }, void 0, signal);
8329
+ } catch (error) {
8330
+ if (!DocumentNotFoundError.isError(error)) throw error;
8331
+ this.logger?.verbose(`Withholding ${documentId} on branch ${branch}: the read side does not hold it`);
8332
+ return META_ONLY;
8333
+ }
8334
+ return this.gate.scopePredicate(document, subject, branch, signal);
8335
+ }
8336
+ };
8337
+ //#endregion
8338
+ //#region src/decision/stream-order.ts
8339
+ /**
8340
+ * The first pair of effective operations whose stored order contradicts their
8341
+ * timestamps, or undefined when the stream is in position order.
8342
+ *
8343
+ * Such a stream cannot be walked, and the auth stream is never reshuffled once
8344
+ * the monotonic rule is on, so run this before enabling enforcement on a fleet.
8345
+ *
8346
+ * `requireStrict` additionally rejects a tie, which is what the auth stream's
8347
+ * monotonic rule requires and what the walk alone does not care about.
8348
+ */
8349
+ function firstOutOfOrderPair(operations, options) {
8350
+ const requireStrict = options?.requireStrict ?? false;
8351
+ const effective = garbageCollect(sortOperations([...operations]));
8352
+ for (let i = 1; i < effective.length; i++) {
8353
+ const previous = effective[i - 1];
8354
+ const current = effective[i];
8355
+ const previousAt = Date.parse(previous.timestampUtcMs);
8356
+ const currentAt = Date.parse(current.timestampUtcMs);
8357
+ if (currentAt < previousAt) return {
8358
+ previous,
8359
+ current,
8360
+ kind: "descending"
8361
+ };
8362
+ if (requireStrict && currentAt === previousAt) return {
8363
+ previous,
8364
+ current,
8365
+ kind: "tied"
8366
+ };
8367
+ }
8368
+ }
8369
+ //#endregion
8370
+ //#region src/read-models/interfaces.ts
8371
+ function supportsLiveReadModelRegistration(coordinator) {
8372
+ return "addReadModel" in coordinator && typeof coordinator.addReadModel === "function";
8373
+ }
8374
+ //#endregion
7228
8375
  //#region src/admin/passthrough-keyframe-store.ts
7229
8376
  const passthroughKeyframeStore = {
7230
8377
  putKeyframe: () => Promise.resolve(),
@@ -7250,6 +8397,7 @@ var DocumentIntegrityService = class {
7250
8397
  async validateDocument(documentId, branch = "main", signal) {
7251
8398
  const keyframeIssues = [];
7252
8399
  const snapshotIssues = [];
8400
+ const streamOrderIssues = await this.findStreamOrderIssues(documentId, branch, signal);
7253
8401
  const replayCache = new KyselyWriteCache(passthroughKeyframeStore, this.operationStore, this.documentModelRegistry, {
7254
8402
  maxDocuments: 1,
7255
8403
  ringBufferSize: 1,
@@ -7276,9 +8424,10 @@ var DocumentIntegrityService = class {
7276
8424
  } catch {
7277
8425
  return {
7278
8426
  documentId,
7279
- isConsistent: keyframeIssues.length === 0,
8427
+ isConsistent: keyframeIssues.length === 0 && streamOrderIssues.length === 0,
7280
8428
  keyframeIssues,
7281
- snapshotIssues
8429
+ snapshotIssues,
8430
+ streamOrderIssues
7282
8431
  };
7283
8432
  }
7284
8433
  const revisions = await this.operationStore.getRevisions(documentId, branch, signal);
@@ -7304,9 +8453,10 @@ var DocumentIntegrityService = class {
7304
8453
  }
7305
8454
  return {
7306
8455
  documentId,
7307
- isConsistent: keyframeIssues.length === 0 && snapshotIssues.length === 0,
8456
+ isConsistent: keyframeIssues.length === 0 && snapshotIssues.length === 0 && streamOrderIssues.length === 0,
7308
8457
  keyframeIssues,
7309
- snapshotIssues
8458
+ snapshotIssues,
8459
+ streamOrderIssues
7310
8460
  };
7311
8461
  }
7312
8462
  async rebuildKeyframes(documentId, branch = "main", signal) {
@@ -7328,12 +8478,26 @@ var DocumentIntegrityService = class {
7328
8478
  scopesInvalidated: scopes.length
7329
8479
  };
7330
8480
  }
8481
+ async findStreamOrderIssues(documentId, branch, signal) {
8482
+ const scopes = await this.discoverScopes(documentId, branch, signal);
8483
+ const issues = [];
8484
+ for (const scope of scopes) {
8485
+ throwIfAborted(signal);
8486
+ const pair = firstOutOfOrderPair((await this.operationStore.getSince(documentId, scope, branch, -1, void 0, void 0, signal)).results, { requireStrict: scope === "auth" });
8487
+ if (pair !== void 0) issues.push({
8488
+ scope,
8489
+ branch,
8490
+ ...pair
8491
+ });
8492
+ }
8493
+ return issues;
8494
+ }
7331
8495
  async discoverScopes(documentId, branch, signal) {
7332
8496
  const revisions = await this.operationStore.getRevisions(documentId, branch, signal);
7333
8497
  return Object.keys(revisions.revision);
7334
8498
  }
7335
8499
  };
7336
8500
  //#endregion
7337
- export { BaseReadModel, ChannelError, ChannelErrorSource, ChannelScheme, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, DRIVE_AUTH_ERROR_MESSAGES, DefaultSubscriptionErrorHandler, DocumentChangeType, DocumentIntegrityService, DocumentModelRegistry, DocumentModelResolver, DriveClient, DriveCollectionId, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, IntervalPollTimer, InvalidModuleError, JobAwaiter, JobExecutorEventTypes, JobStatus, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, Mailbox, ModuleNotFoundError, NullDocumentModelResolver, OptimisticLockError, PollBehavior, PollingChannelError, ProcessorManager, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, ReactorEventTypes, ReactorSubscriptionManager, ReadModelCoordinator, RelationalDbProcessor, RelationshipChangeType, RevisionMismatchError, SimpleJobExecutorManager, SyncBuilder, SyncEventTypes, SyncOperation, SyncOperationAggregateError, SyncOperationStatus, SyncStatus, SyncStatusTracker, addRelationshipAction, batchOperationsByDocument, consolidateSyncOperations, createDocumentAction, createForwardingLogger, createMutableShutdownStatus, createRelationalDb, deleteDocumentAction, documentActions, driveIdFromUrl, envelopesToSyncOperations, errorToInfo, getMigrationStatus, instrumentPgPool, isDriveAuthError, makeConsistencyKey, parseDriveUrl, parsePagingOptions, removeRelationshipAction, runMigrations, sanitizeArg, trimMailboxFromAckOrdinal, updateRelationshipAction, upgradeDocumentAction, workerEntryPath };
8501
+ export { ALWAYS_READABLE_SCOPES, APPEND_CONDITION_FAILED_PREFIX, AppendConditionFailedError, AuthEnforcementDisabledError, BareReadGate, BaseReadModel, ChannelError, ChannelErrorSource, ChannelScheme, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, DRIVE_AUTH_ERROR_MESSAGES, DefaultSubscriptionErrorHandler, DocumentChangeType, DocumentIntegrityService, DocumentModelRegistry, DocumentModelResolver, DriveClient, DriveCollectionId, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, IntervalPollTimer, InvalidModuleError, JobAwaiter, JobExecutorEventTypes, JobStatus, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, Mailbox, ModelReadGate, ModuleNotFoundError, NullDocumentModelResolver, OptimisticLockError, PollBehavior, PollingChannelError, ProcessorManager, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, RECOVERABLE_GRAPHQL_ERROR_CODES, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, ReactorEventTypes, ReactorSubscriptionManager, ReadModelCoordinator, RelationalDbProcessor, RelationshipChangeType, RetryAccounting, RevisionMismatchError, SeededStateReader, SimpleJobExecutorManager, SyncBuilder, SyncEventTypes, SyncOperation, SyncOperationAggregateError, SyncOperationStatus, SyncScopeGate, SyncStatus, SyncStatusTracker, addRelationshipAction, authDecisionModel, batchOperationsByDocument, buildDecisionModel, classifyJobFailure, consolidateSyncOperations, createDocumentAction, createForwardingLogger, createMutableShutdownStatus, createRelationalDb, decideAtHead, deleteDocumentAction, documentActions, documentDecisionModel, driveIdFromUrl, envelopesToSyncOperations, errorToInfo, firstOutOfOrderPair, getMigrationStatus, instrumentPgPool, isDriveAuthError, isRecoverableGraphQLError, makeConsistencyKey, parseDriveUrl, parsePagingOptions, quarantinesDocument, readDecisionModel, removeRelationshipAction, runMigrations, sanitizeArg, selectDecisionModel, supportsLiveReadModelRegistration, syncOperationErrorType, trimMailboxFromAckOrdinal, updateRelationshipAction, upgradeDocumentAction, workerEntryPath };
7338
8502
 
7339
8503
  //# sourceMappingURL=index.js.map