Skip to content

chore(api): Add context information to analysis logs: BED-7265#2316

Merged
StephenHinck merged 25 commits intomainfrom
BED-7265
Feb 12, 2026
Merged

chore(api): Add context information to analysis logs: BED-7265#2316
StephenHinck merged 25 commits intomainfrom
BED-7265

Conversation

@StephenHinck
Copy link
Copy Markdown
Contributor

@StephenHinck StephenHinck commented Jan 29, 2026

Description

Added contextual information to logs identified as common during analysis runs to provide improved context during log review and investigation of issues. Currently, those logs may prevent a user or administrator from understanding where within the process a certain log applies or is related to other steps in the process.

Motivation and Context

Resolves BED-7265

Why is this change required? What problem does it solve?

How Has This Been Tested?

Validated locally through multiple analysis runs with test data.

Screenshots (optional):

Types of changes

  • Chore (a change that does not modify the application functionality)

Checklist:

Summary by CodeRabbit

  • Refactor
    • Enhanced observability across analysis and data-processing with richer structured telemetry and contextual logging.
    • Reworked Active Directory post-processing into a multi-step pipeline with early-error returns and aggregated reporting.
    • Standardized call patterns by replacing variadic relationship arguments with explicit composite types for clearer, consistent invocation.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 29, 2026

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

Moved three AD preprocessing steps into the AD post-processing pipeline, changed DeleteTransitEdges to accept a single graph.Kinds parameter, and added structured bhlog/measure instrumentation (namespace, function, scope) across analysis, datapipe, and logging helper files.

Changes

Cohort / File(s) Summary
AD post pipeline
cmd/api/src/analysis/ad/post.go, packages/go/analysis/ad/post.go, cmd/api/src/daemons/datapipe/analysis.go
AD post now runs FixWellKnownNodeTypes, RunDomainAssociations, LinkWellKnownNodes as a multi-step pipeline with early returns and per-step stats aggregation; removed those steps from RunAnalysisOperations.
DeleteTransitEdges signature & callers
packages/go/analysis/post.go, packages/go/analysis/post_integration_test.go, cmd/api/src/analysis/ad/post.go, cmd/api/src/analysis/azure/post.go
Changed DeleteTransitEdges from variadic ...graph.Kind to single graph.Kinds; updated call sites to pass graph.Kinds(...) and adjusted operationName/measurement.
AD instrumentation (post & helpers)
packages/go/analysis/ad/...
packages/go/analysis/ad/ad.go, packages/go/analysis/ad/adcs.go, packages/go/analysis/ad/adcscache.go, packages/go/analysis/ad/local_groups.go, packages/go/analysis/ad/ntlm.go, packages/go/analysis/ad/owns.go
Added defer measure.ContextMeasure / ContextLogAndMeasure with bhlog attr (Namespace, Function, Scope) to many AD post functions and helpers; instrumentation only.
Azure & Hybrid instrumentation
packages/go/analysis/azure/post.go, cmd/api/src/analysis/azure/post.go, packages/go/analysis/hybrid/hybrid.go
Added context-aware measurement wrappers around Azure and Hybrid post-processing; Azure updated to pass graph.Kinds(...) into DeleteTransitEdges.
Datapipe / pipeline / dataquality instrumentation
cmd/api/src/daemons/datapipe/agi.go, cmd/api/src/daemons/datapipe/agt.go, cmd/api/src/daemons/datapipe/pipeline.go, cmd/api/src/services/dataquality/dataquality.go
Enhanced LogAndMeasure / ContextMeasure calls to include bhlog attributes (Namespace, Function, Scope) and updated messages for richer telemetry; no behavior changes.
General analysis instrumentation & ops
packages/go/analysis/post_operation.go, packages/go/analysis/post.go
Reworked measurement wrappers to include structured attributes and operationName; updated DeleteTransitEdges telemetry and operation-name construction.
Logging helpers
packages/go/bhlog/attr/attr.go
Added new slog.Attr helpers: Namespace(string), Scope(string), Function(string) to support structured attributes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ADPost as AD.Post
    participant Preproc as PreprocessingFns
    participant DeleteEdges as DeleteTransitEdges
    participant PostSteps as Post*Steps
    participant DB

    Client->>ADPost: Trigger Post(ctx,...)
    ADPost->>Preproc: FixWellKnownNodeTypes -> RunDomainAssociations -> LinkWellKnownNodes
    Preproc-->>ADPost: return (stats) / error
    ADPost->>DeleteEdges: DeleteTransitEdges(ctx, db, baseKinds, graph.Kinds(...))
    DeleteEdges->>DB: remove transit edges
    DeleteEdges-->>ADPost: edge-deletion stats
    ADPost->>PostSteps: FetchLocalGroupData -> PostDCSync -> PostProtectAdminGroups -> ... -> PostNTLM
    PostSteps->>DB: read/write as needed
    PostSteps-->>ADPost: per-step stats / error
    ADPost->>ADPost: merge per-step stats
    ADPost-->>Client: return aggregated stats or error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • elikmiller
  • superlinkx
🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding context information to analysis logs with the associated ticket reference.
Description check ✅ Passed The PR description covers most required sections: describes changes clearly, provides motivation (BED-7265), documents testing approach, specifies change type as chore, and confirms checklist completion.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch BED-7265

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

aggregateStats := analysis.NewAtomicPostProcessingStats()

if deleteTransitEdgesStats, err := analysis.DeleteTransitEdges(ctx, db, graph.Kinds{ad.Entity, azure.Entity}, ad.PostProcessedRelationships()...); err != nil {
if err := adAnalysis.FixWellKnownNodeTypes(ctx, db); err != nil {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These are post-processing steps that were never officially moved into the ad.Post function appropriately. Moving for consistency.

tieringEnabled = appcfg.GetTieringEnabled(ctx, db)
)

if err := adAnalysis.FixWellKnownNodeTypes(ctx, graphDB); err != nil {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These are post-processing steps that were never officially moved into the ad.Post function appropriately. Moving for consistency.

Comment thread cmd/api/src/analysis/ad/post.go
defer measure.ContextMeasure(
ctx,
slog.LevelInfo,
operationName,
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.

Typically, it's advised not to pass in arguments purely for logging purposes, it complicates the function with pretty small gain. Is it possible to wrap this at the call sites instead or hardcode it here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

How do you like this instead? Small change to the function signature to take a Kinds type, rather than []Kind (which are functionally equivalent in dawgs), then built the "operationName" for use in logging, rather than passing it through the function signature.

@StephenHinck StephenHinck self-assigned this Feb 10, 2026
@StephenHinck StephenHinck marked this pull request as ready for review February 10, 2026 21:18
@coderabbitai coderabbitai Bot added the api A pull request containing changes affecting the API code. label Feb 10, 2026
@StephenHinck
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 10, 2026

✅ Actions performed

Review triggered.

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@cmd/api/src/services/dataquality/dataquality.go`:
- Line 28: The deferred measurement logs currently use success-only wording like
"Successfully Completed …" which is misleading because the defer runs on all
exits (including errors); update the deferred completion message(s) in the
measurement-related defer blocks to neutral wording (e.g., "Completed …" or
"Measurement finished: …") so it doesn't imply success, and change every
occurrence referenced (the defer in the dataquality measurement setup and the
similar defer block between lines 41–55) to use the neutral message; keep the
rest of the defer behavior and any timing/metric recording intact.

In `@packages/go/analysis/post.go`:
- Around line 226-233: The logging attribute incorrectly lists
attr.Function("FetchComputersWithURA") inside the measure.ContextMeasure call
used for the "Finished deleting orphaned nodes" block; replace that string with
the actual enclosing function name (e.g., attr.Function("DeleteOrphanedNodes")
or whatever the real function is) so the function attribute on
measure.ContextMeasure matches the real function that calls it (update the
attr.Function value where measure.ContextMeasure(...) is deferred).
🧹 Nitpick comments (2)
cmd/api/src/daemons/datapipe/pipeline.go (1)

264-269: Missing attr.Scope attribute for consistency.

The measure.LogAndMeasure call at line 238 includes attr.Scope("summary"), but this slog.InfoContext call omits the Scope attribute. For consistency in log analysis and filtering, consider adding the same scope.

Suggested fix
 			} else {
 				slog.InfoContext(
 					ctx,
 					"Cache successfully reset by datapipe daemon",
 					attr.Namespace("analysis"),
 					attr.Function("Analyze"),
+					attr.Scope("summary"),
 				)
 			}
cmd/api/src/analysis/ad/post.go (1)

50-50: Unnecessary double parentheses.

The inner parentheses around ad.PostProcessedRelationships() are redundant.

✨ Suggested fix
-	} else if deleteTransitEdgesStats, err := analysis.DeleteTransitEdges(ctx, db, graph.Kinds{ad.Entity, azure.Entity}, graph.Kinds((ad.PostProcessedRelationships()))); err != nil {
+	} else if deleteTransitEdgesStats, err := analysis.DeleteTransitEdges(ctx, db, graph.Kinds{ad.Entity, azure.Entity}, graph.Kinds(ad.PostProcessedRelationships())); err != nil {

Comment thread cmd/api/src/services/dataquality/dataquality.go
Comment thread packages/go/analysis/post.go
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/go/analysis/post.go (1)

166-181: 🛠️ Refactor suggestion | 🟠 Major

Group and hoist variable initializations into a single var block.

operationName is initialized separately from the existing var block. Please group these initializations and hoist them to the top of the function to comply with the Go guidelines.

Proposed refactor
 func DeleteTransitEdges(ctx context.Context, db graph.Database, baseKinds graph.Kinds, targetRelationships graph.Kinds) (*AtomicPostProcessingStats, error) {
-	operationName := fmt.Sprintf("Delete %v post-processed relationships", strings.Join(targetRelationships.Strings(), ", "))
-
-	defer measure.ContextMeasure(
-		ctx,
-		slog.LevelInfo,
-		operationName,
-		attr.Namespace("analysis"),
-		attr.Function("DeleteTransitEdges"),
-		attr.Scope("process"),
-	)()
-
 	var (
+		operationName  = fmt.Sprintf("Delete %v post-processed relationships", strings.Join(targetRelationships.Strings(), ", "))
 		relationshipIDs []graph.ID
-		stats           = NewAtomicPostProcessingStats()
+		stats            = NewAtomicPostProcessingStats()
 	)
+
+	defer measure.ContextMeasure(
+		ctx,
+		slog.LevelInfo,
+		operationName,
+		attr.Namespace("analysis"),
+		attr.Function("DeleteTransitEdges"),
+		attr.Scope("process"),
+	)()

As per coding guidelines: “Group variable initializations in a var ( ... ) block and hoist them to the top of the function when possible.”

@StephenHinck
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 10, 2026

✅ Actions performed

Full review triggered.

Comment thread packages/go/analysis/post_integration_test.go Outdated
Comment thread packages/go/analysis/post_integration_test.go Outdated
Comment thread cmd/api/src/analysis/ad/post.go Outdated
@StephenHinck StephenHinck merged commit b5c0012 into main Feb 12, 2026
13 checks passed
@StephenHinck StephenHinck deleted the BED-7265 branch February 12, 2026 22:56
@github-actions github-actions Bot locked and limited conversation to collaborators Feb 12, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

api A pull request containing changes affecting the API code.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants