Skip to content

sentry_set_context opens file handles resulting in hitches #1395

Closed

Description

@jeremy-wildlight

Description

System profiling demonstrates that sentry_set_context can easily take 300 to 800 ms in a frame, depending on OS environmental factors because internally, the function appears to create file handles (which also touches USN journal state and so on).

In the context of a single-process crash collection workflow, is this file lock needed? It would be preferable to have a mode of operation where this file was just created once or ideally not at all.

When does the problem happen

  • During build
  • During run-time
  • When capturing a hard crash

Environment

  • OS: Windows 10/11 64-bit
  • Compiler: Clang 18.1.8

Steps To Reproduce

Run any game and attempt to call sentry_set_context every frame.

Activity

  1. added
    Bug
    Native
    on Sep 30, 2025
  2. linear commented on Sep 30, 2025

    @linear
  3. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Sep 30, 2025
  4. JoshuaMoelans commented on Oct 1, 2025

    @JoshuaMoelans
  5. moved this from Waiting for: Product Owner to No status in GitHub Issues with 👀 3on Oct 1, 2025
  6. supervacuus commented on Oct 1, 2025

    @supervacuus
    Collaborator

    Hi @jeremy-wildlight!

    System profiling demonstrates that sentry_set_context can easily take 300 to 800 ms in a frame, depending on OS environmental factors because internally, the function appears to create file handles (which also touches USN journal state and so on).

    Every scope-mutating function (sentry_set_x() or more generally sentry_[verb]_x()) will need to flush the scope to disk, depending on the combination of crash backend (only the crashpad backend currently does this) and platform requirements (macOS depends on this entirely, Windows only for WER handled exceptions and on Linux it isn't required).

    In particular, on Windows, this is only required for fast-fail crashes because those are handled entirely outside the monitored application via WER (and no client-side hook can pull the last state of the global scope to persist into an error).

    An alternative for you would be to examine the Breakpad backend (which doesn't flush on any platform). I really cannot say a lot about your use case, but you can have a look at the preliminary discussion here: https://docs.sentry.io/platforms/native/advanced-usage/backend-tradeoffs/

    There are multiple options to counter this from our side as well:

    • we could introduce an option to disable disk flushing, which means only SEH exceptions will retrieve a proper scope (which could be enough if you don't expect fast-fail crashes)
    • we could move the scope updates into the crashpad interface, similar to how we did it with attachments recently, which would mean we'd get rid of scope sync via disk entirely, but there would still be IPC overhead
    • we could defer scope persistence, meaning we only enqueue your scope mutation, and a background worker does persistence and disk flushing
    • we could optimize the hot-path, but that seems comparatively inconsequential since we still would need to sync to disk at some point

    The first three sound sensible as optimizations for that path.

    However, it would be interesting to know more about your use case for changing the context on every frame, since the context and every scope item primarily exist to enrich events, and the external flushing is entirely about crash events (since regular events are generated inside the application, they can access the current scope state at any point).

    It might be sufficient to disable disk flushing or make it more explicit, since you may not rely on per-frame data for enriching/identifying fast-fail crashes.

    Another option would be to use local scopes (example for adding attachments to local scopes) exclusively within your frames, which are applied to specific events and not flushed like global scope mutations:

    sentry-native/include/sentry.h

    Lines 1642 to 1645 in 075b3bf

    /**
    * Creates a local scope.
    */
    SENTRY_API sentry_scope_t *sentry_local_scope_new(void);

    sentry-native/include/sentry.h

    Lines 1656 to 1662 in 075b3bf

    /**
    * Sends a sentry event with a local scope.
    *
    * Takes ownership of `scope`.
    */
    SENTRY_API sentry_uuid_t sentry_capture_event_with_scope(
    sentry_value_t event, sentry_scope_t *scope);

    And configure that local scope with any sentry_scope_* interface.

    In the context of a single-process crash collection workflow, is this file lock needed? It would be preferable to have a mode of operation where this file was just created once or ideally not at all.

    There is no file lock involved when flushing the scope to disk. The file lock is used solely during initialization when a run directory is chosen for the current process or when old runs are cleaned up.

    CC: @jpnurmi, @mujacica

  7. supervacuus commented on Oct 1, 2025

    @supervacuus
    Collaborator

    Hi @JoshuaMoelans,

    The only thing we additionally do is create a short-lived lock on the scope, but we do not touch any file handles.

    We do! When closing the mutation lock, we also invoke the backend flusher, which Crashpad currently uses on Windows and macOS.

  8. jeremy-wildlight commented on Oct 1, 2025

    @jeremy-wildlight
    Author

    Thanks @supervacuus for all the helpful context! We had recently upgraded from an earlier version of the library which apparently didn't flush the file so we never noticed. To answer your question, we had previously updated the scope whenever interesting game state had changed (player position, map, and so on) which could really be "any time". The thinking was that updating the context "just in time" (i.e. in a top-level exception handler or before an assert) might be error-prone since the application is in an inconsistent state at the time of a crash/exception/assert.

    Some other thoughts:

    • On Windows at least, creating the file handle in the first place is often the expensive part as opposed to dirtying a page -- would it be possible to cache the file handle in memory?
    • It might be useful to have an option to update the context in a "best effort" manner, without incurring an actual flush.
    • IPC into the external handler may be relatively cheap if we write to shared mapped page (we'd still pay for some global synchronization mechanism)

    Now that we know this is the current behavior though, we will probably opt to schedule these context updates on a different thread in user-space in cases where the timing is critical. In the meantime, it might be useful for endusers to advertise info about the perf characteristics of the various native API calls to evaluate tradeoffs between scopes, contexts, or other mechanisms.

  9. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Oct 1, 2025
  10. 10 remaining items

  11. added
    Improvement
    on Oct 3, 2025
  12. supervacuus commented on Oct 3, 2025

    @supervacuus
    Collaborator

    To answer your question, we had previously updated the scope whenever interesting game state had changed (player position, map, and so on) which could really be "any time". The thinking was that updating the context "just in time" (i.e. in a top-level exception handler or before an assert) might be error-prone since the application is in an inconsistent state at the time of a crash/exception/assert.

    No, you are absolutely right: the intention is that you update whenever you see a boundary, and you shouldn't be playing a fixup game in the crash hook.

    My question was more about whether you are updating the context so that, in the case of a crash, you have up-to-date context information, or whether you primarily use it to enrich events you send between frames. In the latter case, local scopes would have helped, whereas with crashes, those really don't make a lot of sense.

    While documenting this non-obvious cost is definitely the right first step, we should also ensure that we reduce the cost as much as possible. This accounting, however, is primarily driven by usage scenarios, so thank you again for the insight into yours.

  13. limbonaut commented on Oct 3, 2025

    @limbonaut
    Collaborator

    300 to 800 ms in a frame

    Worth profiling this deeper. These numbers seem way too big for gamedev. So out of curiosity, I tried to reproduce this in the Godot SDK (as it employs sentry-native internally on Windows).

    I used this code on vanilla Windows 11 to test with 4yo laptop:

    class Stats:
    	var desc: String
    	var last_duration: int = 0
    	var total_time: int = 0
    	var num_runs: int = 0
    
    var _stats := Stats.new()
    
    
    # Runs every frame
    func _process(_delta: float) -> void:
    	_benchmark(_test_context, "Setting context", _stats)
    
    
    func _benchmark(callable: Callable, desc: String, stats: Stats) -> void:
    	var start: int = Time.get_ticks_usec()
    	callable.call()
    	var end: int = Time.get_ticks_usec()
    	
    	var duration: int = end - start
    	stats.desc = desc
    	stats.last_duration = duration
    	stats.total_time += duration
    	stats.num_runs += 1
    	
    	_report(stats)
    
    
    func _report(stats: Stats):
    	var last_ms: float = stats.last_duration * 0.001
    	var avg_ms: float = (stats.total_time / stats.num_runs) * 0.001
    	print("%s | last %.1fms | runs %d | avg %.1fms " % [stats.desc, last_ms, stats.num_runs, avg_ms])
    
    
    func _test_context() -> void:
    	SentrySDK.set_context("test_context", {
    		"delta": get_process_delta_time(),
    		"frames": Engine.get_frames_drawn(),
    		"fps": Engine.get_frames_per_second()
    	})

    My results:

    Setting context | last 7.7ms | runs 2011 | avg 5.4ms 
    Setting context | last 5.9ms | runs 2012 | avg 5.4ms 
    Setting context | last 6.1ms | runs 2013 | avg 5.4ms 
    Setting context | last 0.5ms | runs 2014 | avg 5.4ms 
    Setting context | last 7.2ms | runs 2015 | avg 5.4ms 
    Setting context | last 0.4ms | runs 2016 | avg 5.4ms 
    Setting context | last 7.1ms | runs 2017 | avg 5.4ms 
    Setting context | last 6.9ms | runs 2018 | avg 5.4ms 
    Setting context | last 5.8ms | runs 2019 | avg 5.4ms 
    Setting context | last 0.5ms | runs 2020 | avg 5.4ms 
    Setting context | last 7.1ms | runs 2021 | avg 5.4ms 
    Setting context | last 5.7ms | runs 2022 | avg 5.4ms 
    Setting context | last 0.4ms | runs 2023 | avg 5.4ms 
    Setting context | last 7.5ms | runs 2024 | avg 5.4ms 
    Setting context | last 5.8ms | runs 2025 | avg 5.4ms 
    Setting context | last 0.4ms | runs 2026 | avg 5.4ms 
    Setting context | last 7.0ms | runs 2027 | avg 5.4ms 
    

    It's not 300ms, although even 5 ms for setting a small context is still too much, in my opinion. This would result in considerable frame-time spikes.

  14. jeremy-wildlight commented on Oct 3, 2025

    @jeremy-wildlight
    Author

    In my case, the 300+ms timing is the worst case I found in profiling sessions in a sample size of ~10 machines over many many minutes of gameplay. Even 0.5ms would actually be well outside my budget for what I could tolerate on the main thread in this case, and the "worst case" or "99th percentile" values tend to be the metrics that really matter from an optimization standpoint. In Windows, the cost of a file handle creation can be highly variable, but depend on things like anti-virus or other factors going on in the system at the time. I observed that some machines didn't exhibit a problem at all, whereas other setups seemed to see the problem consistently. Going deeper would probably require xperf/WPA analysis and I didn't get to that point (it's cheaper now that the problem is known to just take the routine off the critical path).

  15. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Oct 3, 2025
  16. moved this from Waiting for: Product Owner to No status in GitHub Issues with 👀 3on Oct 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ImprovementNativebackend: crashpad

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions