Skip to content

RHINENG-21444: remove ref to inventory.hosts table#2099

Open
TenSt wants to merge 9 commits intoRedHatInsights:masterfrom
TenSt:stepan/RHINENG-21444-remove-ref-to-ih-table
Open

RHINENG-21444: remove ref to inventory.hosts table#2099
TenSt wants to merge 9 commits intoRedHatInsights:masterfrom
TenSt:stepan/RHINENG-21444-remove-ref-to-ih-table

Conversation

@TenSt
Copy link
Collaborator

@TenSt TenSt commented Mar 10, 2026

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

Migrate usage of inventory metadata from the external inventory.hosts table into the local system_inventory table, including workspaces/groups, workloads, tags, OS and timestamps, and update schema, data fixtures, and tests to reflect the new source of truth.

New Features:

  • Store inventory workspaces/groups as JSONB on system_inventory and backfill them from existing inventory host groups via a database migration.

Bug Fixes:

  • Fix workload, group, and SAP SID filtering to operate on system_inventory fields rather than JSON system_profile data on inventory.hosts.
  • Correct handling of system workspaces by storing full group objects instead of only group IDs and ensuring filtering and exports use the new representation.
  • Resolve inconsistencies in package cache expectations, package availability, and repository-based inventory lookups that caused previous tests to rely on outdated data assumptions.

Enhancements:

  • Change query helpers, controllers, and background tasks to join against system_inventory instead of inventory.hosts for tags, groups, OS attributes, timestamps, and workload-related filters.
  • Model subscription manager ownership as a UUID-based OwnerID/SystemProfile field and persist it directly on system_inventory.
  • Align package cache and VMaaS-related logic and tests with the updated package data, including latest kernel package selection and package counts.

Tests:

  • Refresh SQL test data and Go tests across controllers, evaluators, tasks, and listeners to validate behavior against system_inventory-based metadata, new workspaces format, and updated package/erratum expectations.

@TenSt TenSt requested a review from a team as a code owner March 10, 2026 14:10
@sourcery-ai
Copy link

sourcery-ai bot commented Mar 10, 2026

Reviewer's Guide

Refactors inventory-related functionality to stop depending on the inventory.hosts table by migrating group/workload/system-profile data into system_inventory, updating queries and models accordingly, and aligning tests and schema (including a new migration) with the new structure.

File-Level Changes

Change Details Files
Stop using inventory.hosts in application queries and joins in favor of system_inventory, including for workloads, tags, timestamps, IDs, and group/workspace data.
  • Replace inventory.hosts joins with system_inventory joins in shared DB helpers and controller queries
  • Update nested system_profile filter mapping to read from system_inventory workload columns instead of JSON in inventory.hosts
  • Adjust tag and group/group-name filters and SystemTagList queries to use system_inventory.tags and system_inventory.workspaces
  • Change default/ stable sorting and ID query metadata to align with system_inventory.inventory_id and sp.id
base/database/utils.go
manager/controllers/utils.go
manager/controllers/common_attributes.go
manager/controllers/systems.go
manager/controllers/template_systems_update.go
manager/controllers/template_subscribed_systems_update.go
manager/controllers/systemtags.go
manager/controllers/template_systems.go
tasks/caches/refresh_packages_caches.go
manager/controllers/package_systems.go
manager/controllers/systems_advisories_view.go
evaluator/notifications.go
Change representation and storage of workspaces/groups from text[] IDs in inventory.hosts to JSONB group objects stored directly on system_inventory, and update ingestion and tests accordingly.
  • Modify SystemInventory model to store workspaces as JSONB []byte rather than pq.StringArray
  • In listener.upload, marshal host.Groups to JSON and persist in system_inventory.workspaces, and update subscription_manager_id to use OwnerID UUID
  • Update tests to unmarshal workspaces JSON when asserting group contents instead of comparing string arrays
  • Adjust inventory filtering logic for group_name and grouped/ungrouped selection to operate on system_inventory.workspaces JSONB
  • Introduce a DB migration that drops the old workspaces column, adds JSONB workspaces, and backfills from inventory.hosts.groups with a GIN index
base/models/models.go
listener/upload.go
listener/upload_test.go
manager/controllers/utils.go
base/database/utils.go
database_admin/schema/create_schema.sql
database_admin/migrations/146_system_inventory_new_workspaces_field.up.sql
database_admin/migrations/146_system_inventory_new_workspaces_field.down.sql
dev/test_data.sql
Align inventory-related identifiers and owner/consumer semantics with new types and schema.
  • Change inventory SystemProfile.ConsumerID string to OwnerID uuid.UUID and update all consumers (e.g., candlepin calls, subscription_manager_id type)
  • Use sp.inventory_id as the canonical ID in controller DTOs and query metadata, including mapping API field id to inventory_id
  • Update getSubscribedSystem and template-assignment logic to use system_inventory.subscription_manager_id and rh_account_id instead of inventory.hosts.system_profile.owner_id
base/inventory/inventory.go
base/models/models.go
listener/upload.go
manager/controllers/common_attributes.go
manager/controllers/systems.go
manager/controllers/template_subscribed_systems_update.go
base/database/query.go
Update seed data, VMaaS mocks, and tests to reflect the new inventory layout and changed package/erratum expectations.
  • Extend dev/test_data.sql system_inventory inserts to include stale timestamps and JSONB workspaces, and remove inventory.hosts dependency
  • Update VMaaS mock responses and expectations from kernel-5.10.13 to kernel-5.6.13 variants and adjust test expectations for advisories and remediations
  • Change various tests’ expectations for counts, package cache sizes, repo-based inventory selection, and systems/workloads behavior to match new data layout
  • Loosen some culled_timestamp assertions where new schema doesn’t guarantee a value
  • Fix minor test issues (e.g., schema diff assertion order, debug prints, go test hint)
dev/test_data.sql
platform/vmaas.go
evaluator/package_cache_test.go
evaluator/remediations_test.go
tasks/vmaas_sync/repo_based_test.go
tasks/vmaas_sync/metrics_test.go
manager/controllers/package_detail_test.go
manager/controllers/package_systems_export_test.go
manager/controllers/systems_export_test.go
manager/controllers/systems_test.go
manager/controllers/template_subscribed_systems_update_test.go
tasks/system_culling/system_culling_test.go
database_admin/schema_test.go
manager/controllers/advisory_systems_export_test.go
manager/controllers/advisory_systems_test.go
manager/controllers/package_systems_test.go
manager/controllers/systems_ids_test.go
scripts/go_test.sh

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

@github-actions
Copy link

SC Environment Impact Assessment

Overall Impact: 🟢 LOW

View full report

Summary

  • Total Issues: 1
  • 🟢 Low: 1

Detailed Findings

🟢 LOW Impact

Environment configuration change detected

  • File: listener/upload.go
  • Category: environment_config
  • Details:
    • Found Environment in listener/upload.go at line 284
  • Recommendation: Review environment-specific settings to ensure SC Environment is properly configured.

Required Actions

  • Review all findings above
  • Verify SC Environment compatibility for all detected changes
  • Update deployment documentation if needed
  • Coordinate with ROSA Core team or deployment timeline

This assessment was automatically generated. Please review carefully and consult with the ROSA Core team for critical/high impact changes.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

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

  • There are leftover debug prints using fmt.Printf in non-test code (e.g. buildInventoryQuery in manager/controllers/utils.go and systemsAdvisoriesQuery in systems_advisories_view.go); these should be removed or replaced with structured logging before merging.
  • The down migration 146_system_inventory_new_workspaces_field.down.sql has a syntax issue in the UPDATE statement (SET workspaces = ARRAY(SELECT ...) , FROM inventory.hosts ih – note the extra comma before FROM) which will cause the rollback to fail and should be corrected.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- There are leftover debug prints using fmt.Printf in non-test code (e.g. buildInventoryQuery in manager/controllers/utils.go and systemsAdvisoriesQuery in systems_advisories_view.go); these should be removed or replaced with structured logging before merging.
- The down migration 146_system_inventory_new_workspaces_field.down.sql has a syntax issue in the UPDATE statement (`SET workspaces = ARRAY(SELECT ...) , FROM inventory.hosts ih` – note the extra comma before FROM) which will cause the rollback to fail and should be corrected.

## Individual Comments

### Comment 1
<location path="manager/controllers/common_attributes.go" line_range="12" />
<code_context>
 type OSAttributes struct {
-	OS   string `json:"os" csv:"os" query:"ih.system_profile->'operating_system'->>'name' || ' ' || coalesce(ih.system_profile->'operating_system'->>'major' || '.' || (ih.system_profile->'operating_system'->>'minor'), '')" order_query:"ih.system_profile->'operating_system'->>'name' || ' ' || coalesce(ih.system_profile->'operating_system'->>'major' || '.' || (ih.system_profile->'operating_system'->>'minor'), '') collate numeric" gorm:"column:os"`
-	Rhsm string `json:"rhsm" csv:"rhsm" query:"ih.system_profile->'rhsm'->>'version'" gorm:"column:rhsm"`
+	OS   string `json:"os" csv:"os" query:"si.os_name || ' ' || coalesce(si.os_major || '.' || coalesce(si.os_minor::text, 'x'), '')" order_query:"si.os_name || ' ' || coalesce(si.os_major || '.' || coalesce(si.os_minor::text, 'x'), '') collate numeric" gorm:"column:os"`
+	Rhsm string `json:"rhsm" csv:"rhsm" query:"si.rhsm_version" gorm:"column:rhsm"`
 }
</code_context>
<issue_to_address>
**issue (bug_risk):** Casting of `si.os_major` is missing in the concatenation expression and will likely fail at runtime.

In `OSAttributes` `query`/`order_query`, `si.os_major` is a `smallint` (`*int16` in `SystemInventory`) and is concatenated directly with text: `si.os_name || ' ' || coalesce(si.os_major || '.' || coalesce(si.os_minor::text, 'x'), '')`. Postgres will reject `smallint || text` without an explicit cast. Please cast `os_major` to text in both places, e.g. `si.os_name || ' ' || coalesce(si.os_major::text || '.' || coalesce(si.os_minor::text, 'x'), '')`.
</issue_to_address>

### Comment 2
<location path="manager/controllers/utils.go" line_range="415-424" />
<code_context>
 	var cmp string
 	val := []any{}

+	fmt.Printf("key: %s, values: %v\n", key, values)
 	switch {
 	case values[0] == "not_nil":
 		cmp = " is not null"
 	case strings.Contains(key, "[sap_sids"):
-		cmp = "::jsonb @> ?::jsonb"
-		bval, _ := sonic.Marshal(values)
-		val = []any{string(bval)}
+		cmp = " && ?::text[]"
+		val = []any{pq.Array(values)}
 	default:
 		cmp = " = ?"
 		val = []any{values[0]}
 	}

 	subq := fmt.Sprintf("%s%s", nestedFilters[key], cmp)
+	fmt.Printf("subq: %s\n", subq)
 	return tx.Where(subq, val...)
 }
</code_context>
<issue_to_address>
**🚨 suggestion (security):** Leftover debug `fmt.Printf` calls will spam stdout and may leak filter details.

These `fmt.Printf` calls in `buildInventoryQuery` are fine for local debugging but will be noisy in production and may expose filter values (including `key`, `values`, and `subq`) in logs/stdout. Please remove them or replace them with structured logging behind an appropriate debug/trace log level.

Suggested implementation:

```golang
	var cmp string
	val := []any{}

```

```golang
	switch {

```

```golang
	subq := fmt.Sprintf("%s%s", nestedFilters[key], cmp)
	return tx.Where(subq, val...)
}

```

If there are other `fmt.Printf` (or similar) debug calls elsewhere in `manager/controllers/utils.go` or related files used in `buildInventoryQuery`, it would be good to remove or gate them behind the project's structured logging mechanism as well. Without seeing the rest of the codebase, I can't update those here.
</issue_to_address>

### Comment 3
<location path="database_admin/migrations/146_system_inventory_new_workspaces_field.down.sql" line_range="10-11" />
<code_context>
+-- rename the old workspaces field to groups
+ALTER TABLE system_inventory ADD COLUMN workspaces TEXT ARRAY CHECK (array_length(workspaces,1) > 0 or workspaces is null);
+
+UPDATE system_inventory si
+SET workspaces = ARRAY(SELECT jsonb_array_elements(ih.groups)->>'id'),
+FROM inventory.hosts ih
+WHERE ih.id = si.inventory_id;
</code_context>
<issue_to_address>
**issue (bug_risk):** The DOWN migration has a syntax error in the UPDATE statement.

The trailing comma after the `SET` expression makes this `UPDATE` invalid SQL and will cause the migration to fail. Removing it should resolve the issue:

```sql
UPDATE system_inventory si
SET workspaces = ARRAY(SELECT jsonb_array_elements(ih.groups)->>'id')
FROM inventory.hosts ih
WHERE ih.id = si.inventory_id;
```
Also confirm that `ARRAY(SELECT ...)` behaves correctly when `ih.groups` is empty or null so the DOWN migration handles hosts with no groups as intended.
</issue_to_address>

### Comment 4
<location path="manager/controllers/systems_advisories_view.go" line_range="93" />
<code_context>
 	if err != nil {
 		return nil, nil, nil, err
 	} // Error handled by method itself
+	fmt.Printf("filters: %+v\n", filters)

 	sysq, _ = ApplyInventoryFilter(filters, sysq, "sp.inventory_id")
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Leftover debug logging of `filters` in systems advisories query.

This will log all filter criteria on every systems-advisories request and is probably only useful during development. Please remove it, or replace it with structured logging at a guarded debug level to avoid noisy or potentially sensitive output.
</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.

@TenSt TenSt force-pushed the stepan/RHINENG-21444-remove-ref-to-ih-table branch from 736c59b to 7167e42 Compare March 10, 2026 14:14
@TenSt TenSt force-pushed the stepan/RHINENG-21444-remove-ref-to-ih-table branch from 7167e42 to 77aa87e Compare March 10, 2026 14:23
@codecov-commenter
Copy link

codecov-commenter commented Mar 10, 2026

Codecov Report

❌ Patch coverage is 61.36364% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.39%. Comparing base (4c3a143) to head (0ae633f).

Files with missing lines Patch % Lines
base/inventory/inventory.go 0.00% 15 Missing ⚠️
base/database/query.go 0.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2099      +/-   ##
==========================================
- Coverage   59.40%   59.39%   -0.01%     
==========================================
  Files         134      134              
  Lines        8707     8692      -15     
==========================================
- Hits         5172     5163       -9     
+ Misses       2989     2981       -8     
- Partials      546      548       +2     
Flag Coverage Δ
unittests 59.39% <61.36%> (-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.

@TenSt
Copy link
Collaborator Author

TenSt commented Mar 10, 2026

/retest

Copy link
Contributor

@Dugowitch Dugowitch left a comment

Choose a reason for hiding this comment

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

Hey Stepan, migration 142 (#1988) replaced ih.groups JSONB (json array of objects with id and name) with si.workspaces TEXT ARRAY containing just the ids. This was done because the names are not used anywhere. What's the reason for reverting it?

@MichaelMraka
Copy link
Collaborator

Unfortunatelly group names are used in search/filtering. It's a reason to introduce them back.

@TenSt
Copy link
Collaborator Author

TenSt commented Mar 11, 2026

/retest

1 similar comment
@TenSt
Copy link
Collaborator Author

TenSt commented Mar 11, 2026

/retest

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.

4 participants