Karyo

Architecture guide

Karyo 2.1.1rendered at build time
On this page

The invariants a change must not break, why each one exists, and how you would break it without noticing. Read this before you touch a module boundary, a migration, identity, configuration or the engine seams. It is written for someone who already knows Kotlin, Quarkus and JPA; the architecture overview is the map it assumes.

Each rule links to the decision record or document that owns it. When a rule here and the code disagree, the code is what runs: raise it, and fix whichever is wrong.

Module boundaries

Invariant Why How it breaks quietly
A -core depends on -api modules and libs/*, never on another module's -core Keeps each domain's implementation replaceable and the contract surface explicit (ADR 0006) verifyModuleBoundaries (a Gradle task that runs before every test task) fails on a new project dependency on a -core outside the two waivers; it reads declared project dependencies only, so a runtime coupling (an event, an SPI implementor, a shared table) still needs review
The two existing waivers (karyo-demo, and the monitors engine's edge into karyo-replenishment-core) are not precedent Each has a specific, stated reason, or a recorded absence of one Adding a third "by analogy"
When a dependency would point the wrong way, declare the interface in your own -api and let the other module implement it PurgeBlockerLookup and PickZoneLookup work this way (Modules and boundaries) Importing the other module's service instead
An event payload that another module observes lives in the firing module's -api The observer then needs no edge to the firing module's core Declaring the payload in the -core, which forces a core-to-core edge on every observer
Every module whose beans the application must discover carries META-INF/beans.xml Without it Quarkus does not index the module's beans The application starts and the module's endpoints and services are silently missing
Proxied classes are opened by the allopen plugin's annotation list (buildSrc/src/main/kotlin/karyo.kotlin-conventions.gradle.kts, allOpen) Kotlin classes are final; CDI and JPA need to subclass them A class whose only proxy-relevant annotation is missing from the list stays final
Modules call each other in-process, through injected SPIs; there is no HTTP between modules One process, one transaction (ADR 0001) A REST client to localhost; nginx answers /api/internal/ with 404 so such a route could never be reached from outside either

The Gradle graph is one of four coupling channels. Before you rename a table, a column or a stored enum code, search for native SQL that reads it from another module: reporting's views and the forecasting, slotting and simulation engines read shared tables directly and break at runtime, not at compile time (ADR 0011).

Transactions and events

  • Choose an observer's transaction phase deliberately, and say why in the code. An observer in the firing transaction succeeds or fails with the change and can veto it; an AFTER_SUCCESS observer sees committed state and cannot undo the change that fired it (ADR 0008). Putaway task creation after a goods receipt, and packing after the last pick, are after-success on purpose (PackingService.onAutoPackEvent says the annotation is load-bearing). Moving one of them into the transaction, or out of it, changes what a failure means.
  • A change that matters outside the process is written to the outbox in the same transaction. Never call a webhook or any other external system from inside a business transaction (ADR 0009).
  • The relay and several schedulers assume one application instance. ConcurrentExecution.SKIP only stops a tick overlapping the previous tick in the same JVM. A second instance against the same database delivers every webhook twice.
  • Stock state is current rows plus a journal row in the same transaction (ADR 0010). A stock mutation that does not write its journal row is a defect, and so is an update to a journal row.

Stock

  • StockUnit is never cached. Only reference data goes in the Caffeine cache (ADR 0012).
  • 0 <= reserved_amount <= amount is enforced by the database (services/karyo-app/src/main/resources/db/migration/inventory/V103__create_stock_units.sql, stock_units) and must hold in the owning service before it gets there; a violated constraint is an HTTP 500, not a validation message.
  • Reservation, physical transfer and shipping are distinct operations. Reserving does not move stock, moving does not release a reservation, and shipping is its own state change. The stock model and allocation and reservation state the rules.
  • Algorithm order and tie-breaks are behaviour. Stock selection, location finding and replenishment source choice have documented orders; change them only with the document and a test that pins the new order.

Persistence

  • A released migration is immutable, comments included. Karyo has no release yet, so the pre-release schema may still be edited and a development database rebuilt. Flyway validates checksums at boot, so a prose edit stops every existing installation from starting. Add a forward migration (ADR 0005).
  • Migrations live in the application, under services/karyo-app/src/main/resources/db/migration/<module>/, and a new directory must be added to quarkus.flyway.locations or it silently never runs.
  • Use your module's version band. The bands interleave and out-of-order is on. The 1300 band is shared by two modules; read ADR 0005's band table before numbering a crossdock or docstore migration.
  • Test the upgrade, not only the fresh schema. A migration that works on an empty database can fail on a long-lived one that applied the bands in a different order.
  • References to another module's rows are ids, never foreign keys, validated through the owning module's lookup SPI (ADR 0007). Before deleting a row other modules may point at, ask them through an SPI, as the stock purge does with PurgeBlockerLookup.
  • A decision that has to stay correctable lives in code, not in a migration comment (KpiViewRepository).

Identity and owner scope

  • Identity is the Karyo principal UUID. Authentication credentials bind only through an exact canonical issuer and opaque subject. Never compare, trim, case-fold or auto-link a username, email or token subject, and never create a principal at first login. Ownership and personal state take a typed UUID plus a display snapshot (ADR 0037).
  • Grants are the only authority. Karyo authorizes every call from its own stored grants; a token's roles, groups and scopes grant nothing, and its kind and Business Unit claims can only confirm or narrow the stored principal (rule R, ADR 0048). Grants are read per request, so a revoke applies to the next call. Trust and claim mappings are restart-bound environment configuration, not system-property rows. Local suspension or unlinking denies the next request regardless of provider session state.
  • One installation is one Company. A positive business_unit_id identifies a Business Unit, not a permission. Configuration key 0 is the Company layer, not a Business Unit or administrator (ADR 0051).
  • Every call declares one catalogue action. Every REST method declares one action of libs/karyo-security/src/main/kotlin/com/karyo/security/Actions.kt with @DeclaredAction, except identity self-service and public methods, and so does every @Scheduled job and agent tool; there is no @RolesAllowed. services/karyo-app/src/test/kotlin/com/karyo/security/guards/ActionDeclarationTest.kt fails a method without one. A new action is a key in Actions, an auth migration row with its node types, and an ACTION_ROLES entry in scripts/identity_migration.py; the guard tests keep the three equal.
  • Actions and principal_kind are independent axes. Kind defines the affiliation boundary, while grants of actions define what a principal may do and where. The stored kind is authoritative; an absent claim uses it and a malformed claim is denied (ADR 0015, ADR 0048). Never grant an action to fix a scoping problem.
  • Operational rows are keyed by Facility alone (ADR 0050). Use readFacilityScope() for reads and writeFacilityScope() for writes, resolved where the endpoint's declared action is granted. Scalar operations require TenantContext.operationalFacilityId. Readers derive the Business Unit from that Facility. Selection never overwrites TenantContext.clientId affiliation. Identity and tenancy owns the shared boundary for operational scope and administration.
  • Isolation is application code only. There is no row-level security or Hibernate tenant filter. A query that forgets the scope leaks across owners with nothing underneath it.
  • Work without a request names its scope. A scheduler or port-to-port call passes the Facility (or, for an owner-enumerating job, the Business Unit id) explicitly and reads no ambient context. Inventory, layout and transport-order ports take a FacilityId with no ambient overload. On a scheduled thread the request scope is active but unprimed, so an ambient read of clientId or principalKind throws UnprimedTenantContextException instead of answering owner 0. Keep actor attribution too: the journal names who acted. Identity and tenancy has the detail.
  • Every REST method declares its scope kind, and raw ambient scope is a registered opt-in. A new endpoint needs @DeclaredScope(ScopeKind.X); a production file that reads operationalFacilityId, readFacilityScope(), writeFacilityScope(), clientId or principalKind needs @file:OptIn(com.karyo.security.RawScopeAccess::class) and a line in config/scope-consumers.json. Without the opt-in the build fails; review keeps the registry line (ADR 0039, the guards).
  • Managed-realm mappers stay aligned across both token-issuing clients and both realm files. RealmPrincipalKindClaimTest exercises the real mapper pipeline; @TestSecurity alone does not prove signature, issuer or audience validation.
  • karyo-admin and karyo-backend are outbound service identities, not warehouse principals. The first performs optional managed-provider administration and the second reads Keycloak audit events. Never widen either or substitute its client id for sub.

Configuration

  • Read the runtime property ladder before adding a knob. A setting in the property store resolves from the goods owner's row, then the Company layer's row (Business Unit 0), then configuration, then the default, so a database row can override an environment variable (the runtime configuration store). SystemPropertyCatalog is the register of known keys.
  • A @ConfigProperty string needs a non-empty default. An empty default is a start-up failure (application.yaml, quarkus.mailer.username, quarkus.mailer.password).
  • A Kotlin default parameter must not read an injected field. The generated $default bridge reads the CDI client proxy's field, not the bean's; resolve the value inside the method body (PickOrderService.releaseToPicking).
  • Opt-in stays opt-in. The demo data engine, the stock purge, the replenishment scheduler, and external delivery are off or explicit by default for a reason; a change must not switch one on.

Front ends

  • The server is the authority. Route guards and hidden menu entries mirror the caller's actions; they do not replace the declared-action check or the owner scope on the resource (Front ends).
  • A queued floor action is not a server success. The floor app queues selected operations while offline; only the server's response confirms them (ADR 0016).
  • The console has no licence awareness. Every engine screen is an ordinary page in its home sidebar group, the only gate between a caller and a page is the action, and a capability that still needs configuration says so on its own screen - Slotting names the engine that advised and the KARYO_LOCI_BASE_URL setting that connects Loci - rather than locking (Front ends).

Extensions and the engine boundary

  • Extensions compile against -api modules and are built into the image before Quarkus augmentation. Nothing is uploaded into a running application (ADR 0019).
  • Every module in the one distribution is Apache-2.0; no module names an engine's implementation module. The engines plug in through SPIs declared in the -api modules (ADR 0029). A change to such an SPI is a contract change for anyone compiling against it; treat it as a breaking change unless it is additive.
  • No licence decides what the product does. Every capability is available on every installation. LicenseService, GET /api/v1/license and the KARYO_LICENSE* settings remain only as a compatibility bridge that reports everything, and nothing authorizes from them: grants, owner scope and principal kind do that (ADR 0030). The public verification key has one home, in libs/karyo-license.
  • A profile thins the surface, never authority. The Core or Extended profile and its capability switches decide what the console and the floor app show, read at Company key 0 only. No authorization check reads them, a hidden capability's REST routes stay callable, and a hidden entry is absent rather than greyed. A new Extended page carries its capability in navigation and sits in CapabilityRoute (ADR 0052).
  • Loci advises; Karyo decides. Karyo builds the slotting contract from its own facts (pickable stock, picks in the demand window, fixed-location assignments), enforces its hard constraints whatever the engine said (a SKU pinned by a fix assignment is always a hold), and applies an accepted change through its own workflows. The analysis is Loci's alone: without a Loci base URL the route is a 503 problem saying slotting advice requires Loci, and a configured Loci that does not answer is a 502 problem, never invented advice (The engine boundaries).

Build and dependencies

  • Versions live in the catalog. The Quarkus platform is an enforced platform, so a plain constraint cannot raise a version it manages; a security floor goes through the root build's securityFloor (ADR 0003).
  • Images are reproducible. Every image build carries SOURCE_DATE_EPOCH=0 (Docker) or --timestamp 0 (Podman), and a new build site must be added to scripts/check-image-reproducibility.sh, or it is simply not checked (ADR 0023).
  • openhtmltopdf is LGPL-2.1 and is never shaded into Karyo's own jars (THIRD-PARTY-NOTICES.md); the release workflow verifies the legal files inside every jar.

Tests

  • Backend tests run against the assembled application, in services/karyo-app/src/test/kotlin, because a -core cannot boot on its own. config/test-runner-contracts.json decides which runner discovers which file (Testing).
  • Give test data unique synthetic ids. Test profiles can share state within one run; never rely on an empty table.
  • Read skipped counts. One failed application boot can skip most of the suite and still exit cleanly enough to look green.
  • Positive, rejection and owner-boundary tests belong with every change that touches a resource: that the right principal can, that a principal without the action cannot, and that another goods owner cannot.