Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Tighten the search sync comments

Rafi0a6b9f281650
diff --git a/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts b/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
index 8ac6bfc4e6..113925ce0d 100644
--- a/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
+++ b/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
@@ -130,9 +130,8 @@ export async function POST(req: Request) {
const redisRes = await linkCache.expireMany(linksToUpdate);
console.log(`Updated Redis cache: ${JSON.stringify(redisRes, null, 2)}`);
- // A UTM template rewrites each link's destination URL, which the document
- // indexes. The enrollments are already in hand, so this passes them
- // directly rather than resolving them back from the links.
+ // A UTM template rewrites each link's destination URL. The enrollments are
+ // already in hand, so this skips resolving them back from the links.
await queuePartnerSearchSync({
enrollmentIds: programEnrollments.map(({ id }) => id),
delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
diff --git a/apps/web/app/(ee)/api/cron/partners/delete/route.ts b/apps/web/app/(ee)/api/cron/partners/delete/route.ts
index 627a34ca78..86a8ba5e13 100644
--- a/apps/web/app/(ee)/api/cron/partners/delete/route.ts
+++ b/apps/web/app/(ee)/api/cron/partners/delete/route.ts
@@ -159,8 +159,8 @@ export const POST = withCron(async ({ rawBody }) => {
]);
// Queued after the enrollment is gone, so the job reads nothing back and
- // removes the document. The sweep can never do this for us: a pass only sees
- // rows that still exist, so an orphaned document is invisible to it.
+ // removes the document. No sweep can do this: a pass only sees rows that
+ // still exist.
await queuePartnerSearchSync({ enrollmentIds: [enrollment.id] });
await recordAuditLog({
diff --git a/apps/web/app/(ee)/api/cron/partners/merge-accounts/route.ts b/apps/web/app/(ee)/api/cron/partners/merge-accounts/route.ts
index 516382c231..5e94b1dda9 100644
--- a/apps/web/app/(ee)/api/cron/partners/merge-accounts/route.ts
+++ b/apps/web/app/(ee)/api/cron/partners/merge-accounts/route.ts
@@ -327,10 +327,9 @@ export async function POST(req: Request) {
}
}
- // Both sides, because a merge either reassigns a source enrollment to the
- // target partner, which changes every identity field on the document, or
- // deletes it in favour of the target's. Passing all of them lets the job
- // read each one back and work out which happened.
+ // Both sides: a merge either reassigns a source enrollment to the target
+ // partner or deletes it in favour of the target's, and passing all of them
+ // lets the job work out which happened.
await queuePartnerSearchSync({
enrollmentIds: [
...sourcePartnerEnrollments.map(({ id }) => id),
diff --git a/apps/web/app/(ee)/api/cron/partners/search-sweep/route.ts b/apps/web/app/(ee)/api/cron/partners/search-sweep/route.ts
index 830760ad06..faf9104bd1 100644
--- a/apps/web/app/(ee)/api/cron/partners/search-sweep/route.ts
+++ b/apps/web/app/(ee)/api/cron/partners/search-sweep/route.ts
@@ -5,15 +5,11 @@ import { logAndRespond } from "../../utils";
export const dynamic = "force-dynamic";
-// Kicks off a full re-index of the partner search corpus, which the job then
-// carries to completion by re-dispatching itself with a cursor.
+// Kicks off a full re-index, which the job carries to completion by
+// re-dispatching itself with a cursor. The backstop for call-site drift, so the
+// pass interval is the worst-case staleness of any document.
//
-// This is the backstop for call-site drift: a mutation path that never queued a
-// sync, or one added by someone unaware the index exists, is corrected by the
-// next pass rather than staying wrong indefinitely. The pass interval is
-// therefore the worst-case staleness of any document.
-//
-// Runs once a week at 03:00 AM UTC on Sunday (0 3 * * 0)
+// Runs weekly at 03:00 UTC on Sunday (0 3 * * 0)
// GET /api/cron/partners/search-sweep
export const GET = withCron(async () => {
if (!getPartnerSearchProvider()) {
diff --git a/apps/web/lib/actions/partners/bulk-archive-partners.ts b/apps/web/lib/actions/partners/bulk-archive-partners.ts
index c8c08d6434..697060c273 100644
--- a/apps/web/lib/actions/partners/bulk-archive-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-archive-partners.ts
@@ -84,11 +84,9 @@ export const bulkArchivePartnersAction = authActionClient
})),
),
- // Scoped to match the updateMany above, not the findMany. The select
- // is narrowed to ACTIVE_ENROLLMENT_STATUSES while the update is not,
- // so archiving a banned or rejected partner changes a status the
- // selected rows never carried. Passing the partners re-resolves
- // exactly the enrollments the update touched.
+ // Scoped to the updateMany above, not the findMany: the select is
+ // narrowed to ACTIVE_ENROLLMENT_STATUSES and the update is not, so it
+ // also archives statuses the selected rows never carried.
queuePartnerSearchSync({ partnerIds, programId }),
]),
);
diff --git a/apps/web/lib/actions/partners/bulk-invite-partners.ts b/apps/web/lib/actions/partners/bulk-invite-partners.ts
index 66dedf2010..29d15b1509 100644
--- a/apps/web/lib/actions/partners/bulk-invite-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-invite-partners.ts
@@ -200,11 +200,9 @@ export const bulkInvitePartnersAction = authActionClient
);
}
- // createMany returns no IDs, so this passes partners scoped by program
- // and lets the job resolve the enrollments. Queued after the default
- // links exist so the first document already carries them. Partners that
- // skipDuplicates left untouched are re-indexed unchanged, which is
- // cheaper than working out which ones were new.
+ // createMany returns no IDs, so this passes partners and lets the job
+ // resolve the enrollments. Queued after the default links exist, so the
+ // first document already carries them.
await queuePartnerSearchSync({
partnerIds: partners.map(({ id }) => id),
programId,
diff --git a/apps/web/lib/actions/partners/onboard-partner.ts b/apps/web/lib/actions/partners/onboard-partner.ts
index f1f39ec3dd..1a23dfa9f1 100644
--- a/apps/web/lib/actions/partners/onboard-partner.ts
+++ b/apps/web/lib/actions/partners/onboard-partner.ts
@@ -126,10 +126,8 @@ export const onboardPartnerAction = authUserActionClient
// Mark the application event as submitted for the `network` program
markApplicationEventSubmittedNetwork(updatedPartner),
- // Onboarding sets name, country, and description, all of which the
- // document carries. Runs after completeProgramApplications above, which
- // queues its own sync for the enrollments it creates. Both collapse on
- // the same partner, and re-indexing twice is harmless either way.
+ // Onboarding sets name, country and description. Overlaps with the
+ // sync completeProgramApplications queues above, which is harmless.
queuePartnerSearchSync({ partnerIds: [updatedPartner.id] }),
]),
);
diff --git a/apps/web/lib/actions/partners/start-partner-platform-verification.ts b/apps/web/lib/actions/partners/start-partner-platform-verification.ts
index 07479ee041..86233a9125 100644
--- a/apps/web/lib/actions/partners/start-partner-platform-verification.ts
+++ b/apps/web/lib/actions/partners/start-partner-platform-verification.ts
@@ -97,9 +97,8 @@ export const startPartnerPlatformVerificationAction = authPartnerActionClient
const result = await startVerification();
- // All three paths upsert the platform identifier, which is searchable.
- // Queued here, after the write, rather than at each of the four upserts,
- // so one verification produces one sync rather than one per platform row.
+ // All three paths upsert the searchable identifier. Queued once here rather
+ // than at each of the four upserts.
waitUntil(queuePartnerSearchSync({ partnerIds: [partner.id] }));
return result;
diff --git a/apps/web/lib/actions/partners/update-partner-platforms.ts b/apps/web/lib/actions/partners/update-partner-platforms.ts
index cf5baa0013..20c59405a3 100644
--- a/apps/web/lib/actions/partners/update-partner-platforms.ts
+++ b/apps/web/lib/actions/partners/update-partner-platforms.ts
@@ -192,8 +192,7 @@ export const updatePartnerPlatformsAction = authPartnerActionClient
await Promise.all(operations);
- // One queue for the whole action rather than one per platform: a profile
- // change fans out to every program the partner is enrolled in, so this is
- // deliberately not scoped by program.
+ // One queue for the action rather than one per platform, and deliberately
+ // not scoped by program.
waitUntil(queuePartnerSearchSync({ partnerIds: [partner.id] }));
});
diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.ts
index 1a7c2d3452..158b646412 100644
--- a/apps/web/lib/actions/partners/update-partner-profile.ts
+++ b/apps/web/lib/actions/partners/update-partner-profile.ts
@@ -256,9 +256,8 @@ export const updatePartnerProfileAction = authPartnerActionClient
waitUntil(
Promise.allSettled([
- // Name, description, and company name are all searchable, and a
- // profile is shared across programs, so this fans out to every
- // enrollment the partner holds rather than being scoped to one.
+ // A profile is shared across programs, so this is deliberately not
+ // scoped to one.
queuePartnerSearchSync({ partnerIds: [partner.id] }),
(async () => {
diff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.ts
index 05cda53fa8..e5893f3428 100644
--- a/apps/web/lib/api/links/bulk-update-links.ts
+++ b/apps/web/lib/api/links/bulk-update-links.ts
@@ -43,12 +43,9 @@ export async function bulkUpdateLinks(
const imageUrlNonce = nanoid(7);
- // The bulk payload is createLinkBodySchema minus domain/key/externalId, and
- // that omit list does not drop `partnerId` or `programId`, so a bulk update
- // can move links between partners. Read the current owners first, because
- // after the write they are unrecoverable and syncing only the new owner
- // would leave the links searchable under a partner who no longer has them.
- // Only paid for when the payload actually carries an owner.
+ // The bulk payload omits domain/key/externalId but not `partnerId`, so an
+ // update can move links between partners. The former owners are unrecoverable
+ // after the write, so read them first, and only when the payload can move one.
const previousOwners =
rest.partnerId !== undefined || rest.programId !== undefined
? await prisma.link.findMany({
@@ -134,8 +131,7 @@ export async function bulkUpdateLinks(
links: updatedLinks,
}),
// A bulk edit can move the destination URL, and the key or domain behind
- // the short link. Queued on the link delay: the job re-reads the whole
- // document, so nothing else goes stale by waiting.
+ // the short link.
queuePartnerSearchSyncForLinks([...previousOwners, ...updatedLinks], {
delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
}),
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 59194eb331..e938e3a661 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -80,9 +80,7 @@ export async function deleteLink(linkId: string) {
link.discountCode && enqueueDeleteDiscountCode([link.discountCode]),
// The enrollment outlives the link, so this re-serializes the document
- // without it rather than removing the document. Takes the link delay:
- // a deleted short link matching a search is a stale hit, not a wrong one,
- // since the database still filters the candidates the index returns.
+ // without it rather than removing the document.
link.programId &&
link.partnerId &&
queuePartnerSearchSync({
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.ts
index 4c4fad13a4..8557aa2bbf 100644
--- a/apps/web/lib/api/links/update-link.ts
+++ b/apps/web/lib/api/links/update-link.ts
@@ -33,10 +33,9 @@ export async function updateLink({
key: string;
image?: string | null;
testCompletedAt?: Date | null;
- // Required, not optional, because the link body accepts `partnerId` and so
- // an update can move a link between partners. The former owner has to be
- // re-serialized without it, and an optional field here would let the next
- // caller omit it and silently lose that.
+ // Required rather than optional: the link body accepts `partnerId`, so an
+ // update can move a link, and an optional field here would let the next
+ // caller omit the former owner and silently lose its re-index.
programId: string | null;
partnerId: string | null;
};
@@ -212,15 +211,8 @@ export async function updateLink({
// If key is changed: delete the old key in Redis
(changedDomain || changedKey) && linkCache.delete(oldLink),
- // Only the short link and destination URL reach the document, and link
- // edits are frequent, so this takes the longer link delay. The job
- // re-reads the whole document, so nothing else goes stale by waiting.
- //
- // Both owners, because `partnerId` and `programId` are not excluded
- // from the spread above and so can be rewritten. When a link moves
- // between partners the former owner has to be re-serialized without
- // it, and syncing only the new one would leave the link searchable
- // under a partner who no longer has it.
+ // Both owners, because the spread above can rewrite `partnerId`: when a
+ // link moves, the former owner has to be re-serialized without it.
queuePartnerSearchSyncForLinks([oldLink, response], {
delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
}),
diff --git a/apps/web/lib/api/partners/applications/reject-partner.ts b/apps/web/lib/api/partners/applications/reject-partner.ts
index 4768eebf35..8d4417b508 100644
--- a/apps/web/lib/api/partners/applications/reject-partner.ts
+++ b/apps/web/lib/api/partners/applications/reject-partner.ts
@@ -147,10 +147,9 @@ export async function rejectPartner({
waitUntil(
Promise.allSettled([
- // Covers both outcomes above: an instant re-application timeframe deletes
- // the enrollment, anything else rejects it. The job reads the ID back and
- // upserts or deletes accordingly, so this hook does not need to know
- // which branch ran.
+ // Covers both outcomes above: an instant reapplication timeframe deletes
+ // the enrollment, anything else rejects it. The job reads the ID back, so
+ // this does not need to know which ran.
queuePartnerSearchSync({ enrollmentIds: [programEnrollment.id] }),
trackActivityLog({
diff --git a/apps/web/lib/api/partners/queue-partner-search-sync.ts b/apps/web/lib/api/partners/queue-partner-search-sync.ts
index aed80e0699..bf71cdd48c 100644
--- a/apps/web/lib/api/partners/queue-partner-search-sync.ts
+++ b/apps/web/lib/api/partners/queue-partner-search-sync.ts
@@ -6,33 +6,21 @@ import {
} from "./search";
/**
- * How long a sync waits before it runs, so the mutation's transaction has
- * settled by the time the job reads the row back.
+ * How long a sync waits, so the mutation has committed before the job reads the
+ * row back.
*
- * Deliberately not deduplicated. QStash suppresses a repeated key for ten
- * minutes from the first publish, not merely while one is pending, so keying
- * by subject would drop the second of two changes inside that window rather
- * than collapse them. A dropped delete leaves a document nothing can remove.
- * Every edit gets its own job instead, which is safe because the job re-reads
- * current state and is therefore idempotent.
+ * Not deduplicated by subject. QStash suppresses a repeated key for ten minutes
+ * from the first publish, not just while one is pending, so the second of two
+ * changes in that window would be dropped rather than collapsed.
*/
export const PARTNER_SEARCH_SYNC_DELAY_SECONDS = 5;
/**
- * Links change far more often than the other document sources, and a link edit
- * only moves `shortLinks` and `destinationUrls`, so their syncs are spread out
- * rather than run at once. Nothing is lost by waiting: the handler re-reads the
- * whole document, so a late link sync still picks up every other change that
- * landed meanwhile.
+ * Link edits are frequent and only move `shortLinks` and `destinationUrls`, so
+ * their syncs are spread out. Creation uses the default delay, since a new
+ * short link is how people search for that partner.
*
- * This no longer reduces the number of writes. It did when these were
- * deduplicated by subject, and that is gone, so what remains is smoothing when
- * a bulk link operation's jobs run. Flow control is what actually caps the load
- * on the provider, which makes this worth revisiting.
- *
- * Link *creation* uses the default delay instead: a partner's short link is how
- * people search for them, so a newly enrolled partner being unfindable by link
- * is a worse trade than running the job sooner.
+ * Worth revisiting: this stopped reducing writes when deduplication was removed.
*/
export const PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS = 300;
diff --git a/apps/web/lib/api/partners/search/index-enrollments.ts b/apps/web/lib/api/partners/search/index-enrollments.ts
index ef41154383..f6c3af28c6 100644
--- a/apps/web/lib/api/partners/search/index-enrollments.ts
+++ b/apps/web/lib/api/partners/search/index-enrollments.ts
@@ -22,15 +22,12 @@ interface IndexPartnerSearchEnrollmentsOptions {
after?: string;
batchSize: number;
/**
- * Wall-clock budget, checked between batches, so a caller running under a
- * function timeout stops on its own and resumes from the returned cursor.
- * Runs to exhaustion when omitted.
+ * Wall-clock budget, checked between batches, so a caller under a function
+ * timeout stops itself and resumes from the returned cursor. Runs to
+ * exhaustion when omitted.
*
- * A budget rather than a batch count because the constraint being respected
- * is a duration. A batch count only stands in for one if you already know how
- * long a batch takes, which depends on document size, provider latency, and
- * how loaded the database is, and is therefore exactly the thing not worth
- * pinning to a constant.
+ * A duration rather than a batch count, because a batch count only stands in
+ * for one if you already know how long a batch takes.
*/
timeBudgetMs?: number;
/** Injectable clock, so the budget is testable without real time passing. */
@@ -39,16 +36,11 @@ interface IndexPartnerSearchEnrollmentsOptions {
}
/**
- * Pages enrollments by ID and writes them to the index.
+ * Pages enrollments by ID and writes them to the index. Keyset paging, so
+ * per-batch cost stays flat however deep the run gets.
*
- * Keyset paging rather than offset, so per-batch cost stays flat however deep
- * the run gets. Shared by the backfill, which narrows to one program and runs
- * to exhaustion, and the reconciliation sweep, which runs unnarrowed in bounded
- * slices.
- *
- * Upserts only. A document whose enrollment was deleted is not removed here,
- * because an ID absent from a range scan is indistinguishable from one that was
- * never in range. Deletions are the call sites' responsibility.
+ * Upserts only. An ID absent from a range scan is indistinguishable from one
+ * that was never in range, so deletions are the call sites' responsibility.
*/
export async function indexPartnerSearchEnrollments({
searchProvider,
@@ -103,9 +95,8 @@ export async function indexPartnerSearchEnrollments({
break;
}
- // Checked after a batch rather than before, so a run always makes progress
- // however tight the budget is. One batch can therefore overrun it, which is
- // why callers leave headroom rather than budgeting to their whole limit.
+ // Checked after a batch, so a run always makes progress however tight the
+ // budget is. One batch can therefore overrun it, hence the caller headroom.
if (timeBudgetMs !== undefined && now() - startedAt >= timeBudgetMs) {
break;
}
diff --git a/apps/web/lib/api/partners/search/provider.ts b/apps/web/lib/api/partners/search/provider.ts
index 3d5095ac74..d43d60a5f3 100644
--- a/apps/web/lib/api/partners/search/provider.ts
+++ b/apps/web/lib/api/partners/search/provider.ts
@@ -6,18 +6,12 @@ import type { PartnerSearchProvider } from "./types";
let cachedSearchProvider: PartnerSearchProvider | null = null;
/**
- * The provider for everything that writes: the sync jobs, the backfill, and the
- * reconciliation sweep.
+ * The provider for everything that writes: the sync jobs, backfill and sweep.
+ * Null until turbopuffer is configured, which is what keeps this dark.
*
- * Null until turbopuffer is configured, which is what keeps this dark: every
- * caller falls back to the database search path when there is no provider, so
- * an unset key costs the wider field coverage rather than the partner list.
- *
- * Once set in an environment that serves traffic, leave it set. Removing a
- * document is something only the live sync hooks can do, because the backfill
- * and the sweep upsert and never delete. Any window where the app runs with
- * this unset therefore turns every enrollment deleted during it into a document
- * nothing can remove short of rebuilding the namespace.
+ * Once set where traffic is served, leave it set. Only the live sync hooks can
+ * remove a document, so any window with this unset strands every enrollment
+ * deleted during it until the namespace is rebuilt.
*/
export function getPartnerSearchProvider(): PartnerSearchProvider | null {
if (!process.env.TURBOPUFFER_API_KEY?.trim()) {
@@ -33,16 +27,13 @@ export function getPartnerSearchProvider(): PartnerSearchProvider | null {
* Whether the partners list and count read from the index rather than the
* database.
*
- * Reads get their own switch so that turning search off never means turning
- * indexing off. Writes stay on from the first day and are never flipped, so the
- * index keeps tracking deletions even while nothing is reading it, and coming
- * back is a matter of setting this flag rather than rebuilding a namespace.
+ * Separate from the key so that turning search off never turns indexing off.
+ * Writes stay on and are never flipped, so the index keeps tracking deletions
+ * while nothing reads it.
*
- * The same switch is what lets reads stay off until the backfill has finished.
- * An empty index does not fall back to the database: a program with no
- * documents yet produces a successful, empty candidate list, which the callers
- * apply as `id IN ()` after clearing the database search predicate, so every
- * query returns nothing.
+ * It also keeps reads off until the backfill finishes. An empty index does not
+ * fall back: an empty candidate list is applied as `id IN ()` once the database
+ * search predicate is cleared, so every query returns nothing.
*/
export function isPartnerSearchReadEnabled(): boolean {
return process.env.PARTNER_SEARCH_READ_ENABLED?.trim() === "true";
diff --git a/apps/web/lib/api/partners/search/sweep.ts b/apps/web/lib/api/partners/search/sweep.ts
index 3883fa7890..e8fe1e55cf 100644
--- a/apps/web/lib/api/partners/search/sweep.ts
+++ b/apps/web/lib/api/partners/search/sweep.ts
@@ -5,16 +5,10 @@ import type { PartnerSearchProvider } from "./types";
export const PARTNER_SEARCH_SWEEP_BATCH_SIZE = 500;
/**
- * How long one hop indexes before handing off to the next.
- *
- * The job route allows 600s, so this leaves more than half the budget spare.
- * The margin covers the batch in flight when the budget runs out, since the
- * check happens between batches and cannot interrupt one.
- *
- * Deliberately generous rather than tuned. Overrunning the route's limit kills
- * the hop, and QStash then retries the same cursor until it gives up, which
- * stalls the pass with nothing to say so. Finishing a hop early costs one extra
- * message.
+ * How long one hop indexes before handing off. The job route allows 600s, and
+ * the margin covers the batch in flight when the budget expires, since the
+ * check happens between batches. Errs generous: overrunning kills the hop and
+ * QStash retries the same cursor, stalling the pass silently.
*/
export const PARTNER_SEARCH_SWEEP_TIME_BUDGET_MS = 240_000;
@@ -27,24 +21,15 @@ interface SweepPartnerSearchOptions {
}
/**
- * Re-indexes a slice of the corpus, resuming from `after`.
- *
- * This is the backstop for call-site drift. Every hook that fires is an
- * optimization on top of it: a mutation path that forgets to queue a sync, or
- * one added later by someone who does not know the index exists, is corrected
- * by the next pass rather than staying wrong until someone notices.
+ * Re-indexes a slice of the corpus, resuming from `after`. The backstop for
+ * call-site drift: a mutation path that never queued a sync is corrected by the
+ * next pass.
*
- * Re-indexes everything rather than only what a timestamp says changed. A
- * watermark would skip writes, but it cannot see a tag change, because
- * ProgramPartnerTag carries no timestamps, nor a link edit, because that moves
- * neither the enrollment's nor the partner's. Passing over everything is what
- * makes the guarantee unconditional: no document is stale for longer than one
- * pass, whatever drifted and whether or not the column that drifted has a
- * timestamp.
+ * Re-indexes everything rather than filtering by timestamp, because a watermark
+ * cannot see a tag change (ProgramPartnerTag has no timestamps) or a link edit
+ * (which moves neither the enrollment's nor the partner's).
*
- * Deletions stay outside this. A pass only sees rows that still exist, so an
- * orphaned document is invisible to it and is cleared by its call-site hook or
- * by rebuilding the namespace.
+ * Deletions stay outside this. A pass only sees rows that still exist.
*/
export async function sweepPartnerSearch({
after,
diff --git a/apps/web/lib/api/partners/search/sync.ts b/apps/web/lib/api/partners/search/sync.ts
index fab1a449c9..a648f0eef4 100644
--- a/apps/web/lib/api/partners/search/sync.ts
+++ b/apps/web/lib/api/partners/search/sync.ts
@@ -7,9 +7,8 @@ import {
import type { PartnerSearchProvider } from "./types";
/**
- * How many enrollments one sync resolves at a time, matching the backfill's
- * batch size. The provider chunks its own writes below this, so the ceiling
- * here is about how much the database hydrates at once, not the write size.
+ * How many enrollments one sync hydrates at a time. The provider chunks its own
+ * writes below this, so this bounds the database read, not the write.
*/
export const PARTNER_SEARCH_SYNC_BATCH_SIZE = 500;
@@ -30,15 +29,10 @@ function unique(values: string[]): string[] {
/**
* Brings the index in line with the database for the given enrollments.
*
- * Current state is read here rather than passed in by the caller, so a delayed
- * or replayed sync converges on the truth instead of re-applying whatever was
- * true when it was queued. That is also what makes deletes fall out for free:
- * an ID the database no longer has is removed from the index rather than
- * treated as an error, so a caller reacting to a deletion queues the same job
- * as one reacting to an edit.
- *
- * No-ops when no provider is configured, matching the read path, which falls
- * back to the database search rather than failing.
+ * State is read here rather than passed in, so a delayed or replayed sync
+ * converges on current truth. That is also what makes deletes free: an ID the
+ * database no longer has is removed rather than treated as an error, so callers
+ * queue the same payload whether they edited or deleted.
*/
export async function syncPartnerSearchDocuments({
enrollmentIds,
@@ -86,16 +80,12 @@ interface FindPartnerSearchSyncEnrollmentIdsOptions {
}
/**
- * One page of enrollment IDs belonging to the given partners, for the changes
- * that fan out beyond a single enrollment: a profile edit or a platform change
- * touches every program the partner is enrolled in.
- *
- * Paged by enrollment ID so the caller can resume, because the fan-out is
- * unbounded: a partner enrolled in hundreds of programs produces hundreds of
- * documents from one profile write.
+ * One page of enrollment IDs for the given partners, for changes that fan out
+ * beyond a single enrollment: a profile or platform edit touches every program
+ * the partner is in.
*
- * `programId` narrows to a single enrollment per partner, which is what the
- * enrollment-scoped callers (group moves, status changes, tags) pass.
+ * Paged because that fan-out is unbounded. `programId` narrows it to one
+ * enrollment per partner.
*/
export async function findPartnerSearchSyncEnrollmentIds({
partnerIds,
diff --git a/apps/web/lib/jobs/handlers/partner-search-sync-job.ts b/apps/web/lib/jobs/handlers/partner-search-sync-job.ts
index ad1600c6d8..1da988e098 100644
--- a/apps/web/lib/jobs/handlers/partner-search-sync-job.ts
+++ b/apps/web/lib/jobs/handlers/partner-search-sync-job.ts
@@ -8,24 +8,20 @@ import * as z from "zod/v4";
import { defineJob } from "../index";
/**
- * How many concurrent syncs may aim writes at the provider at once. A bulk
- * group move fans out to dozens of jobs, and without a ceiling they would all
- * write at the same moment. Interactive single-partner edits queue behind that
- * work, which is the tradeoff: a search index a few seconds stale is cheaper
- * than a rate-limited provider. Tune against the provider's write limits.
+ * How many syncs may write to the provider at once. A bulk group move fans out
+ * to dozens of jobs that would otherwise all write at the same moment.
+ * Interactive edits queue behind that, which is the trade. Tune against the
+ * provider's write limits.
*/
const SYNC_PARALLELISM = 20;
/**
* Two shapes, because the two kinds of change have different blast radii.
*
- * `enrollments` carries IDs the caller already knows, and is the only shape
- * that can express a deletion, because the handler discovers an enrollment is gone by
- * failing to read it back.
- *
- * `partners` is for changes that fan out beyond one enrollment (a profile edit,
- * a platform change), where the caller knows the partner but not how many
- * programs it reaches.
+ * `enrollments` carries IDs the caller already has, and is the only shape that
+ * can express a deletion, since the handler finds out by failing to read one
+ * back. `partners` is for changes that fan out past one enrollment, where the
+ * caller knows the partner but not how many programs it reaches.
*/
const inputSchema = z.discriminatedUnion("type", [
z.object({
@@ -56,9 +52,8 @@ export const partnerSearchSyncJob = defineJob({
async handle(input) {
const searchProvider = getPartnerSearchProvider();
- // Matches the read path, which falls back to the database search rather
- // than failing. An environment without the key should not accumulate a
- // backlog of jobs that can never succeed.
+ // An environment without the key should not accumulate a backlog of jobs
+ // that can never succeed.
if (!searchProvider) {
console.log(
"[partnerSearchSyncJob] No search provider configured. Skipping...",
@@ -90,9 +85,8 @@ export const partnerSearchSyncJob = defineJob({
return;
}
- // These IDs came from the database a moment ago, so the sync will upsert
- // rather than delete them, unless the enrollment disappeared in between,
- // in which case removing it from the index is the right outcome anyway.
+ // These IDs came from the database a moment ago, so this upserts rather
+ // than deletes, unless one vanished in between, which is also correct.
const { upserted, deleted } = await syncPartnerSearchDocuments({
enrollmentIds,
searchProvider,
diff --git a/apps/web/lib/partners/complete-program-applications.ts b/apps/web/lib/partners/complete-program-applications.ts
index e44e561727..b98552bc06 100644
--- a/apps/web/lib/partners/complete-program-applications.ts
+++ b/apps/web/lib/partners/complete-program-applications.ts
@@ -91,9 +91,7 @@ export async function completeProgramApplications(userEmail: string) {
const partner = user.partners[0].partner;
// Program enrollments to create. `id` is narrowed to required because the
- // search sync below reads it back: Prisma leaves it optional on the create
- // input, so without this the invariant would have to be asserted at the
- // point of use rather than guaranteed here, where it is actually set.
+ // search sync below reads it back, and Prisma leaves it optional here.
const programEnrollments: (Prisma.ProgramEnrollmentCreateManyInput & {
id: string;
})[] = filteredProgramApplications.map((programApplication) => ({
@@ -276,9 +274,8 @@ export async function completeProgramApplications(userEmail: string) {
),
);
- // One queue at the end covers both the new enrollments and the platforms
- // backfilled from the application above, since the job re-reads the whole
- // document rather than the fields any one write touched.
+ // One queue covers both the new enrollments and the platforms backfilled
+ // above, since the job re-reads the whole document.
await queuePartnerSearchSync({
enrollmentIds: programEnrollments.map(({ id }) => id),
});
diff --git a/apps/web/tests/partners/queue-partner-search-sync.test.ts b/apps/web/tests/partners/queue-partner-search-sync.test.ts
index aa61bc3a3c..89fe23b162 100644
--- a/apps/web/tests/partners/queue-partner-search-sync.test.ts
+++ b/apps/web/tests/partners/queue-partner-search-sync.test.ts
@@ -94,9 +94,8 @@ describe("queuePartnerSearchSync", () => {
});
// QStash suppresses a repeated key for ten minutes from the first publish,
- // not merely while one is pending. Keying by subject would therefore drop the
- // second of two changes inside that window, and a dropped delete leaves a
- // document nothing can remove. Every change gets its own job instead.
+ // not just while one is pending, so keying by subject would drop the second of
+ // two changes rather than collapse them.
it("never deduplicates, so a later change cannot be dropped", async () => {
await queuePartnerSearchSync({ enrollmentIds: ["pge_1"] });
await queuePartnerSearchSync({ enrollmentIds: ["pge_1"] });