Architectural Decision Records¶
This file tracks significant architectural decisions made in MarmotGraph Core v4. Each entry documents what was decided, why, and the consequences.
ADR-001: Single-module Maven project¶
Status: Accepted
Decision: Restructure from a multi-module Maven layout to a single module containing all source code.
Why: Reduces build complexity and inter-module dependency management overhead. The previous multi-module structure was inherited from v3 but added friction without meaningful isolation guarantees at the build level.
Consequences: All packages live under one artifact. Logical separation is enforced by package conventions and code review, not by the build system. The internal sub-package convention (see ADR-006) becomes the primary encapsulation mechanism.
ADR-002: PostgreSQL as primary store¶
Status: Accepted
Decision: Migrate the authoritative data store from graph-only to a relational database (PostgreSQL via JPA/Hibernate). Schema migrations are managed by Flyway.
Why: Graph databases are powerful for traversal queries but less suited as a primary record-of-truth store. PostgreSQL provides strong transactional guarantees, mature tooling, and simpler operational characteristics for the role of primary store. The graph DB is now used exclusively for query execution (see ADR-003).
Consequences: All instance payloads, structural metadata (types, properties, spaces), users, relations, and stored queries live in PostgreSQL. The graph DB is populated by syncing from the primary store, not treated as the source of truth.
ADR-003: Pluggable graph engine via Spring profiles¶
Status: Accepted
Decision: Abstract the graph query engine behind the GraphDB interface. Concrete adapters (neo4j, nograph) are activated via Spring profiles (spring.profiles.active).
Why: Different deployment environments and use cases require different graph backends (Neo4J for production query performance, "nograph" for fast local development without a running graph DB). Decoupling via an interface allows swapping without changing business logic.
Consequences:
- GraphDB defines exactly three operations: delete, upsert, executeQuery.
- New graph adapters must implement this interface and provide a @Profile-annotated configuration.
- The nograph profile is the default; it satisfies the interface but returns empty results for queries. (Superseded by ADR-037: nograph evaluates queries in PostgreSQL.)
- Arango support is planned but not yet a production adapter.
ADR-004: Keycloak as identity provider (OIDC/JWT)¶
Status: Accepted
Decision: Use Keycloak as the sole identity and access management system. Authentication is JWT-based (Bearer tokens issued by Keycloak).
Why: Keycloak provides a battle-tested OIDC implementation. The system was already using Keycloak in v3; v4 retains this to avoid breaking existing client integrations.
Consequences: All API consumers must obtain a Bearer token from Keycloak before calling protected endpoints. The dev setup includes a pre-configured Keycloak instance (utils/devSetup).
ADR-005: Authorization belongs in services, not the API layer¶
Status: Accepted
Decision: API controllers must not contain permission checks. Authorization logic lives exclusively in the service layer (services/authorization).
Why: Centralizing authorization in services ensures it applies regardless of which API version or controller invokes the operation. Distributing it across controllers leads to duplication and permission gaps.
Consequences: API controllers only specify whether authentication is required (via @AuthenticationAspect.None annotation to opt out, or nothing to require a valid token). The AuthenticationAspect AOP component handles token validation. Actual Functionality-based permission checks are done inside services via PermissionService / AuthorizationService.
ADR-006: internal package convention for module privacy¶
Status: Accepted
Decision: Within each module (e.g. services/authorization, primaryStore, graph/neo4j), classes meant only for internal use within that module are placed in an internal sub-package. The module's root package exposes only the interfaces intended for cross-module consumption.
Why: Java has no package-level access modifiers that span sub-packages. This convention documents intent and is enforced by code review.
Consequences: When consuming another module's functionality, only types from its root package (not internal) should be imported. Violations signal a design issue.
ADR-007: API versioning with parallel versions¶
Status: Accepted (extended by ADR-019)
Decision: Multiple API versions (v3, v3beta) coexist simultaneously. New experimental endpoints are added to v3beta; stable endpoints graduate to v3.
Why: Consumers need a transition period when APIs change. Killing v3beta before all clients migrate would break integrations.
Consequences: When an endpoint moves from v3beta to v3, the v3beta controller should delegate to the v3 implementation (not duplicate logic). The goal is to minimize the number of distinct implementations — use adapters/redirects to maintain backward compatibility with minimal code duplication.
ADR-008: AOP-based authentication via AuthenticationAspect¶
Status: Accepted
Decision: Use Spring AOP to intercept all public methods on @RestController classes and validate JWT tokens before the method body executes.
Why: Avoids boilerplate token-validation code in every controller method. A single aspect provides a consistent authentication boundary with an explicit opt-out (@AuthenticationAspect.None) for public endpoints.
Consequences: Any new @RestController method is protected by default. To expose an endpoint without authentication, annotate it with @AuthenticationAspect.None. No controller method should call token-validation logic directly.
ADR-009: Nightly full recompute as reconciliation for summary tables¶
Status: Accepted
Decision: The current_*_summary tables (current_property_occurrence_summary, current_type_summary, current_incoming_link_summary, current_target_type_summary, added in V17/V19/V20/V21) are kept up to date incrementally by statement-level triggers on their source tables. In addition, a PL/pgSQL procedure refresh_summary_tables() (V27) fully recomputes all four tables from the source tables in one transaction, and is invoked once a day by SummaryTablesReconciliationService via Spring's @Scheduled.
Why: Incremental triggers can drift from the source data over time — e.g. triggers are explicitly disabled during bulk operations (TriggerOrchestrator), or a future bug in trigger logic could leave a delta uncorrected. A periodic full recompute from source tables is the simplest way to guarantee eventual consistency without having to prove the incremental logic is bug-free forever.
Consequences: The recompute is a TRUNCATE + INSERT ... SELECT per table, so it briefly takes an exclusive lock on each summary table; it's scheduled off-peak (default: 03:00, configurable via org.marmotgraph.structure.summaryReconciliationCron / SUMMARY_RECONCILIATION_CRON) and is safe to invoke manually (CALL refresh_summary_tables();) after bulk data fixes. Any new summary table must add its recompute logic to the same procedure.
Update (V28): current_instance.type_id is nullable — an instance can exist (e.g. as a relation target) before it has been assigned a type. current_incoming_link_summary.source_type_id and current_target_type_summary.target_type_id are NOT NULL, so the increment branches of trg_sync_current_incoming_links_summary, trg_sync_current_target_type_summary, trg_current_prop_occ_summary_on_instance_space_change, and refresh_summary_tables() now skip rows whose (target) instance is not yet typed, instead of inserting a NULL into a NOT NULL column. When the target instance is later assigned a type, trg_current_instance_summary_type_change (V25) fires on that UPDATE and adds the corresponding summary rows — so untyped targets are simply deferred, not lost.
ADR-010: Python SDK as an independent package under sdks/python¶
Status: Accepted (target API version changed to /v4 by ADR-019)
Decision: Add a publishable Python client SDK at sdks/python, structured as its own pyproject.toml-based package (src/marmotgraph/) rather than a script or notebook helper. It targets the stable /v3 REST surface exclusively (never /v3-beta — see ADR-007: /v3-beta delegates to /v3 once endpoints graduate, so /v3 is always the current contract). The SDK depends only on requests; response models are plain dataclasses rather than pydantic, to keep the install footprint minimal for an SDK whose job is just to move JSON over HTTP. Errors are raised as exceptions (MarmotGraphAPIError) rather than returned as a Result/EmptyResult wrapper object, and resource methods take keyword arguments directly rather than per-endpoint builder classes — both deviate intentionally from the internal Java client's shape in favor of idiomatic Python.
Why: An early hand-written prototype (not checked into this repository) validated the overall shape (resource objects per API area, a Page abstraction for pagination, pluggable token providers for Keycloak) but mirrored Java idioms (builder-per-endpoint classes, a Result wrapper requiring .is_successful() checks) that read as unnatural in Python. Rebuilding it as a proper package, inside this repository, keeps the SDK in sync with the server it targets and makes the versioning relationship (which server API version it speaks) explicit and reviewable in the same PRs that change the API.
Consequences: Changes to /v3 request/response shapes should be reflected in sdks/python in the same change where practical, same as the versioning discipline in ADR-007. The SDK implements methods for endpoints that are currently stubbed server-side (see QueriesV3/parts of InstancesV3) so client code doesn't need to change again once those land — such methods are explicitly marked in their docstrings and in sdks/python/docs/. The package is versioned independently of the server (marmotgraph.__version__, read by pyproject.toml), not tied to the server's pom.xml version. Releases are published to PyPI by .github/workflows/python-sdk.yml on a sdk-python-vX.Y.Z tag, which sets the version.¶
ADR-011: External user identification by Keycloak nativeId, not the internal numeric id¶
Status: Accepted
Decision: Any REST API surface that takes a user identifier from a client (e.g. PUT/DELETE /instances/{id}/invitedUsers/{userId}) interprets that identifier as the user's Keycloak subject id (User.nativeId, a UUID-shaped string), never the internal User.id (Long, DB-generated). Server-side code resolves nativeId -> User.id via UserRepository.findByNativeId(...) at the point where it needs to touch tables keyed by the internal id (e.g. invitation.user_id). InvitationService (services/invitation) implements this for inviteUserForInstance/revokeUserInvitation/listInvitations.
Why: The internal Long id is a DB-generated sequence value with no meaning outside this service; clients only ever see a user's Keycloak subject (also used for UserWithRoles.getPrivateSpace()'s "private-" + nativeId" and AuthContext.getUserId()). Exposing the internal id would leak storage details and wouldn't round-trip with anything a client already has (tokens, /users/me). This wasn't self-evident from the entity model alone — InvitationId.userId is typed Long while the API path variable is typed UUID, and the previous (unused, commented-out) implementation got this wrong, assigning the instance's UUID where the user's Long id was expected.
Consequences: Invitation mutations throw a generic NotFoundException if no User row exists for the given nativeId (e.g. the user has never logged in, so no row was provisioned yet) — this is a 404, not a silent no-op, for inviteUserForInstance; revokeUserInvitation treats an unresolvable userId as a no-op instead, since "no invitation exists for this (possibly unknown) user" is already the desired end state for a revoke. listInvitations returns nativeId strings (InvitationsRepository.findInvitedUserNativeIdsByInstanceId), matching what callers can re-submit to the invite/revoke endpoints. Any future endpoint accepting a user-identifying UUID from a client should follow the same resolution path rather than assuming it's the internal id.
ADR-012: Stored queries are tagged instances, not a separate CRUD stack¶
Status: Superseded by ADR-038
Decision: saveQuery/removeQuery (QueriesV3, PUT/DELETE /queries/{queryId}) are implemented by a new services/queries/QueryService that delegates all instance lifecycle work (create, full-replacement contribute, release-status-guarded delete, permission checks) to the existing InstanceService, rather than introducing a parallel persistence path for queries. A stored query is simply an Instance whose payload is tagged with EBRAINSVocabulary.META_QUERY_TYPE, plus one row in the pre-existing (but previously unused) query table (new QueryRepository) that denormalizes meta.type — the root type the query runs against — read directly off the client's raw JSON-LD payload via QuerySpecification before InstanceService normalizes it. There are no dedicated CREATE_QUERY/WRITE_QUERY/DELETE_QUERY functionalities; queries reuse the standard CREATE/WRITE/DELETE instance permissions.
Why: The query JPA entity/table and the meta/responseVocab/structure payload shape already existed from an earlier (pre-rewrite) design that modeled a query as "an instance plus a root-type index row" — there was no reason to re-derive that shape. Reusing InstanceService means query storage gets space resolution, conflict-on-existing-id detection, full-replacement contribution, and release-status checks for free, and stays consistent with how every other instance-shaped resource (including moveInstance, ADR-free but same pattern) is implemented in this codebase: controller -> services/*Service directly, not through the dead primaryStore/Instances facade (see NOT_IMPLEMENTED.md §3).
Consequences: query.instance_id and current_instance.instance_id both FK to instance.id with ON DELETE NO ACTION, and there is no JPA-level cascade from Instance to Query (only Query -> Instance, via @MapsId + cascade = CascadeType.ALL on Query.instance, which is why saveQuery/removeQuery always touch the query row and delegate to InstanceService within the same @Transactional boundary — deleting Query before Instance in one flush, mirroring how InstanceService.removeInstance already orders Instance/CurrentInstance deletes). extractRootType parses meta.type from the pre-normalization payload, so it currently requires the client to supply a fully-qualified IRI there (no CURIE/prefix expansion via applyPrefixMap yet) — this will need revisiting once runDynamicQuery/executeQueryById are implemented and query payloads start round-tripping through the graph layer.
ADR-013: Graph reindexing as a two-pass bulk load, with manipulations locked meanwhile¶
Status: Accepted
Decision: GraphDB gets a reindex(DataStage, Supplier<Stream<List<IndexableInstance>>>) operation which replaces the whole content of a stage in the graph. It is exposed as POST /v3/graph/reindex (admin, new REINDEX_GRAPH functionality, asynchronous; GET returns the status) and orchestrated by services/graph/GraphReindexService. The primary store side (GraphReindexSourceInternal) reads the stage in keyset-paginated batches of 1000 instances, each in its own read-only transaction, decompresses the payloads and resolves their link targets to lifecycle ids (registered identifier of the stage, falling back to interpreting the reference as a UUID). The Neo4j adapter (Neo4JReindexInternal) clears the stage (CALL {} IN TRANSACTIONS), then iterates the source twice: first writing all nodes, then all edges, both via UNWIND with one transaction per batch. Node labels/properties are derived by the same code as upsert (Neo4JInternal.nodeLabels/nodeProperties) so both paths produce the same graph. While a reindexing runs, every method annotated with @ReindexLock.Manipulation (the mutating entry points of InstanceService) is rejected immediately with 503 instead of waiting.
Why: The single-instance upsert issues one autocommitted statement per node and edge and silently drops edges whose target doesn't exist yet - unusable for populating an empty graph. Writing all nodes before any edge removes the ordering problem without needing incomingRelations; batching via UNWIND reduces the round trips from roughly one per node/edge to one per batch. The source is re-read for the edge pass instead of buffering edges, to keep memory bounded independently of the data volume. Payloads are gzip-compressed in Postgres, so a server-side pipeline (e.g. APOC JDBC) is not an option; neo4j-admin import would be faster for the very first load but requires an offline, empty database and is therefore not suitable as an API-triggered operation. Labels can't be parameterized in Cypher - nodes are therefore grouped by label combination per batch instead of relying on dynamic labels (Neo4j >= 5.26), keeping the adapter version-independent. Manipulations are locked (rather than e.g. replayed afterwards) since the incremental indexing path isn't wired up yet (IndexingService has no callers) and a lock is the simplest way to guarantee the rebuilt graph reflects a consistent state of the primary store.
Consequences: The lock is a fair ReentrantReadWriteLock held in-process - it only protects a single application instance; a multi-instance deployment would need a distributed lock (e.g. a Postgres advisory lock). The aspect runs with highest precedence so it wraps the manipulation's transaction (commit happens before the reindexing can start reading). Once the reindexing is queued for the lock, new manipulations are rejected while in-flight ones are awaited (up to 5 minutes). Batches the graph rejects (e.g. nested lists as property values) fall back to instance-by-instance writing so a single bad payload only skips that instance; skipped instances and dropped edges are counted in the status. New mutating service methods must be annotated with @ReindexLock.Manipulation. Edges to targets which only exist in another stage or can't be resolved are dropped.
ADR-014: Releasing copies the derived tables from the current stage¶
Status: Accepted
Decision: Releasing an instance (InstanceProcessorInternal.release) populates the released stage's derived tables in addition to the payload:
- released_identifier is replaced from the identifiers of the released payload, via a native INSERT … ON CONFLICT DO NOTHING, the same way current_identifier is filled.
- released_relation and released_property_occurrence are replaced by copying the instance's rows from current_relation and current_property_occurrence with INSERT … SELECT.
- The released relations are then resolved against the released stage only. Outgoing relations of the instance are resolved by UUID and by released identifier, and released relations of other instances that point to this one are resolved as well.
- Unreleasing (InstanceProcessorInternal.unrelease) removes these rows and unresolves the incoming released relations before the released instance is deleted.
Why: Previously only the payload was released. registerReleasedIdentifiers only added entities to the non-owning, non-cascading mappedBy list of ReleasedInstance, and ReleasedIdentifier.instance is mapped insertable = false. As a result, released identifiers were never persisted, and released relations and property occurrences were never written. This broke lookups by identifier, incoming links, and the graph reindex (ADR-013) for the released stage. A release publishes exactly the current payload, and the current stage has already extracted relations and property occurrences from it (including the property/type ids). Copying them is therefore cheaper and guaranteed consistent, compared with running the extraction a second time. Resolution is scoped to the released instance, unlike the global resolveRelations of the current stage, so a release stays a per-instance operation.
Consequences:
- Released relations only resolve to targets that are released themselves (enforced by the FK to released_instance). Relations to unreleased targets stay unresolved until the target is released.
- As with the current stage, an identifier already claimed by another released instance stays with that instance.
- Data released before this change has no released identifiers, relations or property occurrences until it is released again.
- Migration V29 adds indexes on released_relation for the incoming resolution and unresolution.
ADR-015: Query execution through QueryService¶
Status: Accepted - listing, fetching and the query format are changed by ADR-038 (the execution and the access filter are unchanged); the Cypher translation is replaced by ADR-064 (APOC is no longer needed)
Decision: All endpoints of QueriesV3 go through services/queries/QueryService:
- Listing (GET /queries): the query table gives the ids, InstanceService.getInstancesById restricts them to readable spaces, and the search term is matched in memory against meta.name/label/description.
- Fetching (GET /queries/{id}): InstanceService.getInstance returns the stored query, but only if a query row exists for it.
- Executing, stored (GET /queries/{id}/instances) or ad-hoc (POST /queries): the query is normalized as JSON-LD and the query-vocabulary prefix (EBRAINSVocabulary.QUERY) is stripped to obtain a QuerySpecification. That specification goes to GraphDB.executeQuery.
The access filter handed to the graph is built from these inputs:
- the spaces the user can read in the requested stage, intersected with restrictToSpaces if that is given;
- plus the user's invitations, which apply to the in-progress stage and only when no explicit spaces are requested;
- no filter at all for users with global read rights.
If the filter turns out empty, the graph isn't queried. GraphDB.executeQuery also takes an optional instanceId, which QueryToCypherInternal translates into a restriction on the root node.
The Neo4j write path (both upsert and the reindexing of ADR-013) is aligned with what QueryToCypherInternal expects:
- Names: node properties, relations and type labels are addressed by the Neo4JUtils.sanitizeLabel form of their vocabulary, compacted beforehand as described in ADR-016.
- Type labels: taken from the compacted types (_types).
- JSON-LD keywords are stored as technical properties with a _ prefix: @id as _id, @type (full IRIs) as _type.
- Embedded objects without an _id get a virtual id <lifecycleId>#<n> instead of being dropped.
A filter whose value is provided neither as a request parameter nor in the query doesn't restrict the results ($param IS NULL OR …).
Why: The translator already defined how a query maps onto the graph, but the data written to Neo4j didn't match it (no type labels, no embedded nodes, property names not in the translator's form), so no query could return anything. Aligning the write side kept the translator intact. The service reuses InstanceService for reading stored queries, so permission checks and payload post-processing stay in one place (as in ADR-012). Ignoring filters without a value means a stored query with a parametrized filter returns everything when the parameter is omitted, instead of nothing. This matches how such queries are used from the query builder.
Consequences:
- A graph populated before this change (or ADR-016) has to be reindexed (POST /v3/graph/reindex) to be queryable.
- New or changed instances appear in query results right after the change is committed (see ADR-017).
- @id in query results is the instance's UUID (the node's _id), not the namespaced IRI. For embedded objects it is their virtual id.
- Nested filters use apoc.map.clean, so the Neo4j instance needs the APOC plugin. The dev docker-compose.yml enables it.
- Search in the query list is done in memory, which is fine for the expected number of stored queries per user but doesn't scale to very large numbers.
- QueryService.saveQuery still reads meta.type from the raw, pre-normalization payload (ADR-012). A query sent in fully expanded form can therefore be executed ad hoc, but not saved.
ADR-016: Graph-internal vocabulary compaction with CURIE prefixes¶
Status: Accepted
Decision: Before anything reaches a graph database, its vocabulary is compacted by graph/vocabulary/GraphVocabulary. Every namespace (the part of an IRI before the last /) is replaced by a short prefix, joined to the local name with __. For example, https://schema.org/name becomes sch__name. The mapping lives in the existing curie_prefix table:
- Namespaces already registered there reuse their prefix.
- New namespaces get a prefix of at most three lower-case letters or digits, starting with a letter. It consists of the first characters of the second-level domain plus the initial of the last path segment (https://schema.org becomes sch, https://openminds.om-i.org/props becomes omp). On collision, a sequential number is appended (sch2, sch3, …).
- The mapping is cached in memory and only grows.
- Registration is a native INSERT … ON CONFLICT DO NOTHING in its own transaction, followed by a re-read. Several application instances therefore converge on the same mapping.
What gets compacted:
- Payloads: a copy is made. Property names are compacted on all levels. The compacted types are added as _types, which the adapters use as type labels. @type values, @id references and all other values keep their original form, and the payload in Postgres is never touched.
- Queries: a copy of the QuerySpecification is made. Root type, property paths and type filters are compacted; the response property names are not.
The Neo4j adapter applies this in its GraphDB facade (upsert, reindex, executeQuery), before its own Cypher-specific sanitization. Other graph adapters are meant to do the same. The bean is not created for the nograph profile.
Why: Graph databases restrict identifiers: labels and property keys must be valid identifiers to be used without escaping. Sanitizing full IRIs (httpsschemaorgname) is lossy (http:// and https:// collide), long, and unreadable when inspecting the graph. Prefixes of at most three characters (plus a sequence number) keep the names short and readable. As long as the local names consist of letters, digits and _, they are also injective. Prefixes never contain an underscore, so the __ separator keeps the mapping reversible. The short base form makes collisions more likely, especially between namespaces of the same domain, but collisions are resolved by the sequence number.
The compaction lives in the generic graph layer rather than in the Neo4j internals, so it can be shared by future adapters. It is applied by each adapter's facade rather than by a wrapper around GraphDB, so nograph has no overhead and an adapter can opt out.
Query results don't need translating back: they are keyed by the query's (uncompacted) property names, and values are never compacted. That is also why types are kept as full IRIs in @type and only their compacted form is added under _types. Filters on @type therefore work with full IRIs, and returned types need no expansion.
Consequences:
- Graphs populated before this change have to be reindexed.
- Prefixes must never be changed or removed in curie_prefix while a graph is populated, or its content no longer matches the translated queries.
- Local names with characters other than letters, digits and _ are still sanitized by the Neo4j adapter, so collisions remain possible within one namespace (e.g. foo-bar and foo_bar).
- An adapter that returns graph-internal terms (e.g. whole nodes or relation names) would need the reverse translation, which doesn't exist yet.
ADR-017: Continuous graph synchronization through after-commit events¶
Status: Accepted
Decision: The primary store announces its changes as Spring application events:
- InstancesChangedEvent(stage, internal ids) is published by the instance processing (create, contribute, reconcile) for the in-progress stage, by the release for the released stage, and by moving an instance to another space.
- InstanceRemovedEvent(stage, UUID, space) is published by removing an instance (in progress) and by unreleasing it (released).
services/graph/GraphIndexingListener consumes them with @TransactionalEventListener(AFTER_COMMIT):
- For changes, it reads the instances via GraphSourceInternal in a new read-only transaction. This is the renamed GraphReindexSourceInternal, so references are resolved the same way as by the reindex. It then calls GraphDB.upsert for each instance.
- For removals, it calls GraphDB.delete.
- The listener only exists outside the nograph profile.
GraphDB.upsert now takes the stage, the IndexableInstance and a lazy supplier of the instances linking to it. In Neo4j, the upsert runs in one write transaction:
1. Check whether the instance already exists in the stage.
2. Remember the edges other instances have to it.
3. Detach-delete its nodes (root and embedded).
4. Recreate its nodes and outgoing edges.
5. Restore the remembered incoming edges.
6. Only if the instance is new to the stage: call the supplier and add the edges of the linking instances, which couldn't be created before because the target was missing. The linking instances are found via the relation tables, by the instance's identifiers or its UUID (migration V30 adds hash indexes on target_reference).
The upsert and the reindexing share their Cypher statements (Neo4JStatements). The unused legacy primaryStore/internal/IndexingService was removed.
Why:
- After commit: the graph must never contain changes which are rolled back. Updating after the commit, rather than within the transaction, keeps the graph out of the primary store's transaction. A Neo4j failure therefore never fails a manipulation: Postgres is authoritative, failures are logged, and a reindex brings the graph back in sync.
- Synchronous in the request thread: query results are consistent with a manipulation as soon as it returns. It also runs under the ReindexLock read lock of the manipulation, so it can't interleave with a reindexing (ADR-013).
- Events: they decouple services/instances from the graph layer and cover all mutation paths, including the parallel reconciliation, whose batches each commit on their own.
- Keeping incoming edges: the instances they come from haven't changed. Loading all linking instances on every update would be expensive for frequently referenced instances, so they are only loaded when the node is new.
Consequences:
- Manipulations take longer by the time the graph update takes. A slow or unavailable graph slows down writes until its operations time out.
- If a graph update fails, the graph stays out of sync until the next upsert of the affected instance or a reindex.
- If an instance gains an identifier that existing links already reference, those links only become edges when the linking instance is upserted again or after a reindex. The incoming edges are only completed when the instance is new to the stage.
- New mutation paths must publish the corresponding event.
- The upsert in Neo4j is synchronized per application instance. Parallel reconciliation workers therefore write to the graph one at a time.
ADR-018: Concurrent manipulations limited by the connection pool size¶
Status: Accepted
Decision: services/graph/ManipulationThrottle limits the number of concurrent transactional manipulations to maximumPoolSize / 2 of the Hikari pool (at least 1). It is an aspect around methods annotated with both @ReindexLock.Manipulation and @Transactional. It runs right after the ReindexLock and around the transaction, so a permit covers the commit and the after-commit graph synchronization.
- If no permit becomes available within the pool's connectionTimeout, the manipulation is rejected with 503.
- Nested manipulations within the same thread take only one permit.
- The reconciliation is not transactional itself. Each of its parallel batches waits for a permit (runBlocking) instead.
In addition, GraphIndexingListener is no longer transactional itself. It reads the primary store in short, separate REQUIRES_NEW transactions. GraphVocabulary.registerMissing is no longer synchronized, because the database already arbitrates concurrent prefix registrations.
Why: Spring releases the connection of a transaction only after its after-commit listeners have returned. The graph synchronization (ADR-017) therefore needs a second connection while the first one is still held. Before this change, the listener held the second connection for the whole graph update, and a new graph vocabulary prefix needed a third one, inside a synchronized block. With virtual threads, concurrency is unbounded. A few concurrent manipulations could thus hold all connections while waiting for one more, and the pool timed out (Connection is not available, request timed out). Bounding the manipulations to half the pool guarantees that each of them can get its second connection. The limit is derived from the pool, so increasing spring.datasource.hikari.maximum-pool-size increases the allowed concurrency as well.
Consequences:
- Under load, manipulations queue for a permit. They fail with 503 if none is available within the connection timeout, rather than failing later with a connection timeout.
- The budget of 2 connections per manipulation is a hard assumption. Code which acquires further connections during a manipulation (e.g. new REQUIRES_NEW calls while the listener's read transaction is open) must be accounted for in ManipulationThrottle.CONNECTIONS_PER_MANIPULATION.
- Read requests are not throttled. They can still compete with manipulations for connections, which delays them but cannot deadlock them, since they hold only one connection at a time.
- New transactional mutation entry points must be annotated with @ReindexLock.Manipulation. Parallel background processing within a manipulation must use runBlocking.
- The limit is per application instance. Each instance has its own pool.
ADR-019: v4 as the current API version, v3 delegates to it¶
Status: Accepted (v3 contract restored by ADR-020)
Decision: A new API version v4 (/v4, package api/v4, OpenAPI group v4) is introduced as a copy of v3 and becomes the implementing version. All v3 controllers are reduced to thin delegators to their v4 counterparts (XxxV3 → XxxV4), keeping their own request mappings and OpenAPI annotations so the /v3 contract stays unchanged. v3beta keeps delegating to v3 (and therefore transitively to v4). The delegation chain is thus v3beta → v3 → v4 (changed by ADR-020: v3beta delegates to v4 directly).
Why: v4 needs room to evolve (breaking changes in request/response shapes) without affecting existing /v3 clients. Following ADR-007, older versions delegate to the newest implementation instead of duplicating logic, so there is a single implementation to maintain.
Consequences:
- New functionality and changes go into api/v4. When a v4 endpoint diverges from v3, the v3 delegator becomes a compatibility shim (adapting parameters/results) instead of a plain forward.
- v3 controllers still bind their own request parameters (e.g. the @InitBinder of InstancesV3 for multi-valued parameters) since they're independent Spring handlers.
- Calls from a v3 controller into a v4 controller go through the Spring proxy, so aspects (AuthenticationAspect, metrics) are applied again on the v4 method — consistent with the existing v3beta → v3 delegation.
- The SDKs (sdks/java, sdks/python, see ADR-010) target /v4, the current contract. Changes to /v4 request/response shapes should be reflected in the SDKs in the same change. /v3 remains available for clients using older SDK versions.
ADR-020: v3 frozen to its contract before v4¶
Status: Accepted (extended by ADR-021)
Decision: The /v3 API is restored to the contract it had before the rewrite (reference: the OpenAPI spec of the last deployed v3), while its implementation keeps delegating to v4 (ADR-019). The v3 controllers act as compatibility shims:
- They only expose the parameters of the old contract (v3-specific parameter objects in api/v3/models, e.g. ResponseConfigurationV3). Parameters introduced later are passed to v4 with the values which reproduce the old behavior (e.g. updateIfExists=false, withOccurrenceCount=true).
- Endpoints added after the rewrite (/graph/reindex, POST /spaces/inference, POST /spaces/resolve) exist in v4 only.
- Response payloads which changed their format are mapped back (UserV3, UserWithRolesV3, SpaceSpecificationV3). durationInMs is serialized as an integer for v3 (V3ResponseAdvice).
- Parameters without an implementation anymore (reflect, global, identifier/async of the space inference) are accepted but ignored. The health endpoints and the event history rerun stay removed since there is nothing backing them anymore.
- v3beta delegates to v4 directly since it was built on the v4-shaped signatures.
Why: Existing v3 clients (incl. generated ones) must keep working without changes - additive changes are backwards compatible in theory, but strictly typed or generated clients can break on them (e.g. a decimal durationInMs, renamed operation ids). Keeping a single implementation in v4 follows ADR-007.
Consequences:
- Changes to v4 must not leak into v3: new parameters need a v3 default in the shim, new response formats need a mapping. The OpenAPI document of v3 (/v3/api-docs/v3) can be compared with the reference spec to detect drift.
- Known remaining differences, all without effect on the JSON on the wire: the generic result schemas are named ResultWithExecutionDetails… instead of Result…, parameter defaults are documented explicitly, durationInMs is documented as number and the additive fields of shared models (e.g. transactionId, marker/nextMarker, additional type information) are present.
- GET /users/me/roles returns clientId as null since the client isn't tracked anymore.
ADR-021: v3 payload compatibility only in the v3 API layer¶
Status: Accepted
Decision: The services produce the v4 format only. All formatting which existed for backwards compatibility with v3 is moved out of the services into the v3 API layer:
- InstanceService returns instances with the plain UUID as @id (the persisted payload keeps the namespaced id - only the output changes), @type as stored (always a single value since JsonLdService.normalizeTypes() reduces it on ingestion) and the non-payload properties _space (always), _permissions and _alternative (on request; the alternative in its raw form) - same _ convention as the summary of outgoing links (common/constants/InstanceResponseProperties). _resolvedId of the outgoing link summary is always a UUID.
- The response flags singleAtType, backwardsCompatibleAlternatives and atIdAsUUID are removed from ResponseConfiguration since v4 doesn't need fallbacks anymore.
- api/v3/models/InstanceFormatV3 translates instances back into the v3 format: @id qualified with the instance namespace, .../meta/space (only if an instance namespace is configured), alternatives and permissions under the internal namespace (alternatives with qualified keys) and @type as a list (also nested). It is applied by v3 and v3beta on every response containing instances or query specifications (which are instances too). It deep-copies nested structures before changing them since they might be shared with the persisted payload.
- The type specification (GET/PUT /types/specification) is strongly typed in v4 (TypeSpecification: name, description, color, labelProperty, searchableProperties, embeddedOnly; the name is always the one of the type parameter). The KGv3-vocabulary format is produced/parsed by TypesV3, which TypesV3Beta uses as well.
- The SDKs (ADR-010) follow the v4 format: the flags are removed, Instance exposes space/permissions/alternative, the UUID is the @id itself (no extraction from a namespaced id anymore), @type is a single value and TypeSpecification uses the typed keys.
Why: The compatibility logic was spread over the services (with TODOs to make it configurable) and controlled by opt-out flags which every v4 client had to set to get the "new" behavior. Keeping it in the v3 layer gives v4 a single, clean format and keeps the v3 contract (ADR-020) in one place. It also fixed inconsistencies: atIdAsUUID didn't affect the payload's @id and dropped the space, alternatives weren't returned at all without the backwards compatible format and the incoming links were always formatted for v3.
Consequences:
- v4 responses are a breaking change compared to the previous (unreleased) v4 state and the SDK versions targeting it.
- New response properties added to instances in the services must be considered in InstanceFormatV3 (map or remove them for v3).
- Service methods returning instances are formatted for v4; other consumers (e.g. QueryService) inherit that format.
- The identifier lookup (getInstancesByIdentifiers) still maps plain UUIDs to the namespaced form since the identifiers are persisted namespaced - this is a property of the stored data, not of the API format.
ADR-022: Marker based pagination only in v4¶
Status: Accepted
Decision: The API v4 paginates exclusively with opaque markers: from is removed from all v4 endpoints (request and response) and every listing endpoint supports marker/nextMarker (before, only GET /instances did). Additionally, returnEmbedded is removed from v4.
- PaginationParam (size, returnTotalResults, marker) is the v4 parameter object. Offset based pagination is only exposed by older versions: v3 binds PaginationParamV3 (from/size/returnTotalResults, its frozen contract) and passes an OffsetPaginationParam to the services; v3beta binds PaginationParamV3 too, except for GET /instances which keeps accepting both (OffsetPaginationParam). If both a marker and an offset are given, the marker wins.
- Keyset pagination per endpoint - the marker is the (base64 encoded JSON) sort key of the last result of the page (MarkerUtils):
- instances: label + internal id (unchanged)
- incoming links: the composite id of the relation (the relations are now sorted by it - they weren't sorted at all before)
- types: the type name
- spaces and stored queries (paginated in memory): the space name / query id (MarkerUtils.paginate)
- query execution: the id of the root instance (root._id, the graph already sorted by it). The graph adapters receive a GraphQueryPage (offset, size, root id to start after) instead of the API pagination parameters and return the root id of the last result (GraphQueryResult). The count query is not restricted by the marker.
- nextMarker is only provided if the page is full (size results) - the following page can therefore still be empty, but clients can stop as soon as there is no nextMarker.
- from is only serialized if set (offset based pagination) and removed from the v4 OpenAPI schemas of the paginated results.
- Embedded instances are always returned by the services; v3/v3beta remove them in their API layer on returnEmbedded=false (InstanceFormatV3, following ADR-021).
- The global @ModelAttributes for ResponseConfiguration and PaginationParam in RestControllerAdvice are removed - they bound from/returnEmbedded for every controller. The defaults are defined by the parameter objects themselves.
Why: Offset pagination gets slower with every page (the skipped results still have to be evaluated) and is inconsistent if the data changes between the requests (results are skipped or returned twice). Markers continue directly after the last result. Offering both in v4 would keep the costly variant alive for new clients. returnEmbedded only removed parts of the payload on the way out, which clients can do themselves if needed.
Consequences:
- Breaking change for v4 clients (and the SDKs targeting v4, which are adapted: options/arguments take a marker instead of start, Page only follows nextMarker, returnEmbedded is removed).
- Random access to a page ("jump to page 5") is not possible in v4 anymore - only forward iteration. The total number of results is still available.
- Every new listing endpoint needs a deterministic sort order with a unique key to support markers.
- The listing parameters have to stay the same between the pages - a marker only encodes the position, not the query.
ADR-023: Incoming links in v4 grouped by property and type¶
Status: Accepted
Decision: GET /v4/instances/{id}/incomingLinks returns the incoming links grouped by the linking property and the (source) type of the relation - {"<property>": {"<type>": {"data": [...], "total", "size", "marker", "nextMarker"}}} (common/model/PaginatedData, wrapped in a ResultWithExecutionDetails) - instead of a flat page of full instances.
- property and type are optional filters (before: both required).
- The linking instances are returned as a summary with the same properties as the summary of outgoing links (@id, @type, _label, _space, _linkStatus; common/constants/OutgoingLinkSummary) plus _hasIncomingLinks (whether the linking instance is linked itself - the counterpart of _hasOutgoingLinks, one query per page). The linking instance always exists, so the status is resolved or restricted (not readable by the user - _label/_space/_hasIncomingLinks are null). The readability check is shared with the outgoing links (InstanceService.LinkReadability).
- Every group is paginated on its own with size (default 50, InstanceService.DEFAULT_INCOMING_LINKS_PAGE_SIZE). The groups and their totals come from one GROUP BY query, the pages from the existing keyset queries per group (one per group).
- The marker of a group additionally encodes its property and type. A request with a marker only returns that group - in the same response structure. A marker which doesn't match the given property/type is rejected (400).
- v3/v3beta keep their contract (required property/type, flat page of full instances, offset pagination) via InstanceService.getIncomingLinks, which they call directly since the v4 controller doesn't provide that shape anymore.
Why: Clients (e.g. an editor) want to show all incoming links of an instance at once without knowing upfront which properties and types link to it - the flat endpoint required one request per known property/type combination. Full payloads of the linking instances aren't needed for that (and were returned without checking whether the user may read the linking instance); a summary consistent with the outgoing links is enough and can be followed up by fetching individual instances. Paginating per group bounds the response size for heavily referenced instances while still giving an overview of all groups.
Consequences:
- Breaking change of the v4 endpoint; the SDKs return property -> type -> Page<LinkingInstance> where next() of a group's page only fetches that group.
- The number of queries grows with the number of groups (one page query per group) - acceptable since the number of distinct linking property/type combinations per instance is small.
- The v3 incoming links still return full payloads of the linking instances without a read check on them (unchanged behavior).
ADR-024: Strongly typed specifications and type information in v4¶
Status: Accepted
Decision: v4 doesn't use vocabulary IRIs (in particular https://core.kg.ebrains.eu/vocab/meta/) as keys for structural information anymore - this covers the specifications, the type information and the space information:
- Property specification (GET/PUT /properties and /propertiesForType): strongly typed (services/structure/models/PropertySpecification: name, nameForReverseLink, targetTypes, widget, readOnly, labelTooltip, required, orderNumber) instead of free-form JSON-LD. The schema is closed - other keys are dropped. widget, readOnly and labelTooltip are editor-specific but part of the schema since the editor depends on them. readOnly/required are booleans, orderNumber an integer - all fields are nullable so "not specified" is distinguishable from false/0 (relevant for the precedence of the type specific specification). In /v3 they keep their former IRIs (https://editor.kg.ebrains.eu/vocab/meta/property/{widget,readOnly,labelTooltip}, https://core.kg.ebrains.eu/vocab/meta/{required,orderNumber}).
- Type specification: already typed (ADR-021).
- Space specification: PUT /spaces/{space}/specification takes the same SpaceSpecification as body which GET returns (instead of query parameters); name/identifier are ignored (always the ones of the path).
- Type information (/types, /typesByName): TypeInformation and its nested models (Property, TargetType, SourceType, SpaceReference, SpaceTypeInformation, IncomingLink) use plain keys (identifier, name, occurrences, properties, targetTypes, ...). The properties don't merge the raw specification as dynamic fields anymore but expose the typed nameForReverseLink/widget/readOnly/labelTooltip/required/orderNumber (the type specific specification takes precedence over the global one; specified target types are merged into targetTypes).
- Space information (/spaces, /spaces/{space}): SpaceInformation is a typed model (identifier, name, permissions - the latter only on request) instead of a DynamicJson with vocabulary keys. Type in space (GET /spaces/{space}/types): TypeInSpace with space/type.
- The property specification is persisted as is (PropertySpecification as compressed JSON with the plain keys, persistence/converters/PropertySpecificationCompressor - the gzip/JSON logic is shared with PayloadCompressor via CompressedJsonConverter). PropertySpecification implements equals since Hibernate relies on it for the dirty checking of converted attributes. The vocabulary IRIs only exist in the v3 translation (which reads targetTypes leniently: single string, list, or references by @id / meta type).
- v3/v3beta keep their contract via translations in api/v3/models: PropertySpecificationV3 (JSON-LD), TypeInformationV3, SpaceInformationV3, TypeInSpaceV3 (records with the vocabulary IRIs as keys) and SpaceSpecificationV3.toSpaceSpecification (query parameters). PaginatedResult.map translates paginated results. The translations are static helpers and not controller methods, since the aspects intercept every public controller method.
Why: A typed contract gives the v4 clients (SDKs, editor) a documented schema and consistent keys. The vocabulary IRIs were a leftover of the JSON-LD based structure of the KG and made every client depend on the EBRAINS namespace.
Consequences:
- Breaking change of the v4 endpoints; the SDKs use PropertySpecification, typed SourceTypes and send the space specification as body.
- Unknown property specification keys (e.g. other editor hints) are no longer stored - also not via v3 - and no longer exposed in the type information (also in v3). Adding one requires a new typed field.
- No data migration: property specifications stored before (JSON-LD with qualified keys) are read as empty specifications and have to be uploaded again.
- The structural responses of v4 don't contain vocabulary keys anymore (instance payloads keep the keys of their data). Classes which still use vocabulary keys (e.g. ReducedUserInformation, common/model/Client, common/model/internal/spaces/Space) aren't exposed by v4.
ADR-025: Jackson data binding for the Java SDK models with plain keys¶
Status: Accepted
Decision: The models of the Java SDK (sdks/java) whose keys are plain (incl. @/_ prefixed ones, e.g. LinkingInstance) are records bound by Jackson (JsonUtil.convert) instead of hand-written fromJson/toJson methods. Request bodies (specifications) are serialized from the records directly. The shared JsonUtil.MAPPER ignores unknown properties, maps unknown enum values to the @JsonEnumDefaultValue constant (UNKNOWN) and binds missing/null lists as empty lists. The extra catch-all of TypeInformation/Property is removed.
- The JSON-LD payloads (JsonLdDocument, Instance) keep reading from the generic Map/List tree. SpaceInformation and TypeInSpace are bound as well since their endpoints use plain keys (ADR-024).
- SuggestionResult keeps a factory since it flattens the nested page of suggestions; its parts are bound.
- The Python SDK keeps its hand-written from_json methods (no binding library, see ADR-010).
Why: The hand-written parsing was chosen since the keys were vocabulary IRIs (and the specifications free-form). With the plain keys of v4 (ADR-024) it was boilerplate only, which had to be kept in sync with the record components manually.
Consequences:
- Breaking change of the Java SDK: the fromJson/toJson methods of the bound models and extra are gone.
- Jackson stays on 2.17 - @JsonAnySetter on record components (2.18) isn't needed without extra.
ADR-026: JSON-Schema validation schemas per type¶
Status: Accepted (amended by ADR-053: $refs can point to other stored schemas by their $id)
Decision: A type can carry 0..n named JSON-Schema documents (type_validation_schema: type_id, name - unique per type, json_schema as gzip compressed JSON in a BYTEA column like the instance payloads - persistence/converters/ValidationSchemaCompressor on top of CompressedJsonConverter -, removed with the type). They are managed via /v4/types/validationSchemas and applied on demand via GET /v4/instances/{id}/validation (services/validation/ValidationSchemaService). Validation uses com.networknt:json-schema-validator 3.x (the line built on Jackson 3, matching Spring Boot 4).
- The schema is checked against the meta-schema of its dialect (draft 4 to 2020-12, 2020-12 if $schema is absent) and compiled when it is stored - invalid documents are rejected with 400.
- Only the meta-schemas (bundled on the classpath of the library) can be loaded. Any other $ref to an external document is rejected - neither remote IRIs (SSRF) nor classpath: resources of the server can be referenced. Schemas have to be self-contained ($defs / local $refs).
- The validated document is the instance as returned by GET /instances/{id} with the default response configuration (the payload with fully qualified property IRIs, plain UUID as @id, @type and _space) - what clients see is what the schema is written against.
- Managing the schemas requires the dedicated, global-only functionality DEFINE_VALIDATION_SCHEMAS (PermissionService.canDefineValidationSchemas) - separate from DEFINE_TYPES_AND_PROPERTIES, so the right to define the expectations on instances can be granted without the right to change the structure of types and properties (and vice versa). Only the global ADMIN role grants it (it grants every functionality). Validating requires read access to the instance only.
Why: Schemas allow clients (e.g. the editor or ingestion pipelines) to check instances against expectations of a type without making the primary store reject non-conforming payloads. JSON-Schema is the established, tool-supported format for such constraints on JSON documents. Compressing the documents keeps the table small (schemas with many property IRIs compress well), consistent with the payloads and property specifications; the key order of the document is kept.
Consequences:
- Validation is advisory: instance writes are not rejected. Since ADR-027, writes run the validation and store the findings.
- Not available in /v3//v3beta.
- Schemas are compiled per validation request (no cache); fine for single instance validation, to be revisited for bulk validation.
ADR-027: Validation of instances on write, findings stored next to the instance¶
Status: Accepted (amended by ADR-028: the validation on write can be skipped)
Decision: Every insertion and update of an instance (POST /instances, POST/PUT/PATCH /instances/{id} - all going through InstanceService.handleContribution) validates the reconciled payload against all validation schemas of its type (ADR-026) and stores the findings in instance_validation_result: one row per instance and schema with validation_schema_id (the name is the one of the schema), executed_at, status (PASSED / FAILED) and the errors (instance location, schema location, keyword, message - gzip compressed JSON like the payloads).
- The validated document is the same as for the on demand validation: the reconciled in progress payload as exposed by GET /instances/{id} (@id, @type, _space). Since it's the reconciled payload, a partial update (PATCH) is validated together with the untouched properties and the other contributions.
- The findings of an instance are replaced on every write which stores the contribution (also if the reconciled payload didn't change, e.g. a repeated PUT without skipIfUnchanged) - so they reflect the schemas at the time of the last write. A type without schemas leaves no findings (also removing the ones of a previous type).
- The validation runs synchronously within the transaction of the write and never rejects it.
- The findings are removed with the instance and with the schema (ON DELETE CASCADE). Changing a schema does not re-validate existing instances.
- services/validation/InstanceValidationService holds the schema registry and the validation without permission checks (the callers ensure the access) and doesn't depend on InstanceService - it's used both by InstanceService (on write) and ValidationSchemaService (on demand), which avoids a dependency cycle.
Why: Persisted findings allow to report (and later query/filter) the compliance of the data without re-running the validation on read. Validating on write keeps them up to date with the payload without an additional process.
Consequences:
- Every write pays for the validation (compilation of the schemas of the type and the validation itself) - negligible for small schemas, to be revisited (e.g. caching compiled schemas) for large ones or bulk ingestion.
- The admin reconciliation of instances (reconcileInstances) doesn't validate - only writes via the API do.
- Moving an instance (which changes _space) doesn't re-validate.
ADR-028: Optional validation on write, bulk validation by global admins¶
Status: Accepted (amended by ADR-076: the bulk validation runs asynchronously)
Decision: The validation on write (ADR-027) can be skipped per request with validate=false on POST /instances, POST/PUT/PATCH /instances/{id} (default true, so existing clients keep the behavior; /v3//v3beta always validate). Skipping removes the stored findings of the instance (if the contribution is stored at all - see skipIfUnchanged), since they wouldn't reflect the new payload anymore: "no findings" means "not validated (yet)", never "stale".
The findings can be (re)created in bulk with POST /v4/instances/validation?space= (all spaces if space is not set), which validates the in progress payloads of all instances against the schemas of their types and replaces their findings. It returns a summary {instances, validated, failed}.
- Requires the dedicated global-only functionality VALIDATE_INSTANCES (PermissionService.canValidateInstances), which only the global ADMIN role grants. With a space, the space is resolved via SpacesService.getSpaceForMgmt (like the inference endpoints).
- Runs synchronously in batches of 1000 instance ids (keyset pagination by the internal id), each batch in its own transaction (InstanceValidationService.validateAndStoreBatch) - one DELETE of the findings per batch, the schemas of a type are loaded once per batch. Compiled schemas are reused across the batches of a run (InstanceValidationService.CompiledSchemas, by schema id - changes to a schema during the run are not picked up).
- Only one bulk validation runs at a time (in-process lock, 409 otherwise). Unlike the reconciliation it doesn't take the ReindexLock since it doesn't change payloads.
Why: Bulk ingestion shouldn't pay for the validation of every write, and schemas which are attached or changed after the data was written (ADR-027: changing a schema doesn't re-validate) need a way to bring the findings up to date. Validating all instances is expensive, hence restricted to global administrators.
Consequences:
- A write with validate=false leaves the instance without findings until the next validating write or bulk validation.
- A concurrent write to an instance of the batch being validated can conflict on the unique constraint of the findings - the batch (or the write) fails and has to be repeated.
- The run is synchronous - long running for large databases (the HTTP request stays open). To be revisited (async job with status) if needed.
ADR-029: Named scopes per type, evaluated on demand in the primary store¶
Status: Accepted (invitations without scope names: see ADR-044)
Decision: A type can carry 0..n named scopes (type_scope: type_id, name - unique per type, specification as gzip compressed JSON, removed with the type). A scope describes the instances related to an instance of the type for a specific consumer/use case (e.g. the subgraph consolidated for a search index). Its specification (common/model/scope/ScopeSpecification) is a fixed-depth tree of steps; each step has a path of one or more hops along a reference property (@id, reverse for incoming links, optional typeFilter) and continues with nested steps from the instances reached by its last hop. Repetitions are stated explicitly - there is no recursion.
- Unlike a query, hops are never shortcut: every instance reached by a hop is part of the scope (also the intermediate ones of a multi-hop path). A target which doesn't match the type filter is neither part of the scope nor traversed further. Unresolved links are ignored.
- Scopes are managed via /v4/types/scopes and require the dedicated global-only functionality DEFINE_SCOPES (PermissionService.canDefineScopes, only granted by the global ADMIN role). The properties are not checked against the known structure - a property without relations simply reaches nothing.
- services/scope/ScopeEvaluationService evaluates a scope for an instance without permission checks: one SQL query per hop over current_relation/released_relation (joined with property and the stage's instance table for the type filter), for all instances of the level at once. The result is the full tree (ScopeElement: @id, @type, _space, _label, _children) mirroring the steps - an instance reached by multiple steps appears multiple times.
- GET /v4/instances/{id}/scope?stage=&name= (services/scope/ScopeService) requires read access to the root instance and reduces the tree to what the user can read (space/instance permissions or invitations): an unreadable instance is removed together with the instances reached through it. Without name, the combination of all scopes of the type is evaluated. returnPermissions adds the user's functionalities per instance (_permissions), returnReleaseStatus the release status of the instance itself (_releaseStatus, top instance only - not aggregated over its release tree; resolved in one query for the whole tree). (Originally GET /v4/instances/{id}/scopes/{name} - the name became an optional query parameter.)
- Invitations apply to 0..n named scopes of the invited instance's type (invitation_scope, PUT /v4/instances/{id}/invitedUsers/{userId}?scope=; without names: the instance only, ADR-044); the invitation covers the instance plus the combination of the (unreduced, in progress) scopes. Unknown scope names are rejected on invitation; names which disappear later are ignored. The scopes are evaluated when the invitations of a user are loaded (InvitationsInternal.getAllInvitationsForUserId) and cached with them (userInvitations cache: evicted per user on invite/revoke, completely on changes of scope definitions and hourly).
- The previous, never completed scope mechanism is removed: the materialized scope_relation table, the "scope relevant" spaces (space.scope_relevant, DEFINE_SCOPE_RELEVANT_SPACE, scopeRelevant of the /v4 space specification) and PUT /v4/instances/{id}/invitationScope. /v3//v3beta keep their contract (ADR-020): scopeRelevant is accepted but ignored (returned as false). The unnamed scope of v3 is mapped to the combination of all named scopes of the instance's type (ScopeService.getScopeForInstance without name: the root with the children of all scope trees, sorted by scope name; ScopeElementV3 with plain keys and optional permissions per instance - resolved by ScopeService like in v4; always restricted - applyRestrictions is ignored). Invitations created via v3 apply to all scopes of the type at the time of the invitation; PUT /instances/{id}/invitationScope (requires UPDATE_INVITATIONS) re-applies the scopes currently defined for the type to all invitations of the instance.
Why: Consumers need the closely related resources of an instance (e.g. for search consolidation or invitations) defined per type and per use case rather than per space. The relations needed for the traversal are already stored in PostgreSQL (with property and resolved target), so the evaluation works with every graph profile (incl. nograph) and is always consistent with the primary store. A fixed-depth specification bounds the number of queries by the size of the specification. Evaluating on demand avoids the invalidation of materialized scopes along every path on each write - materialization is to be considered once performance requires it. The unreduced tree is independent of the user and could be cached later and reduced per request.
Consequences:
- Every evaluation costs one query per hop of the specification; large fan-outs (e.g. incoming links of a popular instance) produce large trees. New indexes on (resolved_target_id, property_id) support the reverse direction.
- Cached invitations don't reflect changes of the graph (new or removed links) until the cache entry is evicted (at most an hour).
- Invitations grant READ (in progress only) on the invited instance and every instance in its invitation scopes - checked in PermissionService.hasPermission, so they apply to the single instance endpoints (e.g. GET /instances/{id}) as well as to listings, queries, link summaries and scopes. They never grant other functionalities (write, release, ...) nor access to the released stage.
- The release status of a "release tree" (ReleaseTreeScope.CHILDREN_ONLY*), which was based on the removed scope, remains unimplemented. (Implemented on top of the named scopes by ADR-030.)
ADR-030: Release status of the release tree based on the named scopes¶
Status: Accepted
Decision: GET /instances/{id}/release/status and POST /instancesByIds/release/status evaluate releaseTreeScope=CHILDREN_ONLY / CHILDREN_ONLY_RESTRICTED on the named scopes of the instance's type (ADR-029, ScopeService.getReleaseStatusOfScope): by default the combination of all scopes of the type (like the unnamed v3 scope), in /v4 optionally restricted to one of them (?scope=name, unknown names → 404; ignored for TOP_INSTANCE_ONLY). /v3//v3beta always use the combination.
- The scope is evaluated in progress; the instance itself is not part of the tree (also if it is reached again through a cycle). The status is the "worst" of the instances in the tree: UNRELEASED if any is unreleased, else HAS_CHANGED if any has changed, else RELEASED - also if the tree is empty (nothing left to release).
- Both require read access to the instance. CHILDREN_ONLY considers the full tree regardless of the user's permissions; CHILDREN_ONLY_RESTRICTED reduces it to what the user can read first (like GET /instances/{id}/scope - an unreadable instance is removed together with the instances reached through it).
Why: The release tree was based on the removed materialized scope (ADR-029). The named scopes describe exactly the closely related instances of an instance, and the combination of all of them is already the mapping of the unnamed scope for v3 - the release tree follows the same rule, so clients (e.g. the Editor) keep working without knowing about named scopes. Restricting to a named scope lets a consumer check the release state of the subgraph it actually consumes (e.g. a search index).
Consequences:
- Every request costs a scope evaluation (one query per hop, ADR-029) plus one query for the release statuses - the bulk variant does this per instance.
- CHILDREN_ONLY reveals the aggregated status of instances the user might not be able to read (one value, no ids) - as before the scope rework.
ADR-031: Compliance score per validation result¶
Status: Accepted
Decision: Every validation result of an instance against a schema (on demand, on write and in bulk - ADR-026/027/028) carries a compliance score: the share of the properties declared on the top level of the schema which the instance fulfills, in percent (0-100). It's computed in services/validation/ComplianceScore from the schema document and the violations reported by the validator, stored in instance_validation_result.compliance (DOUBLE PRECISION, nullable) and exposed as compliance of every schema result (GET /instances/{id}/validation, _validation of returnValidationResults).
- The declared properties are the keys of properties and the names in required of the schema's root.
- A violation is attributed to the property named by the first element of its instance location (a violation within the property's value, at any depth) or - for violations on the instance itself - to the property named by the validator (Error.getProperty(), e.g. a missing required property). A declared property is fulfilled if no violation is attributed to it; several violations within one property count once. Absent optional properties are fulfilled.
- Violations which can't be attributed to a declared property (additionalProperties, minProperties, top level combinators, ...) don't reduce the score - they're reflected by valid only. Properties declared in nested combinators (allOf, $ref, if/then) are not part of the denominator. A schema without declared properties scores 100 if the instance is valid, 0 otherwise.
- valid implies 100; 100 doesn't imply valid.
Why: valid is too coarse to report on the quality of data: an instance missing one of twenty properties is as "invalid" as an empty one. Counting the passed/failed JSON-Schema assertions was rejected since its denominator depends on the data (absent properties skip the assertions of their subschema - emptier instances would score better - and arrays multiply the item assertions). The declared properties give a fixed denominator per schema which matches how schema authors think about expectations, and the score can be derived from the violations which are reported anyway (no verbose output of the validator required). Storing it allows to aggregate (e.g. the average per type, space or schema) without re-validating.
Consequences:
- Results stored before this change have no score (null) until the instance is re-validated (next validating write or bulk validation).
- Schemas which declare their properties only within combinators or $refs get a score based on validity only - schema authors who want a meaningful score declare the properties on the root.
- All declared properties weigh the same.
ADR-032: Contributors of an instance require a dedicated functionality¶
Status: Accepted
Decision: The users who have contributed to an instance (_contributors of returnContributors: username and name) are only exposed to users with the functionality READ_CONTRIBUTORS for the instance. It is a space-level functionality (GLOBAL_AND_SPACE) granted by the EDITOR role (and therefore OWNER and ADMIN). Instances the user lacks it for are returned without _contributors - the request doesn't fail, so lists mixing spaces with different roles stay usable. The permission is evaluated per instance before the contributors are loaded, so no contributions are queried for instances whose contributors aren't readable. Since it's part of the INSTANCE group, it's listed in the _permissions of an instance.
Why: Contributors are personal data (usernames and names) and not needed to consume or review the data. Readers of released data (CONSUMER, public spaces) and reviewers (incl. invited users) shouldn't be able to enumerate who works on which instances. Editors work on the instances together and need to know who else contributed, e.g. to resolve conflicting contributions. A dedicated functionality (instead of reusing WRITE) keeps the permission explicit and allows to grant it independently in the future.
Consequences:
- Invitations (ADR-029) don't grant READ_CONTRIBUTORS - invited reviewers don't see the contributors.
- Clients have to cope with _contributors being absent even though returnContributors was requested.
ADR-033: Favorite instances per user¶
Status: Accepted
Decision: Users can flag instances as favorites (PUT/DELETE /instances/{id}/favorite, /v4 only) and restrict GET /instances to them (favoritesOnly=true). A favorite is a row in favorite_instance (user_id, instance_id, created_at) referencing marmot_user.id and the generic instance.id - not one of its stages - with ON DELETE CASCADE on both.
- Flagging requires read access to the instance in any stage (READ or READ_RELEASED, incl. invitations) and is idempotent. Unflagging requires no permission on the instance (a user can remove favorites they've lost access to) and is idempotent too.
- favoritesOnly is an additional filter (EXISTS subquery) combined with all others (stage, type, space, search) - the space restriction of the user still applies, so favorites the user can't read (anymore) are not listed. Requests without a user (e.g. client-only tokens) have no favorites: flagging fails with 401, favoritesOnly lists nothing.
Why: A favorite expresses the interest of a user in an entity, not in a specific state of it - attaching it to instance keeps it across releases/unreleases and lets it be used in both stages. A dedicated table (instead of e.g. a property in the payload) keeps it personal, out of the contributions and the graph, and lets the database clean it up when the instance or the user is removed. Filtering in the existing listing query avoids a separate endpoint and keeps pagination, sorting and permission handling identical.
Consequences:
- Whether an instance is a favorite of the user is exposed on request (returnFavorite) as _isFavorite on all v4 endpoints returning instances - like the other response options, it's opt-in to avoid the additional (bulk) query when it's not needed.
- Not available in /v3//v3beta.
- Favorites survive the loss of read access; they reappear in the listing when access is regained.
ADR-034: Instances the user has contributed to¶
Status: Accepted
Decision: GET /instances can be restricted to the instances the current user has contributed to (withContribution=true, /v4 only), and whether the user has contributed to an instance is exposed on request (returnHasContributed) as _hasContributed on all v4 endpoints returning instances. Both are derived from the existing contribution table (a row per instance and contributing user) - nothing new is stored.
- withContribution is an additional filter (EXISTS subquery on contribution) combined with all others (stage, type, space, search, favoritesOnly) - like favoritesOnly (ADR-033), the space restriction of the user still applies. Requests without a user (e.g. client-only tokens) have no contributions: the filter lists nothing, _hasContributed is false.
- _hasContributed only reveals the user's own contributions, so - unlike _contributors (ADR-032) - it doesn't require READ_CONTRIBUTORS.
Why: "My instances" is a common entry point for editors. The contribution table already records exactly this, keyed by the same id as instance.id - deriving it keeps it consistent with the contributions by construction and avoids a second source of truth. Filtering in the existing listing query keeps pagination, sorting and permission handling identical (same reasoning as ADR-033).
Consequences:
- Contributions belong to the IN_PROGRESS stage. In the RELEASED stage, the filter/flag reflects the user's current contributions, not those at the time of the release.
- Not available in /v3//v3beta.
ADR-035: Sorting of listed instances¶
Status: Accepted - the query strategy, the indexes and the handling of missing values are refined by ADR-036
Decision: GET /instances (/v4 only) can be sorted by sortBy = NAME (default, the label of the instance), TYPE (the label of the type, its name if it has no label) or LAST_MODIFICATION (instance.last_update_at in the IN_PROGRESS stage, instance.last_release_at in the RELEASED stage) and sortDirection = ASC (default) / DESC.
- Text attributes are compared case-insensitively. Instances without a value for an attribute are listed last in both directions (NULLS LAST).
- Ties are broken by the name (for TYPE) and the internal instance id - always in the requested direction - so the order is total and stable.
- The marker based pagination (ADR-022) stays keyset based: the marker carries the sorting and the values of the sort keys of the last instance of the page. A marker used with a different sorting is rejected with 400. Markers issued before this change (without sorting) are treated as NAME / ASC.
- The ordering is defined once (in the id query of InstanceQueries); the instances loaded by id are brought into the order of the ids instead of re-applying the ORDER BY.
Why: Clients (e.g. the editor UI) need to show the most recently modified instances first or to group lists by type. Sorting in the existing listing query keeps filters, permission handling and marker pagination identical. Keyset pagination (instead of an offset) keeps pages consistent while instances are created or modified, which is why the marker has to encode the sort key values. Two parameters (instead of a combined sort=-name) match the style of the other request parameters and are self-explaining in the OpenAPI spec.
Consequences:
- ~~There are no dedicated indexes for the sort keys~~ - see ADR-036.
- Instances modified while paginating through a list sorted by LAST_MODIFICATION can move to a page which has already been read (or appear twice) - inherent to sorting by a mutable attribute.
- Not available in /v3//v3beta (they keep the name ascending order).
ADR-036: Denormalized and indexed sort keys for the instance listing¶
Status: Accepted
Decision: The sort keys of ADR-035 are denormalized onto the stage tables (current_instance, released_instance) and every sorting is served by one btree index per stage table, for both directions:
- sort_name = lower(label), '' without (or with an empty) label - index (sort_name, instance_id)
- sort_type = lower(coalesce(type.label, type.type_name)), '' without type - index (sort_type, sort_name, instance_id)
- sort_last_modification = instance.last_update_at (current) / instance.last_release_at (released) - index (sort_last_modification, instance_id)
The columns are maintained by triggers only (V38): on insert/update of the stage row (label, type), on updates of instance (timestamps) and on renames of a type (label, type name). They're mapped read-only (insertable/updatable = false); the timestamp as LocalDateTime, so it's compared as timestamp (a timestamptz parameter would cast the column and bypass the index).
The listing queries the instances with and without a value for the leading key separately (with value first - so they're last in both directions) and continues after the marker with a row value comparison - (k1, k2, id) > (?, ?, ?) (Hibernate's SqmTuple, JPA has no row values). Each query is therefore a single range of the index: forward for ASC, backward for DESC, LIMIT stops the scan after the page. The offset based pagination of older API versions spans the two segments with an additional count if the offset lies beyond the first.
Why: The sort keys of TYPE and LAST_MODIFICATION live in other tables (type, instance) - an index on them can't provide the order of a query on the stage table, so every page required to sort all matching rows. NULLS LAST in both directions and the expanded keyset condition (k1 > m1 OR (k1 = m1 AND k2 > m2) OR k1 IS NULL ...) can't be served by a single index range either. Measured on 500k instances, a deep page sorted by last modification went from ~1.1 s (parallel seq scan + sort) to ~1.5 ms (index only scan). Triggers follow the existing denormalization of the space (readonly_space_id, V23) and keep the keys consistent independently of the write path.
Consequences:
- Within a type (secondary key of TYPE), instances without a name are sorted as the empty string - first ascending, last descending. Empty labels count as missing names.
- Writes maintain three more indexes per stage table; an update of instance.last_update_at (every contribution) updates the current stage row too. Renaming a type updates all of its instances.
- Additional filters (type, space, search, favorites, contributions) are evaluated while scanning the sort index - very selective filters on large tables can scan more of the index before a page is filled.
- The sort keys reflect the database state - entities created in the running transaction don't have them before being reloaded.
ADR-037: Query evaluation in PostgreSQL for the nograph profile¶
Status: Accepted
Decision: The nograph profile (graph/nograph, NoGraph implements GraphDB) no longer returns empty query results but evaluates queries directly on the primary store. There is no additional profile - without a graph database, PostgreSQL is the query engine:
- upsert, delete and reindex remain no-ops - there's nothing to keep in sync. GraphIndexingListener and GraphVocabulary are still not created for nograph.
- SQL selects, traverses and restricts access; Java reads and filters the values. Payloads are stored gzip compressed (PayloadCompressor) and can't be inspected by SQL. PostgresGraphStoreInternal therefore only selects instances (root type via type_id, sorted by UUID for the marker), resolves references (by identifier of the stage, the UUID as fallback - like GraphSourceInternal) and finds the instances linking to others (via the relation tables, by identifier or UUID - like findInstancesLinkingTo). Every instance is loaded through the access restriction of QueryService (readonly_space_id in the readable spaces or the instance in the invitations) - an instance the user can't read is never loaded and is treated like a missing node, on the root level as well as on every hop.
- QueryEvaluatorInternal splits each loaded payload into nodes like Neo4JPayloadSplitterInternal (GraphInstance/GraphNode): embedded objects are nodes with the virtual id <uuid>#<n>, links and embedded objects are not part of the node's values. Embedded objects inherit the access of their instance. A reverse hop from an embedded object leads to its parent, a reverse hop from an instance to the nodes (instances or their embedded objects) linking to it.
- The root instances are processed in batches (100-1000, depending on the page size): first, all instances needed by the query are loaded hop by hop for the whole batch (one SQL statement per hop and level, not per instance); then each root is evaluated in memory. Batches are fetched until the page is full, since filters and required items can only be evaluated after loading.
- The semantics follow QueryToCypherInternal: on the root level, a failing filter or a missing required item excludes the root; on nested levels, a failing filter removes the value, a missing required item the object; empty values, lists and objects are omitted; a filter without value doesn't restrict; a list matches if one of its elements matches; the operations only apply to strings; REGEX has to match the whole value. Where the Cypher translation is incomplete, the intended semantics are implemented: filters and required on leaves reached by a multi-hop path are evaluated (Cypher ignores them), the values of such leaves are flattened into one list (Cypher returns nested lists for list values).
- The total number of results is counted by SQL if the query has no filter or required item on the root level; otherwise all root candidates are evaluated, limited to these items.
Why: A separate graph database duplicates the data, has to be synchronized on every write (ADR-017), can be out of sync after failures and needs a reindex after structural changes (ADR-015, ADR-016). Evaluating in PostgreSQL makes queries available in every deployment, always consistent with the primary store and without operating a second database. Making it the behavior of nograph rather than a profile of its own keeps the configuration unchanged: nograph already means "no separate graph database", and an empty query result was never a useful behavior of it. The access restriction is the same tuple as for Neo4j and applied to every loaded instance, so permissions are reflected identically. The traversal follows the approach already used for scopes (ADR-029). Performance is the explicit trade-off: as long as values are not queryable by SQL, every reached instance is decompressed.
Consequences:
- Query cost grows with the number of root candidates and reached instances rather than with the result size: filters on the root level and total counts with such filters load and decompress every instance of the root type (in batches - memory is bounded by the batch and its reached instances).
- Reverse hops rely on the relation tables: links from embedded objects whose type has no registered property (e.g. embedded objects without @type) aren't found in reverse direction.
- The root type is matched against the (single) normalized type of the instance (type_id), type filters against the @type of the reached node.
- If the performance isn't sufficient, values can be made queryable by SQL (e.g. an uncompressed jsonb projection or a value index table maintained on write) to push root filters and counts into SQL - the adapter's structure stays the same.
- Deployments with nograph (the default) now return query results instead of empty ones - including for stored queries used by clients.
- NoGraphIntegrationTest covers the same scenarios as QueryServiceNeo4jIntegrationTest plus embedded objects, type filters and nested access restrictions.
ADR-038: Strongly typed queries, stored independently of the instances¶
Status: Accepted (supersedes ADR-012)
Decision: Queries in v4 are strongly typed and stored in their own table instead of as instances.
- Format (common/model/query/QuerySpecification, also the model the graph adapters evaluate): plain keys, no JSON-LD and no query vocabulary - meta (type, name, description) and structure items with propertyName (the key in the results, a plain string - defaults to the last property of the path), path (a property as string, an object {property, reverse, typeFilter} or a list of them; typeFilter is a list of type IRIs), nested structure, required, sort, filter (op, parameter, value) and singleValue. Unknown keys are dropped. The only namespaced values are the IRIs of the data (root type, properties, type filters). responseVocab is not part of the format: result keys are the property names as given.
- Storage (stored_query, persistence/entities/storedQuery/StoredQuery, migration V39): the query id (UUID) as primary key, the space (by name), the specification as gzip compressed JSON (QuerySpecificationCompressor) and the root type, name and description denormalized for listing/search. response_vocab keeps the response vocabulary of queries saved via v3 - for the v3 format only. The former query side table (FK to instance) is dropped.
- Permissions (QueryService): a stored query belongs to a space, and the space-level functionalities apply as they did for query instances - READ (in progress) to fetch, list and execute it, CREATE to store a new one, WRITE to update, DELETE to remove it. Storing a query in a space which doesn't exist yet registers the space (SpacesService.getOrCreateSpace, requires MANAGE_SPACE - like for instances). The space is returned as myspace for the private space of the user.
- Endpoints (/v4/queries): PUT /{id} and POST take a QuerySpecification; GET /{id}, PUT /{id} and the listing return StoredQuerySpecification (id, space, meta, structure). The listing filters by readable spaces, root type and search term (name/description, case-insensitive) in SQL and paginates by id (marker as before).
- v3/v3beta keep their contract via api/v3/models/QuerySpecificationV3: incoming JSON-LD queries (e.g. from the query builder) are normalized, the query vocabulary is stripped and responseVocab is removed from the property names and stored with the query (v3 saves via QueryService directly since v4 has no such parameter; saves via v4 keep the stored value and never expose it); stored queries are returned as instance-shaped JSON-LD (@type …/meta/Query, _space, query vocabulary keys, property names qualified with the stored responseVocab - https://schema.hbp.eu/myQuery/ for queries without one, e.g. created via v4) and formatted by InstanceFormatV3 as before. Query results are unchanged (they were already keyed by the stripped property names).
- The SDKs use the typed format (Java: QuerySpecification/StoredQuery records; Python: plain-key dicts and StoredQuery).
Why: A query is a definition, not data: storing it as an instance made it appear in the instance listings, the types/properties structure, contributions and (with a graph DB) the graph, subjected it to release semantics it never used, and tied its format to the JSON-LD vocabulary of the KG (the same reason as ADR-024). A dedicated table with a typed specification gives clients a documented schema, lets the listing filter and search in SQL instead of loading every query instance, and removes the special-casing (META_QUERY_TYPE tagging, the side table, the pre-normalization root-type extraction of ADR-012). Reusing the space-level functionalities keeps the permission model unchanged for users.
Consequences:
- Breaking change of the v4 query endpoints and the SDKs targeting them.
- No data migration (like ADR-024): queries stored as instances before remain as (plain) instances of type …/meta/Query and are no longer listed or executable as stored queries - they have to be saved again. The orphaned instances can be removed like any other instance.
- A query saved via v3 is returned by v3 with the response vocabulary it was saved with. A query saved via v3 without any responseVocab is returned with the default one (its property names are full IRIs and therefore not affected). Property names which aren't in the response vocabulary stay full IRIs (in v4 and in the results).
- Unknown query keys (e.g. additional meta fields of the query builder) are not stored - adding one requires a typed field.
- Queries sent to v3 in fully expanded or compacted JSON-LD form can now also be saved (the limitation of ADR-012/015 is gone since saving normalizes like the ad-hoc execution).
- Stored queries are not part of a space's content for DELETE /spaces/{space}/specification - removing a space doesn't affect its queries (they're addressed by space name).
ADR-039: Query options restored after the typed query format, moving stored queries¶
Status: Accepted - the Cypher details (WITH/collect chain, grouping keys, carrying the relation aliases for ensureOrder) are replaced by ADR-064, the semantics are unchanged
Decision: Options of the original KG query format which got lost (or were accepted without effect) on the way to the typed format (ADR-038) are restored, and stored queries can be moved between spaces:
- ensureOrder is a field of the structure items again (also translated by QuerySpecificationV3 in both directions and part of the Java SDK record). The reached instances are returned in the order of the links in the payload. nograph follows the payload order on forward hops anyhow (reverse hops have no inherent order). neo4j sorts by the orderNumber of the forward relations of the item (WITH * ORDER BY r.orderNumber) right before the targets are collected; to keep them in scope, the relation aliases are carried by the WITH statements of the item's substructure (placed after the target alias, so they're no grouping key of the item's own collect).
- singleValue (FIRST/CONCAT) is evaluated (it was stored but ignored by both adapters): QuerySpecification.SingleItemStrategy#apply reduces a list to its first element or joins plain values with ", " (lists of objects are kept). nograph applies it while evaluating (before required is checked), neo4j on the mapped results (QuerySpecification#applySingleValues, with the compacted query since the result keys are derived from it).
- Case-insensitive filters (as in the KG, which compared lower-cased values): EQUALS, CONTAINS, STARTS_WITH and ENDS_WITH compare the lower-cased value and filter value (toLowerCase(Locale.ROOT) / Cypher toLower), REGEX is matched case-insensitively (Pattern.CASE_INSENSITIVE | UNICODE_CASE / (?iu) prefix in Cypher - the pattern itself isn't lower-cased, so character classes like \S keep their meaning). In Cypher, the type checks are done by CASE (IS :: STRING, IS :: LIST<ANY>) since AND isn't guaranteed to short-circuit and toLower fails on non-strings.
- Deduplication (the KG's UNIQUE unless ensureOrder was set): the values of an item - the values of a leaf reached by a path with hops as well as the objects of a nested structure - are distinct unless the item has ensureOrder. Values are compared by value (as the KG did on the projections): two reached instances with identical results are returned once. nograph removes duplicates while evaluating (LinkedHashSet, first occurrence wins), neo4j uses collect(DISTINCT …). Direct values of a node (single-element path) are returned as stored.
- Grouping of the Cypher translation (bug fix): the targets of an item are collected per combination of the aliases in scope before the item (QueryToCypherInternal.Collect), no longer per alias up to the target. Before, the intermediate nodes of a path with two or more hops became grouping keys, so a root was returned (and counted) once per intermediate node.
- Moving a stored query: PUT /v4/queries/{queryId}/spaces/{space} (QueryService.moveQuery) requires WRITE in the current and in the target space - like moving an instance - and registers the target space if needed. Since queries were instances before ADR-038, they could be moved via the instance endpoint; this restores the capability. Saving (PUT /{queryId}?space=) still rejects a different space with a conflict.
Why: The query builder sends ensureOrder (e.g. for ordered authors); dropping it silently changed the semantics of stored queries and lost it on every save via v3. singleValue was documented and accepted, but had no effect. Case-insensitive filters and distinct values are what queries written for the KG expect - e.g. a search parameter typed by a user, or a person reached via several datasets. Moving queries between spaces (e.g. from the private space to a shared one) was possible as long as they were instances.
Consequences:
- Not restored (still differences to the original KG query format): sort is accepted but not evaluated (results are ordered by the root id for the marker pagination - sorting by values would need a different marker), structure items without path (merges), groupBy/groupedInstances, the instance filters on the root level (ID, TYPE, MBB) and custom directives (unknown keys, see ADR-038).
- Behavior change for existing queries: filters match more values than before (case-insensitive), and lists of values/objects can get shorter (duplicates removed). Queries relying on duplicates need ensureOrder.
- The case-sensitive comparison of ADR-037 ("the semantics follow QueryToCypherInternal") is replaced for both adapters.
- ensureOrder is not meaningful for reverse hops - the order of incoming links is undefined.
ADR-040: Embedded instances are reflected in the type structure like standalone instances¶
Status: Accepted
Decision: A nested object with an @type but without @id (an embedded instance, e.g. the translations of a LanguageExample) is represented in the type information the same way as if it was a standalone, linked instance:
- Ownership: its properties belong to its own type (Translation), not to the hosting type. DynamicJson.walk now passes the owner to the visitor - the closest enclosing map with an @type (or the root). Untyped nested maps are transparent: their properties keep belonging to the closest typed owner. Before, the properties of nested maps were attributed to the grandparent map, which flattened them onto the hosting type (or lost the type of an untyped one).
- Relation: the hosting property (translations) is a property of the hosting type with the embedded type as target type. Maps in lists are visited like a single map value, so every embedded instance (and every reference in a list) is a property occurrence. The occurrence stores the embedded type (current_property_occurrence.embedded_type_id, copied to released_property_occurrence); a change of the source or embedded type at the same path updates the occurrence in place.
- Summary: current_embedded_type_summary (type, space, property, embedded type, count) is maintained by triggers on current_property_occurrence and on space changes of instance, and recomputed by refresh_summary_tables(). StructureService.getTargetTypes merges it into the target types of the linked instances, with the space of the hosting instance as target space. StructureService.getIncomingLinks merges it into the incoming links of the embedded type, with the hosting type as source type - a reverse hop along the hosting property leads from an embedded object to its parent.
Why: Embedded structures are instances without identity - clients (e.g. the editor or a graph view of the types) need their structure like the one of any other type, and the relation to the hosting type, instead of a flat union of the properties of all nesting levels.
Consequences:
- Embedded types are listed as types with properties of their own. Their occurrence count is the number of hosting instances containing them (it's derived from the property occurrences per instance).
- Existing data is only corrected when the instances are processed again (POST /v4/spaces/inference?force=true, or POST /v4/spaces/{space}/inference?force=true); the nightly reconciliation then removes the stale summary rows. The type information skips summary rows with a count of 0 (left behind by the decrementing triggers in between).
- Properties without occurrences are only listed in the type information if they are specified (property_in_type.explicit_specification or a specification set). The property_in_type rows registered on the fly when processing instances can't be removed (they're referenced by the occurrences and relations), so the stale ones (e.g. the formerly flattened properties) would otherwise stay listed with 0 occurrences forever. Specifying a property in a type now also marks an already registered row as explicit.
- A nested object with both @type and @id stays a reference (its @type is not considered to be the target type - the type of the referenced instance is).
- Fixed on the way: the target space of a target type was joined against the source space alias, returning wrong (or multiplied) target spaces.
ADR-041: Invitations for users who haven't logged in yet¶
Status: Accepted
Decision: Users can be invited to review an instance before they have a marmot_user row. The inviter either picks a known user or issues an invitation link:
- Picking known users: GET /v4/instances/{id}/invitationCandidates?search= (requires the functionality to invite for review on the instance) searches marmot_user by username/name (case-insensitive, contains, at least 3 characters) or by exact email. It returns at most 20 users as {id (nativeId), username, name}, never their email. The invitation itself uses the existing PUT /instances/{id}/invitedUsers/{userId} (ADR-011).
- Issuing an invitation link: POST /v4/instances/{id}/pendingInvitations (optional body {label, scopes}) creates a row in pending_invitation (id, instance_id, token_hash, label, created_by, created_at, expires_at) plus pending_invitation_scope, with ON DELETE CASCADE on the instance. The scopes are resolved like for known users (ADR-044): the given names (unknown ones are rejected), the instance only if none are given. The response contains a single-use token (256 random bits, only its SHA-256 is stored). Core builds no redemption link: the client that issues the invitation also delivers the token (typically as part of a link to itself) and redeems it. Every call issues a separate invitation. The optional label (trimmed, at most 255 characters, blank means none) is free text for the inviter to recognize the invitation (e.g. whom the link was given to); whether to require one and how to display unlabeled invitations is up to the client. Core doesn't send emails either.
- Redemption: POST /v4/invitations/redemption with {token} (authenticated, no further permission; the token is in the body to keep it out of access logs) turns the pending invitation into a regular invitation for the current user with the scopes of the pending invitation, added to the scopes of an existing invitation of the user (redeeming a link never reduces access the user already has). It then deletes the pending invitation and evicts the user's invitation cache. The pending invitation is locked while it's redeemed, so concurrent requests can't redeem it twice. The response is {instanceId}. Unknown, used or expired tokens get 404.
- Management: GET /v4/instances/{id}/pendingInvitations ({id, label, scopes, createdAt, expiresAt}, never the token) and DELETE /v4/instances/{id}/pendingInvitations/{invitationId} require the same functionality as inviting. Pending invitations expire after org.marmotgraph.invitations.expiration (default 30 days). Expired rows are removed daily (org.marmotgraph.invitations.cleanupCron).
Why: The IdPs are brokered through Keycloak, so a user doesn't exist in Keycloak, let alone in MarmotGraph, before their first login. There is no directory to pick them from, and not every IdP provides a stable identifier. The token proves that the invitee received the link, whatever identity they log in with. The pending invitation records no email address: it wouldn't be checked on redemption (an IdP may assert a different or unverified address, and trusting email_verified from every brokered IdP would let one that asserts arbitrary addresses take over invitations), so storing it would only suggest a binding that doesn't exist. Links offer the same scope options as invitations of known users, so the inviter doesn't have to choose the mechanism by the scopes they want to grant. The search returns no emails and requires a minimum length so the user table can't be listed through it. Delivering and redeeming the token is left to the client, so core needs no mail infrastructure and no knowledge of client URLs (several clients can issue invitations, each redeeming its own), and tenants can use their own channels and templates.
Consequences:
- Until it's redeemed, the link is a bearer capability: whoever logs in with it gets the invitation, so a forwarded link works for the recipient. Single use and expiry limit the exposure. The client should present the link as confidential and carry the token in the fragment of its URL (#{token}) so it doesn't reach the client's server logs either.
- The label is the only hint whom a link was given to. It isn't checked on redemption either, so it's purely informational.
- Pending invitations grant nothing, so getAllInvitationsForUserId and the permission checks stay unchanged.
- v3/v3beta remain limited to known users. ADR-011's 404 for unknown users on PUT .../invitedUsers/{userId} stays.
ADR-042: Invitations without scope names apply to all scopes of the type¶
Status: Superseded by ADR-044
Decision: An invitation for which no scope names are given applies to all scopes defined for the type of the instance at the time of the invitation. This applies to invitations of known users (PUT /v4/instances/{id}/invitedUsers/{userId} without scope) and to invitation links (POST /v4/instances/{id}/pendingInvitations without scopes, resolved when the link is issued, ADR-041). If scope names are given, the invitation applies to those only (unknown names are rejected with 400). The names are resolved by InvitationsInternal.resolveScopes and stored as before (invitation_scope, pending_invitation_scope) - "all" is a copy of the names, not a mode. v3 and v3-beta invitations (which never had scope names) use the same path, InvitationService.inviteUserForInstanceWithAllScopes is removed.
Why: Before, a v4 invitation without scopes applied to the instance only, while a v3 invitation applied to all scopes of the type. The same request meaning two different things depending on the API version would confuse clients, and "all scopes" is what inviters expect by default (reviewing an instance usually means reviewing its related instances). Storing the resolved names keeps the evaluation unchanged (ADR-029) and needs no additional column.
Consequences:
- Scopes added to the type later aren't included in existing invitations. PUT /v3/instances/{id}/invitationScope (UPDATE_INVITATIONS) still re-applies the current scopes to all invitations of an instance; re-inviting does the same for a single user.
- An invitation for the instance only is only possible for types without scopes (or by giving a scope without steps, if the type has one).
- Behavior change for /v4 clients which relied on "no scopes = instance only".
ADR-043: The private space is exposed as "myspace" by the services building the response¶
Status: Accepted
Decision: Internally, the private space of a user is named private-{nativeId} (UserWithRoles.getPrivateSpace()). Requests address it as myspace (AuthContext.resolveSpaceName), and every response exposes it as myspace again: AuthContext.toExternalSpaceName (the inverse of resolveSpaceName) is applied by the service building the response model, at the point where the space name is put into it - not by a post-processing of the response in the API layer, and not by a (request aware) Jackson serializer for SpaceName. Places covered: instances (_space, outgoing/incoming link summaries) and the neighbors graph (InstanceService), scopes (ScopeService, as the last step since permissions are resolved by the internal name), type information including target/source type spaces (TypesService), stored queries (QueryService) and space information / type-in-space (SpacesV4, which builds its model from the Space entity with the translator).
Why: The previous implementation translated in the API layer (and in the graph adapters) per endpoint - which got lost with the refactoring and is easy to miss for new endpoints. A serializer for SpaceName would also apply wherever a SpaceName is serialized for other purposes (events, caches, persisted JSON), and many response models carry the space as a plain String. Translating where the internal name is turned into the response model keeps the translation next to the code which knows that a name is about to leave the system, and keeps the internal name available for everything before (permission checks, filters, sorting by internal data).
Consequences:
- Every new place exposing a space name has to call toExternalSpaceName. Response models carry the space as String from then on (e.g. _space in instance payloads isn't a SpaceName anymore).
- The private spaces of other users are exposed with their internal name (e.g. for administrators).
- The user is always ADMIN of their private space: UserWithRoles adds the role private-{nativeId}:admin to the roles of every user (not for clients without user, nor if the authentication information is lacking).
- GET /spaces always lists the private space of the user (as myspace) - even if it doesn't exist yet because nothing has been stored in it. It is sorted (and paginated by marker) by its internal name like any other space, so it isn't necessarily the first entry.
- Clients without user (no private space) see all spaces with their internal name.
- Tests with a mocked AuthContext need to stub the translation (AuthContextStubs.exposeSpaceNamesAsIs).
- Fixed on the way: the neighbors graph (GraphEntity.space) returned the searchable values of the instance instead of its space.
ADR-044: v4 invitations apply exactly to the named scopes¶
Status: Accepted (supersedes ADR-042)
Decision: A /v4 invitation applies to the instance and the scopes named in the request - to the instance only if no names are given. This applies to invitations of known users (PUT /v4/instances/{id}/invitedUsers/{userId}?scope=) and to invitation links (POST /v4/instances/{id}/pendingInvitations with scopes). /v3 and /v3beta invitations (which have no scope names) keep applying to all scopes of the type at the time of the invitation: their endpoints use InvitationService.inviteUserForInstanceWithAllScopes, which resolves the names and passes them explicitly. InvitationsInternal.resolveScopes no longer has a default. Since choosing scopes requires knowing them, GET /v4/instances/{id}/invitationScopes lists the scope names of the instance's type to whoever is allowed to invite for the instance - the scope definitions (GET /types/scopes) require DEFINE_SCOPES, which inviters usually lack.
Why: With ADR-042, an invitation for the instance only couldn't be expressed for a type with scopes - "no names" meant "all names". Making the request say exactly what it grants removes the special case: an empty list is a valid choice, and "all" is just the full list. The inconsistency ADR-042 wanted to avoid (the same request meaning different things per version) doesn't apply: a v3 request has no scope parameter at all, so its "all scopes" is a compatibility mapping of the unnamed v3 scope, done in the v3 layer.
Consequences:
- Behavior change for /v4 clients which relied on "no scopes = all scopes" (since ADR-042): they have to name the scopes (e.g. all of invitationScopes). Clients offering a choice typically preselect all scopes.
- Invitations stored before keep their resolved names - nothing to migrate.
- Scopes added to the type later still aren't included in existing invitations (unchanged, see ADR-042).
ADR-044: The functionalities LIST_USERS and LIST_USERS_LIMITED are removed¶
Status: Accepted
Decision: The functionalities LIST_USERS and LIST_USERS_LIMITED are removed (core, Java and Python SDK). Every role above CONSUMER no longer grants the global LIST_USERS_LIMITED in addition. The (unused) UserController.getUsers(Set<UUID>), the last check of LIST_USERS_LIMITED, is removed with them.
Why: Neither was checked by any reachable code anymore - the user listings of v3beta (/users, /users/limited) aren't implemented (and didn't check them). Looking up users is covered by the invitation mechanism: GET /v4/instances/{id}/invitationCandidates requires INVITE_FOR_REVIEW on the instance (ADR-041). Keeping the implicit global grant would also have given it to every user since everyone is ADMIN of their private space (ADR-043).
Consequences:
- permissions returned to clients (e.g. /users/me) no longer contain them. Clients checking for them have to check INVITE_FOR_REVIEW instead.
- If the v3beta user listings are re-implemented, they need a permission again (INVITE_FOR_REVIEW or a new functionality).
ADR-045: v4 invitation endpoints are grouped under /invitations¶
Status: Accepted
Decision: All /v4 invitation endpoints live in InvitationsV4 under /v4/invitations, with the instance as sub-resource:
| Before | After |
|---|---|
GET /instancesWithInvitations |
GET /invitations/instances |
GET /instances/{id}/invitationScopes |
GET /invitations/instances/{id}/scopes |
GET /instances/{id}/invitationCandidates?search= |
GET /invitations/instances/{id}/candidates?search= |
GET /instances/{id}/invitedUsers |
GET /invitations/instances/{id}/users |
PUT/DELETE /instances/{id}/invitedUsers/{userId} |
PUT/DELETE /invitations/instances/{id}/users/{userId} |
POST/GET /instances/{id}/pendingInvitations |
POST/GET /invitations/instances/{id}/pending |
DELETE /instances/{id}/pendingInvitations/{invitationId} |
DELETE /invitations/instances/{id}/pending/{invitationId} |
POST /invitations/redemption |
unchanged |
/v3 and /v3beta keep their paths; where they delegate, they delegate to InvitationsV4.
Why: The number of invitation endpoints grew (ADR-041, ADR-044) and they were scattered over /instances/... with prefixed names (invitedUsers, invitationScopes, ...). Grouping them makes the invitation API discoverable as one resource and keeps InstancesV4 focused on instances. The instances/{id} segment leaves room for invitations to other targets (e.g. spaces) later.
Consequences:
- Breaking change for /v4 clients - the old /v4 paths are removed without aliases. The Java and Python SDKs are updated (method names unchanged).
- Earlier ADRs mention the old /v4 paths - they reflect the state at their time.
ADR-046: Comments on instances are stored separately from the payload¶
Status: Accepted
Decision: Reviewers can comment on an instance or on one of its properties. Comments are stored in instance_comment (id, instance_id, property, text, created_by, created_at) and exposed by CommentsV4 (POST and GET /v4/comments/instances/{id}, grouped like the invitations, ADR-045). property is null for a comment on the instance as a whole. Both endpoints require the new functionality COMMENT (ALL_LEVELS, group INSTANCE), granted by the REVIEWER role (and therefore everything above it). Invitations grant it next to READ on the invited instances, incl. the instances in their scopes (Functionality.INVITATION_FUNCTIONALITIES). AuthContext.getFunctionalitiesForInstance includes them for invited instances, so the _permissions of an instance tell clients that they can comment. The author is exposed as createdBy only for the user's own comments (own) and with READ_CONTRIBUTORS.
Why: Comments are about the data, not part of it: storing them in the payload would make them part of contributions, releases and queries. The property is a plain name instead of a reference to the property table: the structure only knows properties that have been used or specified, whereas a comment can be about a missing value, and it isn't checked against the payload for the same reason. Names of reviewers are personal data, and ADR-032 keeps reviewers and invited users from seeing who works on an instance. Applying the same rule to comments keeps that promise, while the author stays recorded and visible to editors.
Consequences:
- created_by is set to null if the user is removed, and comments are removed with the instance (ON DELETE CASCADE). They survive releasing and unreleasing, since they aren't bound to a stage or to a version of the payload: a comment may refer to a value which has changed in the meantime.
- Clients without user can't comment (there would be no author to record).
- Reviewers and invited users see the comments of others, but not their authors.
- A property of an embedded instance can't be addressed: property is a single name without a path.
- Editing and deleting comments is covered by ADR-047.
- The _permissions of an invited instance now always contain READ and COMMENT, also in responses for the released stage, even though an invitation doesn't grant reading the released stage.
ADR-047: Comments can be edited by their author and deleted by their author or the space manager¶
Status: Accepted
Decision: PUT /v4/comments/instances/{id}/{commentId} with {text} replaces the text of a comment and DELETE /v4/comments/instances/{id}/{commentId} removes it. Both require COMMENT for the instance. Editing is limited to the author. Deleting is open to the author and to whoever has MANAGE_SPACE for the space of the instance. An edit sets the new updated_at (null if never edited), unless the text stays the same. Deleted comments are removed from the table. The property of a comment can't be changed.
Why: A comment is stored and exposed as the statement of its author, so nobody else may change its text. Deleting doesn't put words into anyone's mouth, and someone has to be able to remove inappropriate comments and those of removed users, who no longer have an author to clean them up. MANAGE_SPACE is the existing permission for looking after a space, whereas WRITE would let every editor remove the remarks reviewers made about their work. updated_at makes an edit visible, which matters since others may have reacted to the earlier text. Moving a comment to another property would be a different statement, so that takes a new comment.
Consequences:
- Previous texts and deleted comments aren't kept, so there is no history of what a comment said before.
- Users who lost COMMENT (e.g. a revoked invitation) can't edit or delete the comments they wrote before.
- Clients without user can't edit, but can delete with MANAGE_SPACE.
- Comments of removed users can't be edited anymore, only deleted.
- Concurrent edits aren't detected, the last one wins (only the author can edit, so this is unlikely).
ADR-048: Alternatives keep the JSON structure of their values¶
Status: Accepted
Decision: The value of an alternative is the JSON value of the contribution instead of its Java string representation, e.g. {"@id": "..."} instead of {@id=...}. Contributions are grouped by that value. _alternative is added to a response after the summary of outgoing links, so links in alternatives stay {"@id": "..."} as written. InstanceFormatV3 only qualifies the structure of an alternative (value, selected, user and the keys of the user) and leaves the value as it is, apart from wrapping @type in a list as it does in the payload.
Why: The string representation can't be parsed reliably, so a UI could only display it, not treat a link as a link or show an embedded instance. Grouping by the value also separates values which merely looked the same as strings (1 and "1") and merges objects which only differ in the order of their keys. The summary isn't applied since it is based on the relations of the current payload: a link of an alternative which isn't selected has no relation and would be reported as unresolved even if the target exists. The v3 adapter has to leave the value alone now, because it would otherwise qualify an @id that is already qualified and rename keys like name within the value.
Consequences:
- Clients have to handle any JSON type as value. It stays a string for string properties.
- Clients have to resolve the links of alternatives on their own (e.g. to show a label).
- Persisted alternatives keep the old strings until the instance is reconciled with a changed payload hash, since instances with an unchanged hash are skipped. A contribution which doesn't change the resulting payload therefore doesn't update them. POST /v4/spaces/inference?force=true (or /v4/spaces/{space}/inference?force=true) converts them all. A stringified value can't be told apart from a regular string.
ADR-049: Validating a payload without storing it¶
Status: Accepted
Decision: Two v4 endpoints validate a payload against the validation schemas of its type (ADR-026) and return the ValidationResult of GET /instances/{id}/validation, without storing anything:
- POST /instances/validation/payload?space=&schema= for a new instance. It requires CREATE and WRITE in the space, like POST /instances.
- POST /instances/{id}/validation?partial=&schema= for an existing instance. The payload is treated like a PUT, or like a PATCH with partial=true. It requires WRITE and READ on the instance.
The validated document is the one the corresponding write would validate (ADR-027). InstanceService applies the payload to a detached copy of the user's contribution with the logic of the write (applyToContribution) and passes it, together with the stored contributions of the other users, to InstanceProcessorInternal.reconcileInstances. @id and _space are then set as for a response of the API (exposeIdAndSpace). For a new instance, @id is a generated UUID. The space is resolved by name only, so it doesn't have to exist and isn't created.
Why: The frontend needs to show violations before saving. Validating the submitted payload as it is would give wrong results for an existing instance: the document which gets validated on save also contains the values of other contributors, and a PATCH only contains the changed properties. Sharing the merge and the reconciliation with the write keeps both results the same. Running the real write in a transaction which is rolled back was rejected, since the write also creates types and spaces, consumes sequences and publishes events.
READ is required in addition to WRITE for existing instances because the error messages can reveal values contributed by others. Validating doesn't change anything, but the two permissions match what a client needs to edit an instance and see the outcome.
Consequences:
- A positive result doesn't guarantee that the write succeeds: POST /instances still answers 409 if an identifier of the payload points to an existing instance. These endpoints only cover the validation.
- A schema constraining @id sees a generated UUID for a new instance, not the id of POST /instances/{id}.
- The schemas are compiled per request (ADR-026), which is relevant if a client validates on every change of a form.
ADR-050: Deleting a released instance has to be requested explicitly¶
Status: Accepted
Decision: DELETE /v4/instances/{id} takes a forceUnrelease flag (default false). For an instance which is RELEASED or HAS_CHANGED:
- Without the flag, the request is rejected with 409, as before.
- With the flag, the user needs RELEASE in addition to DELETE. The instance is then removed from both stages in one transaction.
For an unreleased instance, the flag has no effect and only DELETE is required. /v3 and /v3beta don't offer the flag and keep answering 409.
Why: Deleting a released instance withdraws published data, so it shouldn't happen as a side effect of a delete, and DELETE alone (granted to EDITOR) mustn't be enough for it. The check runs in InstanceService.removeInstance, not via unreleaseInstance, because the required permission is RELEASE, whereas the standalone unrelease checks UNRELEASE.
Consequences:
- The roles aren't affected in practice: OWNER and ADMIN have DELETE, RELEASE and UNRELEASE, EDITOR only DELETE.
- A forced deletion publishes InstanceRemovedEvent for the RELEASED and the IN_PROGRESS stage, so both are removed from the graph.
ADR-051: Direction of the incoming link summary, _space in queries¶
Status: Accepted
Decision:
- A row of current_incoming_link_summary describes the links to type_id: source_type_id is the type the links come from (the type of the node holding the link - an embedded object if the link is located in one), space_id the space of the linking instance. Migration V44 corrects the triggers and refresh_summary_tables and rebuilds the table. Rows without occurrences are no longer reported as incoming links of a type.
- _space can be used in the path of a query in both graph adapters. The value is the space as returned everywhere else (myspace for the private space of the user). An embedded object is located in the space of its instance. nograph adds the space to the node when loading the instance (it isn't part of the payload), neo4j reads the _space property of the node and translates the name in the results (QuerySpecification#translateValues).
Why: The table was filled the wrong way around, so /types reported the outgoing links of a type as its incoming links - with the target as "source type" - and a type which is only linked to as having none. A client composing queries from this structure offered reverse paths which can't return anything. _space was accepted in a query path but returned nothing: it was missing in the payload nograph evaluates and Neo4JUtils#sanitizeLabel read it from space instead of _space.
Consequences:
- The incoming links in /types and /typesByName change for every client (to the documented behavior).
- V44 recomputes all summary tables once, as refresh_summary_tables does.
- A filter on _space matches the name as returned in nograph. neo4j evaluates it in Cypher on the internal name, so myspace is translated if it's the whole value of the filter (e.g. EQUALS) - partial values of it (CONTAINS, STARTS_WITH, REGEX) are compared to the internal name.
- InstanceProcessorInternal#handleRelations removes the relations of paths the new payload has no links for anymore - before, they stayed in current_relation and were counted and returned as incoming links. Relations left behind by earlier versions can't be identified by SQL (the payloads are compressed) and are removed by a forced inference (POST /spaces/inference?force=true). The released relations are copied from the current ones, so the released stage is corrected when an instance is released again.
- Relations are replaced if the type of their source changes while the links stay the same. Before, type_id kept the old type. Existing ones are corrected by a forced inference too.
- V45 corrects current_target_type_summary: a type change now moves the links to the instance to its new target type, a space change moves both ends of the links of the instance.
ADR-052: Key figures of the graph are provided by a dedicated, read permission bound endpoint¶
Status: Accepted (extended by ADR-077: compliance per type)
Decision: GET /v4/statistics returns the number of instances and property occurrences ("triples") per stage, the instances per type (live and released, the most occurring first) and the compliance of the live instances per validation schema name. Implemented in services/structure/StatisticsService and internal/StatisticsQueries.
- Permissions: every figure only reflects the spaces the user can read in the respective stage (AuthContext#restrictToSpaces). A schema name is only listed if it applies to a readable instance.
- Sources: live instances are counted in current_instance, released ones in released_instance. Live triples and types come from the existing summary tables, the released ones are counted on demand in released_property_occurrence with the same definition.
- Validation groups: schemas of the same name are aggregated across types, since the name is what identifies a metadata model spanning several types (it's only unique per type - ADR-026). Every instance is in exactly one group of a schema: fully compliant (PASSED), or by the score (ADR-031) of a FAILED result: above 80%, 40% to 80% (both bounds included), above 0% and below 40%, not compliant (0%). The sixth group, not assessed, holds instances without a stored result (written with validate=false, or older than the schema) and failed results without a score.
Why: GET /types isn't sufficient: it ignores its stage parameter and only reports live counts, it isn't restricted to the readable spaces and summing its occurrences doesn't give the number of instances, since embedded types are counted too (ADR-040). Fully compliant is based on the status rather than a score of 100, because 100 doesn't imply valid (ADR-031) - an instance with a violation isn't reported as fully compliant, it's counted as above 80%. Without the not assessed group, the shares would look better than what is known about the data.
Consequences:
- The sum of the instances per type can exceed the total number of instances, since an embedded type counts the instances hosting it - as in GET /types.
- Triples are property occurrences as tracked in the primary store, so the http://schema.org/identifier set by the core on every instance is included.
- There are no validation figures for the released stage, since the results are only stored for the in progress payload (ADR-027).
- The released figures are computed per request. If this gets too slow on large graphs, the summary tables can be extended to the released stage or the result can be cached.
ADR-053: Validation schemas can reference each other by their $id¶
Status: Accepted
Decision: A $ref to an IRI other than a meta-schema is resolved by the $id of the stored validation schemas (ADR-026), never by fetching the IRI. The $id (id for draft 4) without fragment is stored in type_validation_schema.schema_iri (unique) when a schema is created or replaced. The resolution is implemented in services/validation/SchemaReferences.
- On PUT, references don't have to resolve yet, so schemas can be uploaded in any order. The upload check treats a document which isn't stored as the empty schema. A JSON pointer into such a document (…#/definitions/x) can't be checked and is accepted too. Broken local references (#/…) are still rejected with 400.
- Nothing but the stored schemas and the meta-schemas bundled with the library is ever loaded. SchemaReferences.StoredSchemaLoader replaces getSchemaResource of the library's SchemaLoader, so its schema id resolvers, resource loaders, remote fetching and the classpath lookup it applies to classpath:/resource: IRIs are never reached. Only an IRI under json-schema.org is mapped to a bundled meta-schema, and every other IRI is looked up as a $id only. A $ref to classpath:… is therefore just an unresolved reference.
- A $id already declared by another schema, or one in the json-schema.org namespace, is rejected with 400.
- References are resolved whenever a schema is compiled, so changes to a referenced schema apply to the referencing ones from then on. A bulk validation run compiles every document once (ADR-028).
- As long as a referenced schema isn't stored (not yet, removed, or its $id changed), the referencing schemas can't be compiled. Their validation then reports the instance as invalid, with a single $ref error and no compliance score, instead of failing the write.
- Migration V46 is a Java migration (db.migration), since the $id of the existing documents can only be read after decompressing them. If several existing schemas declare the same $id, the first one (by id) keeps it.
Why: Metadata models like openMINDS publish one schema per type, and they reference each other by their published IRI (e.g. https://openminds.om-i.org/types/CustomPropertySet?format=json-schema). Such schemas couldn't be uploaded as they are. Matching by $id keeps the documents unchanged and follows the JSON-Schema semantics of $ref. Fetching the IRIs was rejected, since the server would make outgoing requests to URLs chosen by the user (SSRF), and the validation would depend on remote availability. Requiring the references to resolve on upload was rejected, since it forces clients to sort a model by its dependencies and makes schemas referencing each other in a cycle impossible to upload.
Consequences:
- A typo in a reference isn't detected on upload. It shows up as a $ref error of every validation against the schema.
- Removing a schema which others reference isn't prevented. The referencing schemas fail as described above until the referenced one is stored again.
- Instances written while a model is only partially uploaded get $ref errors as findings. A bulk validation (ADR-028) after the upload brings them up to date.
- Every compilation looks up the referenced schemas in the database (once per referenced $id and compilation).
ADR-054: The inference runs asynchronously¶
Status: Accepted
Decision: POST /v4/spaces/inference and POST /v4/spaces/{space}/inference start the inference (InstanceService.reconcileInstances) in the background and return 202 Accepted with the initial InferenceStatus. GET /v4/spaces/inference (admin, INFER_SPACE) returns the status of the current or last run: its state (IDLE, RUNNING, DONE, FAILED), space (null for all spaces), force, start and end time, the total number of instances, the number processed so far, the number of failed batches and an error. This follows the pattern of the graph reindexing (ADR-013).
- Only one inference runs at a time. A second trigger is rejected with 409 (as before). The ReentrantLock is replaced by a compare-and-set on the status, since a ReentrantLock can't be released by a thread other than the one which acquired it.
- The trigger is still a @ReindexLock.Manipulation, so it is rejected with 503 straight away while the graph is reindexed. The background work holds the manipulation lock on its own thread via ReindexLock.runAsManipulation. If a reindexing takes the lock between the trigger and the start, the run ends as FAILED.
- /v3 and /v3beta delegate to /v4 and are asynchronous as well. They keep their empty 200 response.
Why: A run over a large space, or over all spaces with force=true, takes minutes to hours. The request was held open without sending anything, so reverse proxies and load balancers closed it on their idle timeout (clients saw e.g. RemoteDisconnected without any response). The work continued on the server, so a retry ran into the 409 without any way to see the progress.
Consequences:
- Clients no longer know from the response when the inference is done. They have to poll the status.
- The status is kept in memory per application instance and is lost on restart, like the status of the reindexing. A run interrupted by a restart isn't resumed.
- The progress count is now updated atomically (the former Tracker count was updated concurrently without synchronization).
ADR-055: A dedicated test suite validates the API against the permission model¶
Status: Accepted
Decision: src/test/java/org/marmotgraph/core/security (JUnit tag security, mvn test -Dgroups=security, also part of mvn test) verifies the permissions through the API with the complete application and a real Postgres. Only Keycloak is replaced - by FakeIdentityProvider, a local OIDC server issuing RS256 signed tokens, so token validation, the mapping of claims to roles and the AuthenticationAspect are the production ones.
- EndpointCatalog classifies every endpoint of every API version: Public, AuthenticatedOnly (both with a justification), Filtered, NotImplemented or Requires (global, space or instance level functionality). EndpointCatalogCompletenessTest compares it with the registered handlers, so an endpoint nobody has classified fails the build.
- EndpointAuthenticationTest / EndpointAuthorizationTest call every endpoint with invalid tokens and as every persona (roles on the space, on another space, global, invited). Requests are derived from the handler methods by reflection. A rejection only counts as 401/403: a 400 or 404 doesn't prove a check took place.
- ReadVisibilityTest computes per instance and stage what a combination of global roles, space roles and invitations may read and compares it with every read path. SensitiveDataTest and ManipulationProtectionTest cover restricted properties, secrets and abuse scenarios (addressing a resource through another one, escaping a space via identifiers or moves, the lifecycle of invitations).
- The expectations are independent of the production code: Persona states what the roles grant and RoleFunctionalityContractTest pins it against RoleMapping/Functionality.
- KnownSecurityGapsTest (tag known-security-gap, excluded by the excludedGroups property of the pom) states the desired behavior for open findings. It fails today.
Why: ADR-005 puts the permission checks into the services, so nothing at the API level shows whether an endpoint has one - and with three API versions delegating to each other it's easy to miss. Unit tests with a mocked PermissionService can't detect a missing call, nor a listing which forgets to restrict its query. Testing through the API with the real chain verifies what users actually get. A catalog which has to be complete turns "remember to think about permissions" into a failing build.
Consequences:
- Every new endpoint needs an entry in EndpointCatalog (see CLAUDE.md).
- The open findings stay visible but don't block the build - they need a decision: fix them or record in an ADR that the behavior is intended.
- The suite requires Docker, like the other integration tests.
ADR-056: Links, types and contributors only expose what the user is allowed to read¶
Status: Accepted
Decision: The findings of the security test suite (ADR-055) are closed as follows:
- Incoming links of /v3 and /v3beta: a linking instance the user can't read is reduced to the summary with the status restricted known from the grouped incoming links of /v4, instead of being returned as a full instance.
- Neighbors: linked instances the user can't read are left out on every level.
- Alternatives: _alternative keeps the values, but user is empty unless the user holds READ_CONTRIBUTORS on the instance (ADR-032).
- Types: GET /types and POST /typesByName are restricted to the spaces readable in the requested stage (AuthContext#restrictToSpaces, like GET /statistics - ADR-052). This also applies to the breakdown per space, the target types and the incoming links. Requesting a space which can't be read returns an empty result.
- Released type: release copies the type of the instance to the released instance; V47 fills it in for the existing ones with the type of the live instance.
- Invitations: the instance listing and the link summaries only apply them in the in progress stage - as the single read and the queries already did.
- Wildcard space roles: AuthContext#restrictToSpaces expands them (e.g. al*:reviewer) to the matching spaces, so listings, queries, bulk reads, spaces, types and statistics agree with the check on a single instance. A wildcard never covers the private space of a user (SpaceName#matchesWildcard) - neither when enumerating nor when an instance is addressed directly, for reading as well as for writing.
- Neighbors, second level: the second level of outgoing links follows the linked instance instead of repeating the links of the requested one.
Why: Filtering by the space is the rule of every other read path, and the structure of a space (types, counts, the names of the spaces) is information about its content too. The restricted summary keeps page sizes, markers and totals of the older incoming links valid and follows the rule already established for /v4, whereas a dropped entry would need a permission-aware query for each pagination variant. Neighbors are a view of a graph: a node without name and space has no value there. The listing never returned released instances since they had no type, which also hid that invitations were applied to that stage.
Consequences:
- Users without a readable space receive no types anymore, also none which are only specified and have no instances yet.
- A role with a wildcard which was meant to cover private spaces (e.g. *:admin) doesn't reach them anymore. Support access to a private space would need a global role.
- GET /types still only reports live figures and ignores the stage for them (ADR-052): someone who can only read the released stage of a space sees the live figures of that space.
- The V47 backfill takes the live type, which differs from the released one if the type was changed after the last release. Releasing the instance again corrects it.
ADR-057: Removing a specification keeps what is in use, incomplete color schemes are rejected, users are stored independently of the request¶
Status: Accepted
Decision:
- Removing specifications: DELETE /properties, DELETE /propertiesForType, DELETE /types/specification and DELETE /spaces/{space}/specification remove the specification and set explicitSpecification to false. A property (in a type) or space which isn't in use is deleted, types stay since they never have been. (Types: superseded by ADR-062) A property counts as in use if it is part of a type or has occurrences, a property in a type if relations or occurrences reference it.
- Specifying a property which already exists sets explicitSpecification to true.
- GET /properties requires property in all API versions.
- Color schemes: PUT /tenants/{name}/theme/colors is rejected with 400 unless all colors are defined. The stylesheet falls back to the default scheme if an incomplete one is stored.
- Users: the user of a token is created or updated in its own transaction.
Why: A property in use is referenced by foreign keys, so deleting it failed with a 500 although only its specification was meant - the same removal already behaved that way for spaces. The flag only means something if every path maintains it. A scheme without a group made the public stylesheet fail for everybody, a scheme without a single color produced invalid CSS: a partial scheme is never useful. The user is cached together with the token, so when it was saved in the transaction of a request which got rejected, it vanished with the rollback and later requests failed on a foreign key.
Consequences:
- The lookup of an unknown token uses a second database connection for a moment while the transaction of the request is open.
- GET /types/specification still answers 200 with empty values for a type without specification, whereas properties answer 404.
ADR-058: Documentation site built with MkDocs from docs/¶
Status: Superseded by ADR-059
Decision: The user and developer documentation is a MkDocs site (Material theme) in docs/, configured by mkdocs.yml and built in strict mode, so broken links and anchors fail the build. Diagrams are written in Mermaid inside the Markdown files. The decision records are included from ARCHITECTURE.md with a snippet rather than copied.
Why: FEATURES.md and ARCHITECTURE.md are precise, but they're written for maintainers and neither explains how to use the system. Markdown keeps the documentation in the repository, next to the code it describes. Mermaid diagrams are text, so they can be reviewed in a diff and need no image build step.
Consequences:
- FEATURES.md stays the authoritative list of features. docs/ explains them and has to be updated when the behavior it describes changes.
- The endpoint overview in docs/reference/endpoints.md is written by hand, based on EndpointCatalog.
- The theme announces its end of life for May 2027, with Zensical as its successor. A migration would keep the Markdown content.
ADR-059: Documentation site built with Zensical¶
Status: Accepted
Decision: The documentation in docs/ is built with Zensical and configured by zensical.toml. It uses the classic theme variant. The other parts of ADR-058 stay in force: Mermaid diagrams in the Markdown files, the decision records included from ARCHITECTURE.md with a snippet, FEATURES.md as the authoritative list of features, and a hand-written endpoint overview.
Why: Material for MkDocs announces its end of life for May 2027, with Zensical as its successor by the same authors. Zensical supports the theme features and Markdown extensions the documentation uses, so the content didn't have to change. classic keeps the appearance of the Material theme.
Consequences:
- Zensical is still in beta, so docs/requirements.txt limits it to the 0.1 releases.
- zensical build fails on broken links and anchors. zensical serve doesn't support strict mode, so a preview isn't a substitute for a build.
- Diagrams load Mermaid from unpkg when the page is viewed, as they did before.
ADR-060: The documentation is served by the application at /docs¶
Status: Accepted
Decision: The Maven profile docs runs zensical build --strict and copies the result to static/docs in the jar, where Spring serves it without authentication. Only the release build activates the profile. The site uses use_directory_urls = false, and a view controller maps /docs/ to index.html. The default page links to the documentation only if the jar contains it.
Why: Documentation inside the jar always matches the version which is deployed, and needs no separate hosting. Making the profile optional keeps mvn clean package independent of Python. Spring only resolves index.html at the root of its static locations, so page URLs have to name their file.
Consequences:
- The build producing a release has to install Zensical and run mvn package -Pdocs.
- All of the documentation is public on every installation, including the developer section and the description of how open security findings are tracked. This is intended, as the project is open source.
- /docs is served by a resource handler and not by a controller, so it isn't part of EndpointCatalog.
- Diagrams load Mermaid from unpkg in the reader's browser and don't render on an installation without internet access.
- The SDK documentation stays in sdks/python and sdks/java (README and docs/), so it can be published with the SDK artifacts and read on GitHub without the site. docs/sdks/ only holds pages which include those files by snippet, mirroring their folder layout so that the relative links between them work in both places. A new SDK page needs such a wrapper and an entry in the nav of zensical.toml.
- The site has the look of the start page with the default colors of ColorScheme. The logos and colors are static copies in docs/ and docs-theme/, so the documentation doesn't follow the branding of a tenant.
ADR-061: Link suggestions and the list of instances with invitations are not part of /v4¶
Status: Accepted
Decision: GET/POST /v4/instances/{id}/suggestedLinksForProperty and GET /v4/invitations/instances are removed. The /v3 and /v3beta endpoints (.../suggestedLinksForProperty, GET /instancesWithInvitations) stay for backwards compatibility and throw NotImplementedException in the controller instead of delegating to /v4. The Python and Java SDKs drop the corresponding methods and the SuggestionResult/SuggestedLink models.
Why: Neither endpoint was ever implemented in /v4; they only answered with HTTP 500. Link candidates can be found with GET /v4/instances (type, searchByLabel), and the invitations of an instance are listed under /v4/invitations/instances/{id}. Without the stubs, /v4 has no unimplemented endpoints left.
Consequences:
- An implementation for /v3 (needed by clients like the editor) is still open. It has to live in services/ and be called by the /v3 controllers directly, since there's no /v4 endpoint to delegate to.
- The entry of GET /invitations/instances in the table of ADR-045 refers to an endpoint which doesn't exist anymore.
- EndpointCatalog declares the endpoints for the legacy versions only.
ADR-062: Types which are neither specified nor in use are removed¶
Status: Accepted
Decision: A type is removed together with its non-specified type_in_space and property_in_type rows and its rows in the summary tables as soon as it is
- not explicitly specified: neither the type itself, nor its assignment to a space, nor one of its properties (per type) is specified, and it has no scope and no validation schema, and
- not in use: no instance in any stage and no embedded instance has it (and no property occurrence or relation is registered with it).
The check is the database function remove_unused_types(type_ids) (all types if NULL). It runs for the types of an instance (incl. its embedded ones) when the instance is removed or unreleased, for the type when its specification or the specification of one of its properties is removed (DELETE /types/specification, DELETE /propertiesForType) and for all types in the nightly reconciliation of the summary tables. The migration removes the types which have been left behind so far. This supersedes "types stay" of ADR-057.
Why: Types are registered on the fly when instances are processed but were never removed: a type whose last instance was deleted (or which was only created by a specification which was removed again) kept showing up in GET /types with zero occurrences.
Consequences:
- A type which loses its last instance by a change of the payload (other @type, embedded instance dropped) or which loses its scope, validation schema or the specification of its space assignment only disappears with the nightly reconciliation.
- Types locked by a concurrent transaction are skipped (FOR UPDATE SKIP LOCKED). If the last instance of a type is removed while another transaction registers a new instance of an existing type, the registration can fail on the foreign key and has to be retried.
- current_instance, released_instance (type_id) and the property occurrences (embedded_type_id) are indexed for the check.
- GET /types/specification answers 404 after the specification of a type without instances has been removed.
ADR-063: Tools built on top of the graph are listed by claim patterns¶
Status: Accepted
Decision: Tools built on top of the graph (e.g. a search or a dashboard) are stored in tool (id, name, description, category_id, endpoint, claims), the categories they are listed in in tool_category (id, name, icon). Both are exposed by ToolsV4 (/v4 only):
- GET /v4/tools?category={id} lists the tools whose claims match the user information of the caller (AvailableTool: id, name, description, category (id, name), endpoint - without the claims), sorted by category and name. GET /v4/tools/categories lists the categories with at least one of these tools (id, name, icon). Any valid token can call them. Users with DEFINE_TOOLS get all tools and all categories - like a global administrator sees everything elsewhere.
- /v4/tools/definitions (GET, POST), /v4/tools/definitions/{id} (GET, PUT, DELETE), POST /v4/tools/categories and PUT, DELETE /v4/tools/categories/{id} manage the tools (incl. the claims) and categories. They require the new global-only functionality DEFINE_TOOLS (PermissionService.canDefineTools, only granted by the global ADMIN role).
- The claims use the format of the claims of a role definition (/setup/permissions/{role}): {"authenticated": true} or a structure mirroring the user information whose leaves are (lists of) regular expressions, matched entirely, any match lists the tool. The matching is shared with the role mapping (services/authorization/ClaimPatterns, extracted from UserInfoInternal). Patterns are validated when a tool is defined (not empty, valid expressions).
- The user information of the identity provider is kept on the (token-cached) UserWithRoles - not serialized, so /users/me/roles doesn't change - and matched via AuthContext.matchesClaimPattern.
- Category names are unique ignoring the case (409 otherwise). A category with tools can't be removed (409). A tool references an existing category (400 otherwise). endpoint has to be an absolute http(s) URL.
- The icon of a category is the markup of an SVG document, returned inline. SvgIcons only accepts a self-contained document without active content: it is parsed without document type or entities (XXE), the root has to be svg in the SVG namespace, script, foreignObject, iframe, embed, object, audio, video, set, animate, handler and listener elements, on* attributes, javascript: values, processing instructions, @import and links (href, url(...)) to anything but elements of the icon itself are rejected. At most 100000 characters.
- The SDKs provide the endpoints (client.tools() / client.tools).
Why: Which tools a user is offered depends on the groups of the identity provider rather than on the permissions in the graph (a dashboard for a project, a search for curators), so the claims are matched directly instead of introducing roles or functionalities per tool. Reusing the format of the role definitions keeps one syntax for administrators and one implementation. Matching against the cached user information (instead of materializing the visible tools with the roles) makes changes to a definition effective immediately, without another call to the identity provider. The claims are hidden from the listing since they reveal the group structure of the identity provider. Categories are entities of their own so they can carry an icon and be renamed in one place. The icon is returned inline since clients can't send a token with an <img> request, and serving SVG from the API's origin would turn an embedded script into stored XSS - clients may still inline the markup into their page, which is why active content is rejected instead of relying on how the icon is rendered. Clients render the endpoint as a link, so other schemes (javascript:, data:) are rejected.
Consequences:
- A global administrator gets all tools listed, so GET /tools doesn't show them what other users see - to check the claims of a tool they have to read its definition.
- A category without tools is only listed to users with DEFINE_TOOLS.
- IllegalStateException (mapped to 409) signals the conflicts of categories.
ADR-064: Neo4j queries are paginated before the structure is evaluated¶
Status: Accepted
Decision: QueryToCypherInternal cuts the page of root instances first and evaluates the structure per root instance:
- Root selection: MATCH (root:<stage>:<type>) with the access filter, instanceId, the marker and the filters and required checks of direct properties of the root (single-element paths) as plain conditions on the root node.
- Items excluding roots by traversal (required substructures, filters and required on multi-hop leaves on the root level) are projected for every candidate (WITH *, <value> AS v WHERE ...) before the page is cut. Every other item is only evaluated for the roots of the page.
- Pagination: WITH * ORDER BY root._id SKIP/LIMIT, followed by the RETURN of the result map.
- Per-root evaluation: every relation and substructure is a COLLECT { ... } subquery (RollUpApply in the plan) evaluated per row - no collect over the whole result. Every hop is a MATCH clause of its own (a relation can be part of a path several times). ensureOrder sorts by the orderNumber of the item's forward relations inside the subquery, otherwise the values are DISTINCT.
- Semantics of nograph (ADR-037), incl. the parts the former translation didn't implement: filters and required on leaves reached by multi-hop paths are evaluated (on the root level they exclude the root, on nested levels they remove the value) and their values are flattened into one list. On nested levels, the filtered values are computed before the required checks, an object without any non-empty value is removed - so a filter on the only value of a required substructure excludes the root.
- Result keys are the property names (backtick quoted) - the alias mapping in Neo4JInternal is gone. Variables are numbered across the whole query since a subquery can't redeclare a variable of its outer scope.
- The "object not empty" check is a list predicate (any(x IN [...] WHERE ...)) since the planner normalizes a disjunction to a conjunction which grows exponentially with the number of items.
Why: The former translation (a chain of OPTIONAL MATCH / WITH ..., collect(...) with ORDER BY/LIMIT at the end) aggregated the full structure for all instances of the root type before the page was cut. The eager aggregations held the results of all roots in memory, so a page of 20 cost as much as the whole type and large types failed with dbms.memory.transaction.total.max threshold reached. Root filters were only applied after the traversal, too. With per-row subqueries, the memory is bounded by the page (and by one root while candidates are checked), and the planner can stop after the page (Top directly on the root scan).
Consequences:
- Queries with items excluding roots by traversal still evaluate these items for every candidate root (CPU, not memory) - the same trade-off as in nograph. A total count does the same.
- Requires Neo4j 5.9 or later (COLLECT subqueries, IS :: type predicates), APOC isn't used anymore.
- Behavior change on Neo4j: filters and required on multi-hop leaves are no longer ignored, list values of such leaves are flattened, and values / objects which are empty after filtering are removed. Both adapters now return the same results.
- Requests without page size still return everything (no LIMIT); the rows are streamed from Neo4j but collected by the client.
- QueryServiceNeo4jIntegrationTest#cutsThePageBeforeTheStructureIsEvaluated checks the plan (no EagerAggregation, no subquery below Top).
ADR-065: Traversals without a value are returned as empty list¶
Status: Accepted
Decision: A traversal - a query item with a nested structure or a flattened leaf reached by a multi-hop path - without a (non-empty) value is part of the result as an empty list instead of being omitted - on all levels and in all API versions. Items with a singleValue are still omitted if they have no value (as before). Direct properties (single-element paths) without a value are still omitted. This is applied adapter-independent in QueryService (QuerySpecification#emptyTraversalsAsLists) after the graph DB returned the results.
Why: The original KG query format (and therefore the clients of /v3 and /v3beta) relied on the key of a traversal always being present. Doing this in /v4 too avoids a migration effort for clients switching to the new version.
Consequences: - Results of queries with traversals can contain empty lists - the "empty values are removed" rule of ADR-064 / ADR-037 now only applies to direct properties and to the objects within a substructure. - A traversal whose values were all removed (e.g. by a filter on a nested level) is reported as empty list.
ADR-066: v3 references with the instance namespace are reduced to the UUID on write¶
Status: Accepted
Decision: /v3 and /v3-beta translate the payload of instance creation and contribution (POST /instances, POST/PUT/PATCH /instances/{id}) before passing it to /v4: every nested @id of the form {instance namespace}{uuid} (org.marmotgraph.instance.namespace) is replaced by the plain UUID (InstanceFormatV3#toV4Payload). The @id of the payload itself is not changed - it is registered as an additional identifier as before. References with another prefix, or with the instance namespace followed by something else than a UUID, are kept as written. Without a configured instance namespace, nothing is translated.
Why: /v3 returns the @id of instances qualified with the instance namespace (ADR-021). Clients use this @id to link other instances - but the instances are resolved by their UUID, and the qualified form isn't necessarily one of their identifiers (e.g. for migrated data), so these links stayed unresolved. Since the qualified form is produced by the compatibility layer, the compatibility layer has to translate it back.
Consequences:
- Links written through /v3 are stored with the UUID, as if written through /v4. Reading them back through /v3 returns the UUID (nested references aren't qualified on output).
- /v4 doesn't translate: it never returns qualified ids, a qualified reference written through /v4 is kept as written.
- Only instance payloads are translated - not query specifications, type/property specifications or the identifiers passed to /instancesByIds / /instancesByIdentifiers.
ADR-067: A local review tool for the manual validation of the tests and the architecture¶
Status: Accepted
Decision: utils/reviewTool is a local web tool (Python standard library only, python3 utils/reviewTool/review.py) which presents the tests grouped by suite and topic with their actual executions, and the code structure from the package overview down to single classes with dependency rules (ADR-003, ADR-005, ADR-006, ADR-019) and style checks, and style dimensions: aspects the code base solves in more than one way, for which conventions are stated per package pattern and for productive code vs. tests (curated in the guide, adjustable by the reviewer), and the deviations are listed to harmonize or to accept individually with a reason. A UML diagram (SVG, laid out in the browser without external libraries: a layered layout with long edges routed between the boxes and crossings reduced, top-down or left-right) shows one level at a time - a package with its sub packages, classes and neighbouring packages, or a class with its dependencies and dependents - coloured by the state of the review or by open findings, and is the navigation for drilling down. Security findings (heuristics in guide/security.json plus the results of external scanners imported from SARIF) are findings of their class; their open ones rate classes and packages A-E, and an approved security finding is an accepted risk. At every launch the rule feeds (by default security.json of origin/dev, read with git show without fetching) and the scanners (installed vs. latest version, Semgrep rule packs) are checked; every definition of a rule that was ever seen is kept in the review state and stays active next to the current one until it is retired explicitly, adding only the findings the current version doesn't produce. An issue (a finding, the open findings of a rule or a security category, or any item with the reviewer's rejection and open comments) can be handed to Claude Code running locally (claude -p in the repository, tools limited by guide/claude.json, never committing); the tool snapshots the files before the run, shows the run's changes as a diff and can restore them, and the run's session can be continued in the tool or in a terminal. A security finding - or the open findings of a category or rule at once, with a verdict per finding - can also be assessed by Claude Code read-only: it traces the values and their guards and ends with a structured verdict (vulnerable / not vulnerable / uncertain, confidence, level, reason, fix) which the reviewer can adopt as the decision - the verdict is advice, the decision stays with the reviewer. Deviations of a code style dimension can be assessed the same way: whether there is a good reason to deviate from the convention there (verdict keep / align / uncertain per deviation), which the reviewer can adopt by accepting the deviation with the reason. The execution of every REST endpoint can be followed through the code base as a static call tree (controller → services → repositories / graph adapters; interface calls branch into every implementation with its Spring profile, published events into their listeners), with markers for where the permissions are checked and the stores are reached (guide/trace.json) next to the access the security suite expects (EndpointCatalog); an endpoint which requires an access but whose trace reaches no permission check is flagged. Reviewers approve/reject and comment on every level; the decisions are persisted in utils/reviewTool/state together with a snapshot of what was reviewed, so a review can be continued in later sessions and an item which changed after its review is flagged with a diff. The grouping and the explanations are curated in utils/reviewTool/guide/*.json. The executions of dynamic and parameterized tests are recorded by a JUnit TestExecutionListener which the tool puts on the test classpath with -Dmaven.test.additionalClasspath for its own mvn test runs.
Why: A manual review of ~500 test methods with ~7000 executions and ~400 classes needs to be split over several sessions and has to survive code changes in between. The surefire reports only name dynamic tests by index, which isn't reviewable. Keeping the tool out of the Maven build (no plugin, no dependency, no change of the pom) means it can't affect the application or CI.
Consequences:
- The tool isn't part of the build or the shipped application.
- guide/tests.json has to follow renamed/added tests - the tool lists tests which aren't described by the guide and guide entries which don't exist anymore.
- The dependency analysis is based on imports: references within the same package and fully qualified references aren't visible.
- The endpoint traces are derived from the source without compiling it: calls on lambda parameters, untyped vars and external types, reflection and AOP aren't followed, so a missing call in a trace is a hint to check, not a proof.
- The review state is plain JSON plus gzipped snapshots and can be committed to share a review.
- The page and its API only answer requests to localhost (against DNS rebinding), and changing requests need a header of the tool which a foreign page can't send without a CORS preflight - the API starts processes (tests, scanners, Claude Code).
- Claude Code edits the working tree the developer works in; discarding restores a file only if nobody changed it since the run. Several runs at once: ADR-069 (formerly only one run at a time).
ADR-068: Examples of the OpenAPI specification are configurable globally and per tenant¶
Status: Accepted
Decision: The examples which depend on the data structures of a deployment are named slots (ApiExample, initially instancePayload - the request body of the instance creation, contribution and payload validation - and instance - the instance in the response of the instance endpoints, wrapped into {"data": ...}). The endpoints of /v4 reference them (#/components/examples/{slot}) instead of embedding a value, and the value is resolved when the specification is served: tenant override → global override → built-in default (src/main/resources/openapi/examples/{slot}.json, taken from the demo data).
- The overrides are stored in api_example (tenant, name, payload). The global ones are stored for the tenant default, which already stands for "no customization" (ADR-057's fallbacks), so GET /v4/tenants/default/openapi/{group} is the same as /v3/api-docs/{group}.
- PUT/DELETE /v4/openapi/examples/{slot} set and reset the global overrides. They require the new global-only functionality DEFINE_API_EXAMPLES (only granted by ADMIN).
- PUT/DELETE /v4/tenants/{name}/openapi/examples/{slot} set and reset the overrides of a tenant. They require TENANT_MANAGEMENT like the rest of the tenant definition, the tenant has to exist (404) and default can't be changed this way (400).
- GET /v4/tenants/{name}/openapi/{group} serves the specification of a group with the examples of a tenant - public like /v3/api-docs. An unknown tenant gets the global examples (like the theme).
- An override has to be a JSON object. Unknown slots are rejected (404).
- Endpoints declare the slots with @ApiExampleRefs(request = ..., response = ...). An operation customizer of the v4 group adds the references after springdoc has built the operation, so the generated schemas are kept (an explicit @ApiResponse content would replace them).
- The specification itself is still built and cached by springdoc. The examples are inserted into the serialized specification afterwards: a ResponseBodyAdvice for springdoc's /v3/api-docs resources, and TenantApiDocs which asks springdoc's resource for the specification of the tenant endpoint.
Why: The meaningful examples of an instance depend on the types of a deployment (and of a tenant served by it), so they can't be fixed in the annotations. Inserting them after springdoc has produced the specification keeps springdoc's cache (the specification is built by scanning all controllers) and makes changes effective immediately, without a cache to invalidate or a restart. References keep the examples in one place, so a slot can be reused by several endpoints and replaced as a whole. Keeping the slots fixed (instead of free names) means the endpoints which show an example are decided in the code, and an administrator can't produce dangling references.
Consequences:
- Only /v4 references the slots - /v3 and /v3-beta keep their documentation.
- The Swagger UI shows the global examples. The tenant specification is meant for clients and tools of a tenant (it can be loaded into any OpenAPI viewer) - the UI isn't configured per tenant.
- The examples are not validated against the types of the deployment - they're documentation.
- New slots need a default file and a reference from the endpoints.
ADR-069: Parallel Claude Code runs of the review tool share the working tree, coordinated by a hook¶
Status: Accepted
Decision: The review tool (ADR-067) runs up to maxParallel Claude Code runs at once (guide/claude.json, default 3), all in the repository's working tree. Every run gets a PreToolUse hook (utils/reviewTool/reviewtool/hook.py, passed with --settings, with the tool's URL and a secret of the run in its environment) which asks the tool before every edit (Edit, Write, MultiEdit, NotebookEdit) and every Maven command:
- The first run which edits a file claims it until the run ended and was committed. Another run waits for the file; it is denied (and told to leave the file) when waiting would close a cycle of waiting runs or took longer than claimWait.
- The content of a file when a run claims it is the base of the run's diff and commit (instead of a snapshot of the start of the run), so a run only shows and commits its own changes, also after another run changed the file.
- One Maven build at a time (the runs share target/), also against the tool's own test run. The build is released when its tool result arrives in the run's stream.
- The commits of the runs are serialized. The same item can't have two runs of the same mode at once, a session can't be continued while it works.
The runs persisted in target/review-tool/claude/ are listed as a history (Claude runs), grouped by session and filterable, and every run can be reopened and continued.
Why: Assessments and independent fixes take minutes each; one run at a time made working through a review slow. Separate git worktrees per run would isolate them completely, but a run wouldn't see the developer's uncommitted changes, every run would need a full Maven build of its own, the sessions (which Claude Code keys by directory) couldn't be continued after the worktree is removed, and the changes would have to be brought back into the working tree anyway. Coordinating at the level of files keeps the runs in the developer's working tree, where the tool already shows, commits and discards their changes.
Consequences:
- Runs which need the same file run one after the other on it; the second one sees the first one's result. Runs whose files intersect cyclically may leave a file undone - their summary says so.
- Edits through other tools (e.g. sed in Bash) aren't coordinated and aren't part of the diff - Bash isn't allowed to edit by default.
- A Maven build of the developer in a terminal isn't coordinated.
- If the tool isn't reachable, the hook lets the calls pass. After a restart of the tool it doesn't know the runs still working any more (they are marked as interrupted) and denies their edits.
ADR-070: Trivy is the dependency scanner of the review tool¶
Status: Accepted
Decision: The review tool (ADR-067) checks the dependencies for known vulnerabilities (CVEs) with Trivy (Apache 2.0), configured as scanners in utils/reviewTool/guide/security-sources.json like Semgrep and CodeQL:
- trivy scans the dependency manifests of the repository (pom.xml, sdks/java/pom.xml, sdks/python/pyproject.toml, the requirements.txt files) with trivy fs. It runs automatically when it never ran, its version changed, a manifest changed or its last run is older than maxAgeHours (new CVEs are published without any change of the code).
- trivy-image builds the jar and the Docker image (mvn package, docker build) and scans the image with trivy image - the libraries in the jar plus the JRE and the Alpine packages of the base image. It only runs with ▶ Run.
- OWASP dependency-check stays configured but only runs with ▶ Run: it needs an NVD API key to be usable and reports the same CVEs.
Results which aren't in a class of the review - vulnerable dependencies above all - are shown on the Security page as Dependencies: one row per package and version with its vulnerabilities, the fixed versions and the scanners which reported them, merged across scanners by CVE.
Why: Without NVD_API_KEY, dependency-check never ran automatically, so the review tool didn't show vulnerable dependencies at all. Trivy needs no key or account, is fast, and covers Maven, Python and the container image with one tool. Rescanning after maxAgeHours is needed because the vulnerability database changes, not the code. The CI pipeline isn't part of this decision (to be decided separately).
Consequences:
- Trivy has to be installed by the developer (it isn't downloaded by the tool, which only compares the installed with the latest version). After the compromise of Trivy's release pipeline in March 2026, install a release whose checksum / signature you verified.
- Trivy downloads its vulnerability database (from ghcr.io) on the first run and when it's outdated, and resolves the transitive Maven dependencies from Maven Central.
- Dependency results aren't review items: they can't be approved or rejected and don't count towards the ratings of classes and packages - a vulnerable library isn't a finding of a class. They are fixed by upgrading the dependency.
- The Maven build of trivy-image isn't coordinated with the test runs of the tool or Claude Code's builds (ADR-069) - don't start it while those run.
ADR-071: Identifiers are removed explicitly, only if they are not referenced¶
Status: Accepted
Decision: DELETE /v4/instances/{id}/identifiers?identifier=... removes an identifier from the in-progress state of an instance. It requires WRITE in the space of the instance. The identifier is removed from the http://schema.org/identifier of the stored payload and from all contributions to the instance (their http://schema.org/identifier and, if it is the identifier, their @id), the instance is reconciled and the identifier is unregistered (current_identifier). It is rejected if:
- the identifier represents the id of the instance - its UUID, plain or with the instance namespace (400)
- the instance doesn't have the identifier (404)
- a relation targets the identifier, in progress or released, from any instance (409)
Why: Identifiers are never dropped by contributions (an instance keeps the identifiers of its stored payload, see "Identifiers are kept" in FEATURES.md), so wrong or outdated identifiers can't be corrected otherwise. Relations are stored with the identifier as written (target_reference) and stay resolved to the instance after the identifier is gone - so a referenced identifier must not be removed. The identifiers representing the UUID are added by the reconciliation anyway and are what the instance is addressed by.
Consequences:
- The released stage keeps the identifier until the instance is released again. A released instance becomes HAS_CHANGED (the instance's last update is set to now, even if no contribution contained the identifier); in an auto-release space the instance is released right away (requires RELEASE, same as for contributions).
- Stored validation results are recomputed if there are any.
- The check for relations isn't restricted to what the user can read: a 409 reveals that some instance refers to the identifier, but nothing about it.
- The alternatives (_alternative) aren't touched - @id and http://schema.org/identifier aren't part of them.
ADR-072: Batch manipulation of instances, set-based, optionally asynchronous¶
Status: Accepted
Decision: /v4 gets batch endpoints for the manipulations of instances:
- POST /v4/batch/instances creates or updates instances ([{id?, space?, payload}], updateIfExists default true, partial for PATCH semantics, skipIfUnchanged, validate)
- POST /v4/batch/instances/delete (forceUnrelease), POST /v4/batch/instances/release, POST /v4/batch/instances/unrelease take a list of UUIDs
Every batch is a job (batch_job, Flyway V51) with an id, its status (QUEUED, RUNNING, COMPLETED, FAILED), its progress and - once it's done - the outcome per item (CREATED, UPDATED, UNCHANGED, DELETED, RELEASED, UNRELEASED, FAILED with code and message, or ROLLED_BACK). With async=false (default) the job runs in the request and the response is the completed job. With async=true the response is 202 with the queued job, which can be polled with GET /v4/batch/jobs/{id} (GET /v4/batch/jobs lists the jobs of the user). Jobs are only visible to the user who submitted them and are removed after a retention period (org.marmotgraph.batch.retention, default 7 days).
Processing:
- The items are processed in chunks (org.marmotgraph.batch.chunkSize, default 500). Each chunk is processed set-based within one transaction: one lookup of the instances by UUID and identifiers, one saveAll of the contributions, one reconciliation and processing (InstanceProcessorInternal), one global relation resolution, one validation pass reusing the compiled schemas, and therefore one graph synchronization event (ADR-017) for the whole chunk. Deletions and (un)releases go through the same per-instance routines as the single endpoints, but share the transaction of the chunk.
- The JSON-LD normalization of the payloads happens before the transaction (in parallel), so CPU-bound work doesn't hold a connection.
- Expected failures of single items (unknown instance, conflicts, invalid payloads, duplicates within the batch) are recorded for the item and don't affect the other items of the chunk. An unexpected failure rolls back the chunk, which is then reprocessed item by item - each in its own transaction - to isolate the failing item(s). The fast path is therefore taken as long as there are no unexpected failures.
- atomic=true processes all chunks in a single transaction: if any item fails, everything is rolled back - the failing items are reported as FAILED, all others as ROLLED_BACK.
- A chunk (or the atomic batch) takes one permit of the ManipulationThrottle (ADR-018) and the whole job holds the ReindexLock (ADR-013). Jobs run sequentially per chunk; at most org.marmotgraph.batch.maxConcurrentJobs (default 2) jobs run at the same time, further async jobs wait (up to org.marmotgraph.batch.maxQueuedJobs, default 20, 503 beyond). A batch has at most org.marmotgraph.batch.maxItems (default 10000) items (400 beyond).
Permissions: all permissions are checked up front (CREATE+WRITE in the target space for new instances, WRITE in the space of an existing instance, RELEASE additionally for auto-release spaces, DELETE (+RELEASE with forceUnrelease for a released instance), RELEASE, UNRELEASE) - if any item isn't permitted, the whole batch is rejected (401, like the single endpoints) before anything is written or queued. The checks aren't duplicated: the prechecks and the processing call the same checkCan* methods of InstanceService as the single manipulations (evaluated once per space for the upserts), so the rules can't diverge. Instances which don't exist are reported per item (404). The permissions are re-checked per item while processing. An async job runs with the roles of the user at submission time: AuthContext.runAs binds them to the worker thread, since the request (and its token) is gone by then.
Why: Imports of thousands of instances via the single endpoints cost one HTTP round trip, one transaction, one reconciliation, one global relation resolution (resolveRelations scans the unresolved relations of all instances), one schema compilation and one graph update per instance - the relation resolution and the graph update dominate for large imports. Processing a chunk set-based reuses the batch routines of the inference (reconcileInstances / processInstances are already set-based). The chunk transaction is the compromise between throughput and the size (locks, memory) of a transaction; the per-item fallback keeps the error reporting per item without paying for per-item transactions in the normal case. Asynchronous execution avoids the idle timeouts of reverse proxies for large batches (see ADR-054); it's optional, so small batches don't need polling. The job is stored in PostgreSQL (rather than in memory like the inference status) so its outcome survives a restart and the polling works with every application instance behind a load balancer.
Consequences:
- Within a chunk, an item can't refer to the outcome of an earlier item of the same chunk: items resolving to the same instance, or new items sharing a UUID or an identifier, are reported as FAILED (409) except for the first one. Across chunks, the items are processed in order.
- Relations between the items of a batch are resolved at the end of each chunk - so relations to instances of later chunks are resolved by these later chunks.
- The payloads of async jobs are only held in memory: a job interrupted by a restart isn't resumed by the server. The application instance running a job keeps its heartbeat up to date, a job without heartbeat for 5 minutes is marked FAILED (by any application instance). The changes of its already processed chunks remain. ~~Since the outcome per item is only stored at the end, they aren't reported per item.~~ Superseded by ADR-073: the outcome is stored with every chunk and the SDKs resume interrupted jobs.
- An atomic batch holds one transaction (and connection) for its whole duration - it's meant for consistency, not for very large imports.
- Since the roles are taken at submission time, revoking a role doesn't affect an already submitted job.
- The response doesn't contain the instances, only their UUIDs - POST /instancesByIds reads them in bulk.
ADR-073: Interrupted batch jobs are resumed by the SDKs, not by the server¶
Status: Accepted
Decision: A batch job interrupted by a restart (ADR-072) isn't resumed by the server. Instead:
- The outcome of a non-atomic job is stored within the transaction of every chunk (and of every item of the per-item fallback) - the outcome so far, the counters and the heartbeat are written as the last statement of the chunk's transaction. The stored outcome therefore always matches what has been committed.
- Reading a finished job whose outcome doesn't cover all items (BatchJobInformation.of) reports the missing items as NOT_PROCESSED (without id) and derives the counters from the stored outcome. An interrupted atomic job has no stored outcome, all its items are NOT_PROCESSED - its transaction has been rolled back.
- The SDKs (Java, Python) resume in AWAIT mode: while polling, connection errors and 502/503/504 are retried until the timeout (the server might be restarting). A FAILED job with NOT_PROCESSED items is resumed by resubmitting exactly these items with the same options, at most maxResumes / max_resumes times (default 3, 0 disables it). The returned job merges the outcomes in the order of the submitted items and carries the id of the last job. In BACKGROUND and SYNCHRONOUS mode the SDK doesn't keep the items, notProcessed() / not_processed() tells the caller what to resubmit.
Why: A resume by the server would have to act on behalf of the user without a valid token: the job would run with a stored snapshot of the roles, possibly hours later, after the token has expired or been revoked - today AuthContext.runAs only extends the roles of a request which has just been authorized. It would also have to store all payloads (up to 10000 per job) a second time, which costs exactly the import throughput the batches are made for, and the resubmission needs leases between application instances. The SDK still has the items and a valid token. Storing the outcome in the chunk's transaction makes the resubmission exact: every committed item is reported, every NOT_PROCESSED item hasn't been applied - so no item is applied twice and new instances without UUID can't be duplicated.
Consequences:
- One additional update of the batch_job row per chunk (the compressed outcome grows with the job). Since it's the last statement of the chunk's transaction, the row lock is held only until the commit - the heartbeat waits for it at most that long.
- An interrupted job is only noticed once its heartbeat is stale (5 minutes, plus up to one heartbeat interval) - the SDK waits that long before it resumes.
- The resumed job is a new job: the interrupted one keeps its outcome (with the NOT_PROCESSED items) until it expires.
- A job submitted synchronously and interrupted can't be resumed by the SDK - the request fails without job id. GET /v4/batch/jobs lists it.
- Resubmitting after other failures (e.g. an unexpected failure of the whole job) works the same way, limited by maxResumes.
ADR-074: Retraction of the user's own contribution, and the "sync" of a type in the SDKs¶
Status: Accepted
Decision: A user can retract their own contribution to an instance: DELETE /v4/instances/{id}/contribution and, for many instances, POST /v4/batch/instances/retract (a list of UUIDs, outcome per item RETRACTED or DELETED, ADR-072).
- A retraction empties the contribution: the row stays, keeps only its @type (with its original modification time) and is flagged retracted (contribution.retracted, Flyway V52). A retracted contribution doesn't count as a contribution of the user: withContribution, _hasContributed, _contributors and the "only contributor" check below ignore it. The next contribution of the user (PUT, PATCH, batch upsert) revives it - also if its payload doesn't differ (skipIfUnchanged doesn't skip it).
- If other users have contributed to the instance (with non-retracted contributions), the user's contribution is retracted and the instance is reconciled. If the reconciled payload changes, the last update of the instance is set to now (the remaining contributions are older) - a released instance becomes HAS_CHANGED, an instance of an auto-release space is released right away. Stored validation results are recomputed (as for ADR-071). Requires WRITE (+ RELEASE in auto-release spaces) - same as a contribution.
- If the user is the only contributor (other contributions are all retracted, or there are none), the instance is removed - like DELETE /instances/{id}: requires DELETE (and RELEASE with forceUnrelease for a released instance), a released instance is rejected (409) without forceUnrelease.
- WRITE is checked before it's revealed whether the user has contributed at all (404 otherwise).
The SDKs (Java client.batch().sync, Python client.batch.sync) build a "sync" of the instances of a type on top of it: the given instances are upserted (full replacement, skipIfUnchanged), then the instances of the type the user has contributed to (GET /instances?type=&withContribution=true, optionally restricted to spaces) which aren't among the upserted ones are retracted. If a single upsert fails, nothing is retracted (the SDK can't tell which instance the failed item stands for).
Why: Imports which mirror an external source have to remove what has disappeared from the source - but only their own share: other users might have curated the same instances. Retracting the contribution (instead of deleting the instance) keeps their work; removing an instance nobody else contributes to avoids empty instances. The @type is kept since the other contributions are often partial (PATCH) and don't define one - removing the row would leave an instance without type, which is invalid. Whether a user has contributed is therefore evaluated without the @type; the flag makes this evaluation a column check instead of decompressing the payloads, so the contribution filters keep using the primary key of contribution. The sync itself is client-side orchestration of existing endpoints: the listing by contribution (ADR-034) and the batches (ADR-072) already provide everything, and the SDK keeps the knowledge about the list - a server-side sync would need another job type holding all payloads.
Consequences:
- The type the retracting user has contributed stays the type of the instance until another contribution sets a newer one.
- The identifiers contributed by the user are kept by the instance (see "Identifiers are kept" in FEATURES.md) - only DELETE /instances/{id}/identifiers removes them.
- The sync is not atomic: an instance of the type which has been contributed to concurrently by the same user (e.g. another import) is retracted. The retraction of a type is bounded by what the user can read (the listing).
- A user whose DELETE is missing can't retract sole contributions - the whole retract batch is rejected (401), like any batch with a forbidden item.
ADR-075: The deployable Docker image is a GraalVM native image built in CI, development stays on the JVM¶
Status: Accepted
Decision: MarmotGraph Core can be compiled into a GraalVM native executable with Spring Boot's AOT processing. Development, debugging and the tests run on a regular JVM as before; the native executable is only built by Dockerfile.native (multi-stage: GraalVM Community native-image builder, distroless runtime image) - in CI by the GitLab pipeline (.gitlab-ci.yml).
- The Maven profile native extends the one of spring-boot-starter-parent (process-aot, reachability metadata repository) with:
- build-time bytecode enhancement of the JPA entities (hibernate-maven-plugin), since the proxies of lazy associations can't be generated at runtime in a native image,
- the graph engine profile for the AOT processing (-Dnative.graph.profile=nograph|neo4j, default nograph),
- -march=compatibility, so the executable runs on any CPU of the architecture.
- setup/NativeImageHints contributes what the AOT processing can't derive: reflection for every model class of org.marmotgraph.core which isn't a bean, aspect or entity (Jackson binds them in JPA converters, JsonAdapter and clients, not only in controllers), the resources read with getResourceAsStream (openapi/**, defaultTheme/**), the jakarta.json provider used by titanium-json-ld, the JDK proxy of the HttpServletRequest injected into singletons, the SQL exceptions Flyway translates errors with reflectively (without them, a failing connection shows up as a NoSuchMethodException instead of the actual error), and Java serialization for the object graphs of JSON-converted attributes (Hibernate compares them by serializing them once they aren't equals): our serializable models plus the JDK types JSON trees consist of.
- Flyway can't scan the classpath for Java migrations in a native image - setup/FlywayJavaMigrations registers them explicitly there (a test fails if one in db.migration is missing).
- setup/Config is a class instead of a record: the @Value annotations of record components are propagated to the final fields, for which the AOT processing generates (failing) field injection.
- The GitLab pipeline runs the tests with -Pnative (i.e. with enhanced entities) on the JVM and builds one image per graph engine (tag suffix -native-nograph / -native-neo4j), published to the project's container registry for the default branch and tags.
- springdoc is upgraded to 3.0.x (the line for Spring Boot 4): 2.8.x references Spring Data classes which no longer exist, which only fails when the configuration classes are introspected - as the AOT processing does.
Why: A native image starts in a fraction of a second, needs considerably less memory and results in a much smaller image without a JRE - relevant for scaling out and for the resource footprint of deployments. Building it in CI only keeps the fast edit/compile/debug cycle of the JVM and avoids that every developer needs GraalVM and minutes of native compilation.
Consequences:
- Bean conditions (@Profile, @ConditionalOnProperty, spring.autoconfigure.exclude) are evaluated at build time:
- The graph engine is fixed per image. The profile of the build stays active at runtime and further profiles are added - the image sets SPRING_PROFILES_ACTIVE to its engine to replace the default nograph of application.properties. GraphEngineCheck fails the startup if the profile of another engine is activated as well, instead of silently running the compiled one.
- org.marmotgraph.runtimeMetrics (RuntimeMetricsAspect) has to be set at build time to have any effect in a native image.
- Properties which are read by conditions have to be resolvable during the build - ACTUATOR_PWD gets a placeholder value for the AOT processing only.
- New code which deserializes classes outside of org.marmotgraph.core, loads classpath resources by name, uses reflection / dynamic proxies or puts other JDK types into JSON-converted attributes needs an entry in NativeImageHints; new Java migrations an entry in FlywayJavaMigrations. Such gaps only show in the native executable, not in the JVM tests. Verify a native build before releasing such changes - running the AOT-processed jar on GraalVM with the tracing agent (-Dspring.aot.enabled=true -agentlib:native-image-agent=config-output-dir=...) while exercising the API lists all reflective, serialization and resource accesses in one run.
- Verified with the demo data upload (types, schemas, instances, release, validation), CRUD, dynamic queries, the OpenAPI docs and Swagger UI against the nograph image: startup ~1-2 s, ~140 MB RSS after startup.
- GraalVM Community only has the Serial GC. For large heaps, Oracle GraalVM (G1, PGO - GFTC license) can be used via the build args BUILDER_IMAGE / NATIVE_IMAGE_OPTIONS of Dockerfile.native.
- The native compilation needs ~7 GB of heap plus ~1 GB for the rest of the process (with 4, 5 and 6 GB, the analysis runs out of memory, even with --parallelism=2). native-image sizes its heap by the physical memory of the host, not the free one, so it has to be capped (NATIVE_IMAGE_OPTIONS=-J-Xmx7g) on shared machines and runners.
- The JVM image (Dockerfile) stays available, e.g. for diagnosing problems that are specific to the native image.
- The image always contains the documentation (ADR-060) and the commit id: a Python stage of Dockerfile.native builds the site with Zensical (including the files the docs embed as snippets - ARCHITECTURE.md and the SDK guides, which therefore are in the build context), the Maven profile docs bundles it with its Zensical execution skipped (-Dexec.skip=true). .git is bind-mounted for the git-commit-id plugin, which fails the build without it (git.failOnNoGitDirectory=true) - the build context has to be a git checkout; shallow clones (as in GitLab CI) are fine. Local Maven builds keep working without .git and docs.
- Spring Boot's native Flyway support runs Flyway's classpath scanner, which can't read the resources of a native image and warns "Unable to scan location: /db/migration (unsupported protocol: resource)" while the migrations are found nevertheless - the native runtime image sets that logger (org.flywaydb.core.internal.scanner.classpath) to ERROR.
ADR-076: The bulk validation runs asynchronously and reports its progress¶
Status: Accepted
Decision: POST /v4/instances/validation?space= (ADR-028) starts the bulk validation in the background and returns 202 Accepted with the initial BulkValidationStatus. GET /v4/instances/validation (VALIDATE_INSTANCES) returns the status of the current or last run: state (IDLE, RUNNING, DONE, FAILED), space (null for all spaces), start and end time, total (the instances of the space / of all spaces, counted at the start), processed (updated after every batch of 1000) and result - the summary {instances, validated, failed} of the instances processed so far (the former response of the POST) - plus an error message. Same pattern as the inference (ADR-054).
- Only one run at a time: the in-process ReentrantLock is replaced by a compare-and-set on the status (409 as before), since the lock can't be released by the background thread.
- The background work runs as the triggering user (AuthContext.runAs), since the validated representation (_space) depends on the user - same as for a synchronous run.
- A failing batch ends the run as FAILED (as the synchronous run aborted); the findings of the batches processed so far stay replaced.
Why: A progress indicator needs the total and the progress of a run, and a run over all spaces of a large database takes long enough for reverse proxies to close the open request on their idle timeout (see ADR-054) - the consequence ADR-028 left to be revisited.
Consequences:
- Breaking for /v4 clients of the POST: the summary is no longer the response, it's result of the status once its state is DONE.
- The status is kept in memory per application instance and is lost on restart; a run interrupted by a restart isn't resumed. Behind a load balancer, the status has to be polled from the instance which runs the validation.
- processed counts all instances of a batch, result.instances only the ones with an in progress payload - so processed / total is the progress, result the outcome.
ADR-077: Compliance per type in the statistics¶
Status: Accepted
Decision: Every entry of validation in GET /v4/statistics (ADR-052) additionally contains perType: the same compliance groups for every type with a schema of this name (identifier, name - the label or the last segment of the identifier as for types), the type with the most instances first. The figures of the schema name are the sums of its types: one query grouped by schema name and type replaces the one grouped by schema name. Restricted to the readable spaces like the rest of validation.
- The most frequent violations (per location and keyword) are not reported. The errors are stored gzip compressed (ADR-027) and can't be aggregated in SQL - it would need an additional, aggregatable summary of the violations of every result (a table or a JSONB column, written with every validation) and its aggregation on every request of the statistics.
Why: The compliance per schema name doesn't tell which type is responsible for the non-compliance when a name spans several types. Grouping by type in the same query costs next to nothing. The most frequent violations weren't worth the additional storage and write cost and the slower statistics.
Consequences:
- The response grows with the number of types per schema name.
- Where to start fixing the data has to be found via the stored results of single instances (returnValidationResults, GET /instances/{id}/validation).