Skip to content

Optimize IsHostConnectedToFleetMDM on the orbit check-in hot path (#44629)#48375

Merged
getvictor merged 6 commits into
mainfrom
optimize-orbit-mdm-connection-check-44629
Jun 29, 2026
Merged

Optimize IsHostConnectedToFleetMDM on the orbit check-in hot path (#44629)#48375
getvictor merged 6 commits into
mainfrom
optimize-orbit-mdm-connection-check-44629

Conversation

@getvictor

@getvictor getvictor commented Jun 27, 2026

Copy link
Copy Markdown
Member

Related issue: Resolves #44629

This folds the connected-to-Fleet check into GetHostMDM via a connected_to_fleet column that mirrors the existing IsHostConnectedToFleetMDM and hostMDMSelect conditions, and derives the value in GetOrbitConfig from the host_mdm data it already fetches. Result: 2 queries → 1 on the orbit check-in hot path, with no semantic change.

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.

  • Input data is properly validated, SELECT * is avoided, SQL injection is prevented (using placeholders for values in statements), JS inline code is prevented especially for url redirects, and untrusted data interpolated into shell scripts/commands is validated against shell metacharacters.

Testing

Summary by CodeRabbit

  • Performance Improvements
    • Orbit check-ins now determine MDM connection status from existing host MDM data, reducing database work and improving response time.
  • Bug Fixes
    • Added platform-aware connection detection so Windows, Apple, and Android devices report MDM connectivity more accurately.
    • Updated related checks and tests to keep connection status consistent across enrollment and unenrollment changes.

…4629)

GetOrbitConfig ran IsHostConnectedToFleetMDM, a 3-table JOIN, on every
orbit check-in for every host (including Linux/ChromeOS that never use
the result) one line before GetHostMDM. In load testing the Windows
variant was the #1 query by volume.

Fold the connected-to-Fleet check into GetHostMDM via a connected_to_fleet
column that mirrors the existing IsHostConnectedToFleetMDM and
hostMDMSelect conditions, and derive the value in GetOrbitConfig from the
host_mdm data it already fetches. This removes the separate query from the
hot path (2 queries to 1) with no semantic change. The SQL CASE
short-circuits for non-MDM platforms, so Linux/ChromeOS pay nothing for
the enrollment lookup.

Claude-Session: https://claude.ai/code/session_018vexp83A6iFZ6V53HSJAaR
@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai review

@getvictor

Copy link
Copy Markdown
Member Author

/review

@coderabbitai

coderabbitai Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

Warning

  • Copilot's review of this pull request may be incomplete because some of the changed files are excluded by your Copilot content exclusion settings. See Excluding content from Copilot for details.

Pull request overview

This PR optimizes Orbit’s /config check-in hot path by removing the standalone IsHostConnectedToFleetMDM query and instead deriving “connected to Fleet MDM” from the GetHostMDM query result via a new connected_to_fleet computed column.

Changes:

  • Update GetOrbitConfig to derive Fleet-MDM connectivity from GetHostMDM (removing an extra hot-path query).
  • Extend GetHostMDM to compute and return a connected_to_fleet boolean using platform-specific enrollment conditions.
  • Update unit tests/mocks to cover and consume the new HostMDM.ConnectedToFleet field.

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
server/service/orbit.go Removes the extra connectivity query and derives connectivity from mdmInfo.ConnectedToFleet.
server/service/orbit_test.go Updates service tests’ HostMDM mocks to include ConnectedToFleet.
server/fleet/hosts.go Adds ConnectedToFleet to fleet.HostMDM (db-mapped, not serialized).
server/datastore/mysql/hosts.go Computes connected_to_fleet inside the GetHostMDM SQL query via CASE + EXISTS, with a LEFT JOIN hosts.
server/datastore/mysql/mdm_test.go Adds assertions that GetHostMDM().ConnectedToFleet matches IsHostConnectedToFleetMDM across enrollment states.
changes/44629-optimize-orbit-mdm-connection-check User-visible changes entry (content excluded from review).
Files excluded by content exclusion policy (1)
  • changes/44629-optimize-orbit-mdm-connection-check

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread server/service/orbit.go
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 27, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Orbit config NotFound unhandled ✓ Resolved 🐞 Bug ☼ Reliability
Description
GetOrbitConfig ignores only sql.ErrNoRows from GetHostMDM, but the MySQL implementation wraps
missing host_mdm rows as a Fleet NotFound error. Hosts without a host_mdm row will error out instead
of being treated as "not connected", and the new mdmInfo==nil fallback will not run in that case.
Code

server/service/orbit.go[R494-506]

mdmInfo, err := svc.ds.GetHostMDM(ctx, host.ID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return fleet.OrbitConfig{}, ctxerr.Wrap(ctx, err, "retrieving host mdm info")
}
+	// Derive the Fleet-MDM connection state from the host_mdm data fetched above
+	// rather than issuing a separate IsHostConnectedToFleetMDM query. That query
+	// runs a 3-table JOIN on every orbit check-in for every host (including
+	// Linux/ChromeOS, which never use the result); GetHostMDM already computes the
+	// equivalent connected_to_fleet flag. mdmInfo is nil when the host has no
+	// host_mdm row, in which case it is, by definition, not connected to Fleet MDM.
+	isConnectedToFleetMDM := mdmInfo != nil && mdmInfo.ConnectedToFleet
+
Evidence
GetHostMDM wraps the no-row condition as a Fleet NotFound error, so errors.Is(err, sql.ErrNoRows)
will not match; other services already treat GetHostMDM NotFound as a non-fatal condition.

server/datastore/mysql/hosts.go[5119-5173]
server/service/orbit.go[489-506]
server/service/hosts.go[2822-2828]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`GetOrbitConfig` currently treats `GetHostMDM` absence as `sql.ErrNoRows`, but the MySQL datastore returns a Fleet `NotFound` error when there is no `host_mdm` row. This makes Orbit `/config` fail for hosts that don't yet have `host_mdm` data.
### Issue Context
- `server/datastore/mysql/hosts.go` converts `sql.ErrNoRows` into `notFound("HostMDMData")`.
- Other service code handles this correctly via `fleet.IsNotFound(err)`.
### Fix
In `GetOrbitConfig`, change the error handling to:
- Treat `fleet.IsNotFound(err)` as a non-error and proceed with `mdmInfo == nil`.
- Only return an error for non-NotFound errors.
Optionally update the comment that currently implies `mdmInfo` becomes nil when the host has no `host_mdm` row.
### Fix Focus Areas
- server/service/orbit.go[494-506]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread server/service/orbit.go
@coderabbitai

coderabbitai Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9e0b2055-9ab7-4909-b546-6f88d3c3643f

📥 Commits

Reviewing files that changed from the base of the PR and between 780ee01 and d61697c.

📒 Files selected for processing (5)
  • server/datastore/mysql/hosts.go
  • server/datastore/mysql/mdm_test.go
  • server/fleet/hosts.go
  • server/service/orbit.go
  • server/service/orbit_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • server/fleet/hosts.go
  • server/service/orbit.go
  • server/service/orbit_test.go
  • server/datastore/mysql/mdm_test.go
  • server/datastore/mysql/hosts.go

Walkthrough

GetHostMDM now returns a ConnectedToFleet flag computed in SQL from host platform and enrollment data. GetOrbitConfig reads that flag from GetHostMDM and no longer calls IsHostConnectedToFleetMDM. Datastore tests now compare both connectivity paths, and Orbit service tests were updated to set ConnectedToFleet in mocked HostMDM values.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: optimizing IsHostConnectedToFleetMDM on the orbit check-in hot path.
Description check ✅ Passed The description matches the template with a related issue, summary, checklist items, and testing notes.
Linked Issues check ✅ Passed The PR implements the linked issue by folding the connectivity check into GetHostMDM and removing the extra orbit hot-path query.
Out of Scope Changes check ✅ Passed The changes stay focused on the orbit MDM connectivity optimization and related tests, with no clear unrelated additions.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch optimize-orbit-mdm-connection-check-44629

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.

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/service/orbit.go`:
- Around line 494-505: The Orbit config path is only treating sql.ErrNoRows as a
missing host_mdm row, but GetHostMDM now returns its own not-found error for
absent MDM data. Update the error handling in orbit.go around svc.ds.GetHostMDM
so the missing-row case from GetHostMDM is also treated as a non-error and
leaves mdmInfo nil, preserving the ConnectedToFleet=false behavior in the
OrbitConfig flow. Use the GetHostMDM call and the subsequent
isConnectedToFleetMDM derivation to locate the fix.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 941c4ae9-1ae4-41b5-8b42-24852b427fb7

📥 Commits

Reviewing files that changed from the base of the PR and between 1b4fd91 and 780ee01.

📒 Files selected for processing (6)
  • changes/44629-optimize-orbit-mdm-connection-check
  • server/datastore/mysql/hosts.go
  • server/datastore/mysql/mdm_test.go
  • server/fleet/hosts.go
  • server/service/orbit.go
  • server/service/orbit_test.go

Comment thread server/service/orbit.go
- Comment why GetHostMDM uses LEFT JOIN hosts (orphaned host_mdm rows
  degrade connected_to_fleet to false instead of dropping the row).
- Cover Android in the IsHostConnectedToFleetMDM / GetHostMDM parity test.

Claude-Session: https://claude.ai/code/session_018vexp83A6iFZ6V53HSJAaR
AI reviewers (Copilot, CodeRabbit, Qodo) flagged the sql.ErrNoRows-only
guard. The original errors.Is(sql.ErrNoRows) already tolerated GetHostMDM's
wrapped NotFound error (NotFoundError.Is matches sql.ErrNoRows), so the
hot path was not actually broken. Still, lead with the idiomatic
fleet.IsNotFound check (matching the rest of orbit.go) while retaining the
sql.ErrNoRows net so a bare no-rows error is also treated as 'no MDM data'.

Claude-Session: https://claude.ai/code/session_018vexp83A6iFZ6V53HSJAaR
@codecov

codecov Bot commented Jun 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.23810% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 67.47%. Comparing base (1b4fd91) to head (d61697c).
⚠️ Report is 21 commits behind head on main.

Files with missing lines Patch % Lines
server/service/orbit.go 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #48375    +/-   ##
========================================
  Coverage   67.47%   67.47%            
========================================
  Files        3673     3673            
  Lines      232784   232896   +112     
  Branches    12256    12256            
========================================
+ Hits       157079   157156    +77     
- Misses      61606    61623    +17     
- Partials    14099    14117    +18     
Flag Coverage Δ
backend 69.01% <95.23%> (-0.01%) ⬇️

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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

The real GetHostMDM never returns a bare sql.ErrNoRows; it wraps the
missing-row case as a Fleet NotFound error. Drop the redundant
errors.Is(sql.ErrNoRows) branch and make the orbit unit-test mocks return
newNotFoundError() to match the datastore, so the guard is a single
idiomatic fleet.IsNotFound check.

Claude-Session: https://claude.ai/code/session_018vexp83A6iFZ6V53HSJAaR
@getvictor getvictor marked this pull request as ready for review June 29, 2026 15:27
@getvictor getvictor requested a review from a team as a code owner June 29, 2026 15:27

@claude claude 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.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review and subscribe this PR to future pushes, or @claude review once for a one-time review.

Tip: disable this comment in your organization's Code Review settings.

@ksykulev ksykulev 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.

There is a non-blocking test question. But the code itself looks good.

}
ds.GetHostMDMFunc = func(ctx context.Context, hostID uint) (*fleet.HostMDM, error) {
return nil, sql.ErrNoRows
return nil, newNotFoundError()

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.

Is this testing the correct path? GetOrbitConfig no longer calls IsHostConnectedToFleetMDM right? So in essence "host not connected" and "host has MDM but not enrolled" branches now run the same code?

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.

@ksykulev This is fixing an existing testing/code quality issue. The GetHostMDM method does not return sql.ErrNoRows

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.

@ksykulev I will put up a new PR with some test fixes.

Comment thread server/datastore/mysql/hosts.go
@getvictor getvictor merged commit af2d4db into main Jun 29, 2026
45 of 47 checks passed
@getvictor getvictor deleted the optimize-orbit-mdm-connection-check-44629 branch June 29, 2026 16:11
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.

[top steady-state query] Optimize IsHostConnectedToFleetMDM 3-table JOIN on every orbit check-in for every host

3 participants