Skip to content

[docs] Prevent flaky tests in agent-authored changes - #13728

Open
simonrozsival wants to merge 3 commits into
mainfrom
simonrozsival-ci-flakiness
Open

simonrozsival wants to merge 3 commits into
mainfrom
simonrozsival-ci-flakiness

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

CI investigations have exposed recurring sources of test flakiness: timing-based assertions, uncontrolled global state, output and log reuse, shared test directories, and environmental dependencies. Guidance for agents and reviewers makes these patterns visible during test authoring and review, before they enter CI.

The Copilot instructions now summarize the required practices, and the code-review skill includes a focused checklist. The checklist also calls out crosstalk from process-wide runtime state—including JNI global references, GC and finalizer activity, and thread-pool state—and recommends asserting behavior of test-owned objects rather than exact global counter deltas.

Validation: git diff --check passed. No build or tests were run because this change updates documentation only.

simonrozsival and others added 2 commits November 23, 2026 16:18
Recent CI flake investigations kept tracing back to the same test patterns: wall-clock thresholds, sleeps used as synchronization, parameterized cases sharing output directories, shared caches and global state, remote dependency graphs, assertions on stale logs or logcat, filesystem-timestamp checks, unbounded process I/O, Windows file locks, oversized device matrices, and retries that hide nondeterminism.

Add a flake-prevention checklist to the code-review skill's testing rules, prioritize nondeterministic tests in its diff analysis, and summarize the rules in the Copilot instructions so new tests avoid these patterns.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 15:25

Copilot AI 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.

🟡 Changes recommended

The guidance risks test-output collisions and stale logcat assertions, and recommends a retry helper that violates its own exception-handling and logging rules.

3 open issues
What changed in this PR

This documentation-only PR adds flake-prevention guidance for agents authoring and reviewing .NET for Android tests, aiming to catch recurring reliability problems before they reach CI.

Changes:

  • Summarizes deterministic test practices in the Copilot instructions.
  • Adds a detailed checklist covering synchronization, state isolation, logs, dependencies, and retries.
  • Updates the code-review skill to explicitly check for flaky tests.
File Description
.github/​skills/​code-review/​SKILL.md Adds flaky tests to review priorities and points to the checklist.
.github/​skills/​code-review/​references/​testing-rules.md Adds detailed reliability checks and recommended alternatives.
.github/​copilot-instructions.md Summarizes reliable test-authoring practices for agents.

Review effort: Balanced

- **Isolate every case.** Give each parameterized row its own directory, including all distinguishing parameters. Don't share caches, environment variables, the current directory, or fixed `%TEMP%` paths between tests.
- **Avoid crosstalk in process-wide runtime state.** Other tests, framework threads, and pending finalizers also change global reference counts, peer/object maps, GC counts, and thread-pool state. Don't assert exact process-wide deltas; establish a quiescent baseline, observe only objects the test owns (for example a specific handle or weak reference), and use `[NonParallelizable]` when global state can't be avoided.
- **Avoid the network.** Prefer small in-repo fixtures to third-party SDKs or large remote dependency graphs.
- **Assert on the current run only.** Delete old logs before each build, and scope logcat to the current run with a marker or a fresh dump.
| **No wall-clock thresholds** | Assertions such as `elapsed < 160 ms` or build/install times compared against a reference measure agent load, not correctness. Assert the behavior instead, for example that a target or task was skipped (`AssertTargetIsSkipped`) or that the output changed. Performance belongs in a benchmark, not a pass/fail test. |
| **No fixed sleeps as synchronization** | `Thread.Sleep`, `Task.Delay`, or a short fixed timeout that waits for a process, device, emulator, logcat line, or background task to be "ready" is a race. Wait for an explicit condition (exit code, readiness property, `sys.boot_completed`, a unique log marker, `TaskCompletionSource`) with a generous deadline, and print diagnostics when the deadline expires. |
| **Deterministic concurrency and cancellation tests** | Cancellation, dispose, and threading tests must control ordering with gates (`TaskCompletionSource`, `ManualResetEventSlim`, blocking streams) so the code under test is provably in the intended state before the action. A test that "usually" hits the window by delaying is flaky. Do not rely on GC timing or finalizers without a deterministic trigger. |
| **Unique, isolated test directories** | Every parameterized case must get its own output directory. Directory names derived from `TestName` or a subset of parameters can collide across `[TestCase]`/`[Values]` rows (for example rows that differ only by runtime or string arguments), so concurrent or sequential cases overwrite each other. Include all distinguishing parameters, or use the per-test `Root`. |
| **Assert on the current run's outputs only** | Logs, build outputs, TRX files, and logcat buffers left from an earlier run or build can satisfy or fail an assertion. Delete or rotate the log before each build, clear logcat or search after a per-run marker, and take a fresh `logcat -d` before reporting a device failure. |
| **No filesystem-timestamp assumptions** | "File A is newer than B" assertions depend on filesystem timestamp granularity and on tools that preserve timestamps. Prefer content hashes or target/task skip evidence for incremental-build tests. |
| **Bounded process I/O** | Waiting for redirected stdout/stderr to reach EOF hangs when a child process (e.g. a build server, `adb`, or a daemon) inherits the pipes. Wait for process exit with a timeout and bound the output drain. Disable build servers and node reuse in tests that spawn builds. |
| **Windows file locks** | Moving or deleting a just-built tree on Windows can hit sharing violations from lingering processes or scanners. Use the existing helpers (`FileSystemUtils.DeleteDirectoryWithRetry`), retry only the specific transient error (e.g. `ERROR_SHARING_VIOLATION`), bound the total delay, and log each retry. Never retry broadly over `IOException`/`Exception`. |
Comment on lines +239 to +248
### Writing reliable tests

New tests must not fail without a product bug. CI flakes in this repository came repeatedly from the patterns below; avoid them (full checklist: `.github/skills/code-review/references/testing-rules.md`):

- **No timing thresholds.** Don't assert that a build, install, or operation finished within N ms. Assert behavior instead, such as a skipped target or changed output.
- **No sleeps as synchronization.** Wait for an explicit condition (process exit, readiness property, unique log marker, `TaskCompletionSource`) with a generous deadline, and print diagnostics on timeout. Order concurrency and cancellation tests with gates, not delays.
- **Isolate every case.** Give each parameterized row its own directory, including all distinguishing parameters. Don't share caches, environment variables, the current directory, or fixed `%TEMP%` paths between tests.
- **Avoid crosstalk in process-wide runtime state.** Other tests, framework threads, and pending finalizers also change global reference counts, peer/object maps, GC counts, and thread-pool state. Don't assert exact process-wide deltas; establish a quiescent baseline, observe only objects the test owns (for example a specific handle or weak reference), and use `[NonParallelizable]` when global state can't be avoided.
- **Avoid the network.** Prefer small in-repo fixtures to third-party SDKs or large remote dependency graphs.
- **Assert on the current run only.** Delete old logs before each build, and scope logcat to the current run with a marker or a fresh dump.

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.

Since this is global instruction file, you might just have copilot do a pass to make it slightly shorter (and preserve meaning).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants