Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,11 @@ rules = [
Positive dependency rules are allowlists: every selected dependency must match at least one target.
Negated dependency rules are blocklists: matching dependencies become violations.

Cycle projection uses iterative strongly-connected-component and elementary-cycle traversals, so
long dependency chains do not consume Ruby's call stack. It still enumerates all elementary cycles;
dense graphs can have exponentially many results. Scope cycle rules to meaningful components.
Cycle projection uses iterative traversals. By default, it enumerates all elementary cycles; dense
graphs can have exponentially many results. To report one reproducible closed path per cyclic group,
pass `CheckOptions.new(cycle_reporting: :witness)` to the check. Both modes decide whether the
entire selected file graph is acyclic; the witness list is not a count of all paths.
`CycleViolation#witness?` distinguishes a witness from an exhaustive result.

<a id="layer-rules"></a>

Expand Down Expand Up @@ -421,6 +423,9 @@ format option applies to init/check/explain and errors; help/version remain plai
`--format json` produces one document with `schema_version: 1`, `archunit_version`, `command`,
`project_root`, `config_path`, `dependency_analysis`, `rails_imports`, `load_paths`, `source_exclusions`,
`status`, `rules`, `analysis`, and `summary`. The new settings/diagnostics are additive schema-1 fields.
With `check --cycle-reporting witness`, the report adds `cycle_reporting: "witness"` at the top
level and on each witness violation. The default (`exhaustive`) omits these fields. The summary
counts reported violations, not all possible cycles. Witness mode cannot generate or use a baseline.
Rule entries carry `name`, nullable `rationale`, `status`, `analysis`, and `violations`;
each violation carries its `type`,
shared formatter `message`, and `details`. Summary counts describe completed/listed rules and their
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
and excluded-tree workloads; retain generous CI timing ceilings.
- Explain potentially misleading imports-only Rails preset passes in CLI text and JSON when no
imports connect the selected files. Default rules, baselines and exit codes are unchanged.
- Add opt-in file cycle witnesses: one concrete path per cyclic group without enumerating all
paths. Exhaustive output stays the default and is required for path-based baselines.

## 1.1.0 - 2026-11-23

Expand Down
6 changes: 6 additions & 0 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,12 @@ records the decision and probes. Graph queries are available, but semantic CLI t

PlantUML support is a small component-diagram subset. `.archignore` does not support negation or
nested ignore files. Dense graphs can have exponentially many cycles despite iterative traversal.

For file cycle rules, `bundle exec archunit check --cycle-reporting witness` or
`ArchUnit::CheckOptions.new(cycle_reporting: :witness)` shows one concrete cycle per cyclic group.
The whole selected graph is checked; a shorter report cannot turn a cycle into a pass. Self-edges,
external imports and dependencies outside the file selection are treated as in the default mode.
Use the default exhaustive mode for path-based baselines and when you need every cycle path.
No-target-execution is not an OS sandbox against a hostile, concurrently changing filesystem.

For reproducible Linux/Windows timing, startup, memory and changed-source evidence, see the
Expand Down
18 changes: 18 additions & 0 deletions benchmark/study/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,21 @@ bundle exec ruby real_project.rb /path/to/pinned-sparse-discourse ../../pkg/disc
The root RSpec study test is candidate-only, with four pairs and one trial, no native comparator
or startup workers. The comparator is optional research tooling. Failed installation/controls are
study failures, never measured zeroes or evidence of superiority.

## Bounded file cycle reporting

From the repository root, run `bundle exec ruby benchmark/study/cycle_witnesses.rb`. Each fixture
contains every forward edge and one closing edge, so there are exactly `2**(vertices - 2)` simple
cycles. The script checks this count and the deterministic witness path. It compares the two
projection/reporting modes only, excluding discovery, parsing, and serialization. Three alternating
runs per mode; medians below from Ruby 4.0.6 on Windows. These are observations, not CI timing gates.

| Vertices | Exhaustive → witness paths | Median time (ms) | Allocated Ruby objects |
| ---: | ---: | ---: | ---: |
| 10 | 256 → 1 | 2.47 → 0.40 | 7,944 → 927 |
| 14 | 4,096 → 1 | 46.96 → 0.61 | 128,866 → 1,745 |
| 18 | 65,536 → 1 | 1,710.71 → 0.86 | 2,296,780 → 2,835 |

In the last case the exhaustive paths contain 655,360 edge entries versus three in the witness.
Witness mode classifies all components; it bounds report size to one path per cyclic component,
not a fixed number of paths across the project.
70 changes: 70 additions & 0 deletions benchmark/study/cycle_witnesses.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# frozen_string_literal: true

require 'archunit'
require 'json'

# Small, fixed graphs with an independently known exponential number of simple cycles.
module CycleWitnessStudy
PROJECTION = ArchUnit::Common::Projection
private_constant :PROJECTION

module_function

def run
cases = [10, 14, 18].map { |size| measure(size) }
puts JSON.pretty_generate(ruby: RUBY_DESCRIPTION, runs_per_mode: 3, cases:)
end

def measure(size)
labels = (0...size).map { |index| format('file-%02d.rb', index) }
graph = fixture(labels)
samples = collect(graph, labels)
{ vertices: size, edges: graph.length, modes: samples.transform_values { |rows| median(rows) } }
end

def collect(graph, labels)
counts = { exhaustive: 2**(labels.length - 2), witness: 1 }
samples = { exhaustive: [], witness: [] }
3.times do |iteration|
order = iteration.odd? ? counts.keys.reverse : counts.keys
order.each { |mode| samples.fetch(mode) << sample(graph, labels, mode, counts.fetch(mode)) }
end
samples
end

def fixture(labels)
pairs = labels.combination(2).to_a << [labels.last, labels.first]
raw = pairs.map { |source, target| ArchUnit::Edge.new(source:, target:, external: false) }
PROJECTION.project_edges(raw, PROJECTION.per_internal_edge)
end

def sample(graph, labels, mode, count)
GC.start
allocations = GC.stat(:total_allocated_objects)
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
cycles = project(graph, mode)
seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
allocated = GC.stat(:total_allocated_objects) - allocations
validate(cycles, labels, mode, count)
{ milliseconds: (seconds * 1000).round(3), allocations: allocated,
reported_paths: cycles.length, reported_edge_steps: cycles.sum(&:length) }
end

def project(graph, mode)
mode == :witness ? PROJECTION.project_cycle_witnesses(graph) : PROJECTION.project_cycles(graph)
end

def validate(cycles, labels, mode, count)
abort "wrong count for #{mode}" unless cycles.length == count
return unless mode == :witness

path = cycles.fetch(0).map(&:source_label)
abort 'wrong path for witness' unless path == [labels[0], labels[1], labels.last]
end

def median(rows)
rows.first.keys.to_h { |key| [key, rows.map { |row| row.fetch(key) }.sort.fetch(1)] }
end
end

CycleWitnessStudy.run
4 changes: 4 additions & 0 deletions lib/archunit/cli/baseline_identity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ def self.filter(value)
end

def self.cycle(value)
if value.witness?
raise ArgumentError, 'cycle witness reporting is incompatible with baselines'
end

edges = value.cycle.map { |item| edge(item) }
return unless edges.map(&:first).uniq.length == edges.length

Expand Down
33 changes: 33 additions & 0 deletions lib/archunit/cli/cycle_reporting_options.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# frozen_string_literal: true

module ArchUnit
module CLI
# Parsing and preflight validation for the file cycle report policy.
# @api private
module CycleReportingOptions
def cycle_reporting
@cycle_reporting || 'exhaustive'
end

private

def cycle_reporting_option(options)
options.on('--cycle-reporting MODE', %w[exhaustive witness],
'File cycles: exhaustive (default) or one witness per cyclic group') do |value|
@cycle_reporting = value
end
end

def validate_cycle_reporting
return if cycle_reporting != 'witness' || %w[help version].include?(command)

if baseline_path || command == 'baseline'
raise ArgumentError, 'cycle witness reporting is incompatible with baselines'
end
return if command == 'check'

raise ArgumentError, '--cycle-reporting witness is only valid for check'
end
end
end
end
4 changes: 4 additions & 0 deletions lib/archunit/cli/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
require 'optparse'
require_relative '../common/extraction/source_exclusions'
require_relative 'baseline_options'
require_relative 'cycle_reporting_options'

module ArchUnit
module CLI
# Internal command parsing; does not discover or execute project code.
# @api private
class Options
include BaselineOptions
include CycleReportingOptions

attr_reader :command, :project_root, :config_path, :format, :dependency_analysis, :parser,
:rails_imports, :rails_associations, :load_paths, :source_exclusions
Expand Down Expand Up @@ -46,6 +48,7 @@ def parse!

def validate_arguments
validate_baseline_options
validate_cycle_reporting
unless @arguments.empty?
raise OptionParser::InvalidArgument, "unexpected arguments: #{@arguments.join(' ')}"
end
Expand All @@ -66,6 +69,7 @@ def build_parser
load_path_option(options)
source_exclusion_option(options)
baseline_options(options)
cycle_reporting_option(options)
output_options(options)
end
end
Expand Down
14 changes: 13 additions & 1 deletion lib/archunit/cli/report.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def initialize(options)
status: 'error', rules: [], analysis: AnalysisReport.new.to_h
}
@payload[:rails_associations] = true if options.rails_associations
@payload[:cycle_reporting] = 'witness' if options.cycle_reporting == 'witness'
end

def add_rule(rule, violations: nil, analysis: nil)
Expand Down Expand Up @@ -83,7 +84,13 @@ def rule_status(violations)

def violation_payload(violation)
formatted = Testing::ViolationFactory.from_violation(violation)
{ type: violation.class.name, message: formatted.message, details: formatted.details }
result = {
type: violation.class.name, message: formatted.message, details: formatted.details
}
if violation.is_a?(Files::Assertion::CycleViolation) && violation.witness?
result[:cycle_reporting] = 'witness'
end
result
end

def write_text(out)
Expand All @@ -101,6 +108,7 @@ def write_header(out)
end

def write_notice(out)
write_cycle_notice(out) if payload[:cycle_reporting] == 'witness'
out.puts('Rails require_dependency imports: enabled') if payload[:rails_imports]
out.puts('Rails explicit association class names: enabled') if payload[:rails_associations]
case payload[:status]
Expand All @@ -111,6 +119,10 @@ def write_notice(out)
end
end

def write_cycle_notice(out)
out.puts('Cycle reporting: one witness per cyclic group, not all cycle paths.')
end

def write_rule(rule, out)
out.puts("[#{rule[:status]}] #{rule[:name]}")
out.puts(" Because: #{rule[:rationale]}") if rule[:rationale]
Expand Down
4 changes: 2 additions & 2 deletions lib/archunit/cli/runner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ def check(rules)
options = Common::FluentApi::CheckOptions.new(
dependency_analysis: @options.dependency_analysis.to_sym,
rails_imports: @options.rails_imports, rails_associations: @options.rails_associations,
load_paths: @options.load_paths,
source_exclusions: @options.source_exclusions
load_paths: @options.load_paths, source_exclusions: @options.source_exclusions,
cycle_reporting: @options.cycle_reporting.to_sym
)
check_rules(rules, options)
BaselineRun.new(@options).finish(@report, @evaluations)
Expand Down
18 changes: 13 additions & 5 deletions lib/archunit/common/fluentapi/check_options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module FluentApi
# Immutable options shared by every terminal rule check.
CheckOptions = Data.define(
:allow_empty_tests, :logging, :clear_cache, :load_paths, :dependency_analysis,
:rails_imports, :source_exclusions, :rails_associations
:rails_imports, :source_exclusions, :rails_associations, :cycle_reporting
) do
# Normalizes nil or an existing options value for terminal execution.
# @param value [CheckOptions, nil]
Expand All @@ -29,20 +29,19 @@ def self.resolve(value)
# @param rails_imports [Boolean] opt into static Rails require_dependency syntax
# @param rails_associations [Boolean] opt into explicit Rails association class names
# @param source_exclusions [Array<String>] additional project-relative source globs
# @param cycle_reporting [Symbol] :exhaustive or one :witness per cyclic component
def initialize( # rubocop:disable Metrics/ParameterLists
allow_empty_tests: false, logging: nil, clear_cache: false, load_paths: [],
dependency_analysis: :imports, rails_imports: false, source_exclusions: [],
rails_associations: false
rails_associations: false, cycle_reporting: :exhaustive
)
validate_boolean(allow_empty_tests, :allow_empty_tests)
validate_logging(logging)
validate_boolean(clear_cache, :clear_cache)
validate_rails_options(rails_imports, rails_associations)
load_paths = immutable_load_paths(load_paths)
source_exclusions = Common::Extraction::SourceExclusions.normalize(source_exclusions)
unless %i[imports imports_and_constants].include?(dependency_analysis)
raise ArgumentError, 'dependency_analysis must be :imports or :imports_and_constants'
end
validate_modes(dependency_analysis, cycle_reporting)

super
end
Expand Down Expand Up @@ -71,6 +70,15 @@ def rails_associations?

private

def validate_modes(dependency_analysis, cycle_reporting)
unless %i[imports imports_and_constants].include?(dependency_analysis)
raise ArgumentError, 'dependency_analysis must be :imports or :imports_and_constants'
end
return if %i[exhaustive witness].include?(cycle_reporting)

raise ArgumentError, 'cycle_reporting must be :exhaustive or :witness'
end

def validate_rails_options(imports, associations)
validate_boolean(imports, :rails_imports)
validate_boolean(associations, :rails_associations)
Expand Down
70 changes: 70 additions & 0 deletions lib/archunit/common/projection/cycles/cycle_witnesses.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# frozen_string_literal: true

require_relative 'tarjan_scc'

module ArchUnit
module Common
module Projection
module Cycles
# Finds one reproducible non-self cycle in each cyclic component, without enumeration.
class CycleWitnesses
def self.call(adjacency)
new(adjacency).call
end

def initialize(adjacency)
@adjacency = adjacency.transform_values(&:sort)
end

def call
TarjanScc.call(@adjacency).select { |component| component.length > 1 }
.sort_by(&:first).map { |component| witness(component) }.freeze
end

private

def witness(component)
start = component.first
members = component.to_set
next_vertex = @adjacency.fetch(start).find do |target|
target != start && members.include?(target)
end
parents = search(next_vertex, start, members)
restore_path(start, parents)
end

def search(first, start, members)
queue = [first]
parents = { first => nil }
queue.each do |current|
break if current == start

enqueue_neighbours(current, parents, queue, members)
end
parents
end

def enqueue_neighbours(current, parents, queue, members)
@adjacency.fetch(current).each do |neighbour|
next if parents.key?(neighbour) || !members.include?(neighbour)

parents[neighbour] = current
queue << neighbour
end
end

def restore_path(start, parents)
path = []
current = start
until current.nil?
path << current
current = parents.fetch(current)
end
# Shared cycle projection attaches the closing edge itself.
[start, *path.drop(1).reverse].freeze
end
end
end
end
end
end
Loading