Skip to content

fix(intune): make the Compliance reducer independent of caller order - #545

Merged
adamgell merged 14 commits into
mainfrom
fix/compliance-caller-order
Aug 10, 2026
Merged

adamgell merged 14 commits into
mainfrom
fix/compliance-caller-order

Conversation

@adamgell

@adamgell adamgell commented Aug 10, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #543 (framework/pr4-thin-extraction), which rewired tests/intune_windows_compliance.rs to the shared helpers this PR also touches.

The Compliance reducer pushed observations in raw caller order and never sorted them before folding. Six merges read vector position instead of record content. One of them flipped an exported conclusion, which is what makes this more than cosmetic.

RED first

Every test below was written and run before any production change.

1. Conclusion-flipping: last_submission_at and the staleness gate (severe)

reducer.rs set phase.last_submission_at = submitted_at unconditionally on every Submitted row, so the value was whichever submission the caller listed last. That field feeds the staleness gate, so two submissions straddling latest_local exported Submitted or Stale purely on vector order.

two_submissions_straddling_the_evaluation_do_not_flip_the_report_state:

assertion `left == right` failed: the staleness gate must not read whichever submission the caller listed last
  left: Submitted
 right: Stale

2. Lane-level permutation over the scenario corpus

permuting_sibling_records_does_not_change_the_analysis, in the style of Configuration's, using the shared support::wire from #543 for byte-for-byte comparison.

The corpus alone could not fail this test. All 16 scenarios are single-record-per-setting bundles: none carries two observations sharing a grouping token, two report submissions, or two rows describing one policy. Sweeping only the corpus would have shipped a gate that passes vacuously. The test therefore sweeps the corpus plus contended_bundle(), a synthetic input in which every order-sensitive merge is actually contended. The pinned fixture matrix is left untouched.

With the contended case, pre-fix:

assertion `left == right` failed: contended-bundle: input order must not change the analysis

The two snapshots differed in: reporting.state stale vs submitted, reporting.lastSubmissionAt 09:00 vs 11:00, reporting.reportId alpha-report vs zebra-report, settings[0].displayName Alpha… vs Zebra…, settings[0].error 0x80070002 vs 0x80070005, settings[0].scope user vs device, policies[0].state notReceived vs received, policies[0].scope user vs device, and the compliance-local-evaluation-error finding summary quoting a different setting name.

3. Duplication and 4. irrelevant evidence

re_collecting_the_same_records_does_not_change_the_analysis and irrelevant_evidence_does_not_change_an_existing_conclusion both passed pre-fix and are kept as the regression net the lane did not have. They are honest passes, not RED — recorded as such rather than dressed up.

5. Additional RED found by inspection during the work

Two more members of the same class, both confirmed RED before fixing:

a_queued_row_and_an_unknown_row_do_not_swap_the_report_state — the Submitted/Failed arms of the report fold were rank-monotone, but the remaining three tokens fell through to a plain last-writer-wins:

assertion `left == right` failed: the weaker report tokens must fold by rank like the stronger ones do
  left: Unknown
 right: Queued

Plus two_submission_rows_do_not_let_caller_order_pick_the_report_id_or_error (Some("zebra") vs Some("alpha")), a_merged_setting_display_name_does_not_follow_caller_order (Some("Zebra setting") vs Some("Alpha setting")), a_merged_setting_error_does_not_follow_caller_order (0x80070005 vs 0x80070002), two_records_disagreeing_about_scope_do_not_follow_caller_order (Device vs User), two_policy_rows_do_not_let_caller_order_pick_the_policy_state (Received vs NotReceived).

Semantic decision per field changed

Field Decision Reasoning
reporting.last_submission_at Latest submission by timestamp; a single submission is reported whatever its zone; several are ordered only when every one carries a known zone, otherwise None The gate asks "does the service hold a copy of the most recent evaluation?", which depends on the latest successful submission, never on vector position. One zone-less stamp among several means we cannot say which is last; naming one would let the gate declare Stale on a guess. None leaves the state at Submitted — the claim the evidence does support
reporting.state Fold by explicit rank Submitted > Failed > Stale > Queued > Unknown Preserves the documented precedence and extends it to the three tokens that previously fell through to last-writer-wins. Rank is injective over the five variants, so there are no ties to break
reporting.report_id Smallest stated Content-determined where "first" was the collector's serializer. Every submission row stays cited
reporting.error Smallest by (decimal, hex, raw) Configuration's terminal_error ordering
settings[].scope Agreed value, else Unknown (conservative) Scope decides whether a setting reads as a user-targeted policy that was never evaluated (missing coverage) or as a device failure. Genuinely ambiguous with equal authority, so ADR-003 says report neither
settings[].display_name Smallest stated Follows Configuration's smallest_stated. Not dropped on disagreement: the findings quote this label, and falling back to the grouping token loses real usefulness for a cosmetic field. Both records stay cited
settings[].error Smallest by (decimal, hex, raw) Configuration's terminal_error, verbatim
settings[].key.* Smallest stated; identity_contradiction recomputed as "the stating records do not agree" Same answer as the old running comparison, without reading order
settings[].evaluated_at Orderable beats unorderable, newest wins, ties settled on smallest content Preserves existing semantics exactly; only the tie and all-unorderable cases changed, which previously resolved to whichever was listed last. Deliberately does not refuse like last_submission_at: this is provenance, and latest_evaluation re-filters to orderable instants before drawing any conclusion
policies[].state / .scope Agreed value, else Unknown (conservative) Two sources saying received and not received are equally authoritative and there is no third fact to break the tie
prerequisites[].detail Smallest stated among rows carrying the winning state The state fold was already a rank; the detail followed the last unmet row
custom_compliance, service_results, access_impact.decisions Exported arrays sorted by evidence ref Sets of results, not sequences. Nothing reads their position, but the caller's order was reaching the serialized snapshot

Left unchanged as already order-independent, per the brief: settings[].state (rank-monotone), the definite/indefinite setting-state fold (disagreement → Contradictory), fold_freshness, and the access-linkage correlation.

merge_setting also canonicalizes its observations up front. That changes no output today, since every merge in it is individually content-determined; the comment says so rather than overstating it. It is there so a field added later that walks the vector inherits a stable order.

Fixtures

No fixture expectation changed. every_scenario_matches_its_expected_reduction passes unmodified across all 16 scenarios, and no expected.json was touched. The corpus never exercised a contended merge, which is exactly why it did not catch this.

Gates

Gate Result
cargo test -p cmtraceopen-parser 2452 passed, 0 failed (baseline 2442 + 10 new: 7 reducer unit tests, 3 lane tests)
cargo clippy -p cmtraceopen-parser --all-targets -- -D warnings clean
cargo check --workspace clean
cargo check -p cmtraceopen-parser --target wasm32-unknown-unknown clean
git diff --check clean

No tauri::test::mock_app(). No rustfmt run on files not created here.

Out of scope, for a separate PR

The lane's fixture corpus has no scenario in which two records describe the same setting, policy, or submission. That gap is why the order dependence survived review and why the permutation gate needed a synthetic bundle to have teeth. A corpus scenario covering contended evidence would be worth adding, but it changes the pinned SCENARIOS matrix from issue #364 and belongs in its own PR.

Assessability, confidence, linkage, and redaction were not touched.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Compliance results are now consistent regardless of record processing order.
    • Duplicate records no longer change reported outcomes.
    • Conflicting policy, prerequisite, setting, report, service, and access data now resolves predictably.
    • Statuses, timestamps, errors, evidence, identifiers, and displayed details use stable selection and ordering.
    • Irrelevant or competing evidence is less likely to affect final compliance results.
    • Results remain reliable when timestamp information is incomplete or partially unknown.

adamgell and others added 2 commits August 10, 2026 11:55
…, invariant docs)

Three items, all behavior-preserving.

1. The IntuneAccessState <-> IntuneArtifactStatus bijection existed as three
   copies. Both directions now live in intune/evidence.rs beside the enums,
   with exhaustive matches (no `_` arm) so a new variant is a compile error.
   Win32 and Microsoft Store call the shared pair directly; Autopilot's
   declared_status is now the composition of its own lane-local capture-state
   mapping with the shared one. Verified arm by arm as identical first.

2. Mechanical test-support consolidation into tests/support/mod.rs:
   scenario_root, artifact_status_for_capture_state (plus an
   access_state_for_capture_state adapter for Win32), wire, and
   sorted_evidence_ids.

   Deliberately left local: Microsoft Store's insertion-ordered evidence_ids
   (that leaf asserts citation order), and Autopilot's capture_state (returns a
   lane-local enum via serde, not IntuneArtifactStatus).

3. Docs: an ADR-001 addendum recording that the directional doctrine is shared
   prose while its mechanism is per-lane, and a new
   docs/architecture/shared-vs-workload-invariants.md protecting the tested
   divergences from a future "consistency" PR.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The compliance reducer folded observations in raw caller order and never
canonicalized them. Six merges read vector position rather than record
content, and one of them flipped an exported conclusion: phase.state
alternated between Submitted and Stale when two submissions straddled the
latest local evaluation, because last_submission_at was an unconditional
last-wins assignment feeding the staleness gate.

Every field now merges by content, following the template Configuration
already ships: smallest stated value, agreed value (None/Unknown on an
unresolved disagreement, per ADR-003), and terminal error by canonical
code ordering. last_submission_at is the latest submission by timestamp
and refuses to answer when several submissions cannot all be ordered.

Also closed in the same class: the weaker report-status tokens folded by
last-writer-wins rather than by rank, the prerequisite detail followed the
last unmet row, and the three exported fact vectors kept the caller's
order in the serialized snapshot.

No fixture expectation changed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@github-actions github-actions Bot added bug Something isn't working enhancement New feature or request intune Microsoft Intune related parser Log parser related labels Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The compliance reducer retains competing observations before reduction. It applies deterministic rules for policies, prerequisites, settings, timestamps, reports, evidence, and exported collections. Tests cover permutations, duplicates, irrelevant evidence, and synthetic conflicts.

Changes

Compliance determinism

Layer / File(s) Summary
Policy and prerequisite merging
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
Policy and prerequisite statements retain evidence until final reduction. Conflicting policy values resolve to Unknown. Prerequisite states use ranked precedence and deterministic detail selection.
Setting identity and chronology
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
Setting identity, contradictions, display names, scopes, errors, evidence, and timestamps no longer depend on input order. Blank identifiers and display names are omitted.
Report and collection canonicalization
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
Report submissions use explicit state precedence and deterministic metadata selection. Custom-compliance, service, access, report IDs, and errors use canonical ordering. Access correlation accepts equal timestamps and orders undated decisions after dated decisions.
Adversarial determinism tests
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs, crates/cmtraceopen-parser/tests/intune_windows_compliance.rs
Tests cover permutations, reversals, duplicate records, irrelevant evidence, competing settings, policies, reports, timestamps, and synthetic compliance facts.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ComplianceInput
  participant ComplianceReducer
  participant ComplianceAnalysis
  ComplianceInput->>ComplianceReducer: provide competing and reordered facts
  ComplianceReducer->>ComplianceReducer: retain, rank, merge, and sort observations
  ComplianceReducer->>ComplianceAnalysis: export canonical results
Loading

Possibly related PRs

Suggested labels: test, device, windows

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title follows Conventional Commits format and accurately describes the Intune Compliance reducer change.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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 fix/compliance-caller-order

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

# Conflicts:
#	crates/cmtraceopen-parser/tests/intune_windows_compliance.rs
#	docs/architecture/decisions/ADR-001-evidence-strength-confidence.md
#	docs/architecture/shared-vs-workload-invariants.md
@adamgell
adamgell marked this pull request as ready for review August 10, 2026 17:38
Copilot AI lite review requested due to automatic review settings August 10, 2026 17:39
@coderabbitai coderabbitai Bot added the test Testing related label Aug 10, 2026

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 fixes order-dependence in the Intune Windows Compliance reducer by making merges and exported arrays deterministic with respect to evidence content rather than caller vector order, and adds regression tests that actively permute/duplicate inputs to prevent future reintroductions.

Changes:

  • Adds permutation/duplication/irrelevant-evidence regression tests for compliance analysis, including a synthetic “contended” bundle that exercises all previously order-sensitive folds.
  • Refactors compliance reducer merges (reporting, policies, prerequisites, settings, and exported fact arrays) to be order-independent via explicit ranks, agreement rules, and deterministic tie-breaks.
  • Introduces helper merge utilities for policy/prerequisite folding and deterministic timestamp selection.

Reviewed changes

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

File Description
crates/cmtraceopen-parser/tests/intune_windows_compliance.rs Adds RED-first regression tests to ensure compliance analysis is invariant under input permutation, duplication, and irrelevant evidence.
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs Reworks reducer folds to be content-determined (rank/agreement/sorting) instead of last-writer-wins over input vectors.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +425 to +433
/// The smallest value stated by any observation in the group.
///
/// "Smallest" is arbitrary but *content-determined*, which "first" was not.
fn smallest_stated(
observations: &[SettingObservation],
pick: fn(&SettingObservation) -> Option<&String>,
) -> Option<String> {
observations.iter().filter_map(pick).min().cloned()
}
Comment on lines +542 to +547
let mut distinct: Vec<&IntuneTimestamp> = Vec::new();
for stamp in stamps {
if !distinct.contains(&stamp) {
distinct.push(stamp);
}
}

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

Actionable comments posted: 5

🤖 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 `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 201-206: Make all three exported-array comparators total by
extending the evidence comparison with the specified record fields: in
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs lines
201-206, update custom_compliance sorting with policy_id, run_id, and
setting_name; at lines 809-815, update service_results sorting with policy_id,
setting_id, and reported_at; at lines 964-969, update decisions sorting with
occurred_at, device_key, user_key, and resource.
- Around line 1496-1520: Strengthen
two_policy_rows_do_not_let_caller_order_pick_the_policy_state by asserting the
concrete ADR-003 resolved state and scope, not only equality between forward and
reverse results. Mirror the explicit expected-value assertions used by
two_records_disagreeing_about_scope_do_not_follow_caller_order, while retaining
the order-independence checks.
- Around line 425-433: Update smallest_stated to exclude identifiers whose
trimmed value is empty before selecting the minimum; retain only nonblank values
for min(). This keeps the exported key consistent with grouping_token() and
contradicts().

In `@crates/cmtraceopen-parser/tests/intune_windows_compliance.rs`:
- Around line 834-843: The submission test data should exercise the
multi-submission zone-less gate in the reducer. Add a case containing one UTC
submission and one Unspecified submission, then assert last_submission_at is
None while reporting.state remains Submitted; keep the existing fully zoned
submission cases unchanged.
- Around line 646-672: Update the doc comment for
re_collecting_the_same_records_does_not_change_the_analysis to explicitly limit
the idempotence claim to the events and setting_reports vectors, which are the
only fields duplicated by doubled. Clarify that custom_compliance,
service_results, and access_decisions are intentionally unchanged and that the
property does not apply to those fact vectors.
🪄 Autofix

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: ASSERTIVE

Plan: Pro Plus

Run ID: c8413c8b-b743-41ed-8925-a0c221521397

📥 Commits

Reviewing files that changed from the base of the PR and between 2678f1f and 56d3893.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

adamgell and others added 4 commits August 10, 2026 14:23
The three exported fact arrays are canonicalized by sorting on the
`evidence` vector alone. Each of those vectors holds exactly the one ref
its fact was decoded with, and `slice::sort_by` is stable, so two facts
stamped with the same ref compare equal and keep the caller's input
order. PR #545 closed that defect everywhere else and left it open here.

The shape is reachable from the source layer, not hypothetical:
`sources::stage_record` deserializes customCompliance, serviceResults,
and accessDecisions records straight out of the collector's envelope,
reading `context.evidenceRef` verbatim and asserting nothing about
uniqueness. A collector that stamps one artifact-level ref on every row
it emits produces exactly this.

RED: the test fails on all three arrays, which is the point of landing it
before the fix.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Each array sorted on `evidence` alone. That vector holds one ref per
fact and `slice::sort_by` is stable, so two facts sharing a ref kept the
caller's input order: the defect the rest of PR #545 closed, still open
in the three arrays the snapshot exports as sets.

Each comparator now chains the record's own identifying fields after the
evidence comparison, so two distinct facts cannot compare Equal.

Chain order, and why:

- customCompliance: policy_id, run_id, setting_name. Broadest to
  narrowest containment. The policy owns the run, the run reports on the
  setting, so a reader scanning the array walks policies and then their
  runs rather than seeing one policy's runs interleaved with another's.

- serviceResults: policy_id, setting_id, reported_at. Same containment
  first, then time. Time trails deliberately: two rows for one setting
  differ by when the service reported them, but two rows for different
  settings must not be interleaved by timestamp.

- accessDecisions: occurred_at, device_key, user_key, resource. Time
  leads here where it trailed for service results, because a denial is
  an event and the array reads as a sequence of attempts. Subject and
  then resource separate attempts sharing an instant.

Both timestamp links reuse the existing `timestamp_content_key` rather
than the normalized instant, so a zone-less stamp still orders by
content instead of collapsing every such row to `None`.

No expected.json changed: the corpus scenarios carry unique evidence
ids, so the added links never fire there.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Finding 2. `smallest_stated` took `Some("")` at face value, so a
present-but-blank identifier could win the `min` and be exported as the
group's setting id, policy id, or display name.

Every other reader of those fields already disagreed with it:
`ComplianceSettingKey::is_identified` and `grouping_token` both drop a
blank before deciding, and `contradicts` reads one through
`usable_identifier`. The result was a group merged on its URI exporting
`settingId: ""` while `contradicts` had already ruled that same value out
as no statement at all.

The gap is reachable, through the report path only:
`sources::classify_setting_report` copies policy_id, setting_id, and
setting_uri verbatim from a `NormalizedSettingReport` deserialized
straight out of the `settingReports` envelope, where `"settingId": ""` is
valid JSON. The event path cannot produce it, because
`event_setting_key` reads every field through `named_any`, which trims
and rejects a blank before it becomes a key.

Handled with the existing `usable_identifier` rather than a new helper:
its `None` half is already the module's test for "this string states
nothing". The winning value is still exported verbatim; only the decision
about whether a value was stated is normalized.

Also finding 3: `two_policy_rows_do_not_let_caller_order_pick_the_policy_state`
asserted only that forward and reverse agree. Any fixed rank over the
variants would be just as symmetric and would pass while quietly
replacing the ADR-003 conservative merge, so the resolved values are now
pinned to Unknown for both state and scope.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
… claim

Finding 5. `latest_submission_at` has three branches: one submission is
reported whatever its zone, several are ordered when all of them are
zoned, and several of which any one lacks a known zone name no winner at
all. The third is the deliberate semantic decision from PR #545, and it
had no test: `event` builds only `Utc` stamps, so neither the corpus nor
the contended bundle ever reached it.

The new case pairs a zoned submission with an `Unspecified` one and
asserts `last_submission_at` is None and `reporting.state` stays
Submitted. The bundle is arranged so a wrong answer shows up in the
export rather than only in the unnamed instant: the zone-less submission
predates the local evaluation and the zoned one postdates it, so an
implementation that ranked the guessed instant would flip Submitted to
Stale. Deleting the guard branch does make the test fail, which is what
makes it worth having. The existing fully-zoned cases are unchanged.

Finding 4. `re_collecting_the_same_records_does_not_change_the_analysis`
claimed re-collecting "the same records" changes nothing, but `doubled`
concatenates only events and setting reports. The other three vectors
pass through untouched on purpose: they export one entry per input fact
with no merge and no deduplication, because two custom-compliance rows
are two runs and two decisions are two access attempts. Collapsing them
would be the reducer inventing a merge key the sources never state, so
widening the test to cover them would assert the opposite of the intended
behavior. Comment scoped to what the test proves and why the rest is
excluded; the test itself is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai coderabbitai Bot added device Device management related windows Windows platform related labels Aug 10, 2026

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

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 `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 211-217: The exported-record comparators do not fully order
records with identical existing keys. In
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs:211-217,
extend custom_compliance.sort_by with state, error, raw_output, and named_data
tie breakers; at :857-868, extend service_results.sort_by with state,
device_key, and user_key; at :1027-1039, extend decisions.sort_by with decision,
linkage, failure_code, and matched_evidence. Add reversed-input regression tests
for each comparator where records match all existing keys but differ in each
omitted field.
🪄 Autofix

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: ASSERTIVE

Plan: Pro Plus

Run ID: 1cb3b76e-2fdf-4e23-95db-53e4a58df481

📥 Commits

Reviewing files that changed from the base of the PR and between 56d3893 and eb90683.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

@adamgell

Copy link
Copy Markdown
Owner Author

Pushed fixes for all five findings as 56d38935..eb906832 (fast-forward, no force-push).

Finding 1 was correct and was the blocking one. All three comparators sorted on the evidence vector alone and sort_by is stable, so the PR left caller order reaching three exported arrays while claiming to remove it. Fixed RED-first: e7a42014 adds the failing test, 56c03b81 makes the comparators total.

Reachability is proven rather than assumed: all three arrays set evidence: vec![fact.context.evidence_ref.clone()] (a one-element vector), and sources::stage_record reads context.evidenceRef verbatim from the collector envelope with no uniqueness constraint and no dedup anywhere downstream. A collector stamping one artifact-level ref across the rows it emits produces exactly this shape.

Chain order was chosen deliberately, not alphabetically: custom_compliance and service_results lead with containment (policy_id then the narrower id) so one policy's rows cannot interleave with another's, with time last; decisions leads with occurred_at because a denial is an event and that array reads as a sequence. Both timestamp links reuse the existing timestamp_content_key so a zone-less stamp still orders by content rather than collapsing to None.

Findings 3, 4, 5 fixed as described. Finding 5's new test is arranged so a wrong answer is visible in the export rather than only in the unnamed instant: the Unspecified submission predates the local evaluation and the zoned one postdates it, so a naive implementation flips Submitted to Stale. Mutation-verified by deleting the guard arm.

Finding 2 was valid and reachable, not skipped. smallest_stated took Some("") at face value while is_identified, grouping_token, and contradicts all already dropped blanks, so a group merged on its URI could export settingId: "" that contradicts had ruled out as no statement. Reachable through the report path only (classify_setting_report copies verbatim from JSON where "" is valid); the event path cannot produce it because named_any trims and rejects blanks. Handled with the existing usable_identifier helper rather than a new one.

Verified independently before requesting re-review: RED reproduces at e7a42014 (1 failed), full suite green at eb906832, no expected.json touched.

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

@adamgell I will re-review the complete PR, including the updated deterministic ordering and regression coverage.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 4 minutes.

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs (1)

211-217: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Three exported-array comparators remain partial, so caller order survives for tied records. Each comparator omits content fields that distinguish two serialized records. slice::sort_by is stable, so records that tie on the compared fields keep the caller's order, and the serialized snapshot stays a function of the collector. The fix is the same at each site: chain the omitted fields.

  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs#L211-L217: chain state, error, raw_output, and named_data after setting_name for custom_compliance.
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs#L857-L868: chain state, device_key, and user_key after the reported_at comparison for service_results.
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs#L1027-L1039: chain decision, linkage, failure_code, and matched_evidence after resource for decisions.

facts_sharing_one_evidence_ref in crates/cmtraceopen-parser/tests/intune_windows_compliance.rs at Lines 646-678 does not reach this shape, because its facts differ in setting_name, reported_at, and occurred_at. Extend it with one pair per array that ties on every chained field and differs only in an omitted one.

🤖 Prompt for 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.

In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`
around lines 211 - 217, Complete the deterministic ordering for the three
exported-array comparators in reducer.rs: at lines 211-217, extend
custom_compliance ordering after setting_name with state, error, raw_output, and
named_data; at lines 857-868, extend service_results ordering after reported_at
with state, device_key, and user_key; and at lines 1027-1039, extend decisions
ordering after resource with decision, linkage, failure_code, and
matched_evidence. Update facts_sharing_one_evidence_ref in
crates/cmtraceopen-parser/tests/intune_windows_compliance.rs at lines 646-678
with one pair per array that ties on all existing chained fields and differs
only in the newly added field.
🤖 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 `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 1540-1547: Strengthen the three symmetry regression tests in
reducer.rs: at lines 1540-1547, add concrete assertions that report_id is
Some("alpha") and error contains the 0x80070002 code; at lines 1563-1567, assert
display_name is Some("Alpha setting"); and at lines 1582-1585, assert the
exported error uses 0x80070002 rather than 0x80070005. Keep the existing
forward/reverse symmetry checks and follow the concrete-value pattern used by
two_records_disagreeing_about_scope_do_not_follow_caller_order.
- Around line 474-482: Extract the canonical IntuneErrorCode ordering tuple into
a shared helper, then update terminal_error and reduce_reporting to use it
instead of constructing (&decimal, &hex, &raw) inline. Preserve the existing
ordering and ranking behavior at both call sites.

---

Duplicate comments:
In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 211-217: Complete the deterministic ordering for the three
exported-array comparators in reducer.rs: at lines 211-217, extend
custom_compliance ordering after setting_name with state, error, raw_output, and
named_data; at lines 857-868, extend service_results ordering after reported_at
with state, device_key, and user_key; and at lines 1027-1039, extend decisions
ordering after resource with decision, linkage, failure_code, and
matched_evidence. Update facts_sharing_one_evidence_ref in
crates/cmtraceopen-parser/tests/intune_windows_compliance.rs at lines 646-678
with one pair per array that ties on all existing chained fields and differs
only in the newly added field.
🪄 Autofix

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: ASSERTIVE

Plan: Pro Plus

Run ID: 997d8b67-c533-45f4-b605-ce5e9b449d42

📥 Commits

Reviewing files that changed from the base of the PR and between 2678f1f and eb90683.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

adamgell and others added 2 commits August 10, 2026 14:39
…order

Round 2 chained a few of each record's own fields after `evidence`, so
two facts sharing a ref no longer keep caller order. The chains are still
not total: two facts agreeing on every *named* field and differing only
in one the chain omits compare Equal, and `sort_by` is stable, so the
caller's vector picks the exported order again.

The bundle here builds that shape for all three arrays:

- customCompliance agrees on policyId, runId, settingName; differs in
  state, error, rawOutput, namedData.
- serviceResults agrees on policyId, settingId, reportedAt; differs in
  state, deviceKey, userKey.
- accessDecisions agrees on occurredAt, deviceKey, userKey, resource;
  differs in decision and failureCode.

Failing, as it should: all three arrays come back reversed when the
input is reversed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Rounds one and two both fixed the ordering by naming more fields: first
`evidence`, then `evidence` plus a few of each record's own identifiers.
Both were partial, and the third round of the same defect arrived the
same way. `slice::sort_by` is stable, so every pair the key does not
separate keeps the caller's vector order, and which pairs those are is
decided by whichever fields a human remembered to name. Two records
agreeing on the whole named chain and differing only in an omitted field
still compared Equal: `state`, `error`, `raw_output`, `named_data` for
customCompliance; `state`, `device_key`, `user_key` for serviceResults;
`decision`, `linkage`, `failure_code`, `matched_evidence` for
accessDecisions.

Naming those twelve too would close the instance and leave the class:
the next field added to any of the three records reopens it, silently,
with nothing to fail.

`content_key` makes the ordering total by construction instead. It is
the record's own serialized form, so it names every field including the
ones that do not exist yet, and a record gains a field without anyone
touching this module. Two records compare Equal under it exactly when
they serialize identically, which is exactly when swapping them leaves
the exported snapshot byte-identical, so there is nothing left for the
caller's vector to decide.

It is appended as a tie-breaker, not a replacement, so round two's
reading intent survives unchanged: containment first for the two result
arrays, time first for the decision array. Ties are what the key
settles, and no corpus scenario has one, so no expected.json moved and
the serialization runs on essentially no comparison.

Two more sites in this file were the same class and are closed the same
way:

- The `named_data` sort in `merge_setting` compared name then value, the
  two fields `IntuneNamedValue` happens to have today. That struct lives
  in the shared evidence module, so widening it there would have
  reintroduced caller order here, in another module, and stopped `dedup`
  collapsing equal values besides.
- The `observations` sort in `merge_setting` compared the evidence ref
  alone while its comment promised a stable order to any future field
  that walks the vector. Two observations can share a ref, so the
  promise did not hold. `SettingObservation` is internal and not
  `Serialize`, so `structural_key` stands in with the derived `Debug`
  form, which names every field the same way.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai coderabbitai Bot removed the device Device management related label Aug 10, 2026
@coderabbitai coderabbitai Bot removed the windows Windows platform related label Aug 10, 2026
@adamgell

Copy link
Copy Markdown
Owner Author

Round 3 pushed as 1355be13 (RED) and 1c5c198c (fix). The finding was correct: the round-2 chains were still enumerated, so records differing only in an omitted field tied and kept caller order.

Fixed as a class rather than by chaining four more fields, because enumeration fails again the moment anyone adds a field. Each site keeps its named chain and appends content_key — the record's own serde_json serialization — as a final tie-breaker. Two records now tie exactly when they serialize identically, which is exactly when swapping them leaves the exported snapshot byte-identical; at that point caller order has nothing left to decide.

derive(Ord) was considered and rejected on two grounds. It does not work as-is (IntuneTimestamp, IntuneErrorCode, IntuneNamedValue derive only PartialEq, Eq), and making it work would put a semantic ordering on IntuneTimestamp whose derived form sorts by raw_text — deliberately a content key here, not a chronology. It would also make struct field declaration order the primary sort, discarding the round-2 reading intent and reordering exports whenever a field is moved.

The class audit found two further sites in the same file, which is why this is round 3 and not round 4:

  • named_data in merge_setting compared name then value — the two fields IntuneNamedValue has today. That struct lives in the shared evidence module, so widening it there would have reintroduced caller order here, in a different module, with nothing to fail. It also broke dedup, which reads full equality.
  • observations sorted on the evidence ref alone while its comment promised a stable order to any future field walking the vector. Two observations can share a ref, so the promise was false.

Round 2's ordering intent is preserved unchanged: containment-first for customCompliance and serviceResults, time-first for accessDecisions. The key only appends.

Cost is bounded: the key sits inside then_with, so it is computed only when the named chain ties — never in the corpus (all 16 scenarios carry one row per array). Determinism holds across platforms: serde_json::to_string over derived Serialize emits declaration order with no map iteration and no floats in these types.

Verified independently: RED reproduces at 1355be13 (1 failed), full crate green at head (2456 passed, 0 failed), no expected.json touched.

One item left for your judgment rather than changed unilaterally: ComplianceCustomEvaluation.named_data is copied verbatim from a single source fact and never sorted, unlike the merged named_data. It is arguably that fact's own content rather than a collector artifact, so it was left alone. If you read it the other way, it is a fourth site.

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== PR metadata =='
gh pr view 545 --repo adamgell/cmtraceopen --json baseRefName,headRefName,commits --jq '{base: .baseRefName, head: .headRefName, commits: [.commits[].oid]}'

echo '== Changed files =='
git diff --name-only "$(git merge-base HEAD origin/HEAD)" HEAD 2>/dev/null || git diff --name-only HEAD~1 HEAD

echo '== Reducer outline =='
ast-grep outline crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs --items all --type function,struct,impl

echo '== Diff stat and ordering-related diff =='
git diff --stat "$(git merge-base HEAD origin/HEAD)" HEAD 2>/dev/null || true
git diff "$(git merge-base HEAD origin/HEAD)" HEAD -- crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  | rg -n -C 4 'content_key|sort_by|sort_by_key|named_data|observations|custom_compliance|service_results|access_decisions|ComplianceCustomEvaluation' || true

echo '== Current ordering and content-key sites =='
rg -n -C 8 'content_key|sort_by|sort_by_key|named_data|observations|custom_compliance|service_results|access_decisions|ComplianceCustomEvaluation' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

echo '== Tests relevant to order and named data =='
rg -n -C 5 'content_key|caller.order|order.independent|permutation|named_data|observations|custom_compliance|service_results|access_decisions' \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

Length of output: 2465


🏁 Script executed:

#!/bin/bash
set -u

base="$(git merge-base HEAD origin/main)"
echo "== Base: $base =="

echo '== Reducer outline =='
ast-grep outline crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs --items all --type function,struct || true

echo '== Test outline =='
ast-grep outline crates/cmtraceopen-parser/tests/intune_windows_compliance.rs --items all --type function,struct || true

echo '== Current reducer: ordering and serialization code =='
rg -n -C 14 'fn content_key|content_key\(|sort_by|sort_by_key|named_data|observations|custom_compliance|service_results|access_decisions|ComplianceCustomEvaluation' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs || true

echo '== Reducer diff =='
git diff --find-renames "$base" HEAD -- crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

echo '== Current tests: ordering coverage =='
rg -n -C 12 'order|permut|content_key|named_data|observations|custom_compliance|service_results|access_decisions|ComplianceCustomEvaluation' \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs || true

echo '== Test diff =='
git diff --find-renames "$base" HEAD -- crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

Length of output: 168129


🏁 Script executed:

#!/bin/bash
set -u

echo '== Compliance model declarations =='
fd -a 'models.rs' crates/cmtraceopen-parser/src/intune/device/windows/compliance \
  -x sh -c 'echo "--- $1"; rg -n -C 8 "struct Compliance(CustomEvaluation|ServiceResult|AccessObservation|SettingEvaluation)|struct Compliance(LocalPhase|ReportingPhase|AccessPhase)|enum Compliance" "$1"' sh {}

echo '== Evidence named-value and timestamp declarations =='
rg -n -C 8 'struct IntuneNamedValue|struct IntuneTimestamp|derive\(.*Serialize|derive\(.*Debug' \
  crates/cmtraceopen-parser/src/intune/evidence.rs || true

echo '== All ordering and vector normalization calls in compliance code =='
rg -n -C 4 '\.sort_by\(|\.sort\(|\.dedup\(|normalize_evidence|collect_evidence|\.collect\(\)' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance

echo '== Collector staging for the three fact classes =='
rg -n -C 10 'fn stage_record|custom_compliance|service_results|access_decisions|evidenceRef' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance

echo '== Exact access comparator and its test helpers =='
sed -n '1070,1120p' crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
sed -n '1210,1232p' crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

Length of output: 138552


@adamgell I found one defect.

P2: Put occurred_at before evidence in the access-decision comparator.

Line 1101 compares evidence first. This contradicts the stated time-first order for accessDecisions.

A later decision with evidence ID a sorts before an earlier decision with evidence ID z. The exported array is deterministic, but it is not a chronological sequence of access attempts.

Compare occurred_at first. Use evidence as the next tie-breaker. Add a test where evidence order conflicts with timestamp order.

ComplianceCustomEvaluation.named_data does not need reducer-side sorting for this PR. It is copied from one fact. The reducer does not merge or traverse that vector across caller-provided facts.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 4 minutes.

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

Actionable comments posted: 2

🤖 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 `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 349-359: In the tests for structural_key, add regression coverage
that starts from otherwise identical SettingObservation values, changes each
field—including nested fields—and asserts the resulting structural_key values
differ. Ensure the test would fail if Debug formatting omits any field, while
preserving the existing sort behavior.

In `@crates/cmtraceopen-parser/tests/intune_windows_compliance.rs`:
- Around line 834-848: Strengthen
facts_agreeing_on_every_named_key_do_not_follow_caller_order by asserting the
concrete resolved winner for at least one reordered array, not just equality
between forward and reverse outputs. Use the expected ComplianceCustomEvaluation
variant determined by content_key’s serialized JSON ordering, following the
reducer tests’ pattern for pinning ComplianceScope::Unknown, while retaining the
existing symmetry assertion.
🪄 Autofix

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: ASSERTIVE

Plan: Pro Plus

Run ID: 7e9d43d7-0d28-45f8-9881-99bc0d38b629

📥 Commits

Reviewing files that changed from the base of the PR and between eb90683 and 1c5c198.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

@coderabbitai coderabbitai Bot added the device Device management related label Aug 10, 2026

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

Actionable comments posted: 2

🤖 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 `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 1100-1113: Update the `phase.decisions.sort_by` comparator to
compare `occurred_at` chronologically before `evidence`, using
`normalized_timestamp` first and `timestamp_content_key` as the tie-breaker for
equivalent or unorderable timestamps; retain `evidence`, the remaining existing
keys, and `content_key` to preserve a total order. Add a regression test with
opposing chronological and evidence orders, asserting the exported decisions
remain chronological for both input caller orders.

In `@crates/cmtraceopen-parser/tests/intune_windows_compliance.rs`:
- Around line 891-907: Extend the access-decision ordering tests around
twin_access_fact with two facts sharing the same timestamp but using evidence
IDs that sort opposite to their occurred_at values. Assert that
access_impact.decisions follows the documented evidence-first precedence, rather
than timestamp ordering, while preserving the existing fixture structure and
assertions.
🪄 Autofix

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: ASSERTIVE

Plan: Pro Plus

Run ID: c81f5503-b8ba-483e-9e18-68876694a154

📥 Commits

Reviewing files that changed from the base of the PR and between 2678f1f and 1c5c198.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

…e key

Two gaps the previous round left, both of the same shape: a test that
constrains a relationship without constraining the result.

facts_agreeing_on_every_named_key_do_not_follow_caller_order asserted only
that forward and reverse agree. Reversing the content-key comparison, or
substituting any other symmetric rule, keeps the two sides equal while
changing what ships. The resolved order is now pinned as well, and the
expected values were read out of the reducer rather than assumed. Verified by
mutation: reversing the comparison now fails on Alpha before Zebra, where
before it passed.

structural_key orders observations by their Debug rendering, so a lossy Debug
on SettingObservation or on a type it nests would drop a field from the key
and hand the export order back to the caller. The new unit test pins each
field individually, so a field that stops participating fails and names
itself. Verified by mutation: truncating the key fails on grouping_token.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@adamgell

Copy link
Copy Markdown
Owner Author

Round 4 pushed as f96a1483. Both findings were valid and are the same shape as each other: a test that constrains a relationship without constraining the result.

Resolved order now pinned. facts_agreeing_on_every_named_key_do_not_follow_caller_order asserted only forward == reverse. Reversing the content-key comparison keeps both sides equal while changing what ships. Expected values were read out of the reducer rather than assumed. Mutation-verified: reversing the comparison now fails on "Alpha before Zebra", where before it passed silently.

structural_key content coverage added. The new unit test pins each SettingObservation field individually rather than the struct as a whole, so a field that stops participating fails and names itself. Mutation-verified: truncating the key to 40 chars fails on grouping_token.

Worth noting for the record that the resolved-order gap is the same class as the finding you raised two rounds ago about the policy test asserting symmetry without values. That fix was applied to the policy test and not carried to the tests written afterwards, which is exactly how a closed class reopens. Both are now mutation-verified rather than merely present.

Gates: full crate 2457 passed / 0 failed, clippy -D warnings clean, git diff --check clean (it caught a trailing blank line, fixed before commit), no non-ASCII in added lines, no expected.json touched.

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== PR head =='
git rev-parse HEAD
git show -s --format='%H%n%s%n%b' f96a1483

echo '== Changed paths in Round 4 =='
git diff-tree --no-commit-id --name-status -r f96a1483

echo '== Reducer outline =='
ast-grep outline crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  --items all --type function,struct,impl

echo '== Test outline =='
ast-grep outline crates/cmtraceopen-parser/tests/intune_windows_compliance.rs \
  --items all --type function,struct

echo '== Round 4 diff =='
git show --find-renames --format=fuller --stat --patch f96a1483 -- \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

echo '== Ordering and structural-key implementation sites =='
rg -n -C 12 \
  'fn (content_key|structural_key)|structural_key\(|content_key\(|sort_by\(|facts_agreeing_on_every_named_key_do_not_follow_caller_order|SettingObservation' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

Length of output: 2866


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== Reducer outline =='
ast-grep outline crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  --items all --type function,struct

echo '== Test outline =='
ast-grep outline crates/cmtraceopen-parser/tests/intune_windows_compliance.rs \
  --items all --type function,struct

echo '== Round 4 diff =='
git show --format=fuller --patch f96a1483 -- \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

echo '== Current locations =='
rg -n \
  'fn (content_key|structural_key)|structural_key\(|content_key\(|sort_by\(|facts_agreeing_on_every_named_key_do_not_follow_caller_order|SettingObservation' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

echo '== Reducer excerpts =='
rg -n -A45 -B12 \
  'fn (content_key|structural_key)|sort_by\(' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

echo '== Test excerpts =='
rg -n -A100 -B15 \
  'facts_agreeing_on_every_named_key_do_not_follow_caller_order|structural_key' \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

Length of output: 47173


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== SettingObservation declaration =='
rg -n -C 16 'struct SettingObservation\b' crates/cmtraceopen-parser/src

echo '== Access comparator and nearby tests =='
sed -n '1078,1118p' crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
rg -n -C 10 \
  'access.*(order|timestamp|evidence)|decisions.*(order|timestamp|evidence)|occurred_at|access_fact\(' \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

echo '== SettingObservation structural-key coverage =='
sed -n '1170,1230p' crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

Length of output: 47684


@adamgell I found two defects.

  1. P2: Sort access decisions by occurred_at before evidence.
    In crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs, Line 1101 still compares evidence first. This contradicts the time-first contract in the preceding comment. A later decision with evidence ID a sorts before an earlier decision with evidence ID z. Compare occurred_at first, then use evidence as the next tie-breaker. Add a regression test with conflicting evidence and timestamp order.

  2. P2: Cover the remaining SettingObservation fields in the structural_key test.
    structural_key_separates_observations_differing_in_any_single_field does not mutate key, evaluated_at, or context. SettingObservation has all three fields. The test name and comment claim every field has coverage, but a lossy Debug implementation for any of these fields would pass this test and can restore caller-order dependence. Add one independent mutation for each missing field.


✏️ Learnings added
Learnt from: adamgell
URL: https://github.com/adamgell/cmtraceopen/pull/545

Timestamp: 2026-08-10T18:56:35.102Z
Learning: In `crates/cmtraceopen-parser`, deterministic-order regression tests must assert both permutation invariance and the expected exported order. Equality between forward and reversed input alone does not detect a symmetric comparator that produces the wrong canonical order.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 34 minutes.

@coderabbitai coderabbitai Bot added the windows Windows platform related label Aug 10, 2026

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

Actionable comments posted: 3

♻️ Duplicate comments (3)
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs (3)

1100-1113: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

decisions still sorts by evidence before occurred_at.

The doc comment at Lines 1090-1095 states that time leads the record fields. The comparator compares left.evidence first, so two denials with distinct evidence refs order by evidence_id and source_artifact_id. Those are collector-assigned strings, so the exported array orders by artifact naming, not by chronology. The PR description claims this was corrected; the code does not show the correction.

timestamp_content_key also orders by raw_text first, so a set that mixes stamp formats stays non-chronological even after the reorder. Compare normalized_timestamp first, then timestamp_content_key for unorderable stamps.

🕒 Proposed comparator reorder
     phase.decisions.sort_by(|left, right| {
-        left.evidence
-            .cmp(&right.evidence)
-            .then_with(|| {
-                left.occurred_at
-                    .as_ref()
-                    .map(timestamp_content_key)
-                    .cmp(&right.occurred_at.as_ref().map(timestamp_content_key))
-            })
+        left.occurred_at
+            .as_ref()
+            .and_then(normalized_timestamp)
+            .cmp(&right.occurred_at.as_ref().and_then(normalized_timestamp))
+            .then_with(|| {
+                left.occurred_at
+                    .as_ref()
+                    .map(timestamp_content_key)
+                    .cmp(&right.occurred_at.as_ref().map(timestamp_content_key))
+            })
+            .then_with(|| left.evidence.cmp(&right.evidence))
             .then_with(|| left.device_key.cmp(&right.device_key))
             .then_with(|| left.user_key.cmp(&right.user_key))
             .then_with(|| left.resource.cmp(&right.resource))
             .then_with(|| content_key(left).cmp(&content_key(right)))
     });

Add a regression test where chronological order and evidence order disagree, for example an earlier decision carrying evidence id z-… and a later one carrying a-…, then assert the exported array is chronological in both caller orders.

🤖 Prompt for 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.

In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`
around lines 1100 - 1113, Update the decisions comparator to sort by occurred_at
before evidence, using normalized_timestamp first and timestamp_content_key only
as the fallback for unorderable stamps. Preserve the remaining tie-breakers
after time and evidence. Add a regression test with conflicting chronological
and evidence order, asserting chronological exported results for both input
caller orders.

503-507: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

The error ordering tuple is still duplicated.

(&decimal, &hex, &raw) is the canonical order for IntuneErrorCode, and it is written here and again in reduce_reporting at Lines 859-861. Two copies can drift, and a drift would rank the setting error and the submission error differently for the same code. A previous review raised this and the response marked it addressed; the code still shows both inline copies. Extract one helper and call it from both sites.

♻️ Proposed helper
+/// A total, content-derived ordering key for one error code.
+fn error_content_key(error: &IntuneErrorCode) -> (&Option<i64>, &Option<String>, &String) {
+    (&error.decimal, &error.hex, &error.raw)
+}
+
 fn terminal_error(observations: &[SettingObservation]) -> Option<IntuneErrorCode> {
     observations
         .iter()
         .filter_map(|observation| observation.error.as_ref())
-        .min_by(|left, right| {
-            (&left.decimal, &left.hex, &left.raw).cmp(&(&right.decimal, &right.hex, &right.raw))
-        })
+        .min_by_key(|error| error_content_key(error))
         .cloned()
 }
🤖 Prompt for 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.

In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`
around lines 503 - 507, Extract a shared ordering helper for IntuneErrorCode
using the canonical decimal, hex, and raw tuple, then replace the inline tuple
comparisons in the shown min_by call and reduce_reporting with that helper.
Ensure both setting-error and submission-error ordering paths use the same
helper.

1664-1671: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Three tests assert symmetry without pinning the resolved value. Each site compares forward against reverse only. Any symmetric rule change passes, so replacing min with max, or the smallest-stated rule with a newest-wins rule, leaves all three green while changing the exported snapshot. The policy test at Lines 1772-1781 and the scope test at Lines 1731-1735 already pin the concrete outcome next to the symmetry check; these three do not. A previous review raised this and the response marked it addressed.

  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs#L1664-L1671: assert report_id is Some("alpha") and error names the 0x80070002 code.
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs#L1687-L1691: assert display_name is Some("Alpha setting").
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs#L1706-L1709: assert the exported error is the 0x80070002 code, not the 0x80070005 code.
🤖 Prompt for 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.

In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`
around lines 1664 - 1671, Pin the concrete resolved values in all three symmetry
tests: at
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs lines
1664-1671, assert report_id is Some("alpha") and error contains the 0x80070002
code; at lines 1687-1691, assert display_name is Some("Alpha setting"); and at
lines 1706-1709, assert exported error is 0x80070002 rather than 0x80070005,
while retaining the existing forward/reverse symmetry assertions.
🤖 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 `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 1203-1222: Expand the mutations table in
structural_key_separates_observations_differing_in_any_single_field to include
independent changes to key, evaluated_at, and context, using valid alternate
values for each type. Keep the existing assertion pattern so
structural_key(&base) differs for every mutation, making the test’s “each field”
claim complete and protecting export identity and ordering behavior.

In `@crates/cmtraceopen-parser/tests/intune_windows_compliance.rs`:
- Around line 744-758: Extend
facts_sharing_an_evidence_ref_do_not_follow_caller_order with a concrete
ordering assertion for contended_bundle: inspect the analyzed/exported access
decisions and assert that acc-zebra precedes acc-alpha according to their
timestamps, rather than relying only on equality between forward and reverse
inputs. Keep the existing caller-order invariance assertion unchanged.
- Around line 760-868: Extend the reducer tests around
facts_agreeing_on_every_named_key_do_not_follow_caller_order to independently
vary each setting-observation structural_key component: key, evaluated_at, and
context. Add cases where only one component differs while all other ordering
fields remain equal, and verify reversed caller input produces the same
deterministic export, so removing any component from structural_key is detected.

---

Duplicate comments:
In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 1100-1113: Update the decisions comparator to sort by occurred_at
before evidence, using normalized_timestamp first and timestamp_content_key only
as the fallback for unorderable stamps. Preserve the remaining tie-breakers
after time and evidence. Add a regression test with conflicting chronological
and evidence order, asserting chronological exported results for both input
caller orders.
- Around line 503-507: Extract a shared ordering helper for IntuneErrorCode
using the canonical decimal, hex, and raw tuple, then replace the inline tuple
comparisons in the shown min_by call and reduce_reporting with that helper.
Ensure both setting-error and submission-error ordering paths use the same
helper.
- Around line 1664-1671: Pin the concrete resolved values in all three symmetry
tests: at
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs lines
1664-1671, assert report_id is Some("alpha") and error contains the 0x80070002
code; at lines 1687-1691, assert display_name is Some("Alpha setting"); and at
lines 1706-1709, assert exported error is 0x80070002 rather than 0x80070005,
while retaining the existing forward/reverse symmetry assertions.
🪄 Autofix

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: ASSERTIVE

Plan: Pro Plus

Run ID: 4dfc40b5-2af5-4c4b-9526-12660824d275

📥 Commits

Reviewing files that changed from the base of the PR and between 2678f1f and f96a148.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

adamgell and others added 4 commits August 10, 2026 15:35
The comparator in reduce_access leads with `evidence` while its comment says
time leads and a reader scans the array as a sequence of attempts. Nothing
caught that because every prior test asserted only caller-order invariance,
which every symmetric rule satisfies.

Two failing tests state the order the comment promises:

- a unit test whose bundle makes chronology disagree with both candidate
  alternatives: evidence ids sort the later decision first, and raw stamp
  text does too, so neither `evidence` nor `timestamp_content_key` can
  produce the asserted sequence;
- an integration test over `contended_bundle`, whose `acc-zebra` at 11:50
  and `acc-alpha` at 11:55 already disagree with their evidence ids.

Both fail against the current comparator. The fix follows.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The comment above the decisions sort said time leads and the array reads as
a sequence of attempts; the comparator led with `evidence`. Make the code
match the comment rather than the other way round, because chronology is the
reading an operator needs from a denial log.

The leading key is now the normalized instant, not `timestamp_content_key`.
That key compares `raw_text` first, so leading with it would have ordered by
how a source spelled the time rather than by when it happened: a "07/31/2026"
stamp sorts before any "2026-..." stamp, and an Offset stamp reading
13:50+02:00 sorts after a Utc stamp reading 12:00Z though it is earlier. The
corpus never showed this because every stamp in it is one shape, and
same-shape RFC 3339 sorts chronologically as text by accident.

A stamp whose zone is unknown has no instant `normalized_timestamp` will
vouch for, so `chronological_key` sorts those after every dated decision
rather than interleaving them on a guess. `timestamp_content_key` follows so
undated decisions still separate from one another by their raw stamps, and so
two decisions sharing an instant but not a spelling still order. Evidence is
retained as a tie-break after that, and `content_key` still closes the
comparison, so the order stays total.

No fixture order changes: every corpus scenario holds at most one access
decision.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The doc claimed the test "pins each field individually". The table covered
six of nine fields, omitting key, evaluated_at and context. A field that does
not participate in structural_key is exactly the defect the test exists to
catch, so the fix is to make the claim true rather than to narrow it.

Adding three rows would only restore the claim until the next field lands, so
the table is now derived from an exhaustive destructuring instead:

- the pattern carries no `..`, so a new field on SettingObservation is an
  E0027 compile error here (verified by adding a probe field: the pattern and
  the fixture both stopped compiling);
- unused_variables is denied on the function and every binding is consumed by
  the assert_ne! guarding its mutation, so naming a field without mutating it
  is also a compile error (verified by deleting one assertion: "error: unused
  variable: `scope`");
- those assertions also prove each mutation is a real change, so no row can
  pass vacuously.

The base observation is now fully populated. It had error, evaluated_at and
named_data empty, which contradicted its own "fully populated" comment and
would have let a None-to-Some mutation pass against a Debug that never
renders the inner value.

The integration suite says where this coverage lives and why it cannot live
there: SettingObservation is pub(super), so an integration test cannot name
it. The access-decision chain described in that doc is also corrected to the
comparator's current order.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A class-level pass over every ordering comment in reducer.rs, on the theory
that a defect reported four times is a habit rather than four accidents.

- latest_submission_at said "a single submission" and "several submissions"
  where the code counts *distinct stamps*. Two submissions carrying the same
  stamp are one instant and take the single-stamp branch, which the old
  wording read as impossible.
- reduce_access said the compliance record must *precede* the decision. The
  filter is `reported <= occurred`, so a record sharing the decision's instant
  is accepted. Say what is actually refused.
- the new decisions comment described the trailing group as zone-less stamps
  only. It also holds decisions with no stamp at all, which sort ahead of the
  zone-less ones because `None` precedes `Some`, and which state nothing for
  either time link.

Also verified rather than assumed: every timestamp in the compliance corpus
is `YYYY-MM-DDTHH:MM:SSZ` and nothing else, which is what the new comparator
comment claims when it says the corpus hid the raw-text ordering problem.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@adamgell

Copy link
Copy Markdown
Owner Author

Round 5 pushed as 0a931daa (RED), 08339705 (fix), a2e759f7, ed0fd9c7.

The Major finding was correct, and the sub-question about raw_text turned out to be the whole answer. timestamp_content_key is (raw_text, original_offset, normalized_utc, kind), so it compares raw text first and cannot produce chronology: "07/31/2026 11:50:00" sorts before "2026-07-30T00:00:00Z" because '0' < '2', a full day backwards. Even at a fixed format, an Offset stamp reading 2026-07-31T13:50:00+02:00 (11:50Z) sorts after a Utc stamp reading 12:00:00Z despite being the earlier instant, and IntuneTimestampKind::Offset exists precisely because sources emit that shape.

So merely dropping the chronology claim would have preserved an order that looks chronological on this corpus and silently is not. The reason it stayed invisible is now confirmed: every timestamp in the compliance corpus is exactly YYYY-MM-DDTHH:MM:SSZ, and same-shape RFC 3339 sorts chronologically as text by accident.

The comparator now leads with chronological_key (the normalized instant), then timestamp_content_key, then evidence and the record fields, closing with content_key. Unplaceable decisions sort after the dated run rather than before it, since None < Some would have made them read as "before everything"; within that trailing group timestamp_content_key still separates them.

Compile-time enforcement achieved on the field table, and I verified it independently rather than accepting the claim: adding a probe field to SettingObservation produces error[E0027]: pattern does not mention field. A new field can no longer escape the coverage table silently.

Three further overclaiming comments were found and fixed beyond the ones flagged - reduce_access said a compliance record must precede a decision when the filter is reported <= occurred; latest_submission_at said "a single submission" when the code counts distinct stamps; and the new decisions comment initially described only zone-less stamps when the trailing group also holds stampless ones. That class of defect is what every round here has actually been about.

Verified independently: RED reproduces at 0a931daa with ["a-later", "a-unplaceable", "z-earlier"] against the expected ["z-earlier", "a-later", "a-unplaceable"]; full crate green at head; no fixture touched (every corpus scenario holds at most one access decision, so no exported order could change).

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== Current head and Round 5 commits =='
git rev-parse HEAD
git show -s --format='%H%n%s%n%b' 0a931daa 08339705 a2e759f7 ed0fd9c7

echo '== Round 5 changed files =='
git diff --name-status 0a931daa^ ed0fd9c7

echo '== Reducer and test outlines =='
ast-grep outline crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  --items all --type function,struct,impl
ast-grep outline crates/cmtraceopen-parser/tests/intune_windows_compliance.rs \
  --items all --type function,struct

echo '== Round 5 focused diff =='
git diff --find-renames 0a931daa^ ed0fd9c7 -- \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

echo '== Current ordering helpers and access comparator =='
rg -n -C 16 \
  'fn (chronological_key|timestamp_content_key|content_key|structural_key)|access_decisions|sort_by\(|reduce_access|latest_submission_at' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

echo '== Timestamp and observation declarations =='
rg -n -C 14 \
  'struct IntuneTimestamp|enum IntuneTimestampKind|struct SettingObservation|struct ComplianceAccess' \
  crates/cmtraceopen-parser/src

echo '== Relevant tests =='
rg -n -C 18 \
  'chronological|unplaceable|access.*(order|decision)|structural_key|SettingObservation|facts_agreeing_on_every_named_key' \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

Length of output: 7489


🏁 Script executed:

#!/bin/bash
set -u

echo '== Reducer and test outlines =='
ast-grep outline crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  --items all --type function,struct 2>&1 || true
ast-grep outline crates/cmtraceopen-parser/tests/intune_windows_compliance.rs \
  --items all --type function,struct 2>&1 || true

echo '== Round 5 focused diff =='
git diff --find-renames 0a931daa^ ed0fd9c7 -- \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

echo '== Current ordering helpers and access comparator =='
rg -n -C 18 \
  'fn (chronological_key|timestamp_content_key|content_key|structural_key)|access_decisions|sort_by\(|reduce_access|latest_submission_at' \
  crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs || true

echo '== Timestamp and observation declarations =='
rg -n -C 16 \
  'struct IntuneTimestamp|enum IntuneTimestampKind|struct SettingObservation|struct ComplianceAccess' \
  crates/cmtraceopen-parser/src || true

echo '== Relevant tests =='
rg -n -C 20 \
  'chronological|unplaceable|access.*(order|decision)|structural_key|SettingObservation|facts_agreeing_on_every_named_key' \
  crates/cmtraceopen-parser/tests/intune_windows_compliance.rs || true

Length of output: 107994


🏁 Script executed:

#!/bin/bash
set -u

echo '== Timestamp normalization helpers =='
sed -n '1180,1224p' crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs

echo '== Timestamp construction and kind assignment =='
rg -n -C 12 \
  'IntuneTimestampKind::(Utc|Offset|Local|Unspecified|Invalid)|normalized_utc:|IntuneTimestamp \{' \
  crates/cmtraceopen-parser/src/intune \
  -g '*.rs' || true

echo '== Full PR changed paths and static whitespace check =='
base="$(git merge-base HEAD origin/main 2>/dev/null || git merge-base HEAD origin/HEAD 2>/dev/null || true)"
printf 'base=%s\n' "$base"
if [ -n "$base" ]; then
  git diff --check "$base" HEAD
  git diff --name-only "$base" HEAD
fi

echo '== Round 5 diff check =='
git diff --check 0a931daa^ ed0fd9c7

echo '== Current working tree =='
git status --short

Length of output: 116979


@adamgell No defects found in Round 5.

normalized_timestamp accepts only trusted Utc and Offset timestamps. The access-decision comparator uses the normalized instant first. It places unplaceable decisions after dated decisions. It then applies content tie-breakers and content_key.

The new regression test pins both the resolved order and caller-order independence. The SettingObservation table exhaustively destructures the current fields without ... A new field requires test maintenance at compile time.

git diff --check passes for the PR and the Round 5 range. The working tree is clean. I did not execute the test suite in this sandbox.


✏️ Learnings added
Learnt from: adamgell
URL: https://github.com/adamgell/cmtraceopen/pull/545

Timestamp: 2026-08-10T19:52:02.776Z
Learning: In `crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`, `timestamp_content_key` is a deterministic content tie-breaker, not a chronological key, because it compares `IntuneTimestamp.raw_text` first. Access-decision chronology must use `normalized_timestamp` for `IntuneTimestampKind::Utc` and `IntuneTimestampKind::Offset`; local, unspecified, and invalid timestamps are unplaceable and must not be ordered as instants.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Action performed

Full review finished.

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

♻️ Duplicate comments (1)
crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs (1)

499-507: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the IntuneErrorCode ordering tuple.

The tuple (&decimal, &hex, &raw) still appears twice: here and in reduce_reporting at Lines 875-881. Two copies can drift, and a drift makes the setting error and the submission error rank differently for the same code. A prior review round raised this and the duplication is still present in the final state.

♻️ Proposed helper
+/// A total, content-derived ordering key for one error code.
+fn error_content_key(error: &IntuneErrorCode) -> (&Option<i64>, &Option<String>, &String) {
+    (&error.decimal, &error.hex, &error.raw)
+}
+
 fn terminal_error(observations: &[SettingObservation]) -> Option<IntuneErrorCode> {
     observations
         .iter()
         .filter_map(|observation| observation.error.as_ref())
-        .min_by(|left, right| {
-            (&left.decimal, &left.hex, &left.raw).cmp(&(&right.decimal, &right.hex, &right.raw))
-        })
+        .min_by_key(|error| error_content_key(error))
         .cloned()
 }

Then apply the same helper at Lines 875-881.

🤖 Prompt for 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.

In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`
around lines 499 - 507, Extract the shared IntuneErrorCode ordering tuple from
terminal_error into a dedicated helper, then update both terminal_error and
reduce_reporting to use it for comparisons. Ensure both setting and submission
error ranking rely on the same decimal/hex/raw ordering definition.
🤖 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.

Duplicate comments:
In `@crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs`:
- Around line 499-507: Extract the shared IntuneErrorCode ordering tuple from
terminal_error into a dedicated helper, then update both terminal_error and
reduce_reporting to use it for comparisons. Ensure both setting and submission
error ranking rely on the same decimal/hex/raw ordering definition.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: c820ae66-1fe2-4a06-a6dc-0876ae321dcc

📥 Commits

Reviewing files that changed from the base of the PR and between 2678f1f and ed0fd9c.

📒 Files selected for processing (2)
  • crates/cmtraceopen-parser/src/intune/device/windows/compliance/reducer.rs
  • crates/cmtraceopen-parser/tests/intune_windows_compliance.rs

@adamgell
adamgell merged commit ad4d85a into main Aug 10, 2026
16 checks passed
@adamgell
adamgell deleted the fix/compliance-caller-order branch August 10, 2026 20:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working device Device management related enhancement New feature or request intune Microsoft Intune related parser Log parser related test Testing related windows Windows platform related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants