-
Notifications
You must be signed in to change notification settings - Fork 729
feat: add backfill script (CM-1218) #4193
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ulemons
wants to merge
1
commit into
feat/stewardship-tables
Choose a base branch
from
feat/backfill-stewardship-script
base: feat/stewardship-tables
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
services/apps/packages_worker/src/bin/stewardship-backfill.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import { getServiceLogger } from '@crowd/logging' | ||
|
|
||
| import { getPackagesDb } from '../db' | ||
| import { runStewardshipBackfill } from '../stewardship/runStewardshipBackfill' | ||
|
|
||
| const log = getServiceLogger() | ||
|
|
||
| let shuttingDown = false | ||
|
|
||
| // Graceful stop: finish the in-flight batch, then exit. Safe to interrupt — every | ||
| // write is ON CONFLICT DO NOTHING so re-running resumes where it left off. | ||
| const shutdown = () => { | ||
| if (shuttingDown) return | ||
| shuttingDown = true | ||
| log.info('Shutting down stewardship backfill (stopping after the current batch)...') | ||
| } | ||
|
|
||
| process.on('SIGINT', shutdown) | ||
| process.on('SIGTERM', shutdown) | ||
|
|
||
| const main = async () => { | ||
| log.info('stewardship backfill starting...') | ||
|
|
||
| const qx = await getPackagesDb() | ||
| await qx.selectOne('SELECT 1') | ||
| log.info('Connected to packages-db.') | ||
|
|
||
| const rawBatchSize = parseInt(process.env.STEWARDSHIP_BACKFILL_BATCH_SIZE ?? '10000', 10) | ||
| if (!Number.isFinite(rawBatchSize) || rawBatchSize <= 0) { | ||
| throw new Error( | ||
| `STEWARDSHIP_BACKFILL_BATCH_SIZE must be a positive integer, got: ${process.env.STEWARDSHIP_BACKFILL_BATCH_SIZE}`, | ||
| ) | ||
| } | ||
| const batchSize = rawBatchSize | ||
|
|
||
| const totals = await runStewardshipBackfill(qx, { batchSize }, () => shuttingDown) | ||
|
|
||
| log.info({ ...totals }, 'stewardship backfill complete') | ||
| process.exit(0) | ||
| } | ||
|
|
||
| main().catch((err) => { | ||
| log.error({ err }, 'stewardship backfill fatal error') | ||
| process.exit(1) | ||
| }) |
60 changes: 60 additions & 0 deletions
60
services/apps/packages_worker/src/stewardship/runStewardshipBackfill.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { | ||
| QueryExecutor, | ||
| insertUnassignedStewardships, | ||
| listCriticalPackagesWithoutStewardship, | ||
| } from '@crowd/data-access-layer' | ||
| import { getServiceChildLogger } from '@crowd/logging' | ||
|
|
||
| const log = getServiceChildLogger('stewardship-backfill') | ||
|
|
||
| export interface BackfillResult { | ||
| inserted: number | ||
| skipped: number | ||
| batches: number | ||
| } | ||
|
|
||
| interface BackfillOptions { | ||
| batchSize: number | ||
| } | ||
|
|
||
| /** | ||
| * Seeds one `stewardships` row (status=unassigned, origin=auto_imported) for | ||
| * every critical package that doesn't already have one. Idempotent: ON CONFLICT | ||
| * DO NOTHING means re-running is safe and will just report 0 inserts. | ||
| * | ||
| * Designed to be called from a Temporal activity or directly from the bin script. | ||
| * The `isStopping` callback lets the caller signal a graceful shutdown between | ||
| * batches — the function returns the totals collected so far. | ||
| */ | ||
| export async function runStewardshipBackfill( | ||
| qx: QueryExecutor, | ||
| options: BackfillOptions, | ||
| isStopping: () => boolean = () => false, | ||
| ): Promise<BackfillResult> { | ||
| const { batchSize } = options | ||
| let lastId = 0 | ||
| let inserted = 0 | ||
| let skipped = 0 | ||
| let batches = 0 | ||
|
|
||
| while (!isStopping()) { | ||
| const ids = await listCriticalPackagesWithoutStewardship(qx, { | ||
| afterId: lastId, | ||
| limit: batchSize, | ||
| }) | ||
|
|
||
| if (ids.length === 0) break | ||
|
|
||
| const batchInserted = await insertUnassignedStewardships(qx, ids) | ||
| const batchSkipped = ids.length - batchInserted | ||
|
|
||
| inserted += batchInserted | ||
| skipped += batchSkipped | ||
| batches++ | ||
| lastId = ids[ids.length - 1] | ||
|
|
||
| log.info({ batches, inserted, skipped, lastId, batchInserted, batchSkipped }, 'Batch complete.') | ||
| } | ||
|
|
||
| return { inserted, skipped, batches } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
services/libs/data-access-layer/src/osspckgs/stewardships.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import { QueryExecutor } from '../queryExecutor' | ||
|
|
||
| /** | ||
| * Returns a page of critical package ids that do not yet have a stewardship row, | ||
| * ordered by id ascending. Used as the cursor-based pagination source for the | ||
| * stewardship backfill. | ||
| */ | ||
| export async function listCriticalPackagesWithoutStewardship( | ||
| qx: QueryExecutor, | ||
| options: { afterId: number; limit: number }, | ||
| ): Promise<number[]> { | ||
| // pg returns BIGINT columns as strings; Number() is safe here because | ||
| // package ids are well within JS safe-integer range. | ||
| const rows: Array<{ id: string | number }> = await qx.select( | ||
| ` | ||
| SELECT p.id | ||
| FROM packages p | ||
| LEFT JOIN stewardships s ON s.package_id = p.id | ||
| WHERE p.is_critical = true | ||
| AND p.id > $(afterId) | ||
| AND s.package_id IS NULL | ||
| ORDER BY p.id ASC | ||
| LIMIT $(limit) | ||
| `, | ||
| options, | ||
| ) | ||
| return rows.map((r) => Number(r.id)) | ||
| } | ||
|
|
||
| /** | ||
| * Inserts one unassigned stewardship row per package id. Idempotent: | ||
| * ON CONFLICT DO NOTHING skips ids that already have a row. | ||
| * Returns the number of rows actually inserted. | ||
| * | ||
| * Re-checks is_critical at insert time to guard against concurrent criticality | ||
| * changes between the SELECT and INSERT phases. | ||
| */ | ||
| export async function insertUnassignedStewardships( | ||
| qx: QueryExecutor, | ||
| packageIds: number[], | ||
| ): Promise<number> { | ||
| if (packageIds.length === 0) return 0 | ||
| const result: { count: string } = await qx.selectOne( | ||
| ` | ||
| WITH ins AS ( | ||
| INSERT INTO stewardships (package_id, status, origin, opened_at, last_status_at) | ||
| SELECT p.id, 'unassigned', 'auto_imported', NOW(), NOW() | ||
| FROM packages p | ||
| WHERE p.id = ANY($(packageIds)::bigint[]) | ||
| AND p.is_critical = true | ||
| ON CONFLICT (package_id) DO NOTHING | ||
| RETURNING 1 | ||
| ) | ||
| SELECT COUNT(*) AS count FROM ins | ||
| `, | ||
| { packageIds }, | ||
| ) | ||
| return parseInt(result.count, 10) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cursor skips newly critical packages
Medium Severity
The backfill advances
lastIdand only lists packages withp.id > afterId. Critical packages whoseis_criticalflips to true after that id was passed are never selected in that run, yet the loop still exits when no higher ids remain. Those packages stay without astewardshipsrow until the job is run again from the start.Additional Locations (1)
services/libs/data-access-layer/src/osspckgs/stewardships.ts#L19-L21Reviewed by Cursor Bugbot for commit 399b9ba. Configure here.