@@ -3847,6 +3847,7 @@ export class ExactReviewQueue {
38473847 new Set(snapshotBatchOwnership.itemKeys),
38483848 snapshotBatchOwnership.activeBatches,
38493849 this.freshPublicationItemKeysSync(snapshot, startedAt),
3850+ this.supersededPublicationItemKeysSync(snapshot),
38503851 );
38513852 let snapshotBatchCandidates = snapshotBatchDeparture?.due
38523853 ? this.publicationBatchCandidates(
@@ -3912,6 +3913,7 @@ export class ExactReviewQueue {
39123913 new Set(snapshotBatchOwnership.itemKeys),
39133914 snapshotBatchOwnership.activeBatches,
39143915 this.freshPublicationItemKeysSync(snapshot, recheckedAt),
3916+ this.supersededPublicationItemKeysSync(snapshot),
39153917 );
39163918 snapshotBatchCandidates = snapshotBatchDeparture?.due
39173919 ? this.publicationBatchCandidates(
@@ -5929,7 +5931,10 @@ export class ExactReviewQueue {
59295931 // shared helper counts candidate rows, so widen only its scan window by
59305932 // requestedSize; passing +1 here would silently collapse every batch to one.
59315933 const activePublishers = exactReviewQueueActivePublicationCount(state);
5932- const excludedItemKeys = new Set<string>(batchOwnership.itemKeys);
5934+ const excludedItemKeys = new Set<string>([
5935+ ...batchOwnership.itemKeys,
5936+ ...this.supersededPublicationItemKeysSync(state),
5937+ ]);
59335938 for (const item of Object.values(state.items)) {
59345939 // Direct receipts and terminal acknowledgement drivers must remain on
59355940 // the normal publisher. Exclude them before admission so they cannot
@@ -5940,14 +5945,8 @@ export class ExactReviewQueue {
59405945 if (exactReviewGithubCircuitBlocksItem(state, item, now)) {
59415946 excludedItemKeys.add(item.key);
59425947 }
5943- const revision = exactReviewPublicationRevision(item.decision);
5944- if (
5945- revision &&
5946- revision.sourceRevision < this.publicationHeadRevisionSync(revision.targetKey)
5947- ) {
5948- excludedItemKeys.add(item.key);
5949- }
59505948 }
5949+ const freshItemKeys = this.freshPublicationItemKeysSync(state, now);
59515950 const readyCandidates =
59525951 activePublishers >= publicationCapacity
59535952 ? []
@@ -5960,28 +5959,25 @@ export class ExactReviewQueue {
59605959 excludedItemKeys,
59615960 false, // batching replaces legacy publication blocking at this admission point
59625961 true, // one durable item path per commit; later events remain FIFO candidates
5963- this.freshPublicationItemKeysSync(state, now) ,
5962+ freshItemKeys ,
59645963 exactReviewPublicationFreshLaneMaxItems(this.env),
59655964 )
59665965 // A direct receipt has already committed its GitHub effect. Its
59675966 // immutable lifecycle plan must return through the fenced legacy
59685967 // publisher, which is the only path that replays that plan.
59695968 .filter(exactReviewQueueIsBatchablePublication)
5970- .filter((item) => !item.terminalFinalization)
5971- .filter((item) => {
5972- const revision = exactReviewPublicationRevision(item.decision);
5973- return (
5974- !revision ||
5975- revision.sourceRevision >= this.publicationHeadRevisionSync(revision.targetKey)
5976- );
5977- });
5978- const firstOwner = readyCandidates[0]?.decision.targetRepo.split("/", 1)[0]?.toLowerCase();
5969+ .filter((item) => !item.terminalFinalization);
5970+ const selection = exactReviewPublicationBatchSelection(
5971+ readyCandidates,
5972+ freshItemKeys,
5973+ exactReviewPublicationBatchSize(this.env),
5974+ exactReviewPublicationBatchWaitMs(this.env),
5975+ now,
5976+ );
59795977 // One GitHub App installation token is scoped to one owner. Keeping a batch
59805978 // owner-homogeneous lets the workflow retain least privilege without serially
59815979 // minting and exporting a different credential for every item.
5982- return readyCandidates
5983- .filter((item) => item.decision.targetRepo.split("/", 1)[0]?.toLowerCase() === firstOwner)
5984- .slice(0, leaseSize);
5980+ return selection?.candidates.slice(0, leaseSize) ?? [];
59855981 }
59865982
59875983 private async claimPublicationBatch(value: unknown) {
@@ -7853,6 +7849,20 @@ export class ExactReviewQueue {
78537849 return Number(row?.source_revision || 0);
78547850 }
78557851
7852+ private supersededPublicationItemKeysSync(state: ExactReviewQueueState) {
7853+ // Active batch ownership can preserve an older row after a newer head lands.
7854+ // Departure and claim must exclude that same row when ownership expires.
7855+ return new Set(
7856+ Object.values(state.items).flatMap((item) => {
7857+ const revision = exactReviewPublicationRevision(item.decision);
7858+ return revision &&
7859+ revision.sourceRevision < this.publicationHeadRevisionSync(revision.targetKey)
7860+ ? [item.key]
7861+ : [];
7862+ }),
7863+ );
7864+ }
7865+
78567866 private nextExactReviewItemRevisionSync(itemKey: string, minimumRevision = 1): number {
78577867 return Math.max(minimumRevision, this.publicationHeadRevisionSync(itemKey.toLowerCase()) + 1);
78587868 }
@@ -10854,6 +10864,7 @@ export class ExactReviewQueue {
1085410864 new Set(batchOwnership.itemKeys),
1085510865 batchOwnership.activeBatches,
1085610866 this.freshPublicationItemKeysSync(state, now),
10867+ this.supersededPublicationItemKeysSync(state),
1085710868 );
1085810869 const sourceAuthorityNext = await this.nextSourceAuthorityVerificationAt();
1085910870 const commandIntakeNext = this.commandIntakeStore.nextAttemptAt();
@@ -12959,6 +12970,7 @@ function exactReviewPublicationBatchDeparture(
1295912970 ownedItemKeys: ReadonlySet<string>,
1296012971 activeBatchCount: number,
1296112972 freshItemKeys: ReadonlySet<string> = new Set(),
12973+ supersededItemKeys: ReadonlySet<string> = new Set(),
1296212974) {
1296312975 if (
1296412976 !exactReviewPublicationBatchingEnabled(env) ||
@@ -12974,47 +12986,35 @@ function exactReviewPublicationBatchDeparture(
1297412986 item.state === "pending" &&
1297512987 !item.terminalFinalization &&
1297612988 !ownedItemKeys.has(item.key) &&
12989+ !supersededItemKeys.has(item.key) &&
1297712990 !exactReviewGithubCircuitBlocksItem(state, item, now),
1297812991 )
1297912992 .sort((left, right) => left.createdAt - right.createdAt || left.key.localeCompare(right.key)),
1298012993 freshItemKeys,
1298112994 exactReviewPublicationFreshLaneMaxItems(env),
1298212995 );
1298312996 const maxItems = exactReviewPublicationBatchSize(env);
12997+ const waitMs = exactReviewPublicationBatchWaitMs(env);
1298412998 const nextEligibilityAt = pending.reduce(
1298512999 (earliest, item) =>
1298613000 item.nextAttemptAt > now ? Math.min(earliest, item.nextAttemptAt) : earliest,
1298713001 Number.POSITIVE_INFINITY,
1298813002 );
1298913003 const candidates = pending.filter((item) => item.nextAttemptAt <= now);
12990- const freshOwner = candidates
12991- .find((item) => freshItemKeys.has(item.key))
12992- ?.decision.targetRepo.split("/", 1)[0]
12993- ?.toLowerCase();
12994- const owner = freshOwner ?? candidates[0]?.decision.targetRepo.split("/", 1)[0]?.toLowerCase();
12995- if (!owner) {
13004+ const selection = exactReviewPublicationBatchSelection(
13005+ candidates,
13006+ freshItemKeys,
13007+ maxItems,
13008+ waitMs,
13009+ now,
13010+ );
13011+ if (!selection) {
1299613012 return Number.isFinite(nextEligibilityAt)
1299713013 ? { candidateCount: 0, maxItems, dueAt: nextEligibilityAt, due: false }
1299813014 : null;
1299913015 }
13000- const candidatesByOwner = new Map<string, ExactReviewQueueItem[]>();
13001- for (const item of candidates) {
13002- const candidateOwner = item.decision.targetRepo.split("/", 1)[0]?.toLowerCase();
13003- if (!candidateOwner) continue;
13004- const group = candidatesByOwner.get(candidateOwner) ?? [];
13005- group.push(item);
13006- candidatesByOwner.set(candidateOwner, group);
13007- }
13008- // Keep a fresh owner's bounded service even when another owner could fill a
13009- // historical batch. Without fresh work, retain the existing full-owner choice.
13010- const selectedOwner =
13011- freshOwner ??
13012- [...candidatesByOwner].find(([, group]) => group.length >= maxItems)?.[0] ??
13013- owner;
13014- const ownerCandidates = candidatesByOwner.get(selectedOwner)!;
13015- const oldestAt = ownerCandidates[0]!.createdAt;
13016- const fullAt = ownerCandidates.length >= maxItems ? now : Number.POSITIVE_INFINITY;
13017- const ageAt = oldestAt + exactReviewPublicationBatchWaitMs(env);
13016+ const fullAt = selection.candidates.length >= maxItems ? now : Number.POSITIVE_INFINITY;
13017+ const ageAt = selection.oldestAt + waitMs;
1301813018 const lastAttemptAt = Number(state.dispatcher?.publicationBatchDispatchedAt || 0);
1301913019 const dispatchRetryMs = state.dispatcher?.publicationBatchDispatchSucceeded
1302013020 ? exactReviewPublicationBatchDispatchCooldownMs(env)
@@ -13028,13 +13028,63 @@ function exactReviewPublicationBatchDeparture(
1302813028 // so they must retain their own wake-up even when today's partial batch is older.
1302913029 const dueAt = Math.min(dispatchDueAt, nextEligibilityAt);
1303013030 return {
13031- candidateCount: ownerCandidates .length,
13031+ candidateCount: selection.candidates .length,
1303213032 maxItems,
1303313033 dueAt,
1303413034 due: dueAt <= now,
1303513035 };
1303613036}
1303713037
13038+ function exactReviewPublicationBatchSelection(
13039+ candidates: ExactReviewQueueItem[],
13040+ freshItemKeys: ReadonlySet<string>,
13041+ maxItems: number,
13042+ waitMs: number,
13043+ now: number,
13044+ ) {
13045+ const candidatesByOwner = new Map<string, ExactReviewQueueItem[]>();
13046+ let oldest: ExactReviewQueueItem | undefined;
13047+ let oldestAged: ExactReviewQueueItem | undefined;
13048+ for (const item of candidates) {
13049+ const owner = item.decision.targetRepo.split("/", 1)[0]?.toLowerCase();
13050+ if (!owner) continue;
13051+ const group = candidatesByOwner.get(owner) ?? [];
13052+ group.push(item);
13053+ candidatesByOwner.set(owner, group);
13054+ if (
13055+ !oldest ||
13056+ item.createdAt < oldest.createdAt ||
13057+ (item.createdAt === oldest.createdAt && item.key.localeCompare(oldest.key) < 0)
13058+ ) {
13059+ oldest = item;
13060+ }
13061+ if (
13062+ item.createdAt + waitMs <= now &&
13063+ (!oldestAged ||
13064+ item.createdAt < oldestAged.createdAt ||
13065+ (item.createdAt === oldestAged.createdAt && item.key.localeCompare(oldestAged.key) < 0))
13066+ ) {
13067+ oldestAged = item;
13068+ }
13069+ }
13070+ const ownerFor = (item: ExactReviewQueueItem | undefined) =>
13071+ item?.decision.targetRepo.split("/", 1)[0]?.toLowerCase();
13072+ // Departure and claim must choose the same installation owner. Once an
13073+ // owner's oldest work has waited a full batch window, cross-owner fresh/full
13074+ // optimization yields to that owner; ordering within the owner stays intact.
13075+ const selectedOwner =
13076+ ownerFor(oldestAged) ??
13077+ ownerFor(candidates.find((item) => freshItemKeys.has(item.key))) ??
13078+ [...candidatesByOwner].find(([, group]) => group.length >= maxItems)?.[0] ??
13079+ ownerFor(oldest);
13080+ const selected = selectedOwner ? candidatesByOwner.get(selectedOwner) : undefined;
13081+ if (!selected?.length) return null;
13082+ return {
13083+ candidates: selected,
13084+ oldestAt: oldest!.createdAt,
13085+ };
13086+ }
13087+
1303813088function exactReviewBatchDispatcherFields(dispatcher: ExactReviewQueueState["dispatcher"]) {
1303913089 return {
1304013090 ...(dispatcher?.githubCredentialCircuits
0 commit comments