This file provides guidance to AI coding agents when working with code in this repository.
This file covers the whole repository. Before working on a specific area, read the matching
rule file in .cursor/rules/:
| Rule | Read it when working on |
|---|---|
api |
Public API surface, binary compatibility, .api files, updateKotlinAbi, IScope/IScopes/Sentry static API, protocol classes |
options |
SentryOptions, namespaced options, ExternalOptions, sentry.properties, ManifestMetadataReader, Spring Boot properties |
scopes |
Scope management, forking, lifecycle, ScopeType, thread-local storage, scope bleeding, Hub → Scopes migration |
deduplication |
Duplicate event detection, DuplicateEventDetectionEventProcessor, enableDeduplication |
offline |
Caching, envelope storage, network failure handling, retries, AsyncHttpTransport, EnvelopeCache, rate limiting |
feature_flags |
addFeatureFlag, FeatureFlagBuffer, maxFeatureFlags, LaunchDarkly and OpenFeature integrations |
metrics |
Sentry.metrics(), IMetricsApi, count/distribution/gauge, MetricsBatchProcessor |
queues |
Queue tracing, queue.publish/queue.process, enableQueueTracing, Kafka instrumentation, messaging span data |
continuous_profiling_jvm |
sentry-async-profiler, IContinuousProfiler, ProfileChunk, JFR files, ProfileLifecycle |
opentelemetry |
sentry-opentelemetry-*, agent vs agentless, span processing, sampling, context propagation |
new_module |
Adding a new integration or sample module |
e2e_tests |
End-to-end tests, MockSentryServer, integration test suites, the OpenTelemetry agent fixture |
Rules can be combined — a tracing scope issue may need both scopes and opentelemetry.
There is no rule for Android profiling yet; read the sentry-android-core profiling code
directly and fetch related rules such as options, offline, or api as needed.
This is the Sentry Java/Android SDK - a comprehensive error monitoring and performance tracking SDK for Java and Android applications. The repository contains multiple modules for different integrations and platforms.
The project uses Gradle with Kotlin DSL. Key build files:
build.gradle.kts- Root build configurationsettings.gradle.kts- Multi-module project structurebuildSrc/andbuild-logic/- Custom build logic and pluginsMakefile- High-level build commands
# Format code in every build and regenerate .api files (REQUIRED before committing)
make format api
# Run all tests and linter
./gradlew check
# Generate documentation
./gradlew aggregateJavadocs
# Dependency updates check
./gradlew dependencyUpdates -Drevision=releaseTo run tests, use the test skill rather than composing the Gradle invocation by hand — it
resolves the per-module test task, including integration test suites, for you.
# Assemble Android test APKs, in a separate Gradle build that includes this one
./gradlew -p sentry-android-integration-tests :sentry-uitest-android:assembleRelease :sentry-uitest-android:assembleAndroidTest
# Run critical UI tests
./scripts/test-ui-critical.sh
# Build the Android sample, in the same separate Gradle build as the UI tests
./gradlew -p sentry-android-integration-tests :sentry-samples-android:assembleDebug
# Build the JVM samples, another separate Gradle build that includes this one
./gradlew -p sentry-samples assemble- First think through the problem: Read the codebase for relevant files and propose a plan
- Check in before beginning: Verify the plan before starting implementation
- Use todo tracking: Work through todo items, marking them as complete as you go
- High-level communication: Give high-level explanations of changes made, not step-by-step descriptions
- Simplicity first: Make every task and code change as simple as possible. Avoid massive or complex changes. Impact as little code as possible.
- Format and regenerate: Once done, format code and regenerate .api files:
make format api - Propose commit: As final step, git stage relevant files and propose (but not execute) a single git commit command. This applies to implementation work; when the task is to open a PR, the
create-java-prskill takes over from here and does commit, push, and open it.
This repo ships task-specific skills, declared in agents.toml with sources under
.agents/skills. Your harness already lists them with their descriptions — prefer them over
performing the steps manually.
The repository is organized into multiple modules:
sentry- Core Java SDK implementationsentry-android-core- Core Android SDK implementationsentry-android- High-level Android SDKsentry-android-ndk- Native (NDK) crash handling
- Spring Framework:
sentry-spring*,sentry-spring-boot* - Logging:
sentry-logback,sentry-log4j2,sentry-jul,sentry-android-timber - Web:
sentry-servlet*,sentry-okhttp,sentry-openfeign,sentry-apache-http-client-5 - GraphQL:
sentry-graphql*,sentry-apollo* - Android UI:
sentry-android-fragment,sentry-android-navigation,sentry-android-navigation3,sentry-compose - Session Replay:
sentry-android-replay - Database:
sentry-jdbc,sentry-android-sqlite,sentry-jcache - Reactive:
sentry-reactor,sentry-ktor-client - Feature Flags:
sentry-launchdarkly-android,sentry-launchdarkly-server,sentry-openfeature - Queues:
sentry-kafka - Profiling:
sentry-async-profiler(JVM continuous profiling) - Monitoring:
sentry-opentelemetry*,sentry-quartz - Other:
sentry-spotlight,sentry-kotlin-extensions,sentry-android-distribution
sentry-test-support- Shared test utilities, includingMockSentryServerand envelope matcherssentry-samples- Example applications, in two separate Gradle builds that include this one:sentry-samples(JVM) andsentry-android-integration-tests(the Android sample, next to the Android UI tests, benchmark and size test). Root tasks such ascheckandspotlessApplydon't reach themsentry-bom- Bill of Materials for dependency management
- Multi-platform: Supports JVM, Android, and Kotlin Multiplatform (Compose modules)
- Modular Design: Each integration is a separate module with minimal dependencies
- Options Pattern: Features are opt-in via
SentryOptionsand similar configuration classes - Transport Layer: Pluggable transport implementations for different environments
- Scope Management: Thread-safe scope/context management for error tracking
- Languages: Java 8+ and Kotlin
- Formatting: Enforced via Spotless
- API Compatibility: Binary compatibility is enforced.
.apifiles are generated, never hand-edited
The following section applies only in cases where the spec (sentry-docs) do not define an exception handling strategy.
Inside the SDK, never add a broad catch (Throwable, Error, Exception,
RuntimeException). Catch the narrowest type the guarded code can actually throw. The many
existing broad catches are legacy, not precedent: they hide real bugs in our own code and make it
appear that Sentry is broken.
A broad catch is allowed only at a boundary where we can't know what the other side throws. Two examples:
- public API entry points like
captureException - Android framework calls that cross into another process (
ContentResolver, system services) - user callbacks like
beforeSendLogsdefined in the spec (sentry-docs)
At a boundary follow the spec (sentry-docs) otherwise if no spec is defined for this case:
- Call
ExceptionUtils.rethrowIfFatal(t)first soOutOfMemoryError,StackOverflowError, etc. are never swallowed. It also rethrowsLinkageError, so code probing an optionalcompileOnlydependency must catch the specific subclass (NoClassDefFoundError, ...) before it. - A code comment is required saying why the catch is broad and what happens on failure (event dropped, feature disabled, ...).
- If wrapping user code with a broad catch, documentation is required explaining how the user is expected to discover that the code they wrote isn't working. Both in the Javadoc and in sentry-docs.
- Logging is not handling:
options.getLogger()is silent unlessdebugis enabled, so a failure that is only logged is invisible in production.
Instrumentation that wraps user code is not a boundary for the user's own exceptions: let them propagate unchanged.
Never hold a lock across a call that can re-enter the SDK. Read what you need under the lock, release it, then make the call.
Finishing a span or transaction, capturing an event, and invoking a user-supplied callback all run
arbitrary SDK code on the calling thread. SentryTracer.finish() calls scopes.captureTransaction(...)
synchronously, which runs every registered EventProcessor — and those processors take their own
locks and call back into SDK components. A lock held across such a call is therefore acquired in the
opposite order from the processor's, which is a deadlock. On Android the blocked thread is usually
the main thread, so it surfaces to users as an ANR rather than a hang.
// Wrong: the lock is held while finish() captures the transaction and runs event processors,
// which take their own lock and then call back into this class.
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
final @Nullable ITransaction transaction = ownedTransaction;
if (transaction != null && !transaction.isFinished()) {
transaction.finish(SpanStatus.OK);
}
}
// Right: read the field under the lock, call finish() outside it.
final @Nullable ITransaction transaction;
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
transaction = ownedTransaction;
}
if (transaction != null && !transaction.isFinished()) {
transaction.finish(SpanStatus.OK);
}The same applies to logging through options.getLogger(), invoking a listener, and any
ISpan/IScopes call reachable from a component that locks.
Moving the call out can break a compound operation that was atomic only because the lock spanned it. When that happens, do not widen the original lock again — serialize the callers with a second lock that the re-entrant path never acquires, and document the order the two are taken in.
Two more rules that catch most of the rest:
- Mark a field
volatilewhen it is written on one thread and read on another without a lock. A plain field read is a data race, not merely a stale value. - Read mutable shared state once per operation. Re-reading the same field for several decisions in one pass lets it change mid-pass, so the results disagree with each other.
Prefer AutoClosableReentrantLock over synchronized, matching the rest of the codebase.
New code that reads a clock uses io.sentry.time, not System.currentTimeMillis(),
System.nanoTime(), SystemClock, DateUtils.getCurrentDateTime(), a SentryDateProvider, or an
ICurrentDateProvider. Those are legacy, not a precedent to follow.
Pick the type by what the number is for:
| You need | Use |
|---|---|
| An instant that leaves the process (event, breadcrumb, session) | EpochClock → Timestamp. Never subtract two of them |
| How long something took | Stopwatch |
| Whether a window has elapsed (TTL, backoff, timeout) | Deadline |
| Several instants compared with each other (spans of a transaction) | AnchoredClock |
| A raw tick, when none of the above fits | MonotonicTicker |
Get the clock from options.getEpochClock() or options.getMonotonicTicker(), not a
getInstance(): on Android the ticker keeps counting through device suspend, and System.nanoTime()
does not. Take it as a constructor parameter; tests use TestMonotonicTicker instead of sleeping.
If none of these fits, propose a new type, and the clock bug it makes impossible, before writing call sites against it. Don't inline raw tick arithmetic as a stopgap.
- Write comprehensive unit tests for new features
- Android modules require both unit tests and instrumented tests where applicable
- End-to-end tests run in the module they test, against
MockSentryServer. Samples have no tests - Assertions: For new unit tests, prefer Google Truth (
com.google.common.truth.Truth.assertThat) overkotlin.test/JUnit assertions for its readable, fluent API. Keep usingkotlin.testfor test structure (@Test,assertFailsWith). Seesentry/src/test/java/io/sentry/DsnTest.ktfor the style. Don't rewrite existingkotlin.testassertions solely to switch libraries. - Truth is wired into the
sentrymodule. When adding Truth-based tests to another module, addtestImplementation(libs.google.truth)to that module'sbuild.gradle.kts.
- Follow existing code style and language
- Write comprehensive tests
- New features must be opt-in by default - extend
SentryOptionsor similar Option classes with getters/setters - Consider backwards compatibility
When adapting code from third-party libraries:
-
Add a license header at the top of the adapted file (before the
packagestatement):// Adapted from <Library Name>. // Copyright <year> <copyright holder>. // Licensed under the <License Name>. // <source URL>
-
Add a full attribution entry to
THIRD_PARTY_NOTICES.mdfollowing the existing format (Source, License, Copyright, Scope, full license text) -
Run the
check-code-attributionskill locally or wait for it to be auto-run against your PR to check for required fields and verify new licenses against Sentry's Open Source Legal Policy.
Use gh pr view to get PR details from the current branch. This is needed when adding changelog entries, which require the PR number.
# Get PR number for current branch
gh pr view --json number -q '.number'
# Get PR number for a specific branch
gh pr view <branch-name> --json number -q '.number'
# Get PR URL
gh pr view --json url -q '.url'User-facing changes get an entry under the ## Unreleased section of CHANGELOG.md. The
create-java-pr skill is the source of truth for the full changelog and PR workflow, including
subsection selection and the rebase caveat when a release renames ## Unreleased.
- Main SDK documentation: https://develop.sentry.dev/sdk/overview/
- Internal contributing guide: https://docs.sentry.io/internal/contributing/
- Git commit message conventions: https://develop.sentry.dev/engineering-practices/commit-messages/
This SDK is production-ready and used by thousands of applications. Changes should be thoroughly tested and maintain backwards compatibility.