Skip to content

feat: add account_advisory backfill job - #2285

Open
katarinazaprazna wants to merge 1 commit into
RedHatInsights:masterfrom
katarinazaprazna:add-aggregator-backfill-job
Open

feat: add account_advisory backfill job#2285
katarinazaprazna wants to merge 1 commit into
RedHatInsights:masterfrom
katarinazaprazna:add-aggregator-backfill-job

Conversation

@katarinazaprazna

@katarinazaprazna katarinazaprazna commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds account_advisory_backfill job to populate historical data in account_advisory

Follow-up

  • Unsuspend the job via app-interface when ready to run
  • Verify it ran and suspend it again (or remove entirely)

Secure Coding Practices Checklist GitHub Link

Secure Coding Checklist

  • Input Validation
  • Output Encoding
  • Authentication and Password Management
  • Session Management
  • Access Control
  • Cryptographic Practices
  • Error Handling and Logging
  • Data Protection
  • Communication Security
  • System Configuration
  • Database Security
  • File Management
  • Memory Management
  • General Coding Practices

Summary by Sourcery

Add a suspended, schedulable job to backfill historical data into the account_advisory table and perform advisory drift checks per account.

New Features:

  • Introduce the account_advisory_backfill job entrypoint for running the backfill logic.
  • Add configuration and scheduling parameters for the account-advisory-backfill cron job in the deployment manifest.

Enhancements:

  • Expose advisory drift checking via a public CheckAdvisoryDrift function and reuse it after backfilling account data.

Tests:

  • Update drift check tests to exercise the exported CheckAdvisoryDrift function rather than the previous unexported helper.

@sourcery-ai

sourcery-ai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds a new one-off account advisory backfill job, wires it into the job runner and Kubernetes cronjob configuration, and introduces supporting cache-task orchestration and public advisory drift checking to validate the populated data.

File-Level Changes

Change Details Files
Introduce an account advisory backfill cache task and wire it into the job runner.
  • Add RunAccountAdvisoryBackfill entry in cache tasks with standard job orchestration and logging.
  • Create BackfillAccountAdvisory workflow that loads all rh_account IDs and runs per-account backfill in parallel with bounded concurrency.
  • For each account, invoke the backfill_account_advisory database function inside a write transaction and then compute advisory IDs from account_advisory to run a drift check.
tasks/caches/caches.go
tasks/caches/backfill_account_advisory.go
main.go
Expose advisory drift checking for reuse and adjust existing callers and tests.
  • Export checkAdvisoryDrift as CheckAdvisoryDrift to allow invocation from the backfill workflow.
  • Update event processing to call the exported CheckAdvisoryDrift function.
  • Fix drift check tests to use the new exported function name.
aggregator/drift_check.go
aggregator/events.go
aggregator/drift_check_test.go
Register the account advisory backfill job as a Kubernetes cronjob with configuration parameters.
  • Add an account-advisory-backfill cronjob object using the job runner entrypoint and account_advisory_backfill job name.
  • Reuse database-admin init container to ensure DB migration readiness before running the backfill job.
  • Introduce ACCOUNT_ADVISORY_BACKFILL_SCHEDULE and ACCOUNT_ADVISORY_BACKFILL_SUSPEND parameters, defaulting to a nightly schedule and suspended state.
deploy/clowdapp.yaml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@katarinazaprazna
katarinazaprazna marked this pull request as ready for review July 29, 2026 23:38
@katarinazaprazna
katarinazaprazna requested a review from a team as a code owner July 29, 2026 23:38

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • The backfill goroutines don’t appear to honor any cancellation/timeout context, so consider threading a context through BackfillAccountAdvisory/WithTx to allow the job to terminate promptly when the process receives a shutdown signal.
  • The fixed concurrency limit (guard := make(chan struct{}, 4)) is hard-coded; consider making this configurable (e.g., via an environment variable) so you can tune throughput vs. DB load without code changes.
  • Per-account LogInfo calls in the inner loop may generate very noisy logs for large rh_account tables; you might want to log only on failures and periodically on progress (e.g., every N accounts) instead.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The backfill goroutines don’t appear to honor any cancellation/timeout context, so consider threading a context through `BackfillAccountAdvisory`/`WithTx` to allow the job to terminate promptly when the process receives a shutdown signal.
- The fixed concurrency limit (`guard := make(chan struct{}, 4)`) is hard-coded; consider making this configurable (e.g., via an environment variable) so you can tune throughput vs. DB load without code changes.
- Per-account `LogInfo` calls in the inner loop may generate very noisy logs for large `rh_account` tables; you might want to log only on failures and periodically on progress (e.g., every N accounts) instead.

## Individual Comments

### Comment 1
<location path="tasks/caches/backfill_account_advisory.go" line_range="31" />
<code_context>
+
+	utils.LogInfo("accounts", len(rhAccountIDs), "starting account_advisory backfill")
+
+	guard := make(chan struct{}, 4)
+
+	for i, rhAccountID := range rhAccountIDs {
</code_context>
<issue_to_address>
**suggestion:** Make the backfill concurrency level configurable instead of hard-coded.

The guard channel currently hard-codes concurrency to 4, which may not suit all environments or align with other job settings. Please source this from configuration (or at least a shared constant) so it can be tuned without code changes and kept consistent with other concurrency controls.

Suggested implementation:

```golang
	utils.LogInfo("accounts", len(rhAccountIDs), "starting account_advisory backfill")

	guard := make(chan struct{}, accountAdvisoryBackfillConcurrency)

```

Please also:
1. Define a shared constant near the top of `tasks/caches/backfill_account_advisory.go` (or in a common config/constants file) like:
   `const accountAdvisoryBackfillConcurrency = 4`
2. If your codebase has a central configuration mechanism (e.g., environment-driven or a config struct), consider wiring `accountAdvisoryBackfillConcurrency` from there instead of a literal, so this value can be tuned per environment.
</issue_to_address>

### Comment 2
<location path="tasks/caches/backfill_account_advisory.go" line_range="19-22" />
<code_context>
+
+func backfillAccountAdvisoryPerAccounts(wg *sync.WaitGroup) {
+	var rhAccountIDs []int
+	err := tasks.WithReadReplicaTx(func(tx *gorm.DB) error {
+		return tx.Table("rh_account").
+			Order("hash_partition_id(id, 128), id").
+			Pluck("id", &rhAccountIDs).Error
+	})
+	if err != nil {
</code_context>
<issue_to_address>
**suggestion (performance):** Loading all account IDs into memory at once may not scale well for large datasets.

This loads all rh_account IDs into a slice before starting any work, which can use a lot of memory and delay processing if the table is large. Consider batching (e.g., LIMIT/OFFSET, cursor/streaming, or server-side pagination) so the backfill can run incrementally with bounded memory.

Suggested implementation:

```golang
func backfillAccountAdvisoryPerAccounts(wg *sync.WaitGroup) {
	const batchSize = 1000

	guard := make(chan struct{}, 4)

	offset := 0

	for {
		var rhAccountIDs []int

		err := tasks.WithReadReplicaTx(func(tx *gorm.DB) error {
			return tx.Table("rh_account").
				Order("hash_partition_id(id, 128), id").
				Limit(batchSize).
				Offset(offset).
				Pluck("id", &rhAccountIDs).Error
		})
		if err != nil {
			utils.LogError("err", err, "unable to load rh_account IDs for account_advisory backfill")
			return
		}

		if len(rhAccountIDs) == 0 {
			break
		}

		utils.LogInfo(
			"batch_size", len(rhAccountIDs),
			"offset", offset,
			"starting account_advisory backfill batch",
		)

		for i, rhAccountID := range rhAccountIDs {
			guard <- struct{}{}

```

Because only part of the function body is visible, you need to:

1. Ensure that the existing per-account processing logic (the code that currently follows `guard <- struct{}{}` and uses `i` and `rhAccountID`) remains unchanged and now operates inside the per-batch inner loop.
2. Confirm that the loop and function are properly closed after your existing per-account logic.
3. Optionally, increment `offset` by the number of IDs processed in each batch (e.g., `offset += len(rhAccountIDs)` at the end of the `for { ... }` loop) if you want deterministic pagination; if you rely on a stable order and no concurrent inserts/deletes, you may instead switch to keyset pagination on `id` for better robustness.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tasks/caches/backfill_account_advisory.go
Comment thread tasks/caches/backfill_account_advisory.go
@codecov-commenter

codecov-commenter commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 4.00000% with 48 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.95%. Comparing base (7ae4e4b) to head (994fe9b).

Files with missing lines Patch % Lines
tasks/caches/backfill_account_advisory.go 0.00% 40 Missing ⚠️
tasks/caches/caches.go 0.00% 6 Missing ⚠️
main.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2285      +/-   ##
==========================================
- Coverage   59.27%   58.95%   -0.32%     
==========================================
  Files         148      149       +1     
  Lines        9488     9536      +48     
==========================================
- Hits         5624     5622       -2     
- Misses       3276     3326      +50     
  Partials      588      588              
Flag Coverage Δ
unittests 58.95% <4.00%> (-0.32%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@katarinazaprazna
katarinazaprazna force-pushed the add-aggregator-backfill-job branch from b87ee57 to 3fb1216 Compare July 30, 2026 00:17
@katarinazaprazna
katarinazaprazna marked this pull request as draft July 30, 2026 00:19
@katarinazaprazna
katarinazaprazna force-pushed the add-aggregator-backfill-job branch from 3fb1216 to a8195f1 Compare July 30, 2026 08:16
@MichaelMraka MichaelMraka self-assigned this Jul 30, 2026
@katarinazaprazna
katarinazaprazna force-pushed the add-aggregator-backfill-job branch from a8195f1 to 994fe9b Compare July 30, 2026 15:21
@katarinazaprazna
katarinazaprazna marked this pull request as ready for review July 31, 2026 12:27

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The backfill goroutine concurrency is hard-coded to 4; consider making this configurable (e.g., via environment or job config) so you can tune load on the database without code changes.
  • The account_advisory backfill goroutines do not appear to honor context cancellation beyond the initial setup; consider wiring context into the per-account work so the job can be aborted cleanly if requested.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The backfill goroutine concurrency is hard-coded to 4; consider making this configurable (e.g., via environment or job config) so you can tune load on the database without code changes.
- The account_advisory backfill goroutines do not appear to honor context cancellation beyond the initial setup; consider wiring context into the per-account work so the job can be aborted cleanly if requested.

## Individual Comments

### Comment 1
<location path="tasks/caches/backfill_account_advisory.go" line_range="38-47" />
<code_context>
+		go func(i, rhAccountID int) {
</code_context>
<issue_to_address>
**suggestion (performance):** Per-account logging at info level in a tight loop may cause excessive log volume.

Per-account info-level logs before/after backfill and on drift check errors will scale with the number of accounts and can significantly increase log volume and overhead. Please consider lowering verbosity for per-account messages (e.g., debug or aggregated progress logs), while keeping actual error logs at info/error.

Suggested implementation:

```golang
			err := tasks.WithTx(func(tx *gorm.DB) error {
				utils.LogDebug("i", i, "rh_account_id", rhAccountID, "backfilling account_advisory")
				return tx.Exec("SELECT backfill_account_advisory(?)", rhAccountID).Error
			})

```

To fully implement the logging-verbosity suggestion, you should also:
1. Scan this file for other per-account `utils.LogInfo` calls (e.g., per-account "completed backfill" or drift-check logs) and down-level them to `LogDebug` or aggregate them into periodic summary logs.
2. Ensure that only actual errors (e.g., failed backfill, drift check failures) are logged with `LogInfo`/`LogError`, keeping the high-level batch start/end logs at info level as they are.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +38 to +47
go func(i, rhAccountID int) {
defer func() {
<-guard
wg.Done()
}()

err := tasks.WithTx(func(tx *gorm.DB) error {
utils.LogInfo("i", i, "rh_account_id", rhAccountID, "backfilling account_advisory")
return tx.Exec("SELECT backfill_account_advisory(?)", rhAccountID).Error
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Per-account logging at info level in a tight loop may cause excessive log volume.

Per-account info-level logs before/after backfill and on drift check errors will scale with the number of accounts and can significantly increase log volume and overhead. Please consider lowering verbosity for per-account messages (e.g., debug or aggregated progress logs), while keeping actual error logs at info/error.

Suggested implementation:

			err := tasks.WithTx(func(tx *gorm.DB) error {
				utils.LogDebug("i", i, "rh_account_id", rhAccountID, "backfilling account_advisory")
				return tx.Exec("SELECT backfill_account_advisory(?)", rhAccountID).Error
			})

To fully implement the logging-verbosity suggestion, you should also:

  1. Scan this file for other per-account utils.LogInfo calls (e.g., per-account "completed backfill" or drift-check logs) and down-level them to LogDebug or aggregate them into periodic summary logs.
  2. Ensure that only actual errors (e.g., failed backfill, drift check failures) are logged with LogInfo/LogError, keeping the high-level batch start/end logs at info level as they are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants