Files
clean-architecture-backend-…/src/application-core/CLAUDE.md
T
DongHyeonka 1443510638 fix(idempotency)!: 이미 적용된 전이는 그 전이를 적용한 핸들에게만 확인한다
문제: 이미 적용된 전이를 다시 보낸 호출에 Redis·PostgreSQL 저장소와
in-memory fake가 다르게 답한다.
- 같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete를 다시
  보내면 Redis·PostgreSQL은 ALREADY_COMPLETED_SAME_RESULT, fake는 NOT_OWNER.
- 같은 경우의 markFailed는 Redis ALREADY_MARKED_SAME_OPERATION, PostgreSQL
  OPERATION_CONFLICT, fake NOT_OWNER. markFailed를 적용한 핸들이 응답을
  잃고 다시 보내면 fake만 NOT_OWNER.
- release한 핸들로 start하면 PostgreSQL은 NOT_OWNER, Redis·fake는 ABSENT.
- 같은 원인(재생 판정이 "어느 핸들이 적용했나"를 보지 않음)이 다른 전이에도
  있다. PostgreSQL은 기록된 renew·release와 digest가 다른 핸들을 모두
  OPERATION_CONFLICT로 답해, 주인이 renew가 돌려준 핸들로 다시 renew해도
  거절하고 넘겨받기 전 핸들의 renew·release도 OPERATION_CONFLICT다. fake는
  적용한 핸들이 start·renew를 다시 보내도 NOT_OWNER다.

방법: 소유자 결정(2026-11-06) 「넘겨받기 전 핸들의 재전송」「해제된 핸들로
start」대로 맞춘다. "적용한 핸들"은 owner identity가 같고 기록보다
revision이 하나 낮은 핸들이다. 라운드6에서 start에 쓴 기준을 모든 전이에
쓴다.
- Redis TRANSITION과 command fake: ALREADY 조건에서 "start가 아니면 아무
  핸들" 분기를 지우고 rev == handle rev + 1만 남긴다. 다른 핸들은 revision
  검사로 내려가 NOT_OWNER·WRONG_STATE.
- PostgreSQL: replayVerdict가 적용한 핸들일 때만 재생(같은 digest → 이미
  처리됨, 다른 digest → OPERATION_CONFLICT)으로 읽는다. 다른 핸들은 owner
  검사로 내려가 NOT_OWNER. complete 재생 판정도 owner token 대신 적용한
  핸들을 본다.
- fake: 마지막으로 적용한 전이와 그 핸들·인자(renew lease, fail disposition)
  를 기억해 start·renew·complete·markFailed 재전송에 저장소와 같게 답한다.
- release한 핸들의 start는 계약이 ABSENT·NOT_OWNER를 둘 다 받고 포트
  Javadoc(IdempotencyStartOutcome)에 적는다. 코드 동작은 그대로.
버린 대안: PostgreSQL complete·fail 재생을 전이 digest 비교만으로
하기(complete digest에 replay TTL이 들어가 같은 결과·다른 TTL 재전송이
RESPONSE_CONFLICT가 된다), Redis를 원래 주석 의도대로 두고 fake·PostgreSQL을
"operation의 아무 핸들"로 넓히기(소유자 결정과 반대, 넘겨받기 전 핸들이 남의
결과를 자기 것으로 확인받는다), 재생 핸들을 attempt만으로 가리기(같은
attempt가 넘겨받으면 attempt가 올라가지만 renew 뒤의 낡은 핸들은 attempt가
같다).
공유 계약 IdempotencyStoreContract에 10케이스를 더했다. 포트 결과 enum
Javadoc 넷, application-core CLAUDE.md·README, persistence-jpa·cache-redis
README, TESTING_STRATEGY, 결정 색인, 업그레이드 안내 5절을 같이 고쳤다.

위험·한계: 템플릿의 호출자(IdempotencyExecutor)는 넘겨받기 전 핸들로 다시
보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접
부르는 코드는 넘겨받기 전 핸들의 재전송에 NOT_OWNER를 받고, PostgreSQL에서
renew를 이어 부를 수 있게 된다. fake로 응답 유실을 흉내 내던 테스트는 이제
"이미 처리됨"을 받는다. 적용한 핸들이 markFailed를 다른 retention·disposition
으로 다시 보낼 때의 답은 저장소마다 다르고 IdempotencyFailOutcome Javadoc과도
다르다(범위 밖, 보고에 적음).

검증: desktop, 공유 잠금, 기준 73d39212.
- RED(기준 커밋 + 계약 테스트만, 로그 ~/r8-f4-red-logs/): in-memory fake
  계약 59 중 4 실패(적용한 핸들의 start·renew·markFailed 재전송,
  "expected: ALREADY_MARKED_SAME_OPERATION but was: NOT_OWNER" 등), Redis
  command fake 2·실 Redis(redisContainerContractTest) 2 실패("expected:
  NOT_OWNER but was: ALREADY_COMPLETED_SAME_RESULT"·"…ALREADY_MARKED_SAME_
  OPERATION"), 실 PostgreSQL(jpaPlatformContractTest) 5 실패(complete는
  ALREADY_COMPLETED_SAME_RESULT, markFailed·renew·release는
  OPERATION_CONFLICT, 두 번째 renew는 "expected: RENEWED but was:
  OPERATION_CONFLICT"). release한 핸들의 start 케이스는 동작 변경이 없어
  처음부터 셋 다 통과한다. lane마다 실패 수는 위 계약 실패 수와 같다.
- GREEN(이 커밋과 같은 트리 377d1232, 로그 ~/r8-f4-green-logs/): 네 leaf
  check(application-core 422·skip 19 fake 시간 케이스, persistence-jpa 664,
  cache-redis 225, redis-runtime 65), 네 leaf testQualityCheck,
  redisContainerContractTest 100, jpaPlatformContractTest 429,
  postgresqlIdempotencyIntegrationTest 10, fake를 쓰는 leaf(composition:
  idempotency check 32, redis-sdk test 310, web test 329, sample-portfolio
  test 339), documentContractTest 66 — 모두 rc=0, 실패 0.
- scripts/check-work-docs.py, git diff --check 통과.

BREAKING CHANGE: IdempotencyStorePort 구현은 이미 적용된 전이의 재전송을 그
전이를 적용한 핸들(기록보다 revision이 하나 낮은 핸들)에게만 "이미 처리됨"
으로 확인하고 다른 핸들은 NOT_OWNER로 답해야 한다. 직접 구현한 store는
IdempotencyStoreContract의 새 케이스로 확인한다.
2026-11-07 01:01:41 +09:00

24 KiB
Raw Blame History

application-core — application use cases

Registered identity

  • Module ID: application-core
  • Gradle path: :application-core
  • Focused test (derived from Gradle path): ./gradlew :application-core:test --console=plain
  • Runtime baseline: Java 21; repository framework baseline: the Spring Boot 4.x version pinned by the shared version catalog.
  • Registry SSOT: src/config/architecture/modules.json.

Package root: dev.caskeleton.application.

코드 주석에서 덜어낸 설계 결정의 근거는 README.md 가 모아둔다 (이 문서는 모듈 규칙 SSOT).

Responsibility

  • Use case inbound ports (CommandUseCase, QueryUseCase) and their command / query contracts.
  • Outbound ports (*Port interfaces) the use cases depend on.
  • Application exceptions and policy types.
  • Coordinate domain models through ports.
  • Own application transaction boundaries through the TransactionPort abstraction.
  • Expose framework-free invocation context through ports such as CorrelationIdPort; adapters own MDC or other concrete storage.
  • Own the framework-free semantic integration-event draft, validated-event value contract and exact typed payload contribution SPI. This is the messaging semantic contract R1 boundary only.

Allowed

  • :domain-core
  • :shared-contract
  • Java standard library types.

Forbidden

  • adapter-* implementation classes.
  • app-bootstrap.
  • Controller request/response DTOs.
  • JPA entities and Spring Data repositories.
  • HTTP status, transport types (org.springframework.web..).
  • org.springframework.transaction.annotation.Transactional (use TransactionPort instead — D3).
  • org.springframework.context.ApplicationContext — direct dependency forbidden (getBean(Class) reflection-style bypass blocked by ArchUnit D11). String-key bean lookup / Class.forName(String) / BeanFactory#getBeansOfType remain ArchUnit's static-analysis blind spot per D12 — guard via code review checklist.
  • Lombok (lombok..) — also forbidden in domain-core. Within application-core, Lombok is currently not in scope for the contract; if you intend to use it, weigh the bytecode opacity cost first.
  • Persistence-layer transaction annotations of any kind inside this module.
  • Diagnostic frameworks (org.slf4j, java.util.logging, Logback, Log4j, Micrometer). Express diagnostic intent through a specific outbound *Port; adapters own rendering.
  • Messaging provider/runtime types: physical topic, Kafka record or metadata, JSON tree/raw JSON payload, serializer/schema-validator implementation, security topology and publication epoch.

Contract types

Type Purpose
usecase.UseCase<I, O> Base type for inbound ports. Concrete inbound ports MUST extend CommandUseCase or QueryUseCase.
usecase.CommandUseCase<C extends Command, R> Inbound port for write use cases. Implementations MUST be annotated @UseCaseCapability.
usecase.QueryUseCase<Q extends Query, R> Inbound port for read-only use cases. Implementations MUST declare transactionMode = READ_ONLY and repositoryAccess = READ_REPOSITORY.
command.Command Marker for write intents. Plain immutable types built from domain values.
query.Query Marker for read intents. Plain immutable types built from domain values.
transaction.TransactionPort Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by adapter-persistence.
secret.SecretSourcePort Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves.
transaction.NestedRootTransactionRejectedException Fail-fast signal raised before action/provider side effects when inRootWrite detects an actual ambient transaction.
transaction.TransactionMode WRITE / READ_ONLY / REQUIRES_NEW. NESTED and NEVER are intentionally absent.
transaction.Isolation READ_COMMITTED (pinned default) / REPEATABLE_READ / SERIALIZABLE. READ_UNCOMMITTED is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through TransactionPort is a planned joint change with feature-application-port-usecase-contract; the shipped call path pins READ_COMMITTED.
capability.UseCaseCapability Mandatory annotation on every concrete use case: declares transactionMode, idempotency, repositoryAccess, externalOutboundAllowed.
capability.Idempotency IDEMPOTENT / KEYED / NOT_IDEMPOTENT.
capability.RepositoryAccess NONE / READ_REPOSITORY / WRITE_REPOSITORY.
messaging.contract.IntegrationEventContractContribution<P> Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution.
messaging.event.IntegrationEventDraft<P> Typed semantic event before local encoding; never JSON, Kafka or persistence state. Built only through IntegrationEventDrafts (INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER).
messaging.event.IntegrationEventDrafts The one way a feature builds a draft: contract id, version and destination from the contract, correlation from the request when canonical (else the event id), SINGLE_TENANT_SCOPE for a feature without tenants.
messaging.event.IntegrationIdentity The one grammar and the length bounds of event, correlation/causation and aggregate ids. Test a value with isCanonical(value, bound); never copy the pattern.
messaging.event.ValidatedIntegrationEvent Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary.
messaging.event.IntegrationEventEncoderPort Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: adapter:outbound:support JsonIntegrationEventEncoder).
outbox.OutboxAppendPort The one outbox append: a ValidatedIntegrationEvent, in the caller's write transaction.
tenant.TenantId The tenant identifier and its one grammar ([A-Za-z0-9][A-Za-z0-9_.-]{0,63}); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only.

Notification (NOTIF-ADR-005)

None of the notification types are in this leaf. ..notification.platform.. and the simple NotificationPort, Notification and NotificationChannel directly under dev.caskeleton.application.notification all belong to leaf application-notification; the shared package prefix is the only link. The R1 orchestration types were removed on 2026-09-25.

Naming convention

This section is the repository's naming rule book. NamingConventionTest (app-bootstrap architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks them against this table. A new feature follows the "new code" column; the "existing exceptions" are named so nobody copies them by accident.

Role Name Where Existing exceptions (do not copy)
Use case (inbound port implementation) <Verb><Noun>UseCase, enforced by ArchUnit application package of the feature *ApplicationUseCase (application-fileserver, application-notification), *Service (notification, fileserver)
Command / query record *Command / *Query next to its use case —
Aggregate persistence (stores and returns whole aggregates) <Aggregate>Repository domain package of the aggregate, owned by the domain —
Technical store the application owns (outbox, idempotency, operation rows) <Thing>StorePort application package *WritePort (old onboarding fixture, removed)
Read model that returns projections, not aggregates <Thing>QueryPort application package; returns projections only (ArchUnit) —
Any other outbound port <Capability>Port application package —
Server-assigned id generation <Aggregate>IdFactory extends IdFactory<<Aggregate>Id> domain package; the id record implements ResourceId<Self> OutboxEventIdFactory (sample; event ids are not resource ids)
Configuration binding *Settings (operational) or *Policy (authorization / domain policy), enforced by ArchUnit the leaf that binds it —
Throwable *Exception, enforced by ArchUnit — —
Contract test kit for a port abstract <Port>Contract in the port owner's testFixtures; the fake's and each adapter's test extend it testFixtures value-type tests were once named *ContractTest; they are *ValueTypesTest now

The one-line rule for stores: if the domain would recognise the thing it stores, it is a Repository in the domain; if it is plumbing the application needs, it is a StorePort in the application.

Package ownership

This section is the rule book for which packages the template owns and where a business feature goes. docs/manual/03-placement.md points here.

  • A business feature is dev.caskeleton.application.<feature> (and dev.caskeleton.domain.<feature>, ...adapter.inbound.web.<feature>, ...bootstrap.autoconfigure.<feature>): one package per feature directly under each root, no command/usecase/port sub-packages.
  • <feature> is not one of the template package names below. A feature beside a template package of the same name lands in the same package tree, and every upstream template update merges into it.
  • Template packages never import a feature package. Business code does not go into a template package, even when the name fits.
  • Everything under the two roots that is not listed here is a feature. A derived service adds features without editing this list; the template edits it when it adds, renames or removes one of its own packages.
Package (dev.caskeleton.application.*) Owning leaf Holds
usecase, command, query application-core inbound port base types and the command/query markers
capability application-core @UseCaseCapability and its enums
transaction application-core TransactionPort and its modes
security application-core authorization port, @RequiresPermission, @SystemInvoked, @SystemCaller, ObjectAccessPolicy
tenant application-core TenantId
observability application-core CorrelationIdPort, UserPrincipalPseudonymizerPort
secret application-core SecretSourcePort, SecretReference
messaging application-core the integration-event semantic contract
outbox application-core transactional outbox append and relay
idempotency application-core keyed idempotency executor and store port
operation application-core durable (long-running) operations
lease, lock application-core distributed lease and lock ports
cache application-core cache region port
realtime application-core live event replay port
notification application-notification notification capability
fileserver application-fileserver file server capability
objectstorage application-objectstorage object storage capability (its content.CallBudget is the call deadline it carries)
Package (dev.caskeleton.domain.*) Owning leaf Holds
identifier domain-core ResourceId, IdFactory
stereotype domain-core @AggregateRoot, @DomainEvent, @ValueObject

Enforcement:

  • scripts/new-feature.sh refuses a feature name that is already a package under any of the five roots, in any leaf — every template package included.
  • NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES: a feature package under either root does not take a name from these tables. Every feature has a domain package, so a feature named operation is caught at dev.caskeleton.domain.operation.
  • NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES: a feature class written into a template package keeps the template's name but imports its own domain, and that import is what fails.
  • These tables are the rule book; the machine copy the rules read is TemplatePackageOwnership (app-bootstrap src/test, so both the architecture suite and the document-contract lane see it). TemplatePackageOwnershipDocumentTest (document-contract lane, mainCheck) fails when the tables and that class differ in a package name or owning leaf, or when a listed package is not in the leaf the table names; TemplatePackageOwnershipRuleTest (architectureTest) fails when a listed name exists in no production class. A new template package joins both in the same change.
  • Not caught: a new template package that nobody lists. Features are generated into the same leaves (scripts/new-feature.sh), so an unlisted package is indistinguishable from a feature. Listing it is part of adding it.
  • Rejected alternatives: allowing only the listed top-level packages (every derived feature would have to edit the template's list — a merge conflict per feature), and a separate application-platform leaf for the platform packages (review 2026-11-01 01-10 (b): clearer boundary, but more registry edges than a naming rule needs).

Canonical use case shape

@RequiresPermission("user:register")
@UseCaseCapability(
        transactionMode = TransactionMode.WRITE,
        idempotency = Idempotency.KEYED,
        repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
public class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand, User> {

    private final UserRepository users;
    private final TransactionPort tx;

    public RegisterUserUseCase(UserRepository users, TransactionPort tx) {
        this.users = users;
        this.tx = tx;
    }

    @Override
    public User handle(RegisterUserCommand cmd) {
        return tx.inWrite(() -> {
            // ... domain coordination
        });
    }
}

The class is plain Java. A composition root constructs it with its ports and configuration values; application-core never self-registers with a DI framework. It is not final: a mutating use case declares @RequiresPermission, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot subclass a final class (RequiresPermissionProxyabilityTest). It is registered as a bean for the same reason — a use case built with new is never checked. A use case only the system calls (a scheduler, a relay, a message consumer) carries @SystemInvoked(reason = ...) instead of a permission and is not a bean: it is a write with no permission check, so no user request may reach it. Its system caller constructs it — a composition module for a scheduler, a @SystemCaller(reason = ...) message handler in ..adapter.inbound.messaging.., or a @SystemCaller scheduled job in the service's own ..adapter.inbound.scheduler.. package. Manual 07 「시스템이 부르는 쓰기」 is the canonical list of the three and where each lives. All of it is enforced — a @SystemInvoked bean fails startup, an inbound adapter that depends on one without being a @SystemCaller fails ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES, SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS keeps the mark (and classes nested in a marked one) off user transports, USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS keeps a user transport from calling a system caller (by its class or by a project interface it implements), and SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES keeps a system caller from being a Runnable or any other type outside the project, which no dependency rule could follow. Paths that name no type (a bean looked up by name, a function a configuration hands over) are not seen; manual 07 lists them and what holds them. A composition with @RequiresPermission beans but no enforcing advisor fails startup too (composition:service-runtime PermissionEnforcementGuard, both checks).

Allowed transactional shapes

Use case shape transactionMode TransactionPort call When
Write command WRITE tx.inWrite(...) Default for CommandUseCase.
Physical-root write command WRITE tx.inRootWrite(...) Only when orchestration must prove there is no ambient transaction and expose a result after commit.
Read-only query READ_ONLY tx.inRead(...) Default for QueryUseCase.
Outbox / audit / compensation REQUIRES_NEW tx.inNew(...) Only when the use case MUST commit independently of the caller.

NESTED and NEVER propagation are forbidden. inRootWrite MUST reject an actual ambient transaction before invoking its action or PlatformTransactionManager; it MUST NOT emulate root-only behavior with REQUIRES_NEW. Both inWrite and inRootWrite satisfy the direct boundary fitness rule for a WRITE_REPOSITORY + WRITE use case. READ and REQUIRES_NEW mappings remain exclusive.

Callback signature contract (D11)

TransactionPort callbacks are Supplier<T> / Runnable and cannot throw checked exceptions. This matches Spring's TransactionCallback<T> constraint. Wrap domain checked exceptions into RuntimeException subclasses (DomainException extends RuntimeException); IOException → UncheckedIOException; SQLException is auto-translated by Spring's DataAccessException hierarchy.

inNew pool-sizing constraint (D12)

inNew acquires a new physical JDBC connection. Pool size MUST satisfy:

hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1

Forbidden: calling tx.inNew(...) inside a loop over many records — pool exhaustion + deadlock risk. Batch records inside ONE inNew call, or move the loop outside the transaction boundary.

Idempotency (KEYED) — feature-rate-limit-idempotency-contract

@UseCaseCapability(idempotency = Idempotency.KEYED) is supported. A KEYED use case wraps its work with dev.caskeleton.application.idempotency.IdempotencyExecutor — the one owner-safe generation; the V1 IdempotencyScope/tryBegin API is gone.

  • Scope: the caller passes an IdempotencyScopeDigest — a versioned HMAC of principal + client key + operation code, computed before the executor sees it. The raw Idempotency-Key never reaches this layer or the store.
  • Store: IdempotencyStorePort, contributed by exactly one provider selected with app.capabilities.idempotency.provider (redis → cache-redis, postgresql → persistence-jpa; default disabled). In-memory prod storage is forbidden.
  • Executor: built once by composition:idempotency IdempotencyAutoConfiguration from IdempotencySettings (processing lease 30s, replay TTL APP_IDEMPOTENCY_TTL 24h ≤72h and not shorter than the lease, failure retention 24h and not shorter than the replay TTL). Do not construct it in a use case or a sample config.
  • The action returns IdempotentAction.Outcome (Success / RetryableNoEffect / EffectUnknown); a thrown exception counts as effect-unknown. In progress → 409 IDEMPOTENT_IN_FLIGHT, fingerprint mismatch (SHA-256) → 422 IDEMPOTENT_REQUEST_MISMATCH; IdempotencyUnavailableException and IdempotencyRecoveryRequiredException mean the store could not prove the outcome, so do not blindly retry.
  • Every store answers an execution whose processing lease ran out with RecoveryRequired and never takes it over; only a claim that never started or a retryable failure is taken over. The answer leaves the record to its holder: the holder's first late complete/markFailed is recorded, a lease that ran out is not renewed and a claim whose lease ran out is not started — both answer LEASE_EXPIRED, not NOT_OWNER, and the executor turns a refused start into "not applied" (owner decision 2026-11-04, re-review RR5-01-02·03). A record lives for the lease plus the replay TTL. IdempotencyStoreContract holds Redis and PostgreSQL to both on real servers; the in-memory fake models no time, so it runs only the contract's time-free cases (re-review 2026-11-04 RR-01-11, RR-03-11, RR3-03-04).
  • Every transition names the operation its record was claimed under (IdempotencyOwner.claimOperationId()). Another one is OPERATION_CONFLICT in every store and changes nothing; so is an inspection that brings the owner token under another operation (owner decision 2026-11-06).
  • A transition already applied is confirmed ("already …") only to the handle it was applied from — the record one revision past it. Any other handle is NOT_OWNER, the same attempt's handle from before a takeover included; a start through a released handle is ABSENT or NOT_OWNER by whether the store keeps the released record (owner decision 2026-11-06, IdempotencyStoreContract).

The former ArchUnit freeze rule inbound_port_implementations_do_not_declare_keyed_idempotency and its fixture were removed when this branch merged.

Read / query path (feature-application-query-bypass-contract)

The read side has two equally-valid shapes; pick per read, do not force one:

Shape Returns When How
Through-aggregate (default for simple reads) domain aggregate via a *Repository port read shape == write aggregate and the aggregate is the minimal invariant boundary (no lazy collections needed) QueryUseCase → repository port → WorkLog
Projection (CQRS-lite) application-layer projection DTO via a *QueryPort read shape ≠ write, or to skip aggregate hydration / lazy-collection joins QueryUseCase → *QueryPort → WorkLogSummary (record); query via JPQL SELECT new / JdbcTemplate
  • D1 — purity guardrail (core, machine-enforced): a read port whose simple name ends with QueryPort MUST return application-layer projection DTOs only — never a domain aggregate, JPA entity, or web type, including through generic type arguments (List<DomainType>). Enforced by ArchUnit query_ports_do_not_leak_domain_jpa_or_web_types. Projection usage itself is opt-in, not a forced default; the demo lives in sample-portfolio (WorkLogSummaryQueryPort / WorkLogSummary).
  • D3 — Strict ceremony: every read goes through a QueryUseCase bean. There is no thin web→read-port path — that would bypass the mandatory @UseCaseCapability fitness function.
  • D4 — transaction: reads default to TransactionPort.inRead. A no-tx (autocommit) read is an opt-in only when spring.jpa.open-in-view=false is confirmed and the read is projection-only (no lazy access) and a single statement; otherwise keep inRead.
  • D5 — capability: a repository-backed projection read is still repositoryAccess = READ_REPOSITORY. "Projection vs aggregate" is the return shape axis, orthogonal to the repository-access level axis — no new enum. Outbound-HTTP reads (no repository) stay RepositoryAccess.NONE.
  • Full CQRS with a separate physical read store (D2) is out of scope — escalation only.

ArchUnit guardrails (enforced)

  • application_does_not_depend_on_adapters_or_transport
  • application_does_not_use_spring_transactional_annotation
  • application_does_not_depend_on_application_context (D11)
  • APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK
  • inbound_port_implementations_end_with_use_case
  • inbound_port_implementations_declare_capability
  • query_ports_do_not_leak_domain_jpa_or_web_types (query-bypass D1 — *QueryPort return purity)

Test

cd src
./gradlew :application-core:test
./gradlew :app-bootstrap:architectureTest

The messaging types above establish semantic contract R1 only. They do not claim JSON Schema qualification, Kafka publication, durable outbox persistence or any messaging R2 capability.