Skip to content

fix(hangfire): run each job in its own scope and trace so earlier jobs' breadcrumbs don't fill its events - #6074

Merged
ric-oliv merged 6 commits into
mainfrom
ai/triagent-3632
Dec 4, 2026
Merged

ric-oliv merged 6 commits into
mainfrom
ai/triagent-3632

Conversation

@jamescrosswell

@jamescrosswell jamescrosswell commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Hangfire jobs ran on whatever scope the worker thread happened to have. In practice that is the root scope, shared by every job. Breadcrumbs from one job, including the Exception breadcrumb left by each captured failure, ended up on the events of every later job. A job that keeps failing ends up with a breadcrumb trail of nothing but its earlier failures.

SentryServerFilter now pushes a new scope for each job, with its own trace, and pops it when the job leaves the Processing state.

Notes for review

  • Behaviour change: anything a job sets on the scope (tags, user, contexts, breadcrumbs) no longer carries over to later jobs on the same server. That's the point of the fix, but an app that relied on one job's scope data showing up on another job's events will see a difference.
  • Why not pop in OnPerformed: Hangfire logs a job's failure (AutomaticRetryAttribute, the source of the events in Hangfire job failures result in SentryCheckInIdKey error #3626) while electing the job's next state, which runs after OnPerformed. Popping there would put the error event and its breadcrumb back on the shared scope. Popping in OnStateApplied keeps them in the job's scope. A separate SentryJobScopeCloser filter does the popping, registered at order int.MaxValue, so other filters' OnStateApplied (job attributes, higher orders, global filters added after UseSentry) still run inside the job's scope. SentryServerFilter itself stays at the default order so its scope starts before other filters' OnPerforming. Checked against Hangfire.Core 1.8.12 and 1.8.25: the election runs on the same worker thread, and the scope set in OnPerforming is still current.
  • Fallback: if a state change from Processing happens on another thread (for example, a job deleted from the dashboard mid-run), the next OnPerforming on that worker disposes the leftover scope before pushing a new one.
  • Global mode: PushScope is a no-op there, so jobs keep sharing the one scope and trace. Sentry.Hangfire isn't strong-named, so unlike Sentry.Quartz it can't read IsGlobalModeEnabled to skip the call. In global mode with Debug on, each job logs a "Push scope called in global mode" warning.
  • Earlier approach dropped: the first commit deduplicated exception breadcrumbs in Hub by message. Hangfire's failure messages include the job ID and retry attempt (Failed to process the job '838861': … Retry attempt 2 of 5 …), so none of the breadcrumbs in the original report would have matched.
  • New trace per job: like Sentry.Quartz, each job's scope starts a new trace, using the public IHub.ContinueTrace(null, null) (Sentry.Hangfire can't see Scope.SetPropagationContext). This is skipped when PushScope didn't push (global mode or a locked scope), so the shared scope's trace isn't reset.

Closes #3632

🤖 Generated with Claude Code

…adcrumbs

An exception breadcrumb is skipped when the scope already holds one with
the same message and data.

Closes #3632

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit cac97e2.

Main concerns: data sent to Sentry, host performance, reach.

This label is a hint for reviewers, not an approval.

Comment thread src/Sentry/Internal/Hub.cs Resolved

@sentry-junior sentry-junior Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Good to approve, with optional comments

This fixes #3632 at the cause: each Hangfire job now runs in its own scope and trace, pushed in OnPerforming and popped by SentryJobScopeCloser (order int.MaxValue) once the job leaves Processing, so other filters' OnStateApplied still see the job's scope. Tests cover retries, per-job traces, later filters, the leftover-scope fallback with a real Hub, two workers, and the closer's registration from both public UseSentry overloads. No public API change.

  • Optional: in global mode with Debug on, every job logs a "Push scope called in global mode" warning (SentryServerFilter.PushJobScope, via SentryScopeManager.PushScope). Harmless, but noisy for desktop-style apps that run Hangfire; the description already calls it out.
  • Optional: the "didn't push, so keep the shared trace" guard in PushJobScope is tested only for global mode (ServerFilterTests.OnPerforming_GlobalMode_KeepsSharedScopesTrace); the locked-scope case takes the same path but has no test.

This is an automated preliminary review.

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Mutation testing breaks the lines a PR changes on purpose, one mutation at a time, and checks that a test fails each time. A changed line no test runs fails the check, and a mutant that survives the tests only warns. Full report

Sentry.Hangfire: tests caught 10 of 10 mutants on the changed lines

Stryker couldn't build 11 mutants on the changed lines, so no test ran against them.

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.60%. Comparing base (4ef7835) to head (cac97e2).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6074      +/-   ##
==========================================
+ Coverage   78.46%   78.60%   +0.13%     
==========================================
  Files         537      540       +3     
  Lines       20167    20218      +51     
  Branches     4056     4065       +9     
==========================================
+ Hits        15825    15893      +68     
+ Misses       3494     3481      -13     
+ Partials      848      844       -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Breadcrumbs and exception breadcrumbs from one Hangfire job no longer leak
into the events of later jobs on the same server. Replaces the earlier
approach of deduplicating exception breadcrumbs in Hub, which didn't match
Hangfire's failure messages: they include the job ID and retry attempt.

The scope is pushed in OnPerforming and popped in OnStateApplied when the job
leaves the Processing state, because Hangfire logs a job's failure while
electing its next state, after OnPerformed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jamescrosswell jamescrosswell changed the title fix: recurring exceptions no longer fill the scope with duplicate breadcrumbs fix(hangfire): run each job in its own scope so breadcrumbs from earlier jobs don't fill its events Dec 1, 2026
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
Each job now fails once, is retried and fails again, so the test covers
the Processing -> Scheduled transition behind the original report as well
as Processing -> Failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
Jobs shared the root scope's trace ID, so events from unrelated jobs ended
up in one trace. The job scope now gets its own trace, like Sentry.Quartz.

The trace is only reset when PushScope actually pushed: in global mode, or
when the current scope is locked, it returns without pushing, and resetting
would change the trace of the scope the whole app shares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jamescrosswell jamescrosswell changed the title fix(hangfire): run each job in its own scope so breadcrumbs from earlier jobs don't fill its events fix(hangfire): run each job in its own scope and trace so earlier jobs' breadcrumbs don't fill its events Dec 1, 2026
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
@jamescrosswell
jamescrosswell marked this pull request as ready for review December 2, 2026 07:54
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 2, 2026
…Applied

The job scope was closed in SentryServerFilter's own OnStateApplied, which
runs at the default order, so filters ordered later or added after UseSentry
no longer saw the job's scope. A separate filter registered at int.MaxValue
now closes it.

Also covers two workers sharing the filter, checks the leftover-scope case
against a real Hub, and avoids the closure allocation in GetCurrentScope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot removed the risk: medium PR risk score: medium label Dec 3, 2026

@ric-oliv ric-oliv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM! Apps that call AddAspNet() still share scopes between concurrent jobs, but tracking this separately in #6092.

@ric-oliv
ric-oliv merged commit b410382 into main Dec 4, 2026
47 checks passed
@ric-oliv
ric-oliv deleted the ai/triagent-3632 branch December 4, 2026 11:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recurring exceptions in Hangfire jobs result in lots of useless breadcrumbs

2 participants