rails_tia 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +180 -0
  4. data/docs/configuration.md +109 -0
  5. data/docs/github-actions.md +147 -0
  6. data/exe/rails-tia +5 -0
  7. data/ext/rails_tia/allocated_classes.c +111 -0
  8. data/ext/rails_tia/extconf.rb +7 -0
  9. data/lib/rails_tia/action_view_support.rb +67 -0
  10. data/lib/rails_tia/audit.rb +42 -0
  11. data/lib/rails_tia/boot.rb +12 -0
  12. data/lib/rails_tia/ci/base.rb +38 -0
  13. data/lib/rails_tia/ci/git.rb +49 -0
  14. data/lib/rails_tia/ci/github_actions.rb +237 -0
  15. data/lib/rails_tia/ci/gitlab.rb +199 -0
  16. data/lib/rails_tia/ci.rb +36 -0
  17. data/lib/rails_tia/cli.rb +328 -0
  18. data/lib/rails_tia/configuration.rb +169 -0
  19. data/lib/rails_tia/constant_reads.rb +84 -0
  20. data/lib/rails_tia/context.rb +17 -0
  21. data/lib/rails_tia/coverage_collector.rb +198 -0
  22. data/lib/rails_tia/described_class_support.rb +75 -0
  23. data/lib/rails_tia/fallback.rb +79 -0
  24. data/lib/rails_tia/formatter.rb +88 -0
  25. data/lib/rails_tia/http.rb +89 -0
  26. data/lib/rails_tia/junit_report.rb +116 -0
  27. data/lib/rails_tia/map.rb +178 -0
  28. data/lib/rails_tia/metrics.rb +71 -0
  29. data/lib/rails_tia/minitest.rb +243 -0
  30. data/lib/rails_tia/native_extension.rb +6 -0
  31. data/lib/rails_tia/object_allocations.rb +23 -0
  32. data/lib/rails_tia/predictor.rb +61 -0
  33. data/lib/rails_tia/rails_support.rb +86 -0
  34. data/lib/rails_tia/run_report.rb +116 -0
  35. data/lib/rails_tia/static_mapping.rb +85 -0
  36. data/lib/rails_tia/templates/minitest.yml +39 -0
  37. data/lib/rails_tia/templates/rspec.yml +45 -0
  38. data/lib/rails_tia/version.rb +3 -0
  39. data/lib/rails_tia.rb +27 -0
  40. data/skills/rails-tia/SKILL.md +49 -0
  41. metadata +145 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 10132161455d6d51c81c32553b448f1546786ea9afc2ce14d20c6b292faabcc6
4
+ data.tar.gz: 38190ba394d09d28671779259cacd48e3fac8d27f5d24e91b440ce8662b434a4
5
+ SHA512:
6
+ metadata.gz: f2ad83d87e55b130a6ad24cc5e054554850d4bc58cc9a9a7ac8ea53cb1c0d5a8b23953856de984571e5347628de50f5e27da12bb40be04bd7304d45ec8118b7c
7
+ data.tar.gz: 68046db4176323093c3cbdf2511f6b126c19edb592f72417eac2339dda45b750bd4f2049389bb41ba7c1569a5c35c37ba54c94a04f445ddc893f8076b36755b7
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shinichi Maeshima
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # rails_tia
2
+
3
+ rails_tia uses coverage from a full RSpec or Minitest run on your default branch to map Rails project files to tests. For each pull or merge request, it selects tests that match the map or a naming rule, plus any changed test files.
4
+
5
+ > rails_tia is under active development. Its command-line interface and configuration options may change between releases.
6
+
7
+ ## Installation
8
+
9
+ Use Ruby 3.3 or later with Minitest or `rspec-core` (`~> 3.9`). Add rails_tia to your application's Gemfile.
10
+
11
+ ```ruby
12
+ gem 'rails_tia', group: :test
13
+ ```
14
+
15
+ Bundler installs Rubydex for constant tracking even when the collector is disabled. If a precompiled Rubydex gem is unavailable, its source build also requires a Rust toolchain. See the [Rubydex platform packages](https://rubygems.org/gems/rubydex/versions/0.4.4).
16
+
17
+ Installing the source gem requires make and, on CRuby, a C compiler. For a local path dependency, run `bundle install` and `bundle exec rake compile` in the gem checkout using the Ruby that generates the map.
18
+
19
+ Run these commands from the application root to install dependencies and generate `.rails_tia.yml`.
20
+
21
+ ```bash
22
+ bundle install
23
+ bundle exec rails-tia init
24
+ ```
25
+
26
+ `init` chooses Minitest when `test/` exists and `spec/` does not. Otherwise it chooses RSpec. Use `--runner minitest` or `--runner rspec` to choose explicitly.
27
+
28
+ ### AI agent skill
29
+
30
+ The gem includes a [rails-tia skill](skills/rails-tia/SKILL.md) for selecting tests, configuring map collection, and explaining selection results. From the application root, copy the skill into the project directory for your agent. Repeat the copy after upgrading the gem to pick up skill updates.
31
+
32
+ **Codex**
33
+
34
+ ```bash
35
+ mkdir -p .agents/skills
36
+ cp -R "$(bundle info rails_tia --path)/skills/rails-tia" .agents/skills/
37
+ ```
38
+
39
+ For example, ask “Use rails-tia to run the tests affected by my uncommitted changes.”
40
+
41
+ **Claude Code**
42
+
43
+ ```bash
44
+ mkdir -p .claude/skills
45
+ cp -R "$(bundle info rails_tia --path)/skills/rails-tia" .claude/skills/
46
+ ```
47
+
48
+ In Claude Code, enter `/rails-tia Run the tests affected by my uncommitted changes` to invoke the skill directly.
49
+
50
+ ## Configuration
51
+
52
+ Review the generated `.rails_tia.yml` for your application's layout. Use `full_run.paths` for changes that affect the whole suite and `static_mapping` for files you can match to tests by name. The [configuration reference](docs/configuration.md) covers every setting, its default, and the rules generated for each runner.
53
+
54
+ ## Generate a map
55
+
56
+ From the project root, run the full suite with an empty fragment directory (`tmp/rails_tia/fragments` by default). Load the collector before Rails and `bootsnap/setup` so it can start coverage and disable Bootsnap's compile cache. If you call `Bootsnap.setup` directly, pass `compile_cache_iseq: false` and `compile_cache_yaml: false` during collection.
57
+
58
+ ### RSpec
59
+
60
+ ```bash
61
+ bundle exec ruby -rrails_tia/boot -S rspec \
62
+ --require rails_tia/formatter --format RailsTia::Formatter
63
+ ```
64
+
65
+ To generate a SimpleCov report in the same run, put `require 'simplecov'` and `SimpleCov.start` in `spec/coverage_setup.rb` and pass `-r./spec/coverage_setup` before `-rrails_tia/boot`. If `rails_helper.rb` starts SimpleCov, move that setup into the shared file and use `require_relative 'coverage_setup'` in the helper. Keep ordinary line coverage enabled, with optional branch coverage. One-shot line coverage is unsupported.
66
+
67
+ ### Minitest
68
+
69
+ With the Minitest preset, pass `test/` to include system tests.
70
+
71
+ ```bash
72
+ bundle exec ruby -rrails_tia/minitest bin/rails test test/
73
+ ```
74
+
75
+ Map collection supports serial execution and Rails process workers. For thread-parallel suites, set `PARALLEL_WORKERS=1` during collection. Disable SimpleCov and any other tool that stops coverage before Minitest finishes. Tests using `ActiveSupport::Testing::Isolation` cause collection to fail.
76
+
77
+ ### Merge the fragments
78
+
79
+ After a successful run, gather the fragments from every node and process in `map.fragment_dir` and merge them into `tmp/rails_tia/map.json.gz` (the default `map.path`).
80
+
81
+ ```bash
82
+ bundle exec rails-tia map merge
83
+ ```
84
+
85
+ Fragment names use `CI_NODE_INDEX` and `TEST_ENV_NUMBER` when set. To customize paths, set `RAILS_TIA_FRAGMENT_PATH` per worker or pass `--fragments DIR` and `--output PATH` to `map merge`. A failed test or hook marks the map stale and triggers a full run at selection.
86
+
87
+ ## Select and run tests
88
+
89
+ `select` prints one path per line or nothing when no tests match. A missing or stale map, or a matching full-run rule, produces a single `full_run_token` (`spec` for RSpec, `test/` for the Minitest preset). This Bash script preserves paths with spaces, skips an empty selection, and propagates errors.
90
+
91
+ ```bash
92
+ #!/usr/bin/env bash
93
+ set -e
94
+ bundle exec rails-tia select > specs.txt
95
+ [ -s specs.txt ] || exit 0
96
+
97
+ specs=()
98
+ while IFS= read -r spec; do
99
+ specs+=("$spec")
100
+ done < specs.txt
101
+ bundle exec rspec "${specs[@]}"
102
+ ```
103
+
104
+ For Minitest, use `bundle exec ruby bin/rails test "${specs[@]}"` on the last line. If you customize `full_run_token`, use a value your runner accepts as one argument, or handle it in your script. Paths containing newlines are unsupported.
105
+
106
+ `select` sends its summary to standard error and writes metrics to `tmp/rails_tia/metrics.json` by default. Use `--metrics PATH` to change the output file or `--junit-dir DIR` to estimate time savings from JUnit timings.
107
+
108
+ ### Local Git and explicit changes
109
+
110
+ Outside GitLab, automatic adapter selection uses Git. The Git adapter cannot fetch maps, so generate one locally or copy a merged map to `map.path`. It compares `origin/master...HEAD` by default. Set `RAILS_TIA_DIFF_BASE` to use another base, such as `origin/main`. Fetch enough history to include the common ancestor.
111
+
112
+ To supply project-relative paths yourself, pass a newline-delimited file or use `-` for standard input.
113
+
114
+ ```bash
115
+ bundle exec rails-tia select --changed-files-from changed-files.txt
116
+ ```
117
+
118
+ ## CI integration
119
+
120
+ When using CI event data, the GitLab and GitHub Actions adapters select individual tests only for `merge_request_event` and `pull_request`, respectively. Other events trigger a full run.
121
+
122
+ ### GitLab CI
123
+
124
+ Store a personal, project, or group access token in the masked CI/CD variable `RAILS_TIA_GITLAB_TOKEN`. Make it available to merge request jobs. The adapter targets GitLab 17+ and requires `read_api` access to merge requests, pipelines, and job artifacts.
125
+
126
+ Configure the map pipeline in `.rails_tia.yml`.
127
+
128
+ ```yaml
129
+ ci:
130
+ adapter: gitlab
131
+ gitlab:
132
+ map_ref: main # Defaults to master.
133
+ map_pipeline_source: schedule
134
+ map_job_name: rspec-map
135
+ map_artifact_glob: tmp/rails_tia/fragments
136
+ ```
137
+
138
+ In the map job, run the full suite with coverage and publish the fragment directory from every worker. Use a single job or GitLab's numeric parallel jobs (e.g. `rspec-map 1/4`). If you customize fragment paths, update both the job artifacts and `map_artifact_glob`.
139
+
140
+ In merge request jobs, run `bundle exec rails-tia map fetch` before selection. It merges fragments from the latest successful matching pipeline. If no pipeline matches, selection runs the full suite. Incomplete jobs, invalid or stale fragments, and API or download errors fail the fetch and preserve the existing map. Stop the job if fetching fails.
141
+
142
+ ### GitHub Actions
143
+
144
+ Set `ci.adapter` to `github_actions` so pull request jobs can fetch the map published by your full-suite workflow. The [GitHub Actions guide](docs/github-actions.md) includes a complete RSpec workflow and a matrix example for parallel collection.
145
+
146
+ ## Audit and diagnostics
147
+
148
+ Periodically run the full suite on the same commit as a selection. Compare its JUnit results with the saved prediction to find failures the selection missed.
149
+
150
+ ```bash
151
+ bundle exec rails-tia audit --predicted specs.txt --junit tmp/junit
152
+ ```
153
+
154
+ Collect XML from every shard, including failed jobs, in a fresh directory. Each failing testcase needs a project-relative `file` attribute. Pass `--expect-junit FILE` once per expected XML file, relative to that directory, to detect missing shards. Audit exits with status 1 for a missed failure or invalid input.
155
+
156
+ Run `bundle exec rails-tia doctor` to check configuration, test discovery, map freshness, the CI adapter, and static mappings.
157
+
158
+ ### Run history
159
+
160
+ Set `RAILS_TIA_REPORT_DIR` (for example, `tmp/rails_tia/reports`) to record map generation timings, merge statistics, selection reasons, and audit results as JSON. Use a fresh directory per job outside `map.fragment_dir` and save it as a CI artifact or upload it to private storage, even when tests fail. The merge also saves the map under `maps/<map_id>.json.gz`.
161
+
162
+ To link an audit to its prediction, replace `--predicted specs.txt` with `--selection-report PATH`, using the `select-<report_id>.json` file from the commit under test.
163
+
164
+ ## Tracking and limitations
165
+
166
+ - **Ruby and ActiveRecord.** Line coverage records code exercised by the suite. Rails tracking adds model definitions observed through ActiveRecord. On CRuby, creating an object of a preloaded application class can also link the test to its definition, for example when a request instantiates a form with declarative validations. See the [allocation tracking settings](docs/configuration.md#dependency-tracking). Reads such as `Config::LIMIT` can link a test that executes the referencing method to the file defining the constant. RSpec also tracks definition files for each named `described_class` and its ancestors, even when an example executes no lines in those files. Reopened classes and unexecuted code can still need static rules.
167
+ - **Views.** ActionView records rendered templates, partials, and layouts inside the project. Fragment and collection caching can hide nested renders. Disable caching during collection or cover those views with static mappings or full-run paths. New and unrendered templates also need rules.
168
+ - **External dependencies.** Coverage cannot see dependencies on services or data files. Add project files that affect them to `full_run.paths`.
169
+
170
+ Rails tracking starts automatically when Rails is loaded. Disable individual trackers with `rails.active_record: false`, `rails.action_view: false`, or `described_class.enabled: false`.
171
+
172
+ ## Development
173
+
174
+ - [Design decisions and architecture](docs/design.md)
175
+ - [Rails test fixture](test_apps/rails_app/README.md)
176
+ - [Contributor guidelines](AGENTS.md)
177
+
178
+ ## License
179
+
180
+ [MIT](LICENSE.txt)
@@ -0,0 +1,109 @@
1
+ # Configuration reference
2
+
3
+ Run `bundle exec rails-tia init` from your application root to generate `.rails_tia.yml`. It chooses Minitest when `test/` exists and `spec/` does not, and RSpec otherwise. Use `--runner rspec` or `--runner minitest` to choose explicitly.
4
+
5
+ For a custom file, pass `--config PATH` to CLI commands and set `RAILS_TIA_CONFIG` to the same file during collection. Relative paths in the YAML resolve from the project root even when the configuration lives in a subdirectory. The project root defaults to the working directory. Use `--root PATH` to override it for CLI commands.
6
+
7
+ The defaults below apply when a key is omitted, including when there is no configuration file. The generated presets populate `full_run.paths` and `static_mapping`, and the Minitest preset also sets `spec_glob` and `full_run_token`. Both presets add the generated configuration file to the full-run paths when it is inside the project. See the [RSpec preset](../lib/rails_tia/templates/rspec.yml) and [Minitest preset](../lib/rails_tia/templates/minitest.yml) for the rules.
8
+
9
+ Dots in the tables indicate nested YAML keys. For example, configure `map.max_age_days` as follows.
10
+
11
+ ```yaml
12
+ map:
13
+ max_age_days: 7
14
+ ```
15
+
16
+ ## Test discovery and output
17
+
18
+ | Key | Default | Purpose |
19
+ | --- | --- | --- |
20
+ | `spec_glob` | `spec/**/*_spec.rb` | Project-relative glob for discovering test files and selecting changed tests directly. The Minitest preset uses `test/**/*_test.rb`. |
21
+ | `full_run_token` | `spec` | Single line printed by `select` for a full run. Use a value your runner accepts as one argument, or handle it in your selection script. The Minitest preset uses `test/`. |
22
+ | `metrics_path` | `tmp/rails_tia/metrics.json` | Destination for JSON selection metrics. Override for one run with `select --metrics PATH`. |
23
+
24
+ ## Dependency map
25
+
26
+ | Key | Default | Purpose |
27
+ | --- | --- | --- |
28
+ | `map.fragment_dir` | `tmp/rails_tia/fragments` | Directory where workers write fragments and `map merge` reads them. Start each collection with an empty directory. |
29
+ | `map.path` | `tmp/rails_tia/map.json.gz` | Merged map written by `map merge` or `map fetch` and read by `select`. |
30
+ | `map.max_age_days` | `3` | Maximum map age in days. A missing, empty, or stale map triggers a full run at selection. |
31
+
32
+ ## Full-run rules
33
+
34
+ Any matching rule makes `select` print `full_run_token`.
35
+
36
+ | Key | Default | Trigger |
37
+ | --- | --- | --- |
38
+ | `full_run.paths` | `[]` | A changed path matches any listed glob. Use project-relative paths such as `Gemfile.lock` or `config/**/*` for files at any depth under `config/`. |
39
+ | `full_run.max_changed_files` | `300` | The number of changed files exceeds this limit. Set to `null` to disable the limit. |
40
+ | `full_run.labels` | `[]` | Any listed string exactly matches a merge or pull request label. |
41
+ | `full_run.commit_message_tokens` | `[]` | The commit message contains any listed string, for example `'[run all tests]'`. |
42
+
43
+ ## Static mappings
44
+
45
+ `static_mapping` is a list of rules (default `[]`) for dependencies that coverage can miss, including new files. Each rule needs a `source` and at least one of `test` and `test_glob`. All three keys accept a string or a list of strings.
46
+
47
+ | Rule key | Meaning |
48
+ | --- | --- |
49
+ | `source` | A regular expression matching the entire project-relative changed path. A list combines its patterns as alternatives in one expression. Capture groups are numbered across the whole list. |
50
+ | `test` | A project-relative test path template. Each `%s` uses the next capture group in order. Use separate rules when different source patterns each supply a value for the same placeholder. |
51
+ | `test_glob` | A fixed project-relative glob. Matches must resolve to files inside the project. Absolute paths and `..` components are invalid. |
52
+
53
+ For example, append these rules to the generated `static_mapping` list to cover policy classes and browser code. If `app/policies/order_policy.rb` changes, the first rule selects `spec/authorization/order_spec.rb` when it exists. The second selects all existing system specs for a change under `frontend/`.
54
+
55
+ ```yaml
56
+ - source: 'app/policies/(.+)_policy\.rb'
57
+ test: 'spec/authorization/%s_spec.rb'
58
+ - source: 'frontend/.+'
59
+ test_glob: 'spec/system/**/*_spec.rb'
60
+ ```
61
+
62
+ ## Dependency tracking
63
+
64
+ These settings apply during map collection.
65
+
66
+ | Key | Default | Purpose |
67
+ | --- | --- | --- |
68
+ | `rails.enabled` | `auto` | Enable Rails tracking when Rails is loaded. Set to `true` to enable available integrations explicitly or `false` to disable all Rails trackers. |
69
+ | `rails.active_record` | `true` | Track project model definitions identified by ActiveRecord query and instantiation events. |
70
+ | `rails.action_view` | `true` | Track project templates, partials, and layouts rendered through ActionView. |
71
+ | `rails.object_allocations` | `auto` | Track allocations on CRuby when Rails support is enabled. Set to `false` to disable the process-wide hook or `true` to require the native extension. |
72
+ | `rails.constant_reads` | `true` | Resolve constant reads such as `Config::LIMIT` to project assignments using the existing line coverage. Applies when Rails tracking is enabled. |
73
+ | `rails.app_dirs` | `[]` | Additional project-relative directories for allocation and constant tracking alongside `app/` and `lib/`, for example `[components, engines/billing]`. |
74
+ | `described_class.enabled` | `true` | Track the definition files of an RSpec example's named `described_class` and its ancestors. Works independently of Rails. |
75
+
76
+ Regenerate the map to record allocation dependencies. Creating an ordinary Ruby object or Struct links its test file to the definitions of its named class and ancestors under the configured directories. This includes named ancestors of anonymous subclasses. Other collectors keep their own path rules.
77
+
78
+ Construction counts even if the test never uses the object. Shared mixins can have many consumers, and suite-hook allocations apply to every test. Background-thread allocations belong to the test or hook active at the time, so join asynchronous work before the test finishes. Reusing an instance created during boot or allocating other storage types such as Hash subclasses can leave dependencies unrecorded. Use static mappings for known consumers.
79
+
80
+ If the extension fails to load in auto mode on CRuby, map generation warns and marks the map stale for a full run. The legacy `rails.form_allocations` key is accepted with a deprecation warning when `rails.object_allocations` is omitted.
81
+
82
+ Constant tracking indexes Ruby files in the application directories and runnable test files matching `spec_glob`, Ruby helpers under `spec/support/` and `test/support/`, and the standard `spec_helper.rb`, `rails_helper.rb`, and `test_helper.rb` entry points when map collection starts. Only assignments inside application directories supply definition paths. For example, constants in `config/initializers/` are covered by the generated full-run rule for `config/**/*`. Add custom application directories through `rails.app_dirs`. A change to an indexed constant assignment can select a test that executed the referencing method, even when Rails preloaded the definition. A read outside a method uses file-level coverage. Regenerate the map after enabling tracking or changing the directories.
83
+
84
+ Attribution requires a line counter to advance. Calling a preloaded single-line method (including an endless definition) can leave its line counters unchanged and the consumer unmapped. A method can also execute without reaching every read in it. Rubydex resolves names using the indexed namespaces and ancestors, including constants inherited from a parent class. Dynamic lookups such as `const_get`, constants replaced at runtime, ancestors outside the index, and values copied into another constant during boot can still need static mappings. Class and module declarations, files added after collection starts, and syntax the parser cannot index are outside this collector’s scope. If loading Rubydex or constructing the index raises an error, collection warns and marks the fragment stale for a full run. Map worker reports include successful index construction time in `timings_seconds.constant_index`.
85
+
86
+ ## CI adapters
87
+
88
+ `ci.adapter` accepts `auto` (default), `gitlab`, `github_actions`, or `git`. Automatic selection uses GitLab in GitLab CI and falls back to Git in a Git checkout. Choose `github_actions` explicitly to fetch workflow artifacts. The Git adapter reads a locally generated or copied map.
89
+
90
+ ### GitLab
91
+
92
+ `map fetch` looks for the latest successful pipeline matching the configured ref and source. Set `RAILS_TIA_GITLAB_TOKEN` in CI as described in the [GitLab setup](../README.md#gitlab-ci).
93
+
94
+ | Key | Default | Purpose |
95
+ | --- | --- | --- |
96
+ | `ci.gitlab.map_ref` | `master` | Git ref that runs the map pipeline. Set to `main` for a pipeline on that branch. |
97
+ | `ci.gitlab.map_pipeline_source` | `schedule` | GitLab pipeline source used for map generation, for example `schedule` or `push`. |
98
+ | `ci.gitlab.map_job_name` | `null` | Job name required for fetching. For numeric parallel jobs such as `rspec-map 1/4`, use the base name `rspec-map`. |
99
+ | `ci.gitlab.map_artifact_glob` | `tmp/rails_tia/fragments` | Directory, glob, or file path inside each job artifact used to locate `.json` or `.json.gz` fragments. Match the paths actually archived by the job. |
100
+
101
+ ### GitHub Actions
102
+
103
+ `map fetch` looks for a successful workflow run on the PR target branch at the diff's baseline commit. See the [GitHub Actions guide](github-actions.md) for workflow and artifact setup.
104
+
105
+ | Key | Default | Purpose |
106
+ | --- | --- | --- |
107
+ | `ci.github_actions.map_workflow` | `null` | Workflow filename (for example, `rspec.yml`) or numeric ID. Required for fetching. |
108
+ | `ci.github_actions.map_event` | `push` | Event that produces the map. Use `push` or `schedule`. |
109
+ | `ci.github_actions.map_artifact_name` | `rails-tia-map` | Exact name of the artifact containing the single merged `.json` or `.json.gz` map. |
@@ -0,0 +1,147 @@
1
+ # GitHub Actions
2
+
3
+ Run the full suite on pushes to the target branch and publish its dependency map. Pull requests fetch the map for their exact diff baseline and use it to select tests. Enable the adapter in the application's `.rails_tia.yml`.
4
+
5
+ ```yaml
6
+ ci:
7
+ adapter: github_actions
8
+ github_actions:
9
+ map_workflow: rspec.yml
10
+ map_event: push
11
+ map_artifact_name: rails-tia-map
12
+ ```
13
+
14
+ ## RSpec workflow
15
+
16
+ Save this as `.github/workflows/rspec.yml`. Replace `main` with your target branch. The example uses the application's `.ruby-version`, the default map paths, and the RSpec preset. Include any database or service setup your suite requires.
17
+
18
+ ```yaml
19
+ name: RSpec
20
+
21
+ on:
22
+ push:
23
+ branches: [main]
24
+ pull_request:
25
+ types: [opened, synchronize, reopened, labeled, unlabeled]
26
+
27
+ permissions:
28
+ contents: read
29
+
30
+ jobs:
31
+ map:
32
+ if: github.event_name == 'push'
33
+ runs-on: ubuntu-latest
34
+ steps:
35
+ - uses: actions/checkout@v4
36
+ - uses: ruby/setup-ruby@v1
37
+ with:
38
+ bundler-cache: true
39
+ - name: Generate and merge the map
40
+ run: |
41
+ bundle exec ruby -rrails_tia/boot -S rspec \
42
+ --require rails_tia/formatter --format RailsTia::Formatter
43
+ bundle exec rails-tia map merge
44
+ - uses: actions/upload-artifact@v4
45
+ with:
46
+ name: rails-tia-map
47
+ path: tmp/rails_tia/map.json.gz
48
+ if-no-files-found: error
49
+ overwrite: true
50
+
51
+ selected:
52
+ if: github.event_name == 'pull_request'
53
+ runs-on: ubuntu-latest
54
+ permissions:
55
+ contents: read
56
+ actions: read
57
+ steps:
58
+ - uses: actions/checkout@v4
59
+ with:
60
+ fetch-depth: 2
61
+ persist-credentials: false
62
+ - uses: ruby/setup-ruby@v1
63
+ with:
64
+ bundler-cache: true
65
+ - name: Fetch the map
66
+ env:
67
+ GITHUB_TOKEN: ${{ github.token }}
68
+ run: bundle exec rails-tia map fetch
69
+ - name: Run selected specs
70
+ shell: bash
71
+ run: |
72
+ bundle exec rails-tia select > specs.txt
73
+ mapfile -t specs < specs.txt
74
+ if (( ${#specs[@]} )); then
75
+ bundle exec rspec "${specs[@]}"
76
+ fi
77
+ ```
78
+
79
+ The default PR checkout needs `fetch-depth: 2` to read the merge commit's parents. For an explicit PR head checkout, use `fetch-depth: 0` so Git can find the merge base. The `labeled` and `unlabeled` events refresh selection when a full-run label changes. For a Minitest application, use the [Minitest collection command](../README.md#minitest) and run the selected paths with `bundle exec ruby bin/rails test "${specs[@]}"`.
80
+
81
+ If no successful workflow run matches the baseline, or the map is missing, expired, or stale, selection requests the full suite. Authentication errors, other API errors, and invalid maps fail the fetch step. If you generate maps on a schedule, set `map_event: schedule`. Pull requests still need a map for their exact baseline to use selective execution.
82
+
83
+ ## Collect a map across a matrix
84
+
85
+ Replace the `map` job with the two jobs below under `jobs`. This example splits `spec/**/*_spec.rb` across two workers, with one RSpec process on each worker. Use your existing splitter if your suite uses a different file pattern. Give each job's fragment file and intermediate artifact a distinct name so all fragments reach the merge job. [GitHub artifact transfer example](https://github.com/actions/download-artifact/blob/v4/README.md#download-multiple-filtered-artifacts-to-the-same-directory)
86
+
87
+ ```yaml
88
+ map-shard:
89
+ if: github.event_name == 'push'
90
+ runs-on: ubuntu-latest
91
+ strategy:
92
+ matrix:
93
+ shard: [0, 1]
94
+ steps:
95
+ - uses: actions/checkout@v4
96
+ - uses: ruby/setup-ruby@v1
97
+ with:
98
+ bundler-cache: true
99
+ - name: Run this shard with coverage
100
+ shell: bash
101
+ env:
102
+ CI_NODE_INDEX: ${{ matrix.shard }}
103
+ SHARD_COUNT: ${{ strategy.job-total }}
104
+ run: |
105
+ shopt -s globstar nullglob
106
+ files=(spec/**/*_spec.rb)
107
+ specs=()
108
+ for ((i = CI_NODE_INDEX; i < ${#files[@]}; i += SHARD_COUNT)); do
109
+ specs+=("${files[i]}")
110
+ done
111
+ (( ${#specs[@]} )) || { echo "No spec files for shard $CI_NODE_INDEX" >&2; exit 1; }
112
+ bundle exec ruby -rrails_tia/boot -S rspec \
113
+ --require rails_tia/formatter --format RailsTia::Formatter "${specs[@]}"
114
+ - uses: actions/upload-artifact@v4
115
+ with:
116
+ name: rails-tia-fragments-${{ matrix.shard }}
117
+ path: tmp/rails_tia/fragments/map-${{ matrix.shard }}.json.gz
118
+ if-no-files-found: error
119
+ overwrite: true
120
+
121
+ map-merge:
122
+ needs: map-shard
123
+ runs-on: ubuntu-latest
124
+ steps:
125
+ - uses: actions/checkout@v4
126
+ - uses: ruby/setup-ruby@v1
127
+ with:
128
+ bundler-cache: true
129
+ - uses: actions/download-artifact@v4
130
+ with:
131
+ pattern: rails-tia-fragments-*
132
+ path: tmp/rails_tia/fragments
133
+ merge-multiple: true
134
+ - name: Merge both shards
135
+ run: |
136
+ test -s tmp/rails_tia/fragments/map-0.json.gz
137
+ test -s tmp/rails_tia/fragments/map-1.json.gz
138
+ bundle exec rails-tia map merge
139
+ - uses: actions/upload-artifact@v4
140
+ with:
141
+ name: rails-tia-map
142
+ path: tmp/rails_tia/map.json.gz
143
+ if-no-files-found: error
144
+ overwrite: true
145
+ ```
146
+
147
+ The merge job runs after every shard succeeds. If you change the shard count or run multiple processes per shard, update the expected fragment paths and upload all of them. Set a distinct `TEST_ENV_NUMBER` per process within each shard. Only the final artifact uses the configured `map_artifact_name` and contains a single merged map.
data/exe/rails-tia ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'rails_tia/cli'
4
+
5
+ exit RailsTia::Cli.start(ARGV)
@@ -0,0 +1,111 @@
1
+ #include <ruby.h>
2
+ #include <ruby/debug.h>
3
+ #include <ruby/st.h>
4
+
5
+ struct tracker {
6
+ st_table *classes;
7
+ VALUE last_class;
8
+ int enabled;
9
+ };
10
+
11
+ static int mark_class(st_data_t key, st_data_t value, st_data_t arg)
12
+ {
13
+ /* Identity keys in the native table must stay put during compaction. */
14
+ rb_gc_mark((VALUE)key);
15
+ return ST_CONTINUE;
16
+ }
17
+
18
+ static void mark_tracker(void *data)
19
+ {
20
+ struct tracker *tracker = data;
21
+ if (tracker->classes) st_foreach(tracker->classes, mark_class, 0);
22
+ }
23
+
24
+ static void free_tracker(void *data)
25
+ {
26
+ struct tracker *tracker = data;
27
+ if (tracker->classes) st_free_table(tracker->classes);
28
+ xfree(tracker);
29
+ }
30
+
31
+ static size_t tracker_size(const void *data)
32
+ {
33
+ const struct tracker *tracker = data;
34
+ return sizeof(*tracker) + (tracker->classes ? st_memsize(tracker->classes) : 0);
35
+ }
36
+
37
+ static const rb_data_type_t tracker_type = {
38
+ .wrap_struct_name = "RailsTia::AllocatedClasses",
39
+ .function = { .dmark = mark_tracker, .dfree = free_tracker, .dsize = tracker_size },
40
+ .flags = RUBY_TYPED_FREE_IMMEDIATELY
41
+ };
42
+
43
+ static VALUE allocate_tracker(VALUE klass)
44
+ {
45
+ struct tracker *tracker;
46
+ VALUE object = TypedData_Make_Struct(klass, struct tracker, &tracker_type, tracker);
47
+ tracker->classes = st_init_numtable();
48
+ return object;
49
+ }
50
+
51
+ static void record_allocation(VALUE self, const rb_trace_arg_t *event)
52
+ {
53
+ VALUE object = rb_tracearg_object((rb_trace_arg_t *)event);
54
+ if (!RB_TYPE_P(object, T_OBJECT) && !RB_TYPE_P(object, T_STRUCT)) return;
55
+
56
+ /* NEWOBJ runs during allocation: defer Ruby calls and path lookup until flush. */
57
+ VALUE klass = RBASIC_CLASS(object);
58
+ if (!RTEST(klass)) return;
59
+ struct tracker *tracker = RTYPEDDATA_DATA(self);
60
+ if (klass == tracker->last_class) return;
61
+ st_insert(tracker->classes, klass, 1);
62
+ tracker->last_class = klass;
63
+ }
64
+
65
+ static VALUE start(VALUE self)
66
+ {
67
+ struct tracker *tracker = RTYPEDDATA_DATA(self);
68
+ if (!tracker->enabled) {
69
+ rb_add_event_hook2((rb_event_hook_func_t)record_allocation,
70
+ RUBY_INTERNAL_EVENT_NEWOBJ, self,
71
+ RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
72
+ tracker->enabled = 1;
73
+ }
74
+ return self;
75
+ }
76
+
77
+ static VALUE stop(VALUE self)
78
+ {
79
+ struct tracker *tracker = RTYPEDDATA_DATA(self);
80
+ if (tracker->enabled) {
81
+ rb_remove_event_hook_with_data((rb_event_hook_func_t)record_allocation, self);
82
+ tracker->enabled = 0;
83
+ }
84
+ return self;
85
+ }
86
+
87
+ static int append_class(st_data_t key, st_data_t value, st_data_t array)
88
+ {
89
+ rb_ary_push((VALUE)array, (VALUE)key);
90
+ return ST_CONTINUE;
91
+ }
92
+
93
+ static VALUE drain(VALUE self)
94
+ {
95
+ struct tracker *tracker = RTYPEDDATA_DATA(self);
96
+ VALUE classes = rb_ary_new_capa(tracker->classes->num_entries);
97
+ st_foreach(tracker->classes, append_class, classes);
98
+ tracker->last_class = Qnil;
99
+ st_clear(tracker->classes);
100
+ return classes;
101
+ }
102
+
103
+ void Init_allocated_classes(void)
104
+ {
105
+ VALUE mod = rb_define_module("RailsTia");
106
+ VALUE klass = rb_define_class_under(mod, "AllocatedClasses", rb_cObject);
107
+ rb_define_alloc_func(klass, allocate_tracker);
108
+ rb_define_method(klass, "start", start, 0);
109
+ rb_define_method(klass, "stop", stop, 0);
110
+ rb_define_method(klass, "drain", drain, 0);
111
+ }
@@ -0,0 +1,7 @@
1
+ if RUBY_ENGINE == 'ruby'
2
+ require 'mkmf'
3
+ require_relative '../../lib/rails_tia/native_extension'
4
+ create_makefile(RailsTia::ALLOCATION_EXTENSION)
5
+ else
6
+ File.write('Makefile', "all install clean:\n\t@echo 'NEWOBJ tracking requires CRuby'\n")
7
+ end
@@ -0,0 +1,67 @@
1
+ require 'set'
2
+
3
+ module RailsTia
4
+ # Supplement coverage with files reported by each render, including compiled templates.
5
+ class ActionViewSupport
6
+ # The per-template event includes partial layouts; collection events also fire on cache hits.
7
+ EVENTS = %w[
8
+ render_template.action_view
9
+ render_partial.action_view
10
+ render_collection.action_view
11
+ render_layout.action_view
12
+ !render_template.action_view
13
+ ].freeze
14
+
15
+ def self.available?
16
+ defined?(::ActiveSupport::Notifications) ? true : false
17
+ end
18
+
19
+ def initialize(root:)
20
+ @root = "#{File.expand_path(root).delete_suffix('/')}/"
21
+ @real_root = "#{File.realpath(root).delete_suffix('/')}/"
22
+ @files = Set.new
23
+ @subscriptions = []
24
+ end
25
+
26
+ def subscribe
27
+ return self unless @subscriptions.empty?
28
+
29
+ EVENTS.each do |event|
30
+ @subscriptions << ::ActiveSupport::Notifications.subscribe(event) do |*, payload|
31
+ @files.merge(project_files(payload[:identifier]))
32
+ end
33
+ end
34
+ self
35
+ end
36
+
37
+ def unsubscribe
38
+ @subscriptions.each { |token| ::ActiveSupport::Notifications.unsubscribe(token) }
39
+ @subscriptions.clear
40
+ @files.clear
41
+ end
42
+
43
+ def flush
44
+ files = @files.to_a
45
+ @files.clear
46
+ files
47
+ end
48
+
49
+ private
50
+
51
+ def project_files(identifier)
52
+ # Layout payloads may be virtual names; only identifier contains a resolved path.
53
+ return [] unless identifier.is_a?(String) && File.absolute_path?(identifier)
54
+
55
+ path = File.expand_path(identifier)
56
+ return [] unless path.start_with?(@root) && File.file?(path)
57
+ real_path = File.realpath(path)
58
+ return [] unless real_path.start_with?(@real_root)
59
+
60
+ # Changes to either a symlink or its target must select this render's consumer.
61
+ [path.delete_prefix(@root), real_path.delete_prefix(@real_root)]
62
+ rescue ArgumentError, SystemCallError
63
+ # Inline/virtual templates, removed files and external engines are not project files.
64
+ []
65
+ end
66
+ end
67
+ end