Skip to content

feat(deptrac): isolate Embeddable VO and remove transitive handler closure / изолировать Embeddable VO и убрать транзитивное замыкание handler'ов - #139

Merged
prikotov merged 14 commits into
masterfrom
task/deptrac-embeddable-layer
Nov 25, 2026
Merged

prikotov merged 14 commits into
masterfrom
task/deptrac-embeddable-layer

Conversation

@prikotov

@prikotov prikotov commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

TASK-feat-deptrac-embeddable-layer

⚠️ Известное ложное срабатывание (deptrac): CleanupErrorList — не класс, а @psalm-type = list<string>. Deptrac #1572 ловит его как DomainContract в TasK (1 violation). Это баг deptrac, а не этого PR; правило DomainTypeCatalogRule его правильно не флагает. После фикса deptrac violation уйдёт. Остальные — все истинные, разобраны по коду на трёх проектах.

Зачем

Embeddable VO (Domain\Entity\ValueObject\*Vo) — persistence-часть сущности, но в depfile попадали в общий слой DomainVo и были доступны Application/Presentation. В TasK утекли в 25+ файлов; сниффер ловит только свойства VO — нужен архитектурный gate.

Главная находка при реализации

Application: [+ApplicationCommandHandler]. В Deptrac 4 +Layer = транзитивное замыкание: весь Application-слой наследовал все зависимости handler'ов — Domain, DomainEnum, DomainVo, Presentation. Violation'ы на Application → Domain* не выдавались; ruleset для Application был пуст. Reproducer в TasK давал 0 (TasK#3221 — причину нашло это расследование).

Что сделано

Изменение Детали
Слой DomainEmbeddable Domain\Entity\ValueObject\…Vo; исключён из Domain/DomainVo; доступен Domain (сущность владеет), запрещён DomainVo, handler'ам, Application, Presentation
Слой DomainContract «всё остальное под Domain» (сервисы, репозитории, критерии, калькуляторы, хелперы, нормализаторы) — инверсия, а не перечисление каталогов; разрешён Application, handler'ам, Domain, Integration, Infrastructure
Слой DomainException доменные исключения; разрешён всем, кто работает с Domain, и DomainVo
Убран + у handler'ов правила Application прописаны явно (DTO/Enum/VO/Specification/Contract/Exception)
PolymorphismDependencyRule исключает implements/catch/параметры-команд из слоевых правил — полиморфизм, не coupling
DomainTypeCatalogRule замкнутый набор типов Domain: корень — только интерфейсы, ValueObject\ — суффикс Vo, ничего другого
DepfileRulesetSemanticsTest запускает реальный deptrac на фикстурах; 19 сценариев; красный на depfile из master

Проверено на 3 проектах (с подменой vendor-пакета, иначе правил нет в DI)

task-orchestrator stocks2 TasK
Baseline (v0.34.2) 0 0 0
С PR 0 14+2 63+3
Ложные известные — — 1 (psalm-тип, deptrac#1572)

Все остальные — истинные: Application-мапперы с сущностями (по конвенции разрешено), утечки Embeddable, new Command()+dispatch из сервиса, FieldNormalizer/CleanupErrorList (не из замкнутого набора типов).

BREAKING CHANGE

После обновления make deptrac у потребителей покажет ранее скрытые нарушения. Для TasK рефакторинг — отдельные задачи (TasK#3221 закрыть как устранённую причиной).

Refs: TASK-feat-deptrac-embeddable-layer

…osure / изолировать Embeddable VO и убрать транзитивное замыкание handler'ов

- New layer DomainEmbeddable (Domain\Entity\ValueObject\…Vo): a persistence part
  of entities, owned by Domain, forbidden for DomainVo, handlers, Application
  and Presentation. DomainVo no longer matches Entity\ValueObject.
- Removed `+` from Application: [+ApplicationCommandHandler]. In Deptrac 4
  `+Layer` is a transitive closure, so the whole Application layer silently
  inherited every dependency of the handlers (Domain, DomainEnum, DomainVo,
  Presentation) and no Application → Domain violation was ever reported.
- Application rules are now explicit: own DTO/Enum, Domain DTO/Enum/VO/
  Specification and the new DomainContract layer (interfaces of Domain
  services, repositories, strategies, providers) — but not Domain\Entity.
- DomainContract is granted wherever Domain was granted (Domain, handlers,
  Integration, Infrastructure…), denied to VO/DTO/Specification.
- DepfileRulesetSemanticsTest runs the real deptrac on generated fixtures
  (tempdir, own cache_file) and fails on the previous depfile.

On the consumer project TasK the gate used to report 0 violations; now 151,
all genuine: 82 direct Application → entity, 36 Embeddable leaks, 11 services
dispatching commands directly.

BREAKING CHANGE: consumers will see previously hidden deptrac violations
after updating.

Refs: TASK-feat-deptrac-embeddable-layer
…ксировать слой Embeddable и фикс транзитивного замыкания
…азать PR и перевести задачу в review
…n semantics test / ограничить DomainContract интерфейсами, уточнить типы в тесте семантики

DomainContract now collects only *Interface$ under Domain\Service, Repository,
Strategy, Provider, Criteria, Helper — implementations stay in the Domain layer,
as the existing regex tests expect. PHPStan max: narrow json_decode shapes
explicitly in DepfileRulesetSemanticsTest.

Refs: TASK-feat-deptrac-embeddable-layer
@prikotov
prikotov force-pushed the task/deptrac-embeddable-layer branch from 60896f9 to 1c0867d Compare November 25, 2026 06:58
…/ не давать Embeddable слоям Domain DTO и Specification

Review of the depfile found that the scripted "grant DomainEmbeddable wherever
Domain is granted" also hit value-type layers: DomainDto and
DomainSpecification could own Embeddable VO, contradicting the rule that
persistence parts stay behind entities. DomainEmbeddable is now granted only
to Domain (the owner), Infrastructure and Integration. InfrastructureDto and
DomainSpecification additionally receive DomainContract, so every layer that
sees Domain also sees its interfaces — DomainVo deliberately does not.

Regression test: Domain DTO and Specification holding an Embeddable fail.

Refs: TASK-feat-deptrac-embeddable-layer
…читать критерии поиска и доменные хелперы контрактами

Verified on the consumer project TasK: DomainContract collected only
*Interface, so repository find criteria (*FindCriteria) and Domain\Helper
classes stayed in the Domain layer and Application services creating them
were reported (15 false positives). DomainContract now collects everything
under Domain\{Service,Repository,Strategy,Provider,Criteria,Helper} except
*Model; entities stay in Domain. Consequently Domain service/strategy
implementations also land in DomainContract, where Embeddable is forbidden —
20 more genuine leaks surface (strategies and a usage cost service holding
Embeddable VO directly).

Regex test updated: Domain is asserted on an entity, contracts on an
interface and a criteria class. Semantics test gains criteria/entity cases.

Refs: TASK-feat-deptrac-embeddable-layer
…ировать слой Domain, добавить слой DomainException

Verified on two consumer projects (stocks2, TasK).

- Domain now means entities only: Domain\Entity\… except Embeddable. Every
  other domain type lives in a dedicated layer (DomainVo, DomainEnum,
  DomainDto, DomainSpecification, DomainContract, DomainException), so the
  collector is a single regex instead of seven must_not entries.
- DomainContract is "everything else under Domain" (service/repository
  interfaces and implementations, find criteria, calculators, helpers,
  normalizers, …) instead of a hand-picked directory list that missed
  stocks2's Domain\Calculator and Domain\*Normalizer.
- New DomainException layer: domain exceptions are thrown by entities,
  services and VO alike; granted wherever DomainContract is granted and to
  DomainVo. Previously, inverting the layers surfaced 95 false positives in
  TasK (VO/Entity/Service throwing domain exceptions).

Remaining violations are genuine: stocks2 166 (152 Application mappers taking
entities directly, 14 VO using root-level normalizers), TasK 151 (92 direct
entity use, 46 Embeddable leaks, 11 direct command/query dispatch, 2 VO →
service contract).

Refs: TASK-feat-deptrac-embeddable-layer
…ayer rules / исключить implements, catch и параметры-команды из слоевых правил

Verified on a third consumer project (task-orchestrator): two dependency
kinds are not coupling and produced false positives.

- INHERIT: a Value Object implementing a domain interface
  (StaticChainDefinitionVo implements ChainDefinitionInterface) fulfils the
  contract instead of calling it.
- CATCH: catching a domain exception is error handling.
- PARAMETER on ApplicationCommand/ApplicationQuery: a handler delegating to
  strategies that receive the command as data (task-orchestrator ADR 006) is
  composition inside Application, not dispatching. Only the parameter kind is
  exempt — `new Command()` / bus dispatch stays a violation (TasK: 11 genuine
  cases remain).

New InheritanceAndCatchDependencyRule subscribes to PostProcessEvent and
removes such violations from the result; registered in the shipped depfile
services. Unit-tested for removed/kept kinds.

Results: task-orchestrator 18 → 0, stocks2 166 and TasK 151 unchanged.

Refs: TASK-feat-deptrac-embeddable-layer
…test / сохранить проверяемость VO без суффикса, добавить тест покрытия Domain

Review asked whether replacing the explicit "Domain minus exceptions" list
with "Domain = entities only" weakened anything. Verified class-by-class on
7478 classes of three consumer projects: 1059 classes left the Domain layer
(990 → DomainContract, 66 → DomainException, 0 gained); transitive reachability
lost nothing for any layer — except three interfaces in Domain\ValueObject\
without the "Vo" suffix, which became uncovered (checked by no layer), because
DomainContract excluded the whole ValueObject directory. DomainContract now
excludes only *Vo (those belong to DomainVo); non-Vo value objects stay in
DomainContract and remain checked.

New data-provided test: every kind of domain type outside entities, referenced
from an Application DTO, must yield a violation and never "uncovered". Verified
to fail on the regression with exactly the two non-Vo probes.

Refs: TASK-feat-deptrac-embeddable-layer
… / разрешить Application использовать сущности Domain по конвенции

Review pointed out that Application mappers exist to map domain entities into
DTO — and the convention says exactly that: layers/application.md "Application
orchestrates domain services, repositories and entities", core-patterns/mapper.md
"accepts typed data (DTO/VO/Entity/Criteria)", dto.md "use case maps in/out of
domain models via Mapper". My previous ruleset forbade Application → Domain\Entity,
reporting 152 violations in stocks2 and 92 in TasK — all false positives.

Application is now granted the Domain layer (entities, contracts, DTO, enum,
VO, specification, exceptions). Embeddable stays behind entities and the
command/query dispatch from services stays forbidden. Semantics test inverted:
Application mapper taking a Model is clean; the handler entity case removed
as it encoded the same wrong rule.

After this: task-orchestrator 0, stocks2 166 → 14 (VO using root-level
normalizers), TasK 155 → 63 (Embeddable leaks, direct command dispatch).

Refs: TASK-feat-deptrac-embeddable-layer
…directories / добавить DomainTypeCatalogRule — закрытый набор каталогов типов Domain

The Domain convention defines a closed set of class types; a class fitting
none of them is a convention violation by definition and must be flagged,
not classified into a layer. Verified class-by-class on real FQCNs of the
three consumer projects:

- Domain\TransactionFieldNormalizer, Domain\DohodDividendFieldNormalizer
  (stocks2) — classes directly in the Domain namespace, which may contain
  only interfaces.
- Domain\ValueObject\CleanupErrorList (TasK) and
  Domain\ValueObject\...\*ProfileParametersInterface — in the ValueObject
  directory without the "Vo" suffix.
- Domain\Contract\…ExecutionStrategyInterface (task-orchestrator) — a
  project-specific directory that is not in the closed set and must be
  either renamed into a standard one or consciously added to the catalog.

The rule checks classes (not dependencies), as a twin of
MissingVoSuffixSniff, so it works in projects that do not run PHPCS.
Registered in the shipped depfile services. Unit-tested for the closed set
and the interface-only Domain root.

Refs: TASK-feat-deptrac-embeddable-layer
…реименовать и сократить до PolymorphismDependencyRule

The rule started as a patch and carried dead weight: the CATCH exemption never
fired, because domain exceptions live in the DomainException layer that is
granted wherever they are caught. Removed. Renamed to what it actually does:
exempt two kinds of polymorphism that a layer ruleset cannot express —
INHERIT (VO implements its own domain contract) and PARAMETER on
ApplicationCommand/ApplicationQuery (handler delegating to strategies that
receive the command as data). The docblock now states why each exemption is
not expressible by layers, instead of reading as a list of patches.

Refs: TASK-feat-deptrac-embeddable-layer
@prikotov
prikotov merged commit d0ad7de into master Nov 25, 2026
@prikotov
prikotov deleted the task/deptrac-embeddable-layer branch November 25, 2026 10:03
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