Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

ArchUnit Guardrails

A small hexagonal Java service whose architecture is enforced by 16 executable rules, each one proven to fail on purpose.

The claim this repository demonstrates:

Architecture review is a checklist. A checklist can be executed. Once it is executed on every commit, it runs in about a second, it cannot be talked out of a violation, it gives the same verdict every time, and it never gets tired — which matters a great deal more now that a growing share of pull requests are written by agents that will never read your wiki.

mvn test                          # 16 architecture rules, 20 proofs that they bite, 1 brownfield demo
./scripts/verify-guardrails.sh    # injects a violation and asserts the build goes red
mvn -q compile exec:java          # runs the service: place an order, cancel it, print the events

Requirements: JDK 17+ and Maven. No database, no container, no network, no Spring context needed for the architecture tests.


1. Watch it catch something

scripts/verify-guardrails.sh writes a class into the production sources that breaks three rules, runs the build, and asserts the build fails. This is the real output, with package names trimmed:

==> injected src/main/java/com/example/shop/domain/service/LeakyDemoService.java
==> running the build, expecting it to fail

==> build exit code: 1

==> rules that rejected the change:

    ConventionRulesTest.noAmbientStateInInnerLayers
    LayerBoundaryRulesTest.domainMustNotDependOnOuterLayers
    LayerBoundaryRulesTest.layersAreRespected

==> what the rules said about LeakyDemoService:

    Constructor <...LeakyDemoService.<init>()> calls constructor <...InMemoryOrderRepositoryAdapter.<init>()>
    Field <...LeakyDemoService.repository> has type <...InMemoryOrderRepositoryAdapter>
    Method <...LeakyDemoService.find(...)> calls method <...InMemoryOrderRepositoryAdapter.findById(...)>
    Method <...LeakyDemoService.find(...)> calls method <java.time.Instant.now()>
    Method <...LeakyDemoService.find(...)> gets field <java.lang.System.out>

GUARDRAIL HELD: the injected violation was rejected and the file has been removed again.

Two things are worth noticing in that output.

It names the exact problem. Not "architecture violation in the domain layer", but this constructor, this field, this method call, with file and line numbers. Nothing has to be interpreted.

It is also the fix instruction. Every rule carries a because(...), which ArchUnit appends to the failure message:

Architecture Violation [Priority: MEDIUM] - Rule 'no classes that reside in a package '..domain..'
should depend on classes that reside in any package ['..application..', '..infrastructure..'],
because the domain is the part that has to outlive every framework, database and transport decision;
declare a port in ..domain.port.. and let infrastructure implement it' was violated (3 times):

An agent that reads that message knows what to do next. It does not need a human to explain it, and it does not need to be trusted to remember it.


2. Why this matters more in the age of agents

A review comment is a message; a rule is a constraint. "Please don't let the domain depend on Spring" is a one-time message that is forgotten by next week. The same sentence as a rule fails the build forever, on every branch, including the ones written at 3am by something that has never seen the original review.

Deterministic beats probabilistic where the property is statable. An LLM reviewing a diff might notice a leaked JPA entity. It might not. It will be more confident when it is wrong. ArchUnit reads bytecode: same input, same verdict, always. If a property can be stated exactly — the domain must not depend on infrastructure — there is no reason to check it with something that is guessing.

Agents are excellent at satisfying explicit constraints and blind to implicit ones. An agent asked to "make the payment flow work" will reach for Instant.now(), System.out.println and a repository inside a domain class, because each of those is locally reasonable and gets the tests green. The rule does not merely reject that code, it forces the better design into existence: the TimeProvider and IdGenerator ports in this repository exist because NO_AMBIENT_STATE_IN_INNER_LAYERS made the shortcut impossible. That is the real value — the guardrail does design work, not just policing.

Review bandwidth is the scarcest resource. If a reviewer has to check both behaviour and structure, they will do one properly and skim the other. Move the structural half into CI and review goes back to the thing only a human can judge: is this the right change at all?

The review checklist that is no longer the reviewer's job

Every one of these used to be a comment somebody had to remember to leave, on a diff they had to read carefully, at the end of a long day:

A reviewer used to have to notice… …now enforced by
a domain class that has started importing Spring INNER_LAYERS_MUST_BE_FRAMEWORK_FREE
a use case reaching past its ports into infrastructure LAYERS_ARE_RESPECTED
a JPA entity that has leaked into an API response PERSISTENCE_ENTITIES_ARE_NOT_PUBLIC_API
an Instant.now() that will make the class untestable NO_AMBIENT_STATE_IN_INNER_LAYERS
a value object that has quietly grown setters DOMAIN_MODEL_MUST_BE_IMMUTABLE
a new top-level package nobody agreed to EVERY_CLASS_LIVES_IN_A_KNOWN_LAYER
yet another @Autowired field NO_FIELD_INJECTION
a package cycle introduced by a convenient import NO_CYCLES_BETWEEN_PACKAGES

None of these need a human any more, and none of them can be missed on a busy day, a large diff or a branch written by an agent. What is left for the reviewer is the part no rule can check: whether this is the right change, in the right place, at the right time.

It is cheap and it does not flake. 16 rules, roughly a second, no containers, no network, no LLM calls, no external service to be down.

The rule file is the architecture document that cannot go stale. It is compiled, executed and enforced. If reality drifts from the document, the build fails.

The adoption problem, and the ratchet that solves it

The usual objection is "our codebase violates that rule in 400 places, we cannot switch it on". FrozenLegacyDebtTest demonstrates the answer: record today's violations, fail only on new ones, and burn the frozen debt down whenever someone touches that corner. The rules become a ratchet rather than a wall, which is the difference between a guardrail that gets adopted and one that gets deleted in week two.

What ArchUnit cannot do

Being honest about the limits is part of the argument:

  • It checks structure, not behaviour. It will not tell you that the pricing is wrong.
  • It cannot judge intent — whether an abstraction is in the right place, or whether a boundary is the right boundary. Someone still has to design the architecture.
  • A bad rule is worse than no rule: it is a fast way to make a bad design mandatory.
  • Rules work on compiled classes, so they see what the compiler sees, not what you meant.
  • A rule that has never been seen to fail is indistinguishable from a rule that does nothing. That is why half of this repository is proof that each rule bites.

3. The architecture under test

┌──────────────────────────────────────────────────────────────────────────┐
│ infrastructure - adapters, framework, I/O                                │
│   config/       ShopConfiguration (@Configuration, explicit @Bean)       │
│   persistence/  InMemoryOrderRepositoryAdapter (runs in the demo)        │
│                 JpaOrderRepositoryAdapter + JpaOrderEntity (@Entity)     │
│   payment/      FakePaymentGatewayAdapter                                │
│   time/ id/     SystemTimeProviderAdapter, UuidOrderIdGeneratorAdapter   │
│   event/        InMemoryEventPublisherAdapter                            │
│   bootstrap/    ShopApplication (main)                                   │
│                                                                          │
│   depends on application and domain                                      │
├──────────────────────────────────────────────────────────────────────────┤
│ application - use cases, no framework annotations at all                 │
│   command/      PlaceOrderCommand, CancelOrderCommand       (records)    │
│   service/      PlaceOrderService, CancelOrderService                    │
│   result/       OrderSummary                                (record)     │
│   error/        OrderNotFoundException                                   │
│                                                                          │
│   depends on domain                                                      │
├──────────────────────────────────────────────────────────────────────────┤
│ domain - pure Java, no framework, no infrastructure                      │
│   model/        Order, OrderLine, Money, OrderId, CustomerId, ...        │
│   event/        DomainEvent (sealed) + OrderPlaced, OrderCancelled       │
│   policy/       PricingPolicy, StandardPricing, VolumeDiscountPricing    │
│   port/         OrderRepository, PaymentGateway, TimeProvider,           │
│                 IdGenerator, EventPublisher                              │
│   service/      OrderPricingService                                      │
│                                                                          │
│   depends on nothing but java.*                                          │
└──────────────────────────────────────────────────────────────────────────┘

The compiler enforces none of that direction. Within a single Maven module, import com.example.shop.infrastructure.persistence.InMemoryOrderRepositoryAdapter; inside a domain class compiles perfectly happily. That is the gap ArchUnit fills, and it is exactly the gap an agent falls into.


4. The rule catalog

All 16 rules live in one file, ArchitectureRules.java, which is the single source of truth: the enforcement suites and the effectiveness proofs both consume the same rule objects, so a proof can never be about a different rule than the one that runs in CI.

Rule Fails when Why
LAYERS_ARE_RESPECTED domain → application/infrastructure, application → infrastructure dependencies point inwards only
DOMAIN_MUST_NOT_DEPEND_ON_OUTER_LAYERS a domain class references an outer layer the domain must outlive every framework decision
INNER_LAYERS_MUST_BE_FRAMEWORK_FREE domain/application import Spring, JPA or Hibernate must be constructible with new in a plain test
PERSISTENCE_ENTITIES_ARE_NOT_PUBLIC_API anything outside ..infrastructure.persistence.. touches an @Entity an entity is a database row, not a model
NO_CYCLES_BETWEEN_PACKAGES any cycle between any two packages two packages that need each other are one package
DOMAIN_MODEL_MUST_BE_IMMUTABLE non-final instance field or a setter in ..domain.model.. mutable domain objects cause heisenbugs
COMMANDS_MUST_BE_RECORDS a command that is not a record a command is a value that travels
DOMAIN_EVENTS_MUST_BE_RECORDS an event that is not a record a fact that already happened cannot be edited
PORTS_MUST_BE_INTERFACES a class in ..domain.port.. a port is a contract, not a partial implementation
PORT_IMPLEMENTATIONS_ARE_ADAPTERS implements a port but is not named *Adapter, or lives outside infrastructure the edge of the system is visible at a glance
APPLICATION_SERVICES_ARE_NAMED_SERVICES a class in ..application.service.. not named *Service findability
NO_FIELD_INJECTION @Autowired on a field hidden dependencies and invisible cycles
CONFIGURATION_LIVES_IN_INFRASTRUCTURE_CONFIG @Configuration anywhere else one place answers "what is wired to what"
JPA_ANNOTATIONS_LIVE_IN_PERSISTENCE @Entity/@Table anywhere else schema annotations belong with the database code
NO_AMBIENT_STATE_IN_INNER_LAYERS Instant.now(), UUID.randomUUID(), System.currentTimeMillis(), System.out in domain/application you cannot test a clock you do not control
EVERY_CLASS_LIVES_IN_A_KNOWN_LAYER a new top-level package appears a new package is a new architecture, so it must be deliberate

The rules are grouped into three suites: LayerBoundaryRulesTest, StructureRulesTest and ConventionRulesTest.

Half of the repository is proof

RulesAreEffectiveTest runs every rule against a deliberately broken class in com.example.shop.fixtures and asserts that the failure names the offending class:

@Test
void persistenceEntitiesAreNotPublicApiRejectsAnEntityInApplicationCode() {
    assertRejectedBy(ArchitectureRules.PERSISTENCE_ENTITIES_ARE_NOT_PUBLIC_API, EntityLeakingService.class);
}

assertRejectedBy also fails when a rule reports nothing, so a rule that has quietly stopped matching anything — a renamed package, a broken slice pattern, a predicate that never matched — cannot hide behind a green build. The fixtures are excluded from the enforcement suites by a package-based ImportOption, and two tests assert that the exclusion holds: one for the package filter on its own, one for the filter combined with the build tool's own test-classes filter.


5. Adding a rule

  1. Add the ArchRule to ArchitectureRules.java with a because(...) that reads like the fix instruction you would give in review.
  2. Wire it into the suite it belongs to (@ArchTest static final ArchRule …).
  3. Add a broken class under com.example.shop.fixtures.* that trips it.
  4. Add the proof to RulesAreEffectiveTest and run mvn test — the proof must fail first, otherwise you have written a rule that does not do anything.
  5. Add a row to the table above.

Step 4 is the one that gets skipped and the one that matters. If you want to see the whole loop, run ./scripts/verify-guardrails.sh.


6. Layout

src/main/java/com/example/shop/     domain, application, infrastructure (see the diagram above)
src/test/java/com/example/shop/
  architecture/                     the rules, the three enforcement suites, the proofs
    support/                        ImportOption and ViolationStore implementations
  fixtures/                         deliberately broken classes, excluded from enforcement
docs/why-architecture-tests.md      the longer argument, with the objections answered
scripts/verify-guardrails.sh        proves the guardrails can fail
AGENTS.md                           the contract an agent working in this repository must follow

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages