Repository navigation
Vulnerabilities cron optimization - #39820
Conversation
β¦igger-vuln # Conflicts: # server/service/schedule/schedule.go
β¦ into victor-trigger
Codecov Reportβ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. β View full report in Codecov by Sentry. π New features to boost your workflow:
|
|
@coderabbitai full review |
β Actions performedFull review triggered. |
WalkthroughAdds 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 ( Possibly related PRs
π₯ Pre-merge checks | β 5 | β 1β Failed checks (1 warning)
β Passed checks (5 passed)
βοΈ Tip: You can configure your own custom pre-merge checks in the settings. β¨ Finishing touches
π§ͺ Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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:syncCtxis created but not passed tonvd.Sync.
syncCtx(with the span) is constructed at line 522 butnvd.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 togoval_dictionary.Refreshat line 471 and therefreshCtxcreated at line 470.If
nvd.Syncandgoval_dictionary.Refreshdon't accept a context today, this is a known limitation, but worth noting for future improvement.
There was a problem hiding this comment.
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.
β¦igger-vuln # Conflicts: # server/datastore/mysql/cron_stats.go
β¦ into victor-trigger # Conflicts: # cmd/fleet/cron.go
# Conflicts: # server/service/schedule/schedule.go
mostlikelee
left a comment
There was a problem hiding this comment.
Still reviewing, but submitted some early comments
| return ctxerr.Wrap(ctx, err, "batch check existing software vulnerabilities") | ||
| } | ||
| for _, r := range rows { | ||
| existing[fmt.Sprintf("%d:%s", r.SoftwareID, r.CVE)] = true |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
@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:
- New vulnerabilities are inserted
- Existing vulnerabilities have their
resolved_in_versionandupdated_atupdated 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.
# Conflicts: # server/vulnerabilities/customcve/matching_rules_test.go
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.
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.
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/,orbit/changes/oree/fleetd-chrome/changes.See Changes files for more information.
Testing
Summary by CodeRabbit
New Features
Performance
Bug Fixes
Tests