Skip to content

Cut CI duration from 20 minutes to 6 - #44

Draft
apiology wants to merge 112 commits into
speed_up_specs_masterfrom
parallel_rspec_on_1237
Draft

apiology wants to merge 112 commits into
speed_up_specs_masterfrom
parallel_rspec_on_1237

Conversation

@apiology

@apiology apiology commented Aug 3, 2026 •

Copy link
Copy Markdown
Owner

Claude: This PR was written by Claude Code on behalf of @apiology.

Problem:

Every push waits about 20 minutes for CI:

                         checks  first start to last finish  check-minutes
master (20ee57644)           30                    20.3 min            263
this branch (100a9ffde)      19                     6.0 min             46

Each spec check runs the suite serially, and checks beyond the 20 that run at once queue behind the rest.

Solution:

Runs specs under parallel_rspec, caches gem yardocs keyed on Gemfile.lock, and trims the matrix to 19 checks that cover each Ruby and each supported rbs line once, so all run at once.

Parallel runs exposed four threading bugs in shipped code, each fixed here with a spec that failed before: a diagnoser thread that stopped for good after one file raised; a gem cache file another process could read half-written; one Prism::Translation::Parser shared across threads (castwide#1023); and Source#finalize marking a source finalized before parsing it, so renames could find nothing.

They also exposed a strict-level spec that passed only when an earlier spec had cached kramdown-parser-gfm; it now caches the gem itself.

Specs that uncache a gem (external_spec, library_spec) used to uncache backport from the cache every worker shares, so other workers saw it uncached; they now uncache rainbow and hashdiff, which no other spec reads, so library_spec and yardoc_spec no longer need --single. external_spec stays there with repo_spec: both delete and reinstall the external_bundled_gem fixture Gemfile.lock.

Stacked on castwide#1237.

Applies the exact diff CI's `.rubocop_todo.yml` job computed (Ruby 3.4,
rubocop 1.80.0) so the checked-in todo file matches the codebase's actual
current offense state.
Rebases castwide#1167 (apiology/parallel_rspec) onto
castwide/master instead of v0.59, since master and v0.59 have
diverged substantially and v0.59 carries unrelated changes. This
commit is the net diff of that branch (plus its merge-conflict and
CI-regression fixes) applied directly against master; history was
not preserved per request.

Highlights:
- Parallelize per-gem YARD/RBS pin caching with a thread pool
  (doc_map.rb, shell.rb) instead of caching gems serially.
- Fix a mutex re-entry deadlock in Library#sync_catalog when the
  next cacheable gemspec is already being processed elsewhere
  (castwide#1220), with its regression test.
- Fix an exponential-blowup bug in
  Pin::Method#combine_same_type_arity_signatures (O(n^2) bail-out
  for large signature sets), with its regression test.
- shell.rb's gems 'core' command called
  PinCache.core?/PinCache.cache_core, which never existed; use the
  real Solargraph::RbsMap::CoreMap#pins API instead.
- Bundler::LazySpecification#materialize_for_installation is an
  internal, undocumented Bundler API whose arity changed without a
  deprecation path; guard against all known shapes (modern wrapper,
  old zero-arg method, incompatible-arity method) instead of
  assuming one signature.
- Misc RuboCop/YARD-doc fixes and .rubocop_todo.yml updates.
Each of these explained a distinct class of intermittent CI failure
observed across this PR's rspec matrix/parallel_tests jobs, and will
only get more frequent as test parallelism increases.

- Diagnoser: an uncaught exception during a background diagnosis
  (e.g. a file/directory disappearing mid-diagnosis, such as
  protocol_spec's around-block temp dir cleanup racing the async
  diagnoser thread) killed the thread before it reached the line
  that marks it fully stopped, so Host#fully_stop hung for its full
  240-second timeout every time. Now rescues broadly around
  individual diagnoses and guarantees the fully_stopped flag is set
  via ensure regardless of how the thread's loop exits.
- MessageWorker: stop() never signaled its condition variable, so a
  thread blocked in tick's wait() with an empty queue could never
  wake up to notice stopped? and exit - a permanently leaked thread.
  Also added fully_stopped? tracking (matching Diagnoser) and wired
  it into Host#fully_stopped?, which previously didn't wait on
  MessageWorker's thread at all.
- PinCache#save wrote directly to the final cache path with no
  atomicity. Multiple parallel_tests workers (separate OS processes)
  racing to cache the same not-yet-warm gem for the first time could
  corrupt or truncate each other's writes on the shared cache
  directory. Now writes to a temp file and renames into place
  (atomic on the same filesystem).
- Yardoc.cache invoked a bare `yardoc` command, relying on it being
  found via shell PATH - which fails for unbundled
  environments/subprocesses where it only exists inside the current
  bundle's own bin directory. Now resolves the actual executable via
  Gem.bin_path, independent of PATH.
- rubocop_helpers_spec.rb's "custom version" test unconditionally
  removed the process-global RuboCop constant in its cleanup, even
  when its own version-swap had been a no-op (because something else
  in the process, e.g. protocol_spec.rb's top-level require, had
  already loaded the real gem first) - i.e. even when there was
  nothing to restore. That left RuboCop undefined for the rest of
  the process, cascading into failures in unrelated specs
  (library_spec, protocol_spec's formatting/environment handlers,
  rubocop_spec) whenever this spec happened to run first. Now only
  cleans up (and reloads the real version) when the swap actually
  took effect.

Local full-suite run: 13 failures -> 2, both isolated/self-contained
and already understood (rubocop_helpers_spec's version-swap doesn't
work when rubocop was already required by something else first, and
a pre-existing gem_pins_spec bug in this PR's own test content).
Yardoc.cache's "check cached, else build" was a classic
check-then-act race: two OS processes (e.g. two parallel_tests
workers, each caching the same not-yet-cached gem for the first
time) could both see "not cached" and run `yardoc --db path`
concurrently against the same .yardoc database directory,
corrupting or truncating each other's output. This is very likely
the actual cause of spec/pin/base_spec.rb's intermittent
"deals well with known closure combination issue" failure and the
strict_spec.rb Kramdown-constant failure in CI (both build/read a
gem's YARD pins via this path) - my earlier PinCache#save atomic-
write fix only covered Solargraph's own Marshal cache files, not
this separate tool-managed directory.

Wrap the build in a per-gem flock'd lock file, re-checking cached?
after acquiring the lock (double-checked locking) so only one
process actually builds a given gem; the rest wait for the lock and
then reuse what the first process built instead of racing.

This is the same mechanism a prior, incomplete attempt at this
(Yardoc.processing?, referenced from Library#diagnose but never
actually used to coordinate Yardoc.cache itself) was clearly reaching
for.
The two remaining intermittent failures (Kramdown constant in
strict_spec.rb, 0 pins in pin/base_spec.rb) were never a
cross-process caching race at all - reproduced deterministically
locally with a cold cache, in complete isolation, no concurrency
involved. My earlier PinCache atomicity and yardoc-locking fixes
were solving a real but different problem than this one.

Both tests called ApiMap#cache_gem(spec) for a gem before ever
telling the ApiMap's DocMap that gem was needed (via #catalog with
external_requires). DocMap#cache only builds pins for gemspecs in
its own uncached_yard_gemspecs/uncached_rbs_collection_gemspecs
lists, which are only populated from requires resolved during
#catalog - so cache_gem was silently a no-op, and building only
happened to succeed when something else had already warmed the
gem's cache earlier in the same process (hence "intermittent",
depending entirely on test/file run order and cache state, not
timing).

Fixed both to use the catalog -> cache_all_for_doc_map! -> catalog
sequence already used correctly elsewhere in this same PR (see
rbs_map/conversions_spec.rb's "with superclass pin for
Parser::AST::Node" context): catalog first so DocMap learns about
the dependency, cache_all_for_doc_map! to build it, catalog again to
reload the ApiMap's pin store with the now-cached pins.

Verified: both pass individually and together with ~/.cache/solargraph
completely cleared beforehand (previously guaranteed to fail cold, pass
only by accident once something else had warmed the cache). Full local
suite with a cold cache: 1625 examples, 2 failures - both isolated,
already-known, unrelated issues (rubocop_helpers_spec's version-swap
test doesn't work when rubocop was already required by something else
first, and a real RBS/YARD merge bug in gem_pins_spec.rb) - no other
instances of this cache-ordering bug found anywhere else in the suite.
protocol_spec.rb's around block chdirs into a per-example temp
directory and back, on the main thread, without holding
Solargraph::CHDIR_MUTEX - the same mutex that
Diagnostics::Rubocop#diagnose and the textDocument/formatting
handler already use specifically because RuboCop::Runner internally
chdirs (with a block) to read config files.

An earlier fix in this series made the background diagnoser thread
resilient to errors instead of dying on the first one (rescuing
broadly, guaranteeing fully_stopped? via ensure), so it now keeps
running background diagnoses - including RuboCop ones - for longer
during a test run. That made it far more likely to have an active
chdir in flight from that mutex right as protocol_spec's own
(unsynchronized) chdir ran, which Ruby raises as "conflicting chdir
during another chdir block" (visible in CI as a wave of Protocol
example failures, e.g. "handles textDocument/definition").

Route protocol_spec's chdir calls through the same
Solargraph::CHDIR_MUTEX so they can't overlap with RuboCop's.
An audit of the full diff against master (prompted by "are we dragging
in v0.59 changes that weren't intended?") found several small items
inherited from the original apiology/parallel_rspec branch history,
predating this session's rebase:

- Diagnostics::Base#diagnose and TypeCheck#diagnose gained a
  `workspace:` kwarg (commit "Spec performance fixes", a 33% local
  speedup) so TypeChecker.new could reuse an already-loaded Workspace
  instead of implicitly building a fresh one via
  Workspace.new(File.dirname(filename)) on every diagnose call. The
  kwarg was added but the one production call site,
  Library#diagnose (library.rb), was never updated to pass it, so the
  optimization was inert. Wire it through, and add the same kwarg to
  the other Diagnostics::Base subclasses (Rubocop, UpdateErrors,
  RequireNotFound) so the polymorphic call in Library#diagnose doesn't
  raise ArgumentError for reporters that don't use it.
- Remove RbsMap::StdlibMap.possible_stdlibs: added, never called.
- Remove duplicate/redundant YARD @PARAM comments added to
  ComplexType#qualify and .parse alongside the existing docs.
- Revert a no-op reordering of Workspace#gemfile?/gemspec?/gemspec_files
  back to their master position; both locations are public, so this
  wasn't a visibility change, just unexplained churn.

Left alone: a stray "@todo Missed nil violation" comment in
source/chain.rb, and RuboCop-autocorrect-driven formatting diffs
elsewhere in the branch (YARD/CollectionStyle, quote style) that
predate this rebase and are needed to keep Overcommit clean.
The Hash{Array(String, String) => ...} -> Hash{Array, String, String
=> ...} docstring reformatting in api_map/constants.rb,
api_map/store.rb, doc_map.rb, source_map.rb, and the quote/block-style
cleanup in spec/source/chain_spec.rb weren't related to this PR's
stated purpose (parallel specs, concurrency fixes) - they were fixing
YARD/CollectionStyle and Style/StringLiterals offenses that a fresh
`rubocop --auto-gen-config` surfaces under the currently-installed
RuboCop/rubocop-yard versions but that master's own committed
.rubocop_todo.yml doesn't yet grandfather (a pre-existing drift, not
something this branch introduced).

Revert those files to master's content and add a scoped
YARD/CollectionStyle todo exclusion for the same 4 files, so this
branch stays green without carrying the unrelated reformatting. The
actual fix now lives in a standalone PR:
#42.
Two follow-ups to the earlier extraction:

- The per-file YARD/CollectionStyle todo exclusion was a stand-in for
  actually fixing the cop. Replace it with disabling the cop outright
  in .rubocop.yml, matching castwide#1237's fix: for
  nested-generic/tuple Hash key types, the cop's own long-style
  autocorrect produces syntax that doesn't preserve the original
  tuple's meaning, so there's no safe autocorrected form to converge
  on for those cases.
- UniqueType#to_rbs's all_params.empty? nil-safety fix is an
  unrelated, pre-existing bug (from the original branch's own
  history, unrelated to parallel specs) - move it to
  #43.
Rebases this branch's net contribution onto apiology/speed_up_specs_master
(castwide#1237) instead of master directly, since both branches
independently fixed the same catalog-before-cache_gem gem-pin-caching
ordering bug and both added Diagnostics::Base#diagnose's workspace: kwarg.
Resolving those as one shared fix (favoring castwide#1237's implementation, already
under review upstream) instead of carrying two competing copies.

Conflict resolutions:
- ApiMap#resolve_require: kept castwide#1237's version (raises on a nil workspace,
  per its own review feedback) over this branch's safe-navigation version.
- spec/api_map_method_spec.rb, spec/pin/base_spec.rb: kept castwide#1237's
  structure/helpers (`let(:catalog)`, before-hook pattern) where it
  already covers the same ordering fix; kept this branch's
  cache_all_for_doc_map! call in pin/base_spec.rb since it exercises the
  parallel-caching path this PR is actually about.
- spec/rbs_map/conversions_spec.rb: kept castwide#1237's shared before(:all)
  ApiMap load across all examples in the file (faster than this
  branch's per-example ApiMap.new) - same test cases either way.
- spec/yard_map/mapper_spec.rb: kept castwide#1237's removal of a test whose
  description ("marks correct return type from RuboCop::Options.new")
  no longer matched its body (had been repointed at Open3.capture2e,
  already covered by spec/rbs_map/conversions_spec.rb).
- .github/workflows/rspec.yml: kept castwide#1237's pinned `bundler: 2.5.23`
  install step alongside this branch's `rake full_spec`/pre-caching
  additions.
apiology and others added 3 commits August 4, 2026 07:45
- Bump dev-dependency RuboCop from 1.80.0 to 1.89.0: 1.80.0 had a bug
  where per-file AllCops:Exclude entries didn't remove files from the
  scan target list, so spec/fixtures/invalid_{byte,utf8,node_comment}.rb
  (fixtures with intentionally invalid encoding, used to test
  Solargraph's own error handling) always failed Lint/Syntax regardless
  of Exclude config. 1.89.0 fixes this.
- Consolidate the three fixture exclude entries into one glob.
- Fix the todo-sync step: rubocop --auto-gen-config's exit code
  reflects the total offense count, not just new offenses, so under
  GitHub Actions' default bash -e it aborted before reaching the
  git-diff check that's meant to be the actual pass/fail signal.
- Remove continue-on-error from both rubocop_todo steps and
  regenerate .rubocop_todo.yml against 1.89.0.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018s7rWmpEoZpj4o3To7F286
The previously committed version was missing --no-offense-counts
(78 stray "# Offense count: N" comment lines), causing the
todo-sync check to fail: CI's fresh `bundle install` regeneration
diverged from the committed file even with identical gem versions
installed.
When rubocop is clean (the "Run RuboCop" step already passed), any diff
from regenerating .rubocop_todo.yml can only be a shrink -- offenses
that got fixed without removing their todo entry -- never a new
offense. On push to master, commit and push that cleanup automatically
instead of asking someone to do it by hand.

This can't apply to PRs: GITHUB_TOKEN can't push to a fork's branch,
and most PRs on this repo come from forks. PRs keep the existing
fail-with-diff behavior.
Drop the restated "master only" (already the step's if condition)
and the mechanics recap; keep only why a diff here is always safe
to auto-commit.
Yardoc.load! only reads the on-disk yardoc; it never builds one. The
example asserting that YARD namespaces conflicting with core constants
get adjusted relied on the before(:context) hook calling
ApiMap.load('.'), whose workspace load built pp's yardoc as a side
effect. That hook now constructs a bare ApiMap, so on a cold cache the
registry came back empty and the example failed with

  expected [] to include "RBS::Unnamed::ENVClass#pretty_print"

It passed on any machine whose Solargraph cache already held pp, which
is why it only showed up in CI.

Cache the gem explicitly, mirroring GemPins.build_yard_pins.
parallel_rspec starts four workers at once, and on a cold cache each
one generates the ast and parser gem pins independently. Measured
across five jobs on b5a52db, that is what dominates the suite:
rbs_map/conversions_spec took 17.31s in the undercover job, which
warms "core stdlib ast parser", against 241.68s in the rspec matrix
job and 256.16s in rails_specs, which warm only "core stdlib". The
rspec_specs job warms ast but not parser and sits between them at
161.6s, so parser is the expensive one.

Warm them in full_spec rather than in each workflow, so local runs
benefit too and the list stops being maintained separately in five
places. It costs about 1.5s once the cache is warm.
ParallelTests::RSpec::SummaryLogger and VerboseLogger each dump a
full RSpec summary to stdout on top of --format progress, so every
group printed its totals twice and parallel_tests doubled the numbers
it summed from them. The suite reported "3300 examples, 2 failures,
132 pendings" for what was really 1650 examples, 1 failure and 66
pendings, which made a single failing example look like two and hid
which group owned it.

Verified by bisecting the options file: with either formatter a
two-group run of 5 and 30 examples reports 70; with neither it
reports 35.

Comment both out alongside RuntimeLogger, each with the --out that
makes it usable, since their per-example output is worth having while
chasing a deadlock.
apiology and others added 5 commits October 28, 2026 10:34
After the master merge, strong typecheck reports both filter_map
markers in the full_spec task as "Unneeded @sg-ignore comment".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LTpguFhKz2V87XqntgzKGe
The todo check regenerates the file with the RuboCop version CI
resolves and fails on any difference, including the header line.
The worker loop checks stopped? outside the mutex. If #stop sets the
flag and signals between that check and tick taking the lock, the
signal reaches no waiter and tick then waits forever on an empty
queue, so the thread never exits and Host#fully_stop raises after 240
seconds. Skip the wait when the worker is already stopped.
CI logs at warn, so the raise is the only trace a hung Host#fully_stop
leaves, and it did not say whether the diagnoser, the message worker or
a library's gem caching kept fully_stopped? false. List them.
@apiology
apiology marked this pull request as draft October 29, 2026 03:32
Host#still_running had no spec reaching the branch that names a
library which is not fully stopped, so undercover flagged it.
The spec stubbed Open3.capture3 for the whole process and counted every
call. Libraries from earlier examples that never stop can keep caching
their own gems in the background; when one of their cache runs lands on
the stub after fully_stop, the count rises (seen in CI as expected 1,
got 2 or 3). Stub and count only the 'cache uncacheable' command and let
other calls run as they would.
CI now resolves RuboCop 1.92.2, and the .rubocop_todo.yml job fails
when the regenerated file differs; only the version line changed.
These examples catalog a library and never stop its host, so its gem
cache chain keeps running through later examples and spec files. With
an uncached gem simulated for every library, six cache threads were
still alive at the end of host_spec and 82 cache runs happened; with
each example stopping its host in an ensure, none were alive and 29
ran. Host#stop only blocks new cache runs, so no example waits out a
gem cache in progress.
The give-up specs stubbed Time.now to jump 241s, which rspec-time-guard
also reads, so it sometimes failed the example as taking 241.0s. A
timeout: keyword (default 240) lets the specs reach the deadline at
once without touching the clock.
The spec polled host.flush once a second for at most 10 seconds. Under
load the diagnoser takes longer to publish (12-20s seen at load average
15), so the example failed with an empty buffer. Host notifies its
observers each time it queues a message; wake on that until
publishDiagnostics arrives, bounded by the existing 60s timeout.
Host#stop stops the libraries that exist when it runs. A diagnoser tick
already in progress can still reach Dispatch#generic_library and build
the generic library afterwards; that library never gets @stopped, so
Library#fully_stopped? stays false and fully_stop raises after 240s
with 'library "" still running', as seen in rename_spec in CI. Stop
every library again on each fully_stop poll, and cover it with a spec
that holds the diagnoser inside Library.new until after stop.
Dispatch#generic_library memoized with a bare ||=, so the diagnoser and
a request thread could each build a library. The one whose assignment
lost dropped out of all_libraries, so Host#stop never stopped its gem
cache chain. Build it under a mutex; the new spec races two threads
through a slow Library.new and saw two libraries before this change.
Library#cacheable_specs no longer exists, so stubbing it kept nothing
from caching gems in the background. Library#stop does what those
stubs meant: no gem cache run starts after it.
@apiology
apiology marked this pull request as ready for review October 29, 2026 21:12
apiology and others added 7 commits October 30, 2026 06:11
process_until_changes re-ran Rename#process for up to 20 seconds
because a background thread could map the opened source mid-parse
(Source#finalize set @Finalized before parsing) or build a second
generic library, cataloging a one-pin SourceMap. 185efef and
f640621 close both races, and Library#references_from runs
sync_catalog itself, so a single process call returns the final
result. Measured on this branch: 0/50 lone runs of this file and 0/12
four-group CI-shaped runs with one call, against 4/100 lone-file
failures on castwide master 3c8d348 without those commits.

A retry loop cannot rescue a persistent bad catalog anyway: retries
re-attach the same source, which does not re-catalog, so CI run
41027052195 sat on {:changes=>{}} for the full 20 seconds. Fail on the
first call instead, printing the whole result.
castwide#1468 moved Convention::StructDefinition to
parser/parser_gem/node_processors. CI tests this PR on top of current
apiology/master, so the MethodLength exclusion must name the new path;
the BooleanSymbol and SlicingWithRange entries for the old node file
are no longer needed. Output of the CI --auto-gen-config command on
the pull/44/merge ref.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LTpguJaZ2sSbmHwzJUXWoJ
external_spec and library_spec uncache backport from the shared cache
directory, so another rspec process using the same cache finds it
uncached and fails. Run those examples against a temporary copy of the
cache instead, as #491 does on master.

yardoc_spec needs no such hook here: it already stubs yard_dir to a
temporary directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LTpguHxFEQL9KJ7MGedKby
With cache deletions confined to a private cache, library_spec and
yardoc_spec no longer destroy state other workers read. external_spec
stays in --single with repo_spec: both delete and reinstall the
external_bundled_gem fixture Gemfile.lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LTpguHxFEQL9KJ7MGedKby
castwide#1475, merged in through speed_up_specs_master,
added spec/language_server/progress_spec.rb with a named &block, which
the .rubocop.yml this branch enables flags. Regenerate .rubocop_todo.yml
to list it, keeping the RuboCop 1.92.2 header CI generates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LTpguHxFEQL9KJ7MGedKby
Library#mutex and Library#api_map memoized with a bare ||=. The
language server diagnoser thread and a request thread both reach them
first on a newly opened file, so each could build its own Mutex and
ApiMap. A local detector saw two of each for one library in at least
10 of 60 runs of the spec group CI runs before rename_spec.

A thread that finds nothing to catalog yet builds an uncataloged
ApiMap. If its assignment lands after the other thread cataloged its
own, the uncataloged one replaces it with @sync_count already 0, and
re-attaching the same source never recatalogs, so every rename returns
{:changes=>{}}. That fits rename_spec timing out after 20s on CI run
44205652648 with both earlier race fixes present.

Create the mutex in #initialize and build the ApiMap under its own
lock, not #mutex, which callers hold while calling #api_map.
@apiology
apiology marked this pull request as draft November 18, 2026 16:16
CI resolves RuboCop 1.92.3, so the generated header line differs from
the committed 1.92.2 one; no cop config changes.
Concurrent::Promises.zip(...).value! wraps several failures in
Concurrent::MultipleErrors, so CI crashes no longer showed the same
error the serial loop raised. Waiting on each future in order
re-raises the first gem's own exception.
The uncache specs deleted backport from the shared cache while other
workers were reading it, so External in those workers saw backport as
uncached. Point them at hashdiff and rainbow, which no other spec
reads, so all workers share one cache with no private copy.
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.

1 participant