Skip to content

Vulnerabilities cron optimization - #39820

Merged
getvictor merged 33 commits into
mainfrom
victor-trigger
Feb 18, 2026
Merged

getvictor merged 33 commits into
mainfrom
victor-trigger

Conversation

@getvictor

@getvictor getvictor commented Feb 13, 2026 •

Copy link
Copy Markdown
Member

Related issue: Resolves #31820 and #39898

Vulnerability processing performance improvements, and added OTEL spans to the vulnerabilities cron job.

Optimized the two main bottlenecks in the vulnerability cron job: CPE matching and CVE insertion. In my loadtest testing (10K hosts), the overall initial vulnerabilities job went from over 2 hours down to 53 minutes, and the number of spans (DB accesses) went from ~2 million to ~90K.

  1. CPE matching (TranslateSoftwareToCPE): replaced the goqu query builder with hand-written SQL using raw database/sql queries. Replaced UNION with separate queries because case number 3 was an expensive full text match operation and in most cases we did not need to do that.

  2. CVE insertion (TranslateCPEToCVE and other places): replaced individual INSERT INTO software_cve ... VALUES (?,?,?,?) calls with batch inserts of 500 rows each, using the existing BatchProcessSimple helper. Same pattern applied to OS vulnerability inserts using the existing InsertOSVulnerabilities batch method.

Functional equivalence verified using osquery perf dataset locally. Both changes produce identical output (22,366 CPEs, 131,233 CVEs) when compared against the old code using a before/after comparison tool.

Checklist for submitter

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    See Changes files for more information.

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Summary by CodeRabbit

  • New Features

    • Expanded tracing for automated vulnerability workflows to improve observability.
  • Performance

    • Bulk/batched processing for software and OS vulnerability inserts to speed ingestion and downstream tasks.
    • More efficient CPE lookup and read-optimized database access for faster translations.
  • Bug Fixes

    • Improved error recording and read-after-write consistency to reduce missed or duplicate vulnerability notifications.
  • Tests

    • Test suite updated to support batch insertion semantics.

@getvictor getvictor changed the title Victor trigger Vulnerabilities cron optimization Feb 13, 2026
@codecov

codecov Bot commented Feb 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.70748% with 92 lines in your changes missing coverage. Please review.
βœ… Project coverage is 66.31%. Comparing base (54198ce) to head (ff03726).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
cmd/fleet/cron.go 55.00% 35 Missing and 1 partial ⚠️
cmd/fleet/vuln_process.go 0.00% 10 Missing ⚠️
server/vulnerabilities/nvd/cpe.go 87.80% 6 Missing and 4 partials ⚠️
server/vulnerabilities/nvd/cve.go 52.63% 5 Missing and 4 partials ⚠️
server/datastore/mysql/software.go 84.61% 6 Missing and 2 partials ⚠️
...erver/vulnerabilities/goval_dictionary/analyzer.go 0.00% 7 Missing ⚠️
server/vulnerabilities/nvd/db.go 37.50% 3 Missing and 2 partials ⚠️
server/vulnerabilities/customcve/matching_rules.go 25.00% 2 Missing and 1 partial ⚠️
...atastore/mysql/operating_system_vulnerabilities.go 90.47% 1 Missing and 1 partial ⚠️
server/vulnerabilities/oval/analyzer.go 71.42% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #39820      +/-   ##
==========================================
+ Coverage   66.29%   66.31%   +0.02%     
==========================================
  Files        2443     2442       -1     
  Lines      195700   195399     -301     
  Branches     8644     8373     -271     
==========================================
- Hits       129740   129580     -160     
+ Misses      54211    54067     -144     
- Partials    11749    11752       +3     
Flag Coverage Ξ”
backend 68.09% <68.70%> (-0.01%) ⬇️

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

β˜” View full report in Codecov by Sentry.
πŸ“’ 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.
  • πŸ“¦ JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@getvictor
getvictor requested a review from Copilot February 13, 2026 16:13
@coderabbitai

coderabbitai Bot commented Feb 13, 2026

Copy link
Copy Markdown
Contributor
βœ… Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds OpenTelemetry tracing and an automation context to the vulnerability cron workflow and wraps key vulnerability routines in spans; introduces batch software-vulnerability insert and lookup APIs (InsertSoftwareVulnerabilities, ListSoftwareVulnerabilitiesByHostIDsSource) and updates datastore, mocks, and tests to use bulk insertion for software and OS vulnerabilities; refactors NVD CPE lookup to a prioritized set of queries with deprecation resolution and adds a read-only SQLite accessor; changes vulnerability processing to aggregate vulnerabilities and perform batch inserts followed by read-after-write collection logic.

Possibly related PRs

πŸš₯ Pre-merge checks | βœ… 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (5 passed)
Check name Status Explanation
Title check βœ… Passed The title 'Vulnerabilities cron optimization' directly and clearly describes the primary objectiveβ€”optimizing the vulnerabilities cron job's performance, which is the central theme of this PR.
Linked Issues check βœ… Passed The PR successfully addresses the core objective from issue #31820: optimizing vulnerability processing bottlenecks (CPE matching and CVE insertion), reducing combined execution time from ~1.5 hours to ~25 minutes with verified functional equivalence.
Out of Scope Changes check βœ… Passed Changes are tightly scoped to optimization goals: CPE query refactoring, CVE batch insertion, and OpenTelemetry instrumentation in the cron job. All modifications directly support the performance improvement objectives without introducing unrelated features.
Merge Conflict Detection βœ… Passed βœ… No merge conflicts detected when merging into victor/35239-infra-trigger-vuln
Description check βœ… Passed The PR description comprehensively covers the main objectives (CPE matching and CVE insertion optimizations), includes performance metrics (2 hours to 53 minutes), and documents testing (changes file added, automated tests, manual QA). However, several template sections are missing or incomplete.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor-trigger

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

πŸ€– Fix all issues with AI agents
In `@server/datastore/mysql/software.go`:
- Around line 2989-3022: InsertSoftwareVulnerabilities allows entries with empty
CVE to be inserted unlike the singular InsertSoftwareVulnerability; fix by
filtering out vulnerabilities with vuln.CVE == "" before batching (or skip them
when building each batch) so only items with non-empty CVE are included in the
values/args; keep using the same function name InsertSoftwareVulnerabilities and
ensure totalAffected only counts rows from valid entries and the function
returns nil error semantics unchanged.

In `@server/vulnerabilities/nvd/cpe.go`:
- Around line 632-648: The loop over results can skip valid non-deprecated
matches because it uses break after a failed resolve; modify the loop in the
block that calls cpeItemMatchesSoftware and resolveDeprecatedCPE so that when a
matching result is Deprecated and resolveDeprecatedCPE returns no replacement
you continue to the next result (replace the break with continue), and
optionally call resolveDeprecatedCPE with the specific deprecated item
(results[i]) instead of the whole results slice to limit resolution to that
item.
- Around line 206-233: The resolveDeprecatedCPE function can loop infinitely on
cyclic deprecation chains; add cycle detection by tracking visited CPE IDs (or
rowids) while traversing the inner loop (use a map keyed by deprecatedItem.ID or
deprecation.RowID) and break/return a clear error or fallback (e.g., stop
traversing this chain and continue to next item) if you encounter an ID already
in the visited set; update references to deprecatedItem/deprecation in that loop
to check and mark visited before following the next link.

In `@server/vulnerabilities/nvd/cve_test.go`:
- Around line 853-869: The mock InsertSoftwareVulnerabilitiesFunc dereferences
vuln.ResolvedInVersion without checking for nil, which can panic in tests;
update the closure used in ds.InsertSoftwareVulnerabilitiesFunc to guard
vuln.ResolvedInVersion (in the loop that builds c := cve{...}) β€” check if
vuln.ResolvedInVersion is nil and either return an error or use a safe default
(e.g., empty string) for resolvedInVersion before assigning to
c.resolvedInVersion, keeping references to vuln.ResolvedInVersion, the cve
struct, cvesFound map, and softwareIDToCPEs to locate the code to change.

In `@server/vulnerabilities/nvd/cve.go`:
- Around line 337-344: The InsertOSVulnerabilities path currently builds one
giant INSERT and can exceed MySQL max_allowed_packet; modify the implementation
of InsertOSVulnerabilities to chunk the osVulns slice (use the same pattern as
InsertSoftwareVulnerabilities) β€” e.g. use BatchProcessSimple (or equivalent
batching helper) to process 500-item batches and call the existing insert logic
per-chunk, ensuring the ds.InsertOSVulnerabilities callsite (where allOSVulns is
constructed) or the underlying method accepts/handles batched input and
preserves the existing logging/error handling (level.Error(logger)...).
🧹 Nitpick comments (1)
cmd/fleet/cron.go (1)

522-536: syncCtx is created but not passed to nvd.Sync.

syncCtx (with the span) is constructed at line 522 but nvd.Sync(opts, logger) at line 530 doesn't receive it. The span will capture the time, but the context (and its trace propagation) won't flow into the sync operation. Same pattern applies to goval_dictionary.Refresh at line 471 and the refreshCtx created at line 470.

If nvd.Sync and goval_dictionary.Refresh don't accept a context today, this is a known limitation, but worth noting for future improvement.

Comment thread server/datastore/mysql/software.go Resolved
Comment thread server/vulnerabilities/nvd/cpe.go Resolved
Comment thread server/vulnerabilities/nvd/cpe.go Resolved
Comment thread server/vulnerabilities/nvd/cve_test.go Resolved
Comment thread server/vulnerabilities/nvd/cve.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR optimizes the vulnerability processing cron job to address severe performance issues at scale (issue #31820), where Linux vulnerability processing was taking multiple hours in environments with 45k hosts and 42k software items. The optimizations focus on reducing database roundtrips, improving SQLite database access patterns, and adding observability through OpenTelemetry tracing.

Changes:

  • Replaced individual vulnerability inserts with batch inserts to reduce database roundtrips
  • Optimized CPE matching by using sequential queries with early exit instead of UNION queries
  • Added read-only SQLite database access with memory-mapping for faster reads
  • Added comprehensive OpenTelemetry tracing to all vulnerability processing stages

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
server/vulnerabilities/nvd/db.go Added sqliteDBReadOnly function with memory-mapped I/O for 1GB cache
server/vulnerabilities/nvd/cpe.go Refactored CPE search from UNION query to sequential queries with early exit; added helper functions for matching and deprecation resolution
server/vulnerabilities/nvd/cve.go Changed from individual InsertSoftwareVulnerability calls to batch InsertSoftwareVulnerabilities; added logic to track existing vulnerabilities for webhook notifications
server/vulnerabilities/nvd/cve_test.go Updated tests to use new batch insert APIs (InsertSoftwareVulnerabilities, InsertOSVulnerabilities)
server/fleet/datastore.go Added InsertSoftwareVulnerabilities and ListSoftwareVulnerabilityKeysBySource interface methods
server/datastore/mysql/software.go Implemented batch insert methods with 500-item batches; implemented key listing for existing vulnerability tracking
server/mock/datastore_mock.go Added mock implementations for new batch insert and list methods
cmd/fleet/cron.go Added OpenTelemetry tracing spans to all vulnerability processing stages for observability

πŸ’‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread server/vulnerabilities/nvd/cpe.go Resolved
Comment thread server/datastore/mysql/software.go Resolved
@getvictor getvictor linked an issue Feb 14, 2026 that may be closed by this pull request
@getvictor
getvictor marked this pull request as ready for review February 16, 2026 17:07
@getvictor
getvictor requested a review from a team as a code owner February 16, 2026 17:07
…igger-vuln

# Conflicts:
#	server/datastore/mysql/cron_stats.go
… into victor-trigger

# Conflicts:
#	cmd/fleet/cron.go
Comment thread cmd/fleet/cron.go Resolved
Base automatically changed from victor/35239-infra-trigger-vuln to main February 17, 2026 15:18
# Conflicts:
#	server/service/schedule/schedule.go
@fleetdm fleetdm deleted a comment from kilo-code-bot Bot Feb 17, 2026
@fleetdm fleetdm deleted a comment from kilo-code-bot Bot Feb 17, 2026

@mostlikelee mostlikelee left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Still reviewing, but submitted some early comments

Comment thread server/datastore/mysql/software.go Resolved
Comment thread server/datastore/mysql/software.go Outdated
return ctxerr.Wrap(ctx, err, "batch check existing software vulnerabilities")
}
for _, r := range rows {
existing[fmt.Sprintf("%d:%s", r.SoftwareID, r.CVE)] = true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

wont this filter out updates to resolved_in_version?

Also, the updated_at timestamp is used to delete "old" vulnerabilities, so this would also affect cleanup

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I believe this is not a concern. Step 3 below updates everything, including updates to resolved_in_version and updated_at for all vulnerabilities.

@coderabbitai can you confirm?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@getvictor Yes, I can confirm your understanding is correct. The batch insertion logic does update resolved_in_version and updated_at for all vulnerabilities, including existing ones.

Here's how it works:

Step 1 (existence check) only identifies which vulnerabilities are truly new, but Step 3 (the actual database operation) processes ALL vulnerabilities in the filtered slice, not just the new ones:

// Step 3 processes 'filtered', not 'newVulns'
if err := common_mysql.BatchProcessSimple(filtered, vulnBatchSize, func(batch []fleet.SoftwareVulnerability) error {
    // ...
    INSERT INTO software_cve (cve, source, software_id, resolved_in_version)
    VALUES ...
    ON DUPLICATE KEY UPDATE
        source = VALUES(source),
        resolved_in_version = VALUES(resolved_in_version),
        updated_at = ?

The ON DUPLICATE KEY UPDATE clause ensures that:

  1. New vulnerabilities are inserted
  2. Existing vulnerabilities have their resolved_in_version and updated_at updated with the new values

The existence check in Step 1 is only used to determine the return value (newVulns), which tells the caller which vulnerabilities were newly inserted. This matches the behavior of the legacy InsertSoftwareVulnerability method, which also used ON DUPLICATE KEY UPDATE to handle both inserts and updates.

So @mostlikelee's concern about filtering out updates is not an issueβ€”all vulnerabilities get their fields updated appropriately.

mostlikelee
mostlikelee previously approved these changes Feb 18, 2026
# Conflicts:
#	server/vulnerabilities/customcve/matching_rules_test.go
@getvictor
getvictor merged commit 092b51f into main Feb 18, 2026
44 checks passed
@getvictor
getvictor deleted the victor-trigger branch February 18, 2026 19:59

This branch was previously deployed

1 inactive deployment
Docker Hub β€” ff037265 Deployed Feb 18, 2026 by getvictor via publish #77868
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.

False negative CPEs Vulnerability processing takes multiple hours at scale

3 participants