diff --git a/.github/workflows/decision-model-lint.yml b/.github/workflows/decision-model-lint.yml new file mode 100644 index 0000000000..255629ae72 --- /dev/null +++ b/.github/workflows/decision-model-lint.yml @@ -0,0 +1,77 @@ +name: Decision model lint + +on: + pull_request: + types: [opened, reopened, synchronize, labeled, unlabeled] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }} + cancel-in-progress: true + +permissions: {} + +jobs: + lint: + name: Decision model lint + # Never pull_request_target, which would give a pull request's code the key. Forks get no + # secrets, so skip them. Every label change re-runs the lint, because a skipped run would + # replace the last result. + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + pull-requests: write # to keep one comment with the findings + steps: + # The pull request's merge commit and its first parent: HEAD^1..HEAD is what it changes. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: '24' + + - run: npm ci --prefix lint --ignore-scripts + + - name: Lint + env: + OPENROUTER_API_KEY: ${{ secrets.WARDEN_OPENROUTER_API_KEY }} + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.number }} + LABEL: Override decision model lint + OVERRIDDEN: "${{ contains(github.event.pull_request.labels.*.name, 'Override decision model lint') }}" + run: | + report="$RUNNER_TEMP/decision-model-lint.md" + status=0 + lint/node_modules/.bin/decision-model-linter --config lint/decision-model-linter.config.ts \ + --base HEAD^1 --format markdown > "$report" || status=$? + + # Only 1 means findings; any other failure means the linter did not finish. + if [ "$status" -eq 1 ] && [ "$OVERRIDDEN" = true ]; then + printf '\nThe `%s` label keeps these errors from failing the check.\n' "$LABEL" >> "$report" + elif [ "$status" -eq 1 ]; then + printf '\nThese errors fail the check; fix the code to resolve them. If you and a reviewer are confident an error is wrong, a person can add the `%s` label to pass the check while the findings stay reported. Agents should never add this label.\n' "$LABEL" >> "$report" + elif [ "$status" -gt 1 ] && [ "$OVERRIDDEN" = true ]; then + printf 'The linter did not finish (exit %s), and the `%s` label passes the check anyway; see the job log.\n' "$status" "$LABEL" >> "$report" + fi + + marker='' + comment=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ + --jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\"))) | .id" | head -n 1) + body= + if [ -s "$report" ] && { [ "$status" -le 1 ] || [ "$OVERRIDDEN" = true ]; }; then + body=$(printf '%s\n%s' "$marker" "$(cat "$report")") + elif [ "$status" -eq 0 ] && [ -n "$comment" ]; then + body=$(printf '%s\nNo findings on the latest commit.' "$marker") + fi + if [ -n "$body" ] && [ -n "$comment" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$comment" -f body="$body" > /dev/null + elif [ -n "$body" ]; then + gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" -f body="$body" > /dev/null + fi + cat "$report" >> "$GITHUB_STEP_SUMMARY" + + if [ "$status" -ne 0 ] && [ "$OVERRIDDEN" = true ]; then exit 0; fi + exit "$status" diff --git a/.gitignore b/.gitignore index b6301586e8..ca0a10fd16 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,6 @@ agents.lock # Warden local run logs .warden/logs/ + +# decision-model-linter dependencies +lint/node_modules/ diff --git a/lint/decision-model-linter.config.ts b/lint/decision-model-linter.config.ts new file mode 100644 index 0000000000..158bccc3d9 --- /dev/null +++ b/lint/decision-model-linter.config.ts @@ -0,0 +1,41 @@ +// Questions a decision model answers about each changed file on a pull request. Rules here need only +// the changed lines of one file, and need judgment: anything a parser can decide (banned calls or +// imports, formatting, unused code) belongs in Spotless, detekt, Error Prone, or Android Lint. Rules +// that need reading across files belong in the Warden `java-sdk-review` skill. +import type { Config, Model } from "@sentry/decision-model-linter"; + +import android from "./suites/android.ts"; +import gradle from "./suites/gradle.ts"; +import instrumentation from "./suites/instrumentation.ts"; +import kotlinInterop from "./suites/kotlin-interop.ts"; +import publicApi from "./suites/public-api.ts"; +import resources from "./suites/resources.ts"; +import safety from "./suites/safety.ts"; +import tests from "./suites/tests.ts"; + +const jev = { + provider: "openrouter", + name: "typesafe/jev-1.13", + apiKey: process.env.OPENROUTER_API_KEY, + maxInputTokens: 32_768, +} satisfies Model; + +export default { + model: jev, + threshold: 0.7, + // A file the model could not check must never look like a clean pass. + unchecked: "error", + ignores: [ + "**/build/**", + "**/generated/**", + // Samples and test helpers ship no SDK code. + "sentry-samples/**", + "sentry-android-integration-tests/**", + "sentry-test-support/**", + "sentry-system-test-support/**", + // Build logic is not SDK code; only the gradle suite lints it again. + "build-logic/**", + "buildSrc/**", + ], + suites: { safety, tests, publicApi, kotlinInterop, android, instrumentation, resources, gradle }, +} satisfies Config; diff --git a/lint/files.ts b/lint/files.ts new file mode 100644 index 0000000000..02e12a584e --- /dev/null +++ b/lint/files.ts @@ -0,0 +1,14 @@ +// The linter's globs have no brace expansion, so each extension is its own glob. +export const MAIN_JAVA = ["**/src/main/**/*.java"]; +export const MAIN_KOTLIN = ["**/src/main/**/*.kt"]; +export const MAIN_SOURCES = [...MAIN_JAVA, ...MAIN_KOTLIN]; +export const TEST_SOURCES = [ + "**/src/test/**/*.java", + "**/src/test/**/*.kt", + // Also matches flavor source sets such as `androidTestReplay`. + "**/src/androidTest*/**/*.java", + "**/src/androidTest*/**/*.kt", + // Spring and servlet modules run tests against a real server in these source sets. + "**/src/integrationTest*/**/*.java", + "**/src/integrationTest*/**/*.kt", +]; diff --git a/lint/package-lock.json b/lint/package-lock.json new file mode 100644 index 0000000000..355e400ac4 --- /dev/null +++ b/lint/package-lock.json @@ -0,0 +1,25 @@ +{ + "name": "lint", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "devDependencies": { + "@sentry/decision-model-linter": "0.3.0" + } + }, + "node_modules/@sentry/decision-model-linter": { + "version": "0.3.0", + "resolved": "https://sfw.security.sentry.io/npm/@sentry/decision-model-linter/-/decision-model-linter-0.3.0.tgz", + "integrity": "sha512-WGgidB18yGOT+a2LEDq2tTXPgpMXNTTSfMdSHCpuqu0wFU3tv8SQPYSdN7Go0uQark1kXDC/T8Q93Q6a45IoAQ==", + "dev": true, + "license": "FSL-1.1-ALv2", + "bin": { + "decision-model-linter": "dist/cli.js" + }, + "engines": { + "node": ">=24" + } + } + } +} diff --git a/lint/package.json b/lint/package.json new file mode 100644 index 0000000000..84bea4d7a2 --- /dev/null +++ b/lint/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "type": "module", + "devDependencies": { + "@sentry/decision-model-linter": "0.3.0" + } +} diff --git a/lint/suites/android.ts b/lint/suites/android.ts new file mode 100644 index 0000000000..a193e294ff --- /dev/null +++ b/lint/suites/android.ts @@ -0,0 +1,25 @@ +import type { Suite } from "@sentry/decision-model-linter"; + +import { yesNo } from "../yes-no.ts"; + +export default { + files: ["sentry-android*/**/src/main/**/*.java", "sentry-android*/**/src/main/**/*.kt"], + context: { minSdk: "The SDK's minSdk is 21." }, + rules: { + missingRequiresApi: yesNo( + "Do the new lines add a class or method that calls Android APIs newer than `minSdk` and only runs " + + "on those API levels, without `@RequiresApi`?", + "Code that only runs above minSdk is missing `@RequiresApi`.", + "The new lines call no API newer than minSdk, or are annotated `@RequiresApi`.", + "Annotate it with `@RequiresApi(...)` so Lint catches callers that don't check the SDK version.", + ), + redundantNewApiSuppression: yesNo( + "Do the new lines add `@SuppressLint(\"NewApi\")` or `@SuppressWarnings(\"NewApi\")` to code where an " + + "SDK version check already guards the call?", + "A NewApi suppression is added where a version check already guards the call.", + "The new lines add no NewApi suppression, or the suppression is needed.", + "Remove the suppression. The version check already satisfies Lint, and the suppression would hide " + + "future unguarded calls.", + ), + }, +} satisfies Suite; diff --git a/lint/suites/gradle.ts b/lint/suites/gradle.ts new file mode 100644 index 0000000000..d0bd13022c --- /dev/null +++ b/lint/suites/gradle.ts @@ -0,0 +1,29 @@ +// Banned calls such as `afterEvaluate`, `tasks.create`, or string dependency coordinates belong in +// detekt, not here: a parser decides them without a model. +import type { Suite } from "@sentry/decision-model-linter"; + +import { yesNo } from "../yes-no.ts"; + +export default { + files: ["**/*.gradle.kts", "build-logic/**/*.kt", "buildSrc/**/*.kt"], + // The config ignores build logic for the SDK suites; lint it again here. + ignores: ["!build-logic/**", "!buildSrc/**"], + rules: { + configurationCacheHazard: yesNo( + "Do the new lines read a hard-coded local path (such as `~/.m2` or a user directory), or read " + + "`project`, system properties, or environment variables at execution time in a way that breaks " + + "the configuration cache?", + "Build logic reads local paths or breaks the configuration cache.", + "The new lines read no local paths and stay configuration-cache compatible.", + "Use providers (`providers.environmentVariable`, `layout`) and avoid machine-specific paths.", + ), + raisedSupportFloor: yesNo( + "Do the new lines raise `minSdk`, the Java or JVM target level, or the lowest supported version of " + + "a framework the SDK integrates with?", + "A support floor is raised.", + "No support floor is raised.", + "Raising a support floor drops customers. Make sure the PR calls it out and `CHANGELOG.md` (and " + + "`MIGRATION.md` if needed) says so.", + ), + }, +} satisfies Suite; diff --git a/lint/suites/instrumentation.ts b/lint/suites/instrumentation.ts new file mode 100644 index 0000000000..1e56df12c6 --- /dev/null +++ b/lint/suites/instrumentation.ts @@ -0,0 +1,40 @@ +import type { Suite } from "@sentry/decision-model-linter"; + +import { MAIN_KOTLIN, MAIN_SOURCES } from "../files.ts"; +import { yesNo } from "../yes-no.ts"; + +export default { + files: MAIN_SOURCES, + rules: { + firstHeaderValueOnly: yesNo( + "Do the new lines read an HTTP header that may appear more than once (such as `Cookie`, " + + "`Set-Cookie`, or `baggage`) and use only its first value?", + "Only the first value of a header that can repeat is processed.", + "The new lines read no repeatable header, or process every value.", + "Process every value of this header; it can appear more than once.", + ), + replacesThirdPartyBaggage: yesNo( + "Do the new lines remove or overwrite the whole `baggage` header when adding Sentry's entries, " + + "instead of merging with existing third-party entries?", + "Third-party baggage entries are dropped when Sentry's are added.", + "The new lines don't touch baggage, or merge with existing entries.", + "Merge Sentry's entries into the existing `baggage` header instead of replacing it.", + ), + coroutineCancellationAsError: yesNo( + "Do the new lines, in coroutine instrumentation, treat `CancellationException` as an error (mark the " + + "span as errored or capture it) instead of setting `SpanStatus.CANCELLED` and rethrowing?", + "Coroutine cancellation is treated as an error.", + "The new lines don't handle coroutine cancellation, or handle it as cancellation.", + "Handle `CancellationException` separately: set `SpanStatus.CANCELLED` and rethrow it.", + { files: MAIN_KOTLIN }, + ), + wastedWork: yesNo( + "Do the new lines do measurement, allocation, or other expensive work on a hot path (per span, per " + + "event, per frame, per request) before checking whether the result is needed, for example when " + + "there is no active span or the feature's option is disabled?", + "Work is done on a hot path even when its result is thrown away.", + "The new lines check whether the work is needed first, or are not on a hot path.", + "Check first, and skip the work when its result would be discarded.", + ), + }, +} satisfies Suite; diff --git a/lint/suites/kotlin-interop.ts b/lint/suites/kotlin-interop.ts new file mode 100644 index 0000000000..0b6a22fdc8 --- /dev/null +++ b/lint/suites/kotlin-interop.ts @@ -0,0 +1,19 @@ +import type { Suite } from "@sentry/decision-model-linter"; + +import { MAIN_JAVA } from "../files.ts"; +import { yesNo } from "../yes-no.ts"; + +export default { + files: MAIN_JAVA, + rules: { + mismatchedAccessors: yesNo( + "Do the new lines add or change a Java getter or setter whose pair uses a different type (boxed " + + "versus primitive, such as `Boolean` and `boolean`) or a name that doesn't match (`isX` with " + + "`setY`, `getX` with `setX` taking another type)?", + "A getter and setter pair don't match, so Kotlin can't combine them into one property.", + "Every new getter and setter shown matches its pair, or there are none.", + "Use the same type and matching names for the getter and setter, so Kotlin callers get a single " + + "property instead of a getter and a separate `setX(...)` call.", + ), + }, +} satisfies Suite; diff --git a/lint/suites/public-api.ts b/lint/suites/public-api.ts new file mode 100644 index 0000000000..3fe90e47ea --- /dev/null +++ b/lint/suites/public-api.ts @@ -0,0 +1,26 @@ +import type { Suite } from "@sentry/decision-model-linter"; + +import { MAIN_SOURCES } from "../files.ts"; +import { yesNo } from "../yes-no.ts"; + +export default { + files: MAIN_SOURCES, + rules: { + missingApiStatus: yesNo( + "Do the new lines add a public class, interface, or method that is not meant for customers (for " + + "example in a `util` or `internal` package according to the file path) without " + + "`@ApiStatus.Internal`, or new API described as unstable without `@ApiStatus.Experimental`?", + "New public API is missing `@ApiStatus.Internal` or `@ApiStatus.Experimental`.", + "New public API is annotated as intended, or the new lines add no public API.", + "Mark API not meant for customers `@ApiStatus.Internal`, and unstable API `@ApiStatus.Experimental`. " + + "Anything else becomes public API we must keep binary compatible.", + ), + testOnlyWithoutAnnotation: yesNo( + "Do the new lines add a constructor, method, or setter that is evidently there only for tests " + + "(named or commented as such) without `@TestOnly`?", + "Test-only code in production sources is missing `@TestOnly`.", + "The new lines add no test-only code, or it is annotated `@TestOnly`.", + "Annotate it with `@TestOnly`, or inject the collaborator through the constructor instead.", + ), + }, +} satisfies Suite; diff --git a/lint/suites/resources.ts b/lint/suites/resources.ts new file mode 100644 index 0000000000..ad3a7fb47f --- /dev/null +++ b/lint/suites/resources.ts @@ -0,0 +1,67 @@ +// Resources, time, and code that will be misread without a comment. +import type { Suite } from "@sentry/decision-model-linter"; + +import { MAIN_SOURCES } from "../files.ts"; +import { yesNo } from "../yes-no.ts"; + +export default { + files: MAIN_SOURCES, + rules: { + leakOnPartialRelease: yesNo( + "Do the new lines release several resources (streams, files, executors, receivers, callbacks) in one " + + "block so that a failure releasing one leaves the others unreleased?", + "A failure releasing one resource leaks the rest.", + "The new lines release each resource independently, or release at most one.", + "Release each resource in its own `finally` (or try-with-resources), so one failure does not leak the others.", + ), + replacedCloseableNotClosed: yesNo( + "Do the new lines add a setter or assignment that replaces a closeable resource (executor, stream, " + + "transport) without closing the old one or documenting that the caller must?", + "A closeable resource is replaced without closing the old one.", + "The new lines replace no closeable resource, or close or document the old one.", + "Close the resource being replaced, or document that the caller owns it.", + ), + heldSdkExecutor: yesNo( + "Do the new lines store the SDK's executor (`getExecutorService()` or `getTimerExecutorService()`) " + + "in a field, or capture it in a long-lived object, instead of reading it from the options each " + + "time it is used?", + "The SDK's executor is held instead of read from the options when used.", + "The new lines don't hold the SDK's executor, or only read it into a local variable before using it.", + "Read the executor from the options each time. The options replace the no-op executor when the SDK " + + "starts, and re-init closes and replaces it, so a held reference can run nothing or a closed executor.", + ), + timeoutOnWorkerExecutor: yesNo( + "Do the new lines schedule a timeout or deadline (a callback that fires if something hasn't " + + "happened in time) on `getExecutorService()` rather than `getTimerExecutorService()`?", + "A timeout is scheduled on the worker executor.", + "The new lines schedule no timeout, or schedule it on `getTimerExecutorService()`.", + "Schedule timeouts on `options.getTimerExecutorService()`. On the worker executor they queue behind " + + "cached envelopes and other work, and fire late.", + ), + unitlessQuantity: yesNo( + "Do the new lines add a numeric field, parameter, or method for a time or size whose name has no " + + "unit (`Ms`, `Millis`, `Nanos`, `Seconds`, `Bytes`) and whose type does not carry one?", + "A time or size quantity has no unit in its name or type.", + "Every new time or size quantity names its unit, or there are none.", + "Add the unit to the name, for example `timeoutMs` or `maxSizeBytes`.", + ), + unclearClock: yesNo( + "Do the new lines add a timestamp or duration without making clear (by name, type, or comment) " + + "whether it comes from the wall clock or a monotonic clock?", + "A new time value leaves its clock type unclear.", + "The new lines add no time values, or each one makes its clock clear.", + "Use `EpochClock` for wall-clock timestamps and `MonotonicTicker` for durations, and make the clock " + + "clear in the name.", + ), + unexplainedWorkaround: yesNo( + "Do the new lines add code whose reason is not obvious and that a future maintainer would likely " + + "revert or simplify by mistake (a workaround, a `WeakReference`, resetting state, holding a " + + "redundant reference, disabling a cache) without a comment explaining why?", + "Non-obvious code has no comment explaining why it is there.", + "The new lines are self-explanatory, or carry a comment explaining why.", + "Add a comment explaining why this is needed, so it is not reverted later.", + // High threshold: "needs a comment" is easy to over-report. + { threshold: 0.9 }, + ), + }, +} satisfies Suite; diff --git a/lint/suites/safety.ts b/lint/suites/safety.ts new file mode 100644 index 0000000000..2aeabd8ca2 --- /dev/null +++ b/lint/suites/safety.ts @@ -0,0 +1,94 @@ +// The SDK runs inside customers' apps: it must not crash or hang them, hide its own bugs, or send +// personal data they did not opt into. +import type { Suite } from "@sentry/decision-model-linter"; + +import { MAIN_SOURCES } from "../files.ts"; +import { yesNo } from "../yes-no.ts"; + +export default { + files: MAIN_SOURCES, + rules: { + unjustifiedBroadCatch: yesNo( + "Do the new lines add a catch of `Throwable`, `Exception`, `RuntimeException`, or `Error` (in " + + "Java, or Kotlin `catch (e: Exception)` and `runCatching`) that does not both call " + + "`ExceptionUtils.rethrowIfFatal` first and carry a comment saying why the catch must be broad? A " + + "catch whose comment says it must also catch `LinkageError` (such as `NoSuchMethodError` from an " + + "old optional dependency) does not need `rethrowIfFatal`, which would rethrow exactly that.", + "A new broad catch is missing the `rethrowIfFatal` call, the comment explaining why it is broad, or both.", + "No new broad catch, or every new broad catch rethrows fatal errors and explains why it is broad, or " + + "its comment says it must also catch `LinkageError`.", + "Catch the narrowest type the guarded code can throw. A broad catch is only for boundaries such as " + + "public API entry points, calls into another process, or the body of a task submitted to an " + + "executor; it must call `ExceptionUtils.rethrowIfFatal(t)` first and say in a comment why it is " + + "broad and what happens on failure.", + ), + swallowedException: yesNo( + "Do the new lines add a catch block that neither rethrows, logs through the SDK logger " + + "(`options.getLogger()` or a logger field), nor handles the failure in a way a comment explains?", + "A new catch block silently drops the exception.", + "Every new catch block rethrows, logs through the SDK logger, or handles the failure with an explanation.", + "Don't swallow the exception silently. Log it with `options.getLogger().log(...)` so the failure can " + + "be diagnosed, and say what the customer sees when it fires.", + ), + lostExecutorException: yesNo( + "Do the new lines submit or schedule a task (`execute`, `submit`, `schedule*`) on an executor where " + + "an exception thrown by the task would be lost, because the task doesn't catch and log it and " + + "nobody reads the returned `Future`?", + "A task's exception would be lost: the task doesn't catch it, and nobody reads the returned `Future`.", + "The new lines submit no task, or the task catches and logs its exceptions, or the `Future` is read.", + "The executor keeps the exception in a `Future` nobody reads, so the failure vanishes and can leave " + + "state broken. Catch inside the task and log through `options.getLogger()`. The task body is a " + + "boundary, so the catch must call `ExceptionUtils.rethrowIfFatal(t)` first and say in a comment why " + + "it is broad.", + ), + interruptedException: yesNo( + "Do the new lines handle `InterruptedException` inside a broad catch, or catch it without calling " + + "`Thread.currentThread().interrupt()`?", + "`InterruptedException` is caught without restoring the interrupt flag, or only via a broad catch.", + "The new lines do not catch `InterruptedException`, or catch it in its own clause and restore the flag.", + "Catch `InterruptedException` in its own clause and call `Thread.currentThread().interrupt()`.", + ), + throwsBeforeTry: yesNo( + "Do the new lines put code that can throw (`!!`, casts, parsing, lookups) just before a `try` block " + + "that is meant to guard the same operation?", + "Code that can throw sits outside the try block meant to guard it.", + "No new throwing code sits just before the try block that guards it.", + "Move the code that can throw inside the `try` block, or the failure escapes the guard.", + ), + capturesOwnFailure: yesNo( + "Do the new lines call `captureException`, `captureMessage`, or `captureEvent` to report a failure " + + "of the SDK itself, or an exception thrown inside a user callback such as `beforeSend`, " + + "`beforeBreadcrumb`, or `tracesSampler`?", + "The SDK captures its own failure or a user callback's exception as an event.", + "The new lines do not capture the SDK's own failures or user callback exceptions.", + "The SDK must never capture its own exceptions or exceptions from user callbacks; capturing here can " + + "loop. Log through `options.getLogger()` instead. See " + + "https://develop.sentry.dev/sdk/getting-started/principles/#never-capture-your-own-exceptions", + ), + piiWithoutOptIn: yesNo( + "Do the new lines start collecting user-identifiable data (headers, cookies, request or response " + + "bodies, URL query strings, IP addresses, usernames, file paths, device identifiers) without " + + "checking `isSendDefaultPii()`?", + "New personal data is collected without the `sendDefaultPii` opt-in.", + "The new lines collect no new personal data, or only behind `isSendDefaultPii()`.", + "Gate new personal data behind `options.isSendDefaultPii()`; it must not be sent by default.", + ), + scrubberFailsOpen: yesNo( + "Do the new lines scrub or redact sensitive data in a way that passes the original value, or parts " + + "of it, through when the input cannot be parsed?", + "A scrubber passes data through when it cannot parse its input.", + "The new lines add no scrubbing, or the scrubbing redacts the whole value when parsing fails.", + "Fail closed: when the input cannot be parsed reliably, redact the whole value.", + ), + optionalDependencyProbe: yesNo( + "Do the new lines guard a call into an optional (`compileOnly`) dependency with a broad catch, or " + + "with try/catch at each call site, instead of checking once whether the class is available and " + + "catching the specific `LinkageError` subclass?", + "An optional dependency is probed with a broad catch or per-call try/catch.", + "No optional dependency is probed in the new lines, or it is checked once with a specific LinkageError.", + "Check availability once up front (`LoadClass`, `Platform`) and catch the specific `LinkageError` " + + "subclass (`NoClassDefFoundError`, `NoSuchMethodError`). A broad catch with `rethrowIfFatal` " + + "rethrows every `LinkageError` and crashes the app when the dependency is missing.", + ), + }, +} satisfies Suite; diff --git a/lint/suites/tests.ts b/lint/suites/tests.ts new file mode 100644 index 0000000000..21d926cbf2 --- /dev/null +++ b/lint/suites/tests.ts @@ -0,0 +1,46 @@ +// Warden never reviews test files, so every test rule lives here. +import type { Suite } from "@sentry/decision-model-linter"; + +import { TEST_SOURCES } from "../files.ts"; +import { yesNo } from "../yes-no.ts"; + +export default { + files: [ + ...TEST_SOURCES, + // A `com.android.test` module keeps its tests in `src/main`. + "sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/src/main/**/*.kt", + ], + // The config ignores the UI test modules for the SDK suites; lint their tests again here. Matching + // only `src` keeps their build outputs ignored. + ignores: ["!sentry-android-integration-tests/*/src/**"], + rules: { + hollowAssertion: yesNo( + "Does a new or changed test have assertions that would still pass if the behavior its name " + + "describes did not happen, for example asserting only that nothing was thrown, asserting on a " + + "payload without checking the newly added data, or setting up a fake clock, ticker, or scheduler " + + "and never advancing it, so time-dependent behavior is never exercised?", + "A test's assertions don't prove what its name claims.", + "Every new or changed test asserts the behavior it names.", + "Assert the behavior the test names. A test that passes without that behavior protects nothing.", + ), + leakedExecutor: yesNo( + "Do the new lines create a real executor, thread, or timer in a test without closing or shutting it " + + "down in that test or its teardown?", + "A test starts an executor, thread, or timer and never stops it.", + "The new lines start no executor, thread, or timer, or stop each one they start.", + "Shut it down in the test or in teardown, so it does not leak into other tests.", + ), + // A bounded poll is the only option for state nothing signals, such as a thread parking. + flakyWait: yesNo( + "Do the new lines wait by sleeping a fixed time and assuming the work is done by then, by looping " + + "with no deadline, or by assuming thread ordering, or poll for a condition that a `Future`, " + + "latch, idling resource, fake clock, or the executor's own completion could signal instead?", + "The test sleeps a fixed time, waits without a bound, or polls where a deterministic signal exists.", + "The new lines wait on a deterministic signal, poll with a deadline for state nothing signals, or " + + "don't wait.", + "Wait on a deterministic signal: a `Future`, a `CountDownLatch`, an idling resource, a fake " + + "clock, or the executor's own completion. Poll only for state nothing signals, and bound the " + + "poll with a deadline.", + ), + }, +} satisfies Suite; diff --git a/lint/yes-no.ts b/lint/yes-no.ts new file mode 100644 index 0000000000..981267e716 --- /dev/null +++ b/lint/yes-no.ts @@ -0,0 +1,22 @@ +import type { Rule } from "@sentry/decision-model-linter"; + +/** + * A rule asked as a yes/no question. `yes` describes the problem, and a yes answer reports `report`. + * Every rule starts at `warn`; a rule moves to `error` only once it has proven precise on real PRs. + */ +export function yesNo( + prompt: string, + yes: string, + no: string, + report: string, + settings: Omit = {}, +): Rule { + return { + ...settings, + prompt, + values: [ + { value: "TRUE", description: yes, report, severity: "warn" }, + { value: "FALSE", description: no }, + ], + }; +}