notes · · 6 min · updated 2026-10-27

Homebrew Under the Microscope: What 67 Remote AST Tools Found Inside the macOS Package Manager

Package-manager analysis for Homebrew by Max Howell and the maintainer team with prod-code: 371,069 lines across 2,379 Ruby files, Sorbet typing, and the FormulaInstaller bottle pipeline.

On this page · 6 sections
  1. Architecture Graph: Clean DAG Across Core Namespaces
  2. Sorbet Static Typing: Bringing Strong Contracts to Dynamic Ruby
  3. The Bottle Installation Engine: FormulaInstaller#install
  4. Clone Analysis and Subcommand Structure
  5. Text Searches: 12,415 expect( Lines and 2,173 raise Lines
  6. Remote AST Operations on Cluster Nodes

First published on 2026-10-04. The measurements reported in this article are historical and have not been re-run for this revision.

Created in 2009 by Max Howell and shepherded into an indispensable developer standard by Mike McQuaid and the Homebrew maintainer team, Homebrew powers software installation for millions of macOS and Linux workstations. What began as a lightweight Ruby DSL utilizing the operating system’s built-in tools has matured into a sophisticated distribution engine managing binary bottles, complex dependency graphs, sandboxed build environments, and graphical macOS applications (Homebrew Cask).

Behind the familiar brew install invocation lies a high-concurrency package manager responsible for cryptographic SHA-256 validation, bottle relocation inside binary Mach-O executables, prefix isolation (/opt/homebrew on Apple Silicon, /usr/local on Intel), and dynamic API-backed formula resolution.

To understand how Homebrew maintains stability across thousands of daily formula changes while migrating one of the world’s largest dynamic Ruby codebases to static typing, we deployed prod-code’s 67-tool AST suite against a checkout mirrored to a remote 32-core cluster node (node-b:9400).

$ git ls-files '*.rb' | wc -l
2379
$ git ls-files -z '*.rb' | xargs -0 wc -l | tail -n 1
371069 total
$ git ls-files | awk -F. '{if (NF>1) print $NF}' | sort | uniq -c | sort -nr | head -n 6
 2379 rb
  238 md
  138 json
  105 sh
   74 yml
   42 1

The captured inventory shows 371,069 lines of Ruby across 2,379 source files:

  • Core Library & Subcommands (Library/Homebrew/): 214,321 lines across 1,416 files. Package management engines, formula/cask loaders, bottle distributors, sandbox wrappers, and developer CLI commands (dev-cmd/).
  • RSpec Test Harnesses (Library/Homebrew/test/): 156,218 lines across 959 files. Comprehensive integration suites, bottle relocator tests, CLI spec runners, and formula verification fixtures.
  • Other Ruby source: The two named directories account for 2,375 files and 370,539 lines; the remaining four tracked Ruby files account for 530 lines. The extensionless launchers under bin/ are shell scripts and are not included in the Ruby totals.

Architecture Graph: Clean DAG Across Core Namespaces

Homebrew structures its package management logic into clear operational domains:

  1. Formula Engine (Library/Homebrew/formula.rb, formula_installer.rb): Manages build life cycles, bottle pouring, dependency topological sorting, and cellar link creation.
  2. Cask Subsystem (Library/Homebrew/cask/): Declarative DSL for macOS binary packages, handling disk image (.dmg) mounting, .pkg installer automation, quarantine attribute removal, and artifact staging.
  3. Bottle Distribution & Relocation (Library/Homebrew/bottle_prober.rb, extend/os/mac/keg_relocate.rb): Validates pre-compiled binary packages and relocates hardcoded prefix paths within Mach-O headers and dynamic linker tables (dyld).
  4. Hardware & Environment Detection (Library/Homebrew/hardware.rb, os.rb): Probes host architecture (ARM64 vs. x86_64), CPU instruction extensions (AVX2, Neon), macOS version targets, and SDK toolchains.

We ran prod-code dependencies across the monorepo:

$ prod-code dependencies --scope modules
⚡ prod-code Architecture & Dependency Graph Report
────────────────────────────────────────────────────
Scope: modules | Nodes: 284 | Dependencies: 22

✓ Zero circular dependencies detected. Architecture graph is a clean DAG.

Within the extracted graph, 22 dependencies among 284 nodes, no cycle was reported. A graph that sparse covers only a small part of the real require relationships, so it does not establish that the architecture as a whole is a strict DAG, or that low-level hardware probes and path abstractions never depend on CLI commands or installer pipelines.

Correction, 2026-10-27. As published on 2026-10-04, this paragraph said the architecture is organized as a strict Directed Acyclic Graph and that low-level hardware probes and path abstractions never depend on high-level CLI commands or installer pipelines. The report shown has 22 edges over 284 nodes; with most nodes unconnected, the absence of a reported cycle says nothing about the edges the extraction did not capture. Both architectural guarantees are withdrawn; the reported node, edge and cycle counts stand.

Sorbet Static Typing: Bringing Strong Contracts to Dynamic Ruby

One of Homebrew’s most notable architectural achievements is its transition to static typing with Stripe’s Sorbet. In a dynamic language ecosystem where type errors often only surface at runtime on user machines, Homebrew enforces type safety ahead of time.

The article reports 2,426 source files with Sorbet typing pragmas. That is more than the 2,379 tracked .rb files counted above, and how the 2,426 were counted is not recorded, so the two figures are not reconciled here:

  • # typed: strict: Requires explicit method signatures (sig { ... }) for every method, constant, and instance variable.
  • # typed: true: Enforces method call verification and type checking across all annotated callsites.

Methods declare unambiguous parameter and return types:

sig { params(output_warning: T::Boolean).returns(T::Boolean) }
def pour_bottle?(output_warning: false)
  return false if !formula.bottle_tag? && !formula.local_bottle_path
  return true  if force_bottle?
  return false if build_from_source? || build_bottle? || interactive?
  return false if @cc
  return false unless options.empty?
  # ...
end

Where signatures exist and are checked, Sorbet reports many nil and type mismatches before code reaches end-user machines. It does not eliminate those bug categories: T.untyped, T.unsafe and files at lower strictness levels are escape hatches that the Sorbet documentation describes.

The Bottle Installation Engine: FormulaInstaller#install

The mission-critical heart of Homebrew is FormulaInstaller (Library/Homebrew/formula_installer.rb, 1,965 lines). When a user installs a package, FormulaInstaller#install orchestrates a resilient sequence of sanity checks, dependency calculations, bottle pouring, and cellar linking:

sig { void }
def install
  lock

  start_time = Time.now
  unless pour_bottle?
    require "install"
    Homebrew::Install.perform_build_from_source_checks
  end

  check_conflicts

  raise UnbottledError, [formula] if !pour_bottle? && !DevelopmentTools.installed?

  unless ignore_deps?
    deps = compute_dependencies(use_cache: false)
    if ((pour_bottle? && !DevelopmentTools.installed?) || build_bottle?) &&
       (unbottled = unbottled_dependencies(deps)).presence
      raise UnbottledError, unbottled
    end

    install_dependencies(deps)
  end

  return if only_deps?

  if pour_bottle?
    begin
      pour
    rescue Exception
      Keg.new(formula.prefix).ignore_interrupts_and_uninstall! if formula.prefix.exist?
      raise
    else
      @poured_bottle = true
    end
  end

  unless @poured_bottle
    build
    Tab.clear_cache
    clean
  end

  build_bottle_postinstall if build_bottle?
  # ...
ensure
  unlock
end

Key reliability patterns embedded in this pipeline:

  • Flock-Based Mutex Locking: lock and unlock prevent concurrent brew processes from mutating the cellar or clobbering downloaded artifacts simultaneously.
  • Fail-Safe Cleanup Guards: If bottle extraction fails mid-pour, the exception handler immediately invokes Keg#ignore_interrupts_and_uninstall!, leaving no half-extracted binaries or corrupt symlinks in the cellar.
  • Atomic Tab Metadata: Build options, compiler versions, and runtime dependencies are serialized atomically into INSTALL_RECEIPT.json inside each installed keg, ensuring deterministic uninstalls and dependency tracking.

Correction, 2026-10-27. As published on 2026-10-04, this item named the receipt file tab.json. In Homebrew 4.6.0, for comparison (the article did not record its checkout), tab.rb sets the file name to INSTALL_RECEIPT.json and writes it with atomic_write. The file name is corrected; the description of its contents is kept as published.

Clone Analysis and Subcommand Structure

We executed prod-code duplicates to analyze structural repetition across Homebrew:

$ prod-code duplicates --min-lines 6 --max-groups 5
⚡ prod-code Clone & Duplication Harvester Report
────────────────────────────────────────────────────
Files Scanned: 2375 | Lines: 370966 | Clone Groups: 5 | Duplication: 1.1%

Discovered Clone Groups:

[Clone Group #1042] 6 lines | 48 occurrences (Type-1 (Exact Match))
  • Occurrence 1: Library/Homebrew/dev-cmd/audit.rb:1-6
  • Occurrence 2: Library/Homebrew/dev-cmd/bump.rb:1-6
  • Occurrence 3: Library/Homebrew/dev-cmd/bottle.rb:1-6
  • Occurrence 4: Library/Homebrew/dev-cmd/test.rb:1-6
  • Occurrence 5: Library/Homebrew/cmd/install.rb:1-6
  Preview:
    │ # typed: strict
    │ # frozen_string_literal: true
    │
    │ require "abstract_command"
    │
    │ module Homebrew

Across 370,966 scanned lines, structural duplication is remarkably low at 1.1%. As reported, the five groups correspond to subcommand headers and CLI option parser initialization blocks; one of them is shown above.

The shown clone report (capped at five groups by --max-groups 5) does not cover anything outside those groups, so it says nothing either way about duplication in core installation logic, formula validation rules or cask staging routines.

Correction, 2026-10-27. As published on 2026-10-04, this section said core installation logic, formula validation rules and cask staging routines exhibit virtually zero copy-paste duplication. The run shown was capped at five groups and does not examine those areas, so that claim is withdrawn; the reported 1.1% figure and the group shown stand as published.

Text Searches: 12,415 expect( Lines and 2,173 raise Lines

Two text searches give a rough size of Homebrew’s test expectations and error paths:

$ grep -rnE "expect\(" Library/Homebrew/test/ | wc -l
12415
$ grep -rnE "raise " Library/Homebrew/ | wc -l
2173

Both figures count matching lines, not calls: 12,415 lines under the test directory contain expect(, and 2,173 lines under Library/Homebrew/ (tests included) contain raise . The search does not tell typed raises from others; with error classes such as CannotInstallFormulaError, FormulaUnavailableError, UnbottledError and BottleMissingError, Homebrew guards against incompatible CPU architectures, broken binary relocation, conflicting keg symlinks, and corrupt bottle downloads.

Remote AST Operations on Cluster Nodes

To test AST refactoring on large Ruby files with Sorbet annotations, we evaluated prod-code extract-function on bottle tag matching logic in Library/Homebrew/utils/bottles.rb.

The article reports that the remote cluster node parsed the AST, isolated tag resolution expressions into a typed helper method, updated callsites, and re-verified Sorbet typing in 14 milliseconds with 0% local laptop CPU utilization. No command, selection, patch, Sorbet output or CPU measurement is shown, so the extraction, its timing and the CPU figure are author-reported and unverified; this is one of the few operations the article documents, not a result for every tool in the 67-tool suite named in the title.

Homebrew demonstrates how a massive, mission-critical systems tool written in Ruby can achieve enterprise-grade reliability and performance by pairing modular namespaces with Sorbet type checking and atomically written install receipts.

Editorial note, 2026-10-11: the host names, addresses and home-directory paths of our build nodes in this post were replaced with the placeholders node-a, node-b and <user>. No other part of the quoted output was changed.

Cite this article
Citation
Alexander Panasenko (2026-10-04). Homebrew Under the Microscope: What 67 Remote AST Tools Found Inside the macOS Package Manager. https://prod.codes/blog/homebrew-under-the-microscope-67-ast-tools/