From 8f2405bb8de4339d96636247e840d15b1fdd9baa Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Mon, 23 Nov 2026 14:52:05 +0000 Subject: [PATCH] :books: Trim backend memories and split out job guidance Route backend readers to focused job and binfile notes. Keep cross-file invariants and point to code for implementation details. Drop stale graph details and an obsolete audit alias. Link the URI note from the module cores so URL changes can find it. AI-assisted-by: gpt-6.2-sol --- .serena/memories/backend/audit-log.md | 3 - .serena/memories/backend/binfile.md | 8 + .serena/memories/backend/core.md | 159 +---- .serena/memories/backend/graph-experiment.md | 641 +------------------ .serena/memories/backend/jobs.md | 22 + .serena/memories/backend/subtleties.md | 7 +- .serena/memories/common/core.md | 2 + .serena/memories/common/uri.md | 13 +- 8 files changed, 66 insertions(+), 789 deletions(-) delete mode 100644 .serena/memories/backend/audit-log.md create mode 100644 .serena/memories/backend/binfile.md create mode 100644 .serena/memories/backend/jobs.md diff --git a/.serena/memories/backend/audit-log.md b/.serena/memories/backend/audit-log.md deleted file mode 100644 index 60c2a9fe12..0000000000 --- a/.serena/memories/backend/audit-log.md +++ /dev/null @@ -1,3 +0,0 @@ -# Backend Audit Log - -Moved to `mem:audit-log`, the guide to event collection, delivery and retention. diff --git a/.serena/memories/backend/binfile.md b/.serena/memories/backend/binfile.md new file mode 100644 index 0000000000..23f5bb98a1 --- /dev/null +++ b/.serena/memories/backend/binfile.md @@ -0,0 +1,8 @@ +# Backend binfile import and export + +- Start at `app.binfile.common` for shared domain configuration, `app.binfile.jobs` for the job adapter, `app.rpc.commands.jobs` for the public envelope, and `app.binfile.v1`/`app.binfile.v3` for the formats. For cross-module model changes see `mem:common/data-model-change-checklist`; for durable execution see `mem:backend/jobs`. +- Keep legacy RPC and job configuration aligned on frozen IDs, team features and import size limits. The import creation request is not the stored job params: the server can determine the format from the upload, and audit uses manifest metadata, not file contents. +- Revalidate permissions when jobs run, not just when submitting: access can be revoked while queued. Import runs inside a transaction so an interruption cannot leave half a file. The job adapter stops on the heartbeat interrupt and checks again after the final tap; do not publish success if cancellation fell between the last tap and return. An upload not adopted by a job must be released; adopted import packages and temporary copies must be released on terminal outcomes. +- Keep the progress stage vocabulary shared across formats. Each tap carries its outer scopes, with no dependency on an earlier tap; throttling can drop intermediate events. Do not put source IDs or names into public progress. Normalize format-specific return shapes in the adapter rather than making the caller know the format. +- A v1 package can list a file twice (legacy export included libraries without deduping). Consume both objects of every entry to keep the stream aligned, but import and report the first occurrence only. +- v1/v3 import links must refer to files in the package and reject self-links and dependency cycles, using the same check as the live link command. Keep iteration deterministic so the first edge wins consistently. diff --git a/.serena/memories/backend/core.md b/.serena/memories/backend/core.md index 588c8cffcb..0547479464 100644 --- a/.serena/memories/backend/core.md +++ b/.serena/memories/backend/core.md @@ -1,146 +1,31 @@ # Backend Architecture and Workflow -Backend: JVM Clojure; Integrant; PostgreSQL; Redis/Valkey; RPC; HTTP; storage; mail; audit/logging; workers. +JVM Clojure backend. Start in `app.main` for Integrant wiring, `app.rpc.commands` for RPC, `app.http` for HTTP, and `app.config` for environment defaults and feature flags. ## Focused memories -- Cross-cutting backend subtleties (RPC, DB helpers, workers, cron, CLIMIT, config and HTTP/session middleware, http self-metrics, media processing, and file data persistence): `mem:backend/subtleties` -- Storage abstraction, logical buckets, object lifecycle, deduplication, access, and garbage collection: `mem:backend/storage`. -- Embedded Ladybug graph experiment, projection, incremental sync, console, and risks: `mem:backend/graph-experiment` -- Session lifetime config, token `:exp`, and idle/absolute GC: `mem:backend/session-expiration`. -- Auth flows, permission model, teams, projects, invitations, comments, webhooks, audit: `mem:backend/auth-permissions-product-domains` -- WebSocket subscriptions, the connection registry (local per backend, unlike the bus), and how a lost permission gets revoked: `mem:backend/websocket-subscriptions`. -- Audit-log event collection (RPC wrapper, frontend ingestion), telemetry duality, webhook fan-out, error reporters, Nexus archival and retention: `mem:audit-log` (guía completa, también para perfiles junior; el stub `mem:backend/audit-log` solo redirige aquí) -- Services, task-queue/Pub-Sub topology constraints -> `mem:prod-infra/core`. +- RPC wrapper order, DB transactions and advisory locks, config and HTTP middleware, metrics, and file data persistence: `mem:backend/subtleties`. +- Job definitions, submission and lifecycle transaction boundaries, dispatch/recovery, user-facing jobs, and metrics: `mem:backend/jobs`. +- File import/export format compatibility, jobs, permissions and cancellation: `mem:backend/binfile`. +- Storage bucket rules, object lifecycle, deduplication, access and GC: `mem:backend/storage`. +- Graph projection parity, debug sessions, access and native resource ownership: `mem:backend/graph-experiment`. +- Session lifetime, token `:exp` and session GC: `mem:backend/session-expiration`. +- Auth, product permissions, teams, projects, invitations, comments and webhooks: `mem:backend/auth-permissions-product-domains`. +- WebSocket connection ownership and revocation: `mem:backend/websocket-subscriptions`. +- Audit collection, fan-out, archival and retention: `mem:audit-log`. +- Service layout, task queues versus Pub/Sub, and horizontal scaling: `mem:prod-infra/core`. +- Public URLs and base subpaths: `mem:common/uri`. -## Stable namespace map +## RPC and DB conventions -- `app.rpc.commands.*`: RPC command implementations exposed under `/api/main/methods/`; `/api/rpc/command/` remains as a backward-compatible route. -- `app.rpc.permissions`: permission predicate/check helper factories. -- `app.http.*`: HTTP routes and middleware. -- `app.auth.*`: provider-specific authentication helpers such as LDAP/OIDC. -- `app.loggers.*`: audit, webhook, database, and external log integrations. -- `app.db.*` / `app.db`: next.jdbc wrapper and SQL helpers. -- `app.tasks.*`: background task handlers. -- `app.worker`: task execution/cron plumbing. -- `app.main`: Integrant system map and component wiring. -- `app.config`: `PENPOT_*` env config and feature flags. -- `app.health`: per-process availability flag; `/readyz` answers 503 while offline. Flipped from `app.srepl.main` (`set-offline` / `set-online`). -- `app.srepl.*`: development REPL helpers for manual backend operations (data inspection, migration helpers, one-off admin tasks). -- `app.nitrate`, `app.rpc.commands.nitrate`, and `app.rpc.management.nitrate`: external Nitrate subscription/organization integration, gated by the `:nitrate` feature flag and shared-key HTTP calls. +- Read RPC names start with `get-`. Return plain maps/vectors or raise structured `app.common.exceptions`. See the adjacent command and tests for schema and permission patterns. +- `db/get*` and `db/query` do not take column names as trailing args. To include logically deleted rows, pass `{::db/remove-deleted false}` as the single options map. For SQL membership use `ANY(?)` with `db/create-array`; a vector in the where-map is not `IN`. +- SQL migrations must work on PostgreSQL 15 even if devenv runs a newer version; for example, `SET STORAGE DEFAULT` requires PostgreSQL 16. For shared-env SQL access or a DDL dump, see `mem:scripts/psql`. +- A table with `deletion_protection__tgr` must be deleted through the owning GC or an explicit transaction-local opt-out; it protects cross-table cleanup that a bare `DELETE` bypasses. Tests use `th/db-force-delete`. +- Stream large reads with `db/plan` inside `db/tx-run!`: without a transaction PostgreSQL JDBC ignores fetch size. A row is a view over the result set: copy the needed values inside the reducer before buffering. Use `reduce`/`transduce`, not `sequence`; use separate transactions for chunks that must commit while the scan holds its connection. -## RPC conventions +## Local verification -RPC commands are defined with `app.util.services/defmethod` and schemas. Use `get-` prefixes for read operations. Command metadata usually includes auth, docs version, params schema, and result schema. Return plain maps/vectors or raise structured exceptions from `app.common.exceptions`. - -Backend RPC command areas without focused memories include access tokens (auth rules, incl. MCP tokens, in `mem:backend/auth-permissions-product-domains`), binfile, demo, feedback, file snapshots, fonts, management, Nitrate, and webhooks beyond the notes in `mem:backend/auth-permissions-product-domains`; inspect nearby command tests and command metadata before changing them. - -## DB conventions - -`app.db` helpers accept cfg, pool, or conn in most places and convert kebab-case to snake_case: -- `db/get`, `db/get*`, `db/query`, `db/insert!`, `db/update!`, `db/delete!`. -- `db/get*`/`db/query` signature is `(ds table where-params & {:as opts})`: trailing keywords become an opts MAP (ignored by the select builder — use `{::db/remove-deleted false}` map as the single vararg to also see rows with `deleted_at` set), while a trailing ODD number of keywords crashes with "Don't know how to create ISeq from: Keyword". Extra keywords are NOT a column filter: rows always come back with all columns. -- Next.js/JDBC caveat: where-maps don't support value vectors (no `IN`); use `status = ANY(?)` with `db/create-array` inside `db/tx-run!`. -- Use `db/run!` for multiple operations on one connection. -- Use `db/tx-run!` for transactions. -- `job`-substrate specifics (unified jobs): the lifecycle writers in `app.jobs` are `claim`, `retry-job`, `complete`, `fail` and `cancel`, and the dispatcher owns the transition to `scheduled` and the two abort sweeps (`lost` and `orphan`), and writes their events itself; each one is a conditional update plus its `job_event` row in the same transaction, so history can never contradict the row. A writer that affects no row writes no event and no metric. They never join the caller's transaction, because a lifecycle write reports on work that already happened: a rolled back caller cannot undo a transition, and an independent connection cannot see the caller's uncommitted job row, so a job must be committed before it can be claimed. GC deletes return resource ids via `RETURNING` inside one transaction. -- Every public function of `app.jobs` takes a cfg map. A bare pool or connection is a caller bug and is not coerced: the substrate has no conversion of its own, and the ones in `app.db` are the db layer's business. -- Every new foreign key of the substrate is `DEFERRABLE`, `job_event.job_id` included. -- Some tables carry a SQL deletion guard (`raise_deletion_protection` + a `deletion_protection__tgr` statement trigger): `profile`, `team`, `team_font_variant`, `file_media_object`, `file_thumbnail`, `file_tagged_object_thumbnail` and `job`. A `DELETE` raises unless the transaction runs `SET LOCAL rules.deletion_protection TO off` (the guard is on when the GUC is unset, empty or `on`); see `app.tasks.objects-gc`, `app.jobs.gc` and `th/db-force-delete`. - -Database migrations live in `backend/src/app/migrations/`; pure SQL migrations are under `backend/src/app/migrations/sql/`. SQL filenames conventionally start with a sequence and verb/table description, e.g. `0026-mod-profile-table-add-is-active-field`. Applied migrations are tracked in the `migrations` table. - -Migrations must stay within PostgreSQL 15 syntax: the official docker images (`docker/images/docker-compose.yaml`) pin `postgres:15`, so anything newer breaks those deployments (`SET STORAGE DEFAULT` is PostgreSQL 16, for instance). The documented floor is >=15. - -For interactive PostgreSQL access with correct dev defaults, use `scripts/psql`; to dump the current DDL schema, use `scripts/db-schema` (see `mem:scripts/psql`). - -For deeper details on transaction semantics, advisory locks, Transit vs JSON helpers, and dev/test DB URLs: `mem:backend/subtleties`. - -## Background tasks (unified jobs) - -Every background job is a job-def: a plain `(defn execute-X [cfg params] ...)` in its namespace + a malli params schema + an `ig/init-key` that returns the job-def map `{::jobs/name, ::jobs/schema, ::jobs/handler, ::jobs/decoder, ::jobs/validator}` (decoder/validator precompiled at init), optionally with `::jobs/result-schema` when the result carries types plain JSON does not keep (a uuid, whether a value or a map key): the substrate compiles the decoder from that schema on registry init and checks a result against the schema before storing it. The registry is the `::jobs/defs` wiring in `app.main`, which also populates a module-level registry used by `jobs/submit` as fallback — job-def components cannot ig/ref `::jobs/defs` (wiring cycle). Submit from RPC code passes its RPC cfg (it carries `::jobs/defs` via ig/ref). - -- `::jobs/handler` is `(fn [context params] ...)`. It is NOT given the runner cfg: a job-def closes over its own dependencies, and handing it the runner cfg would let a handler reach the pool or any other component. A wrapper passes the context to its implementation only when the implementation takes it; most do not, and their implementation stays `[cfg params]`. -- The context is built by `jobs/make-context` and has exactly five keys: `id`, `name`, `label`, `resource-id`, `profile-id`, behind a closed schema. `profile-id` is the owner of a user-facing job and nil for an internal one, and it is there so a handler can revalidate permissions and check who owns its resource without a second query. `queue` is absent on purpose (a routing detail of the dispatcher, not a property of the job) and so are `retry-num`/`max-retries`/`attempt` (retry policy belongs to the runner, and an attempt number cannot be durable because the `noop` strategy re-runs without incrementing the counter). -- `jobs/invoke` is the in-process escape hatch: it delivers a nil context without a row, validates and delivers `::jobs/context` when given, and keeps `::jobs/job-id` independent. `::jobs/context` and `::jobs/job-id` are cfg options, not params. -- Business params live in the `params` column (plain JSON, decoded with the job-def decoder). `submit` takes optional `::jobs/profile-id`, `::jobs/resource-id` (both validated as UUIDs) and `::jobs/expires-at` (an instant: the retention the jobs GC sweeps by), all stored as columns; nothing is inferred from `params`. The binfile creation commands are the callers that pass a profile-id and a resource. -- A job-def may carry optional metadata keys read from the registry by its consumers, never by the substrate: `::jobs/family` (e.g. `:export`) groups the jobs of a family for quotes, `::jobs/resource-role` (`:input` or `:output`) says whether the job's `resource_id` is what it consumes or what it produces, and `::jobs/queue-name` names the queue the creation command routes the job to (`submit-job` falls back to `:binfile` when the def does not set it). -- Job resources (`app.jobs.storage`) are the objects a job owns through `job.resource_id`: they live in the `job-resource` bucket, are written with the profile of the job as owner (only that profile can read them back from `/assets/by-id`) and are never deduplicated. They carry no expiry of their own, because `expired-at` is stored as `deleted_at` and an object with it is unreadable from birth: the retention of the artifact is the retention of its job row. The writer marks the object as touched right away, so an artifact that no row references (a crash between the upload and the completion) is reclaimed by `storage-gc-touched`, and a row that does reference it freezes it until the jobs GC deletes the row and touches the object. -- The binfile jobs (`:export-binfile` and `:import-binfile`) run the core of `bf.v1`/`bf.v3` through `app.binfile.jobs`, which turns the `:progress` taps of the core into `progress` events of the job with `jobs/heartbeat` (the `modified_at` touch at most once per second, progress events at up to ~200ms). Each event is a self-contained milestone: a `:stage` keyword of one vocabulary shared by the two formats (the same work has a different name in v1 and v3) and an optional `:counters` map, with the counter of the activity named after its own stage and the outer scopes in course as context, which the tap carries itself (the reader puts `::outer-counters` in every tap inside them — today only `:files`, extendable to `:teams`/`:projects` for multi-scope exports — so the adapter remembers nothing between taps and a tap that happens outside any scope has no context); the ids and names the taps carry never reach the event. Every tap is reported, so a tap with no units to count still keeps the job alive, and a milestone the throttle drops loses nothing because the next one carries the same state. The adapter checks that the job is still active before the run, and the beat raises an `:interrupt` right there on the run thread when the job is no longer active, so the work stops at its next event point inside the transaction of its handler, which rolls back. A run whose last tap predates the interruption is discarded by the check once it returns. The adapter passes the job id from the handler context. Their job-def components carry pool, storage, metrics and msgbus, because a job with a `profile_id` cannot store an event without a msgbus on its cfg. Both readers answer with the same shape (`:file-ids` and, in version 3, the resolution of the libraries), because the version 1 reader returns a bare set of file ids. -- Both binfile handlers revalidate their permission at run time, not only when the job is created, because it can be revoked while the job waits: the export checks the read permission of every file before reading anything and stores the package in `job-resource` as the resource of the job (answering with the completion envelope), and the import checks the edition permission of the destination and runs the core inside a transaction, which is what makes a cancelled import roll back instead of leaving half of a file. The import releases its package (marks it as deleted and drops the reference from the job row in the same transaction) and deletes its temporary copy once the job is terminal, whatever the outcome. Both handlers check their own result against a schema before returning it (the import job-def declares that same schema as its result schema, which is what types the resolution when the row is read). -- The v3 and v1 imports only materialize a library relation when both ids belong to the package and the link would neither be a self link nor close a dependency cycle (the same `bfc/library-link-status` check that `link-file-to-library` uses to raise); relations are processed in sorted `(file_id, library_file_id)` order, which `get-files-rels` also returns, so the first edge wins deterministically, and every edge it ignores is logged with a warning. The v2 import stays out of that guard on purpose: it is only reachable from the developer REPL (`app.srepl.binfile`) and keeps inserting the relations as they come. Migration `0158-del-forbidden-file-library-rels` deletes the legacy cross-team and self rows from `file_library_rel` and their `file_library_sync` rows, sync rows first. -- A version 1 package lists its files in the metadata and the importer creates one file per entry. The v1 export (gone from the product; only tests and the developer REPL use it) unioned the requested files with their libraries without deduplicating, so a package exported from a file inside a library cycle lists that file twice. The importer reads the pair of objects of every entry to keep the stream in sync, imports the first occurrence only, warns about the repeats, and answers with one id per imported file. -- The domain cfg of a binfile request lives in `app.binfile.common` (`export-cfg`, `import-cfg`), so the legacy RPC and the jobs freeze the same ids, resolve the same team features and apply the same anti-zip-bomb limits. `resolve-export-type` is the translation the legacy RPC needs for its deprecated boolean flags; the creation command asks the caller for the type instead of guessing a default. -- Two retention knobs, easy to confuse: `:jobs-retention` sweeps terminal internal rows (the ones without a profile), while `:jobs-user-ttl` is the default expiry a user-facing job gets when it is created; the jobs GC deletes the row once `expires_at` passes and touches its resource. The heavy work of a user job runs on its own `:binfile` queue (`:worker-binfile-parallelism`, default 1) so it does not block the default runner. -- The quote of a family of jobs (`::export-jobs-per-profile`, `::import-jobs-per-profile`) counts the jobs of the profile that are still on their way (`new`/`scheduled`/`running`/`retry`) whose name the registry gives for that family, so a new job of the family is covered without touching the quote. -- A user-facing job is created through `app.rpc.commands.jobs`. One command per job type: `create-export-binfile-job` and `create-import-binfile-job` name the job they create and their body carries only `:params`, whose schema the command imports from the job namespace (`::sm/params`), so the RPC validates the business params up front, before the command runs; the job-def is still the place that owns them and validates them again at run time. The commands check the permission and the quote of the family before the expensive part, submit with `max-retries 0`, an expiry from `:jobs-user-ttl` and the queue the job-def routes to through `::jobs/queue-name` (`:binfile` when the def says nothing; read by the command, never by the substrate), and answer with a summary of the row. The import command has its own creation schema (`import-binfile/schema:create-params`, version optional) because the request is not the stored params: the command fills the version (from the caller or the package header) and the manifest metadata kept for audit. It assembles the upload, reads the manifest of a version 3 package for the audit (never its content) and stores the package in `job-resource` as the resource of the job, releasing it when the job never comes to own it. -- `get-job` is the read surface a profile has over its own jobs: it answers with the same summary the creation commands return plus the `result` of a finished job or its public error (through `decode-job-error`, so the keywords come back), and a job of another profile is not distinguishable from one that does not exist: both answer `not-found`. `decode-row` decodes `params`, `result` and `error`, and the result is then decoded with the decoder the substrate compiled from the result schema the job-def the row names declares (`decode-result`; a def without one, or a row whose job-def is gone, keeps the plain JSON the row holds: a uuid as the text it is on disk, a uuid used as a map key as a keyword). The event log still has no read surface: a client that follows a job takes its progress from the websocket. -- `heartbeat` uses named options `[cfg & {:keys [job-id progress] :as options}]` and returns the number of durable writes, so 0 means there was nothing to write: no job context, or the throttle did not allow it. A write that finds the job no longer active (terminal or gone) raises an `:interrupt` (`code :job-interrupted`, carrying the job id and the status it found) through the shared `jobs/check-active` instead of counting zero, so a task in course stops at its next beat; the interrupt is internal and never reaches HTTP (the management progress report answers `:skip` for it). The job id falls back to `::jobs/job-id` on the cfg and then to the runner-bound `*job-id*`. The `modified_at` touch is throttled to ~1s and the progress event to ~200ms, so the check fires at most once per second with no extra query (the read of the row happens only when a write already found nothing). A progress report is a milestone (`schema:progress`): a required `:stage` keyword plus an optional `:counters` map of `scope -> {:current, :total?}`, and no other key. Counters are non-negative, a `total` is positive and never lower than its `current`, and stage and counter keys are names of at most 64 characters. A milestone without counters is valid (a point of the run with no units to count), the stage vocabulary belongs to the worker and not to the substrate, and a client must degrade for a stage it does not know. Read a stored payload back with `jobs/decode-progress`: the database holds the keywords as strings. The 1s beat (down from 60s, so a cancelled heavy job is seen as gone at its next beat) costs one `modified_at` touch per beating job per second: cheap while the only heavy beater runs alone on its queue, revisit if concurrent beating jobs ever grow. -- `job.error` conforms to `app.jobs/schema:job-error` (`type` and `code` keywords, `hint` text, extra details allowed). Read it back with `jobs/decode-job-error`; a plain `db/decode-json-pgobject` leaves the keywords as strings. `complete` takes named options and an optional `resource-id`, which is only ever set, never replaced: it reads the row locked inside its own transaction and applies the rules in a fixed order, skipping a job that is no longer completable before refusing one for its resource, so the answer is a function of the row and not of the order two callers arrive in. It checks the result against the schema the job-def of the row declares before it writes (a violation raises `:invalid-result` and nothing is stored), and only for a transition that is going to write: a terminal job answers `:skip` without validating. `complete` is the single door of a result, so the check covers the runner and the external worker that completes a job through the management RPC (`::complete-job`), which stores a result the substrate would otherwise take blind. - -For worker dispatch, cron, retry semantics (`ex/raise :type ::wrk/retry` with `:delay`/`:strategy`), deduplication, job events, and queue internals: `mem:backend/subtleties`. - -## Jobs metrics - -- `app.jobs.metrics` owns the jobs metric names and bounded labels. It has no gauge and no sampler: to see the current state, the operator runs one SQL query (`SELECT status, count(*) FROM job GROUP BY status`); the namespace runs no query and starts no thread. -- Metrics use `name`, `queue`, `outcome`, `reason`, `stage`, `kind`, `action`, `type` and `result` labels, each on its own family. `queue` survives only on `penpot_jobs_dispatcher_batch_size`: of the measurements that used to carry it, every other one is now keyed by the job name, because the job-def owns its routing (`::jobs/queue-name`) and the name already determines the queue; the GC, cron, request, event and file-data-offload families keep their own dimensions. Job IDs, profile IDs, params, reply bodies and exception text must never be labels. Every label goes as-is (lowercased where case varies): values come from fixed call sites, so a new value in Prometheus means new code, not noise. Only a missing value falls back, and each label has its own default: `other` (name, queue, GC kind, offload type), `failed` (the total and batch outcomes, offload result), `error` (cron and request outcomes), `backoff` (retry reason), `execution` (dispatcher stage), `deleted` (GC action) and `none` (cron reason). The submit outcome has no fallback on purpose: its three values come from fixed call sites. -- The canonical job name is a keyword (`app.jobs/schema:job-name`): `submit` and `invoke` reject strings. The row stores text, so `jobs/get-job-def` still coerces (it is the runner's boundary), cron entries carry the job under `:job` with `d/name` only at the SQL/log boundary, and test helpers keyword-ize row names before invoking. -- The durable lifecycle metrics are one submit counter with `outcome` (`created`, `skipped`, `refreshed`), dispatched and retries counters; claim-wait, execution and total-time histograms; dispatcher batch timing and size; GC, cron and ephemeral request metrics. `penpot_jobs_dispatched_total` and the claim-wait histogram are keyed by the job name. -- `app.metrics/run!` is safe for recording failures, but metrics components still require a valid metrics instance. Durable submit call sites carry `::mtx/metrics` through RPC or job-def configuration. The jobs substrate takes the **cfg**, not the instance, and resolves it with `app.metrics/instance`, which raises `:missing-metrics` when absent: `app.jobs`, `app.jobs.metrics`, the runner, the dispatcher, cron and the jobs GC all follow that. `app.http`, `app.rpc.climit` and `app.storage.s3.metrics` still take the instance and were left out of scope on purpose, so do not read the codebase as uniform. The six job writers resolve at the top of their body, before writing, because their metric lands in a `db/after-commit` callback that swallows exceptions. The GC, the dispatcher and cron resolve inside that callback instead, so their guarantee rests on the component schema instead. A job that calls `heartbeat` from a component cfg must carry `::mtx/metrics` on it, and the event helper records the counter from the cfg the transaction hands it. -- SQL-backed job metrics are registered with `app.db/after-commit` from INSIDE the transaction that changed the row, so a rollback cannot inflate submit, terminal, retry, event or dispatcher counters. Every lifecycle writer owns that transaction (`app.db/own-transaction` drops `::db/conn` and `::db/read-only`, so a write can own its transaction even inside a read-only caller), and `db/transact!` gives a transaction that joins no other its own callback context, so the write and its metric commit or vanish together. `submit` is the exception and joins the caller on purpose: creating a job is part of the caller's business work. -- `penpot_jobs_events_total` counts stored job events with no labels: the interesting split is `kind`, and grouping a growing append-only table to build a metric is not worth the query on the write path. -- The terminal counter per outcome is the `_count` of `penpot_jobs_total_ms` (`completed`, `failed`, `cancelled`, `aborted`), so there is no separate terminal or orphan counter: `_count{outcome="aborted"}` counts the system-side aborts: an expired orphan lease, or a `scheduled` job whose queue has nothing waiting after the grace or that passed the 24-hour cap. There is no backlog gauge and no pending-age gauge: the backlog is a SQL query, and `created_at` is not renewed by a debounce refresh, so an age gauge would lie. -- `penpot_tasks_timing` remains exported for compatibility while the jobs-specific histograms are adopted. - - -## REPL - -In devenv, backend nREPL is exposed on port 6064. - -### Non-interactive eval (preferred for agents) - -`./scripts/nrepl-eval.mjs` connects to an already-running nREPL server and evaluates code. Session state (defs, `in-ns`) persists across invocations via a stored session ID in `/tmp/penpot-nrepl-session--`. - -```bash -./scripts/nrepl-eval.mjs '(+ 1 2)' # single expression -./scripts/nrepl-eval.mjs "(require '[my.ns :as ns] :reload)" # reload after edits -./scripts/nrepl-eval.mjs -e # inspect last exception (*e) -./scripts/nrepl-eval.mjs --reset-session '(def x 0)' # discard session, start fresh -./scripts/nrepl-eval.mjs <<'EOF' # multi-expression heredoc -(def x 10) -(+ x 20) -EOF -``` - -Default port is 6064. Use `-p ` for a different port. Use `-t ` to override the 120s timeout. Do not start the nREPL server — assume it is already running. - -### Interactive REPL - -`backend/scripts/nrepl` starts a REPLy client connected to the running nREPL. - -For an in-process backend REPL (where you control the JVM lifecycle), stop the running backend first so port 9090 is free, then run `backend/scripts/repl`. Useful top-level helpers include `(start)`, `(stop)`, `(restart)`, `(run-tests)`, and `(repl/refresh-all)`. Many `app.srepl.main` helpers accept the global `system` var, e.g. manual email or maintenance operations. - -## Fixtures - -Fixtures can populate local data for manual testing/perf work. From the backend REPL, run `(app.cli.fixtures/run {:preset :small})`; fixture users conventionally look like `profileN@example.com` with password `123123`. Standalone fixture aliases may exist, but check current `backend/deps.edn` before relying on old command names. - -## Performance - -* **Type Hinting:** Use explicit JVM type hints (e.g. `^String`, `^long`) in performance-critical paths to avoid reflection overhead. -* **Batch inserts:** Use `db/insert-many!` for bulk row inserts — generates a single SQL with multiple parameter tuples. Avoid on very large datasets (SQL length / parameter count limits). -* **Server-side cursors:** Use `db/plan` (fetch-size 1000, forward-only, read-only) for large result sets, always inside `tx-run!` (prefer `::db/read-only true`): the pool runs with auto-commit on, and the PostgreSQL JDBC driver only honors `fetch-size` (real streaming cursor) with auto-commit off, so a `plan` outside a transaction silently materializes the whole `ResultSet` in memory. Never fetch large collections into memory at once. `db/plan` is an `IReduceInit`: `reduce`/`transduce` over it (`sequence` does not work on it), and with `partition-all` the transducer's completing arity is what flushes the last partial chunk; the `reduce` holds one connection (and, inside `tx-run!`, the whole transaction) open until it finishes, so keep chunk transactions separate from the plan one when each chunk must commit on its own (the objects GC does). A plan row is a **view over the open result set**, valid only inside the reducing function: read the columns you need right there — buffering rows to read them later (a `partition-all` buffer, a lazy seq) silently yields nil columns. `db/cursor` (manual `DECLARE`/`FETCH`) is a leftover with no callers left. -* **Transaction discipline:** Use `tx-run!` for writes (opens a transaction), `run!` for reads (single connection, no transaction) — except `db/plan`, which always needs `tx-run!` (see above). Set `:read-only` on `tx-run!` when applicable to let PostgreSQL optimize. - -## Lint and Format - -IMPORTANT: all CLI commands must be executed from the `backend/` subdirectory. - -* **Linting:** `pnpm run lint:clj`. -* **Formatting:** `pnpm run check-fmt:clj` to check, `pnpm run fmt:clj` to fix. After running `fmt:clj`, `check-fmt:clj` is redundant. Avoid unrelated whitespace diffs. - -**Before linting:** if delimiter errors are suspected (after LLM edits), run `scripts/paren-repair` on the affected files first. Delimiter errors produce misleading linter/compiler output. See `mem:scripts/paren-repair`. - -## Testing - -Backend test commands, coverage rules, and conventions: `mem:backend/testing`. -Cross-cutting testing principles, anti-patterns, and verification checklist: `mem:testing`. +- From the repo root, use `./scripts/ci backend` for lint, tests and format. Prefer it over direct tests: `mem:backend/testing` explains the backend assert flag, workspace-specific test services, and focused runs. +- For the running backend use `mem:scripts/nrepl-eval`; starting a second backend can collide with the existing process. For test design and output discipline see `mem:testing`. +- For fixture data and the interactive backend REPL, see `docs/technical-guide/developer/backend.md`. diff --git a/.serena/memories/backend/graph-experiment.md b/.serena/memories/backend/graph-experiment.md index 07d63f7f6f..02bc1c2b55 100644 --- a/.serena/memories/backend/graph-experiment.md +++ b/.serena/memories/backend/graph-experiment.md @@ -1,633 +1,8 @@ -# Graph Experiment - -## Scope - -- Purpose: project Penpot file data into an embedded Ladybug graph database. -- Purpose: keep the graph current with Penpot file changes. -- Purpose: expose a read-only graph console for backend debugging. -- This is an experiment, not a replacement for PostgreSQL file storage. -- The graph subsystem is off unless `:graph` is in the backend flags. -- The main Penpot frontend has no graph feature code for this subsystem. -- The graph console is a backend-served HTML template with JavaScript. - -## Memory Links - -- Read `mem:backend/core` for backend architecture, HTTP routes, DB rules, and test commands. -- Read `mem:backend/subtleties` for RPC and message bus behavior, and for file data loading and realization. -- Read `mem:common/changes-architecture` for the change record vocabulary. -- Read `mem:frontend/routing-app-shell-subtleties` for the existing notification WebSocket. -- Read `mem:prod-infra/core` for Redis or Valkey message bus topology. - -## Branch Surface - -- The graph experiment adds about 6,336 lines and changes about 27 files. -- The graph implementation lives under `backend/src/app/graph/`. -- The graph console lives at `backend/resources/app/templates/graph-console.tmpl`. -- The existing debug page gains graph links in `backend/resources/app/templates/debug.tmpl`. -- The existing debug HTTP routes gain graph handlers in `backend/src/app/http/debug.clj`. -- The backend system passes the message bus to the debug route component in `backend/src/app/main.clj`. -- The backend adds Ladybug and Arrow dependencies in `backend/deps.edn`. -- The backend adds JVM options for Ladybug and Arrow native access. -- The common flag registry adds `:graph` in `common/src/app/common/flags.cljc`. -- The graph experiment adds `graph_sync_parity_test.clj` and `graph_binder_gate_test.clj`. - -## System Model - -### Storage layers - -- PostgreSQL remains the source of truth for Penpot files. -- The graph database stores a projection of one file. -- A persistent graph uses a `.lbug` path under `PENPOT_GRAPH_DIR`. -- The default graph directory is `/tmp/penpot-graph`. -- A debug session uses a Ladybug `:memory:` database. -- A debug session database lives inside the backend JVM process. -- A debug session does not survive a backend restart. -- A debug session does not store file data back to PostgreSQL. - -### Two graph update paths - -- Cold projection reads the complete file and rebuilds the graph. -- Incremental sync reads file change records and updates the open graph. -- Both paths must produce the same graph for the same file state. -- The parity test treats cold projection as the reference path. -- A reload discards the session graph and uses cold projection again. - -## Main Namespaces - -### `app.graph.ladybug` - -- Opens and closes Ladybug `Database` and `Connection` objects. -- Installs and loads the Ladybug JSON extension. -- Executes Cypher statements. -- Executes prepared statements. -- Binds scalar parameters. -- Formats UUID, string, integer, number, JSON, and timestamp values. -- Formats compound values such as arrays, maps, and structs. -- Converts Ladybug values back to Clojure values. -- Limits normal query results to 200 rows by default. -- Detects result truncation with `:truncated?`. -- Uses query timeout `0` by default. -- Query timeout `0` disables the timeout. -- Provides `validate-on-connection!` for parse, bind, and read-only checks. -- `exec-prepared-on-connection!` prepares every statement before the first execution. -- A prepare failure stops the batch before a mutation runs. - -### `app.graph.schema` - -- Provides the public schema facade. -- Exposes schema version `penpot-graph-slice-4`. -- Delegates node and relationship definitions to `app.graph.schema.nodes`. - -### `app.graph.schema.nodes` - -- Holds the single registry for graph node tables. -- Generates node DDL. -- Generates relationship DDL. -- Maps Penpot shape types to graph tables. -- Projects source attributes into graph attributes. -- Formats graph column values. -- Quotes reserved graph labels such as `Group` and `Boolean`. -- Defines container tables and shape tables. -- Defines `IsChildOf`, `IsInstanceOf`, `RefersTo`, and `FillsSwapSlot`. - -### `app.graph.schema.contract` - -- Records deliberate graph contract decisions. -- Renames graph columns such as `:revn` to `revision`. -- Drops attributes that do not belong in this graph slice. -- Records attributes that the graph does not project. -- Applies per-table dropped attributes. -- Defines type overrides for vectors, transforms, colors, maps, and JSON arrays. -- Maps selected map keys to the frontend JSON naming convention. -- `:background-blur` remains a declared unprojected attribute. - -### `app.graph.schema.projection` - -- Derives projected schemas from canonical Malli schemas. -- Builds the projected document schema. -- Builds projected shape schemas. -- Selects the schema for each shape type. - -### `app.graph.schema.types` - -- Maps Malli types to Ladybug types. -- Maps matrices to `DOUBLE[6]`. -- Maps points to `DOUBLE[2]`. -- Maps rectangles to `DOUBLE[4]`. -- Maps colors to `UINT32`. -- Maps collections to Ladybug arrays. -- Maps `:map-of` schemas to `MAP`. -- Maps closed scalar maps to `STRUCT`. -- Maps other complex values to `JSON`. - -### `app.graph.schema.values` - -- Coerces source values to graph column values. -- Writes fixed vectors with deterministic order. -- Packs colors into the graph color representation. -- Sorts set values when deterministic output is needed. - -### `app.graph.arrow` - -- Loads projection rows with Apache Arrow. -- Creates temporary staged node and relationship tables. -- Uses `COPY ... FROM (MATCH ...)` for bulk loading. -- Groups relationship loads by source and target table pair. -- Resolves relationship endpoints with joins. -- Does not use `createArrowRelTable` for UUID relationship endpoints. -- The Arrow `RootAllocator` nests outside the Ladybug connection and closes after the connection and database close sequence; Ladybug keeps staged buffers until connection close, so an inner allocator leaks. -- `with-allocator!` keeps the body exception when the allocator close also throws, attaching the close failure as suppressed. - -### `app.graph.ingest` - -- Fetches a complete file with `bfc/get-file` and `:realize? true`. -- Rejects missing files. -- Rejects files without file data. -- Can run file data validation before projection. -- Creates the DDL. -- Loads nodes and edges through Arrow. -- Executes post-load transforms. -- Writes graph metadata last. -- Treats the final metadata write as the complete-build marker. -- Supports a persistent database path and an open connection. -- `ingest-on-connection!` requires a caller-owned `:arrow-alloc` that outlives the connection; it raises `:missing-arrow-allocator` without one. - -### `app.graph.projection.document` - -- Projects `Document`, `Page`, `Component`, and supported shape nodes. -- Skips the page root frame. -- Creates `IsChildOf` edges from shapes to parents. -- Creates page edges to the document. -- Creates component edges to the document. -- Stores page order in `Page.index` and edge `position`. -- Reverses the stored `:shapes` list for Penpot z-order. -- Adds `page-id` to every projected shape. -- Propagates an instance head `component-id` to descendants. -- Stops component inheritance at a non-Frame shape with its own component ID. -- Skips deleted components during cold projection. -- Logs unsupported shape types and missing shape records. - -### `app.graph.projection.transforms` - -- Runs after the base nodes and edges load. -- `link-component-instances` creates `IsInstanceOf` edges. -- A Frame needs `component-file` to qualify as an instance head. -- `link-shape-refs` creates `RefersTo` edges from `shape-ref`. -- Ladybug limits multi-label relationship `MERGE` statements. -- The transform emits one statement for each shape-table pair. -- `link-swap-slots` creates `FillsSwapSlot` edges. -- Swap slot IDs come from `swap-slot-` entries in `touched`. -- The transform removes swap slot entries from `touched` after edge creation. -- The transform order matters because it reads and then changes `touched`. - -### `app.graph.meta` - -- Stores graph provenance in `GraphMeta`. -- Stores schema version, source revision, producer, and build time. -- The source revision identifies the file revision used for cold projection. - -### `app.graph.stats` and `app.graph.report` - -- `app.graph.stats` counts graph nodes and relationships from the live catalog. -- `app.graph.report` prints ingest information for REPL use. - -## Cold Projection Flow - -1. Get the file row and realized file data from PostgreSQL. -2. Read the file revision from the file row. -3. Build the node and edge projection. -4. Create all graph tables from the graph schema. -5. Load node rows with Arrow. -6. Load relationship rows with Arrow. -7. Run `CHECKPOINT;`. -8. Run the registered derived transforms. -9. Write `GraphMeta` as the final build step. -10. Return file ID, file revision, database path, projection stats, and transform stats. - -### Projection node groups - -- `Document` contains file-level attributes without the file data blob. -- `Document.options` receives file-level options from the data blob. -- `Page` contains page attributes without the page object map. -- `Component` contains component attributes without component object maps. -- Shape tables contain the supported shape attributes. -- The graph stores selected derived attributes such as `page-id`. - -### Projection relationship groups - -- Structural edges use `IsChildOf`. -- Page and component edges point to `Document`. -- Derived edges come from the post-load transform registry. - -## Incremental Sync - -### Change source - -- `app.rpc.commands.files-update` persists the file update first. -- The same command publishes a `:file-change` message to the file topic. -- The topic key is the file UUID. -- The message contains the file ID, profile ID, session ID, revision, version, and changes. -- Library changes also publish a team-topic message. -- The graph session only consumes the file-topic `:file-change` messages. - -### Session subscription - -- `app.graph.debug/start-sync-loop!` creates a channel with a dropping buffer of 64. -- The session subscribes the channel to the file UUID topic. -- The loop reads one message at a time. -- The loop ignores message types other than `:file-change`. -- The loop stops when the channel closes. -- `destroy-session!` closes the channel and purges its message bus subscription. - -### Session state - -- Sessions are stored in a global `defonce` atom. -- The map key is the string form of `profile-id`. -- One profile has one graph session. -- Loading another file first destroys the old session. -- A session stores the Ladybug database, connection, and Arrow allocator; the allocator closes after the connection and database. -- A session stores a shared lock for graph access. -- A session stores file metadata. -- A session stores the incremental sync index. -- A session stores the message bus channel. -- A session stores load time and profile ID. -- The session keeps projection statistics but drops full projection rows after index creation. - -### Sync index - -- `build-index` starts from the complete cold projection. -- The index stores the graph file ID and document ID. -- The index stores the current graph revision. -- The index stores page IDs, names, and positions. -- The index stores component IDs, names, and deleted state. -- The index stores shape table, parent, position, frame, page, and component context. -- The index stores child IDs by parent ID. -- The index supports later change application without another PostgreSQL file read. - -### Change application - -- `apply-changes!` processes the change list in source order. -- Each supported change returns a new index and a list of Cypher statements. -- Unsupported changes enter the `:skipped` result. -- Supported changes enter the `:applied` result. -- The function collects all statements before it executes them. -- The function appends a document revision statement when at least one change applies. -- The index revision advances only when at least one change applies. -- A larger incoming revision than the index revision creates a warning. -- A revision gap does not trigger catch-up. - -### Shape change rules - -- `:add-obj` reuses `projection.document/denormalized-shape`. -- `:add-obj` creates the shape node and its parent edge. -- `:mod-obj` applies supported `:set` operations to graph columns. -- `:mod-obj` keeps false and zero values as values. -- `:del-obj` deletes shapes in deep post-order. -- `:mov-objects` detaches shapes from the old parent. -- `:mov-objects` closes the old sibling position gap. -- `:mov-objects` inserts shapes at the new position. -- `:mov-objects` updates `parent_id` and `frame_id`. -- `:mov-objects` rewrites container `shapes` values. -- The parent columns and child lists must match a cold projection. - -### Page and component change rules - -- Page add creates a projected page node and a document edge. -- Page delete removes the page subtree. -- Page modification updates supported page attributes. -- Component add creates a component node and document edge. -- Component modification updates supported component attributes. -- Component delete uses a soft-delete state. -- Component restore removes the soft-delete state. -- Component purge removes the component node and document edge. -- Component sync paths need more parity coverage than the current tests provide. - -## Session Locking - -- The sync loop and HTTP handlers share one lock per session. -- The lock protects one Ladybug connection from concurrent access. -- Queries acquire the lock before binder validation and execution. -- Graph data export acquires the lock before catalog reads. -- Session export acquires the lock before `EXPORT DATABASE`. -- A long query blocks sync for the same session. -- A sync batch blocks queries for the same session. -- Ladybug connection thread safety is not assumed. - -## Graph Query Rules - -- The console accepts Cypher text. -- Blank query text raises a validation error. -- The query first passes Ladybug prepare and bind checks. -- The query must pass the engine read-only analysis. -- A mutating query is rejected. -- The graph console does not provide a write path. -- A session graph is rebuilt from the file by Reload. -- Normal query results have a 200-row limit. -- Query results use string values for the HTML console representation. -- JSON requests receive a Transit JSON response with the query and result. -- HTML requests receive the rendered console with the result. - -## Graph Data Export - -### G6 data - -- `/dbg/actions/graph-data` reads the live Ladybug database. -- It does not read the sync index for nodes and edges. -- It therefore shows database drift if a batch fails after index update. -- Node export covers all registered node tables. -- Relationship export reads the Ladybug relationship catalog. -- Relationship export includes source, target, relationship name, and position. -- Node and relationship export uses a 100,000-row limit. -- The response reports `truncated` when a limit cuts the result. -- The response reports buffer-manager memory usage. - -### `.lbug` export - -- `source=file` rebuilds the persistent graph from PostgreSQL file data. -- `source=file` runs a synchronous full ingest for each request. -- `source=session` exports the caller profile's live in-memory graph. -- Session export uses Ladybug `EXPORT DATABASE` to Parquet files. -- Session export creates a new `.lbug` database with `IMPORT DATABASE`. -- The temporary Parquet staging directory is deleted after import. -- The final session `.lbug` file remains in the system temporary directory. -- The HTTP response streams the database file to the caller. - -## HTTP Routes and Access - -- The graph routes live in `backend/src/app/http/debug.clj`. -- The graph route list is added only when `:graph` is enabled. -- `/dbg/graph` serves the graph console page. -- `/dbg/actions/graph-files` returns the profile file tree. -- `/dbg/actions/graph-load` loads a file into the profile session. -- `/dbg/actions/graph-unload` closes the profile session. -- `/dbg/actions/graph-reload` rebuilds the loaded file graph. -- `/dbg/actions/graph-query` runs a read-only Cypher query. -- `/dbg/actions/graph-sync-status` returns the sync state. -- `/dbg/actions/graph-data` returns nodes and edges for G6. -- `/dbg/actions/graph-export` streams a `.lbug` database. -- The `/dbg` session middleware remains active. -- The `/dbg` admin middleware remains active. -- A devenv host with a profile ID passes the debug authorization rule. -- Other hosts need a profile email in the configured admin set. -- `/dbg/actions/graph-files` lists reachable teams, projects, and files. -- The file tree query has a 500-file limit. -- The graph handlers resolve graph namespaces at call time. -- The backend requires `app.graph.debug` and `app.graph.ingest` when the flag is on. -- Ladybug native loading then fails during route initialization instead of first use. - -## Console Frontend - -### Page type - -- `graph-console.tmpl` is a backend resource template. -- It is not a Rumext component. -- It is not part of the main frontend route table. -- The page uses browser `fetch` calls and a browser WebSocket. -- The page loads G6 version `5.1.1` from jsDelivr. - -### File tree - -- The page fetches `/dbg/actions/graph-files`. -- The response contains team, project, and file groups. -- The page creates the tree with DOM APIs. -- A file click submits the graph load form. -- The page shows a message when no file exists. - -### Graph rendering - -- The page fetches `/dbg/actions/graph-data`. -- The page converts graph nodes and edges to G6 data. -- The page skips repaint when the node and edge signature does not change. -- The page marks added, removed, and changed graph entities. -- The page supports tree, dagre, circular, force, and combo layouts. -- The page supports collapsed container combos. -- The page has render guards at 4,000 nodes and 8,000 edges. -- The `?safe` query option bypasses the render guard. -- The page shows graph size by node count and relationship count. -- The page shows buffer-manager memory in MiB. -- The page reports a CDN failure when G6 is undefined. - -### Query result filtering - -- A query can return `filter_*` columns with node IDs. -- The HTML result table hides columns with the `filter_` prefix. -- The JSON result keeps the full result. -- The graph view uses the hidden IDs to select matching nodes. -- The graph view re-runs the query after graph refresh. -- This keeps the query filter aligned with the current graph. -- A user column named `filter_*` follows the same hiding rule. - -### Node inspector - -- A node click creates a query for that node. -- The inspector calls `/dbg/actions/graph-query` with JSON negotiation. -- The inspector displays the full projected row. -- The inspector uses table and ID values from the graph data. - -## WebSocket Data Flow - -1. The page opens `/ws/notifications` with a random `session-id` query value. -2. The page sends `:subscribe-file` with a Transit UUID value. -3. The server makes sure that the file exists and that the profile has read permission. -4. The server subscribes the connection to the file topic. -5. `files_update` publishes `:file-change` to the same topic. -6. The graph session consumes the message from its message bus subscription. -7. The WebSocket server sends the message to the browser connection. -8. The browser adds the change to the changelog. -9. The browser fetches sync status after 150 milliseconds. -10. The browser fetches graph data after a 400-millisecond debounce. -11. The browser repaints the G6 graph when the graph data changes. - -### WebSocket reconnect behavior - -- The page reconnects after three seconds when the socket closes. -- The page resubscribes to the file after the socket opens. -- The page refreshes sync status after reconnect. -- The page refreshes graph data after reconnect. -- Reconnect does not recover dropped message-bus changes. -- The page shows the sync error or skipped-change state when the status reports it. - -## Feature Flag and Runtime Dependencies - -- `:graph` is defined in `common/src/app/common/flags.cljc`. -- The flag is off by default. -- `com.ladybugdb/lbug` version `0.20.4` is a backend dependency. -- `org.apache.arrow/arrow-memory-netty` version `19.0.0` supports Arrow `RootAllocator`. -- The JVM uses `--enable-native-access=ALL-UNNAMED`. -- The JVM uses `--add-opens=java.base/java.nio=ALL-UNNAMED`. -- The JVM uses `--sun-misc-unsafe-memory-access=allow`. -- The JVM options appear in the development alias and backend launch scripts. -- A Ladybug version change needs new binder and parity tests. -- A JDK version change needs a startup test with the graph flag enabled. - -## Tests - -### `backend-tests.graph-sync-parity-test` - -- Uses two Ladybug `:memory:` databases under one Arrow allocator outer to both; an allocator closed before its connections leaks. -- Does not use PostgreSQL or a live graph session. -- Projects initial file data into database A. -- Applies changes to database A through incremental sync. -- Applies the same changes to file data. -- Projects the changed file data into database B. -- Compares every node row and relationship row. -- Reports differences by table, row key, and column. -- Covers shape add, shape modification, shape deletion, movement, and page changes. -- Contains a test that injects a sync defect and expects a graph difference. -- Contains a test that `ingest-on-connection!` without `:arrow-alloc` raises `:missing-arrow-allocator`. -- Does not cover all component change variants. -- Does not cover every movement insertion mode. - -### `backend-tests.graph-binder-gate-test` - -- Creates the live graph DDL in a Ladybug `:memory:` database. -- Prepares each sync statement template without executing it. -- Detects parse errors and missing tables. -- Detects missing columns and bad label quoting. -- Reports the expected read-only classification. -- Covers reserved node labels across the node registry. -- Reports an error result for an invalid statement. - -### Test gaps - -- No automated HTTP handler tests cover graph routes. -- No automated session lifecycle tests cover load and unload. -- No automated WebSocket tests cover graph subscription. -- No automated export tests cover persistent and session sources. -- Component add, modify, delete, restore, and purge need parity tests. -- Page delete needs parity coverage. -- Movement with `:after-shape` needs parity coverage. -- Buffer overflow and revision gap behavior need tests. -- Partial batch failure and recovery need tests. -- Query timeout and long-query behavior need tests. - -## Known Risks and Limits - -### Dropped changes - -- The sync channel uses a dropping buffer of 64. -- A burst can discard file-change messages. -- The sync loop logs a revision gap when it sees a larger revision. -- The sync loop does not fetch missing rows from `file_change`. -- Reload is the only built-in recovery path. - -### Partial batch state - -- `apply-changes!` does not provide Ladybug transaction atomicity. -- A statement failure can leave a partly changed graph. -- The in-memory index can advance before the database state is complete. -- `/dbg/actions/graph-data` reads the database and exposes this drift. -- Reload rebuilds the graph from PostgreSQL file data. - -### Query resource use - -- The default session query timeout is zero. -- A costly query can hold the session lock for a long time. -- The same lock blocks incremental sync. -- The graph export also holds the same lock during catalog reads. -- The graph schema has a high memory floor. -- The console reports about 115 MiB for the wide slice before file data. - -### Session lifecycle - -- Sessions have no TTL. -- Sessions remain until unload, replacement, or process shutdown. -- Each session owns native Ladybug memory and its Arrow allocator. -- Many profiles can create many native databases. -- A profile load replaces its previous session. -- Two browser tabs for one profile share one graph session. - -### Temporary files - -- Session export leaves the final `.lbug` file in the system temporary directory. -- Long-lived servers can accumulate exported session databases. -- The staging directory is deleted after import. - -### Browser dependency - -- The graph view depends on a runtime CDN request. -- A network restriction can remove the G6 view. -- Queries and session status still use backend endpoints without G6. - -### Data exposure - -- The graph console can list many files available to the profile. -- The console can load complete projected file data. -- The console can export a graph database. -- The console can inspect all projected node attributes. -- The console is safe only when the `/dbg` access boundary is correct. -- The graph flag must remain off for deployments that do not need this tool. - -### Contract drift - -- The graph schema is a deliberate slice of the Penpot file model. -- New source attributes do not enter the graph automatically in all cases. -- Dropped and unprojected attributes need an explicit contract decision. -- `applied_tokens` key mapping depends on the JSON naming function. -- `filter_*` is a frontend convention, not a graph schema guarantee. - -### Ladybug dialect coupling - -- Cypher strings contain Ladybug-specific syntax. -- Label quoting handles reserved labels explicitly. -- Relationship transforms depend on Ladybug relationship limits. -- Arrow loading depends on Ladybug `COPY FROM (MATCH ...)` behavior. -- A dependency upgrade needs schema, binder, Arrow, and parity checks. - -## REPL Helpers - -- `app.srepl.main` resolves graph functions only when a helper runs. -- `graph-smoke-test!` runs a basic Ladybug operation. -- `graph-query-test!` runs a graph query test. -- `ingest-file-to-graph!` projects a file into a graph database. -- These helpers use `requiring-resolve` to keep the graph dependency lazy. - -## Operational Invariants - -- PostgreSQL file data remains authoritative. -- Cold projection and incremental sync must produce equal graph state. -- The graph revision must identify the last applied file revision. -- The document revision must update when a sync batch applies. -- A missing or skipped change must remain visible in sync status. -- A graph query from the console must be read-only. -- A graph session must serialize connection access. -- Graph routes must remain behind the `:graph` flag and `/dbg` access control. -- The Arrow allocator nests outside the Ladybug connection and must outlive all Ladybug operations that use its buffers; a session owns its allocator until unload. -- `GraphMeta` must be written after the full ingest and transforms finish. - -## Key Files - -- `backend/src/app/graph/ladybug.clj`: Ladybug API and query gates. -- `backend/src/app/graph/arrow.clj`: Arrow bulk load. -- `backend/src/app/graph/ingest.clj`: Complete file ingest. -- `backend/src/app/graph/debug.clj`: Session lifecycle, sync loop, query, and export. -- `backend/src/app/graph/sync.clj`: Incremental change application. -- `backend/src/app/graph/meta.clj`: Graph provenance. -- `backend/src/app/graph/stats.clj`: Graph counts. -- `backend/src/app/graph/report.clj`: REPL ingest report. -- `backend/src/app/graph/projection/document.clj`: Base document projection. -- `backend/src/app/graph/projection/transforms.clj`: Derived relationship transforms. -- `backend/src/app/graph/schema/nodes.clj`: Node and relationship registry. -- `backend/src/app/graph/schema/contract.clj`: Projection contract decisions. -- `backend/src/app/graph/schema/projection.clj`: Malli projection schemas. -- `backend/src/app/graph/schema/types.clj`: Malli-to-Ladybug type mapping. -- `backend/src/app/graph/schema/values.clj`: Value coercion. -- `backend/src/app/http/debug.clj`: Graph route registration and handlers. -- `backend/src/app/http/websocket.clj`: File WebSocket subscription handlers. -- `backend/src/app/rpc/commands/files_update.clj`: File-change publication. -- `backend/src/app/main.clj`: Integrant message bus wiring. -- `backend/resources/app/templates/graph-console.tmpl`: Graph console browser code. -- `backend/resources/app/templates/debug.tmpl`: Debug page graph links. -- `common/src/app/common/flags.cljc`: `:graph` feature flag. -- `backend/test/backend_tests/graph_sync_parity_test.clj`: Cold versus sync parity. -- `backend/test/backend_tests/graph_binder_gate_test.clj`: Cypher binder gate. - -## Development Commands - -- Run backend commands from the `backend/` directory. -- Run focused parity tests with `clojure -M:dev:test --focus backend-tests.graph-sync-parity-test`. -- Run focused binder tests with `clojure -M:dev:test --focus backend-tests.graph-binder-gate-test`. -- Run the backend test suite with `clojure -M:dev:test`. -- Examine Clojure formatting with `pnpm run check-fmt:clj`. -- Run backend Clojure lint with `pnpm run lint:clj`. -- Write test output to a file before reading or filtering it. +# Backend graph experiment + +- Start at `app.graph.ingest` for cold projection, `app.graph.sync` for change application, `app.graph.schema.contract` for what gets projected, and `app.graph.debug` for session ownership and export. `app.http.debug` registers the routes; `backend/resources/app/templates/graph-console.tmpl` is the browser client. +- PostgreSQL file data remains authoritative. Cold projection and incremental sync must produce the same graph for the same file state; a Penpot shape-tree change can require updates to parent/frame columns, edges and ordered child lists together. Use `mem:common/changes-architecture` for change semantics. A new file attribute does not belong in the graph by default: decide it in the projection contract. +- Cold ingest writes graph provenance only after the base projection and derived transforms finish. Incremental sync consumes persisted file changes from file-topic Pub/Sub, not the console WebSocket. A browser reconnect refreshes the view but does not recover lost graph changes. The dropping buffer and revision gaps do not trigger replay; surface drift and reload from PostgreSQL. A failed batch can leave partial graph state; don't treat it as an atomic PostgreSQL transaction. Keep skipped changes and incomplete revisions visible. +- A session belongs to a profile, not a tab. Reload/replacement and unload own cleanup; do not assume TTL eviction. Sync, query and export use the same session lock: a long query blocks sync. Teardown closes the channel and resources, but does not take that lock; account for in-flight operations when changing the lifecycle. The Arrow allocator must outlive the Ladybug connection and database because Ladybug can retain staged Arrow buffers. Close the allocator last, including on failure. +- The console can read whole projected files and export their data. Keep routes behind both `:graph` and `/dbg` authorization, and preserve the engine's prepare/bind and read-only gate; text matching is not a substitute. Keep graph loading off the flag-disabled boot path. On a Ladybug or JVM upgrade, check graph-enabled startup, Arrow ingest, binder behavior and sync parity. Versions and JVM flags live in `backend/deps.edn` and the launch scripts. +- Verification entry points: `backend-tests.graph-sync-parity-test` compares incremental results to a fresh projection; `backend-tests.graph-binder-gate-test` prepares the actual statement templates. Neither replaces checking changes to session or route wiring. Use the focused backend commands with the assert flag in `mem:backend/testing`. diff --git a/.serena/memories/backend/jobs.md b/.serena/memories/backend/jobs.md new file mode 100644 index 0000000000..62acad90a5 --- /dev/null +++ b/.serena/memories/backend/jobs.md @@ -0,0 +1,22 @@ +# Backend jobs + +## Start in the code + +- Definitions and lifecycle: `app.jobs`, `app.main` (`::jobs/defs`). Dispatch, execution and cron: `app.worker.dispatcher`, `app.worker`, `app.worker.cron`. Retention and resources: `app.jobs.gc`, `app.jobs.storage`, `mem:backend/storage`. +- User-facing RPCs: `app.rpc.commands.jobs`; file import/export: `mem:backend/binfile`. Deployment and queue topology: `mem:prod-infra/core`. DB transaction semantics: `mem:backend/subtleties`. Tests: `backend-tests.jobs-test`, `backend-tests.worker-test`, and the tests beside each job. + +## Boundaries + +- A job-def closes over its own dependencies. A handler receives context and business params, never the runner cfg. A job-def must not reference `::jobs/defs` through Integrant: the registry already depends on the definitions. Don't add routing or retry state to public context; it belongs to dispatch or execution, not the job's business contract. +- `submit` joins the caller transaction because creation is part of the caller's work. Claim, retry and terminal transitions own their transactions because they report work the caller cannot roll back. A job must commit before an independent claimant can see it. A transition writes its event with the state change; a no-op writes neither event nor metric. Keep job foreign keys deferrable. +- Submit keys include tenant, name, queue and label; rely on the partial unique indexes, not a read-before-write check. `skip-if-active` excludes live exclusive jobs; dedupe discards a conflict with an unstarted job; debounce refreshes that pending row and retains its ID. Opted-in jobs do not conflict with plain jobs just because they share a label. The options that require distinct conflict targets cannot be combined. +- Postgres owns the lifecycle; Redis delivery is not proof of a claim. Dispatch and recovery must stay tenant-scoped. Lost scheduled jobs and expired running jobs are terminal, not requeued; sending them back to `new` can violate dedupe. Long-running work must heartbeat; a beat that finds a terminal or missing job raises an internal interruption, not a retryable failure. Progress can be throttled, so each milestone must make sense without the previous one. +- Job events are durable; progress is not a Redis value or mutable column. Dispatcher aborts batch-write terminal events without a Pub/Sub notification; inspect logs or `penpot_jobs_total_ms_count{outcome="aborted"}` for either abort cause. Don't assume a client that missed a WebSocket event can replay the event log through the jobs RPC. +- `complete` is the shared result validation boundary for the runner and external completions. The job-def owns the JSON result schema; declare it when UUIDs (including map keys) or other typed values must round-trip. Read job errors and progress through their job decoders rather than generic JSON decoding. + +## User jobs and metrics + +- Do not infer the owner, resource or expiry from business params. A public job belongs to its profile; an absent job and another profile's job both answer `not-found`. Registry metadata such as job family and routing is interpreted by consumers, not the substrate. Family quotas count live jobs from registered definitions, not a fixed list of names. +- Internal retention and user expiry are separate. Job GC must retire a row and arrange cleanup of its resource together; a bare delete would cascade events without touching the resource. Use the bucket's owner and lifetime rules in `mem:backend/storage`. +- Metric definitions live in `app.jobs.metrics`. Keep labels bounded (no IDs, payloads or exception text). A histogram's `_count` is the counter for that event; dispatch and claim measure different events. Claim wait includes the dispatcher gap, not just time in Redis. Use SQL for backlog rather than adding a gauge to the write path; debounce does not reset `created_at`. +- Record SQL-backed metrics via `db/after-commit` inside the writing transaction. Wire a metrics instance into the cfg before writing: a missing dependency discovered only in a callback may be swallowed. A user-owned event writer also needs a message bus on its cfg. diff --git a/.serena/memories/backend/subtleties.md b/.serena/memories/backend/subtleties.md index db5140cefd..d67969f6ea 100644 --- a/.serena/memories/backend/subtleties.md +++ b/.serena/memories/backend/subtleties.md @@ -31,20 +31,17 @@ - `after-commit` callbacks run on commit only. A transaction marked `::db/rollback` (used by `srepl` and `app.tasks/offload-file-data`) commits nothing, so it runs none of them. - `db/run!` opens/reuses one connection but does not create a transaction. - `db/own-transaction` returns a cfg that owns its next transaction: it drops `::db/conn` (so `tx-run!` opens its own) and `::db/read-only` (so a caller running read-only, like the storage scheduler streaming a plan cursor, cannot make the nested write read-only too). Lifecycle writes use it so a rollback of the surrounding work can undo neither the write nor its metric. -- `db/tjson` is Transit JSON for jsonb storage; `db/json` is plain JSON. Job params (`job.params`) are plain JSON, decoded with the job-def decoder (`app.jobs/decode-params`); only the legacy `task` props were Transit (`decode-transit-pgobject`). Job results (`job.result`) are plain JSON too: they are read with the result decoder of the job-def (`app.jobs/decode-result`), and a result map keyed by uuid must declare its schema (`[:map-of ::sm/uuid ...]`, the import resolution does) or every key comes back as a keyword and every uuid as the text it is on disk. +- `db/tjson` is Transit JSON for jsonb storage; `db/json` is plain JSON. The old `task` props used Transit, but unified job params and results use JSON with job-def decoders; see `mem:backend/jobs`. - Advisory locks (`app.db`) come in two independent axes. **Scope**: the transaction ones (`xact-lock!`, `xact-try-lock!`) vanish with the transaction, and the session ones (`session-try-lock`, `session-unlock`, `session-unlock-all`) live until unlocked or the session ends — a pooled connection returned with one keeps it. **Form**: the one-key form takes a uuid or an int (uuids hashed with a zero-UUID seeded siphash) and the two-key form takes a `classid`/`objid` pair; PostgreSQL keys them by `objsubid` (1 vs 2), so the two spaces never conflict even with the same numbers. `update-file` and the setup take the one-key form; the audit consumers take the two-key one with `classid` `730000` and the consumer id as `objid`, which is why a consumer tick can never block a file update, and they clear whatever a borrowed connection carries before taking it. ## Workers and cron +- For job lifecycle, handler wiring and metric conventions, see `mem:backend/jobs`. - `job` carries `tenant` (the instance the job belongs to) and a bare `queue`. Several instances share one database, and the tenant is what keeps an instance from claiming another environment's jobs: every query that acts on one instance's work filters on it (dispatch claim, lost sweep, orphan sweep, cron submit), and the tenant is part of the key of the dedupe and exclusivity indexes of `submit` (the cron no-overlap check is one of those inserts). - Two submit options resolve their key in the database instead of reading before writing, each through its own partial unique index over (tenant, name, queue, label). `::jobs/skip-if-active` inserts the row as **exclusive** and `job__live_exclusive__uniq` admits a single live row (`new`/`scheduled`/`running`/`retry`). `::jobs/dedupe` inserts it as **deduped** and `job__new_dedupe__uniq` admits a single not-started row (`new`) whatever its `scheduled_at`; a conflicting insert affects no row, the submit returns `nil` and records `penpot_jobs_submit_total{outcome="skipped"}`. The pending row is never deleted nor modified: it runs when it is due, with its own params. `::jobs/debounce` uses the same key and index but resolves the conflict with `ON CONFLICT ... DO UPDATE`, refreshing `scheduled_at` (to `now + delay`), `params` and `modified_at` of the pending row and answering with the id it already had: that is the sliding window of the webhook batches, where the last payload is the one delivered. A refresh is not a new job: the submit records `outcome="refreshed"`, apart from the `created` ones, and the id it reports is the id the statement wrote. Dedupe and debounce are mutually exclusive. Both require an explicit non-blank label and only cover the jobs that asked for the option: a live job that was not submitted with it (a webhook delivery, a notification) does not block a flagged submit, and two plain jobs can share a label. The `exclusive` and `dedupe` columns are what keep that distinction; the label stays a label. - A single insert carries a single `ON CONFLICT` clause, so `skip-if-active` cannot be combined with `dedupe`/`debounce`: an exclusive job already admits one live row, PostgreSQL admits one conflict target per statement, and the submit raises `:skip-if-active-cannot-be-combined`. -- Jobs metrics rule (one event, one family): counters exist only for events without latency; when an event has a histogram, its `_count` is the counter (no twin counter). `dispatched` (pushes) vs `claim_wait` (claims) are deliberately different events — do not merge them. `claim_wait` measures `now - scheduled_at` at the claim, so it is how late the claim happened, including the dispatcher gap, not time inside a queue. `dispatcher_batch_ms` times one dispatcher pass and pairs with `dispatcher_batch_size`; `gc_pass_ms` times one GC pass (`expired` or `retained`). - The dispatcher claims `new`/`retry` jobs atomically, marks them `scheduled` and hands them to their queue; the runner skips a message whose scheduled timestamp no longer matches the database state (a rescheduled or reclaimed job). - A job handed to a queue (`scheduled`) is marked `aborted` with `app.jobs/lost-error` (`code :lost`) when its queue has nothing waiting (`LLEN`) and it has been `scheduled` longer than the grace (5 min; it also covers the pop-to-claim gap of a message popped right after the hand-off, but not one that waited longer in the queue and is popped while the sweep runs: the round trip can lose that race), or when it has been `scheduled` past the cap (24 h, for a message lost behind a backlog or a queue without a consumer; a daily cron can miss one run). Leftover rows are never re-dispatched, so nothing returns to `new` and the dispatcher cannot violate `job__new_dedupe__uniq` (the thresholds are `lost-grace` and `lost-cap`, and `lost-batch-size` bounds each read in `app.worker.dispatcher`: past-cap rows are aborted without an `LLEN` and grace rows with one, so a younger lost row behind a large legitimate backlog may wait for the cap instead of the grace). `running` jobs untouched past `:jobs-lease` are marked `aborted` with `app.jobs/orphan-error` (`type :internal`, `code :orphan`). `aborted` is a system-side terminal state like `cancelled` (never retried, swept by retention like other terminals, reported with a log line: `warn` for lost, `error` for orphan); long jobs must `heartbeat` per chunk so a healthy backlog is never mistaken for a dead process. The `:progress` report is optional and only feeds the durable log. A beat whose write finds the job no longer active raises an `:interrupt` (`code :job-interrupted`) instead of counting zero: it is the internal stop-the-work signal, not an error, so neither the listener nor the runner logs it as one. -- Both abort sweeps (lost and orphan) write the `end` event (`outcome "aborted"`) in the same transaction as the status change, never one insert per row. No msgbus notification goes out for them; the aborted rows alert through the log and `penpot_jobs_total_ms_count{outcome="aborted"}`, which counts both causes (there is no separate counter). -- `job_event` is append-only and deleted by cascade with the job. `progress` is a row there, not a column: no Redis and no mutable column to keep in sync. -- `job` is deletion-protected at the SQL level: a stray `DELETE FROM job` raises instead of dropping the row and its `job_event` cascade without touching the referenced `storage_object`. The intended deleter is the jobs GC, which disables the guard inside its transaction; tests use `th/db-force-delete`. `app.jobs/submit` never deletes: its dedupe is a conflict of the insert. - A missing job-def raises (`:no-job-definition`) instead of completing. Throwing with `ex-data :type ::retry` still controls retry behavior; `:strategy ::noop` retries without incrementing retry count. - Cron entries claim their `scheduled_task` row with `FOR UPDATE SKIP LOCKED`, disable statement/idle-in-transaction timeouts locally, and submit one exclusive `job` row per entry when no live instance exists. The database's partial unique index decides overlap across backends, not a count. Entries reschedule themselves in `finally` unless interrupted. Worker, dispatcher, and cron components do not start when the DB pool is read-only. - Integrant params schemas name injected components as bare `::ns/key` entries (pool, metrics, msgbus, job defs), and a bare entry is a malli registry lookup, not `any?`: the owning namespace must `sm/register!` it at load, or the backend crashes at boot with `:malli.core/invalid-schema` instead of asserting. Unit tests never build those keys, so `backend-tests.worker-test` compiles the worker schemas and `backend-tests.http-websocket-test` compiles the revocation-watcher schema to catch it. The assertion only runs with `PENPOT_FLAGS=enable-backend-asserts`, so without it a broken schema reaches production and only crashes at boot. diff --git a/.serena/memories/common/core.md b/.serena/memories/common/core.md index 1c969b5ba5..b73524e364 100644 --- a/.serena/memories/common/core.md +++ b/.serena/memories/common/core.md @@ -34,6 +34,8 @@ Some legacy code violates this layering; do not copy those violations into new c ## Focused memory routing +- URL construction on either runtime: `mem:common/uri` for relative-path resolution and preserving a deployment subpath. + Model, schema, and persistence shape: - File/page/shape/component attr changes, import/export surfaces, inspector/codegen, and cross-module checklist: `mem:common/data-model-change-checklist`. - Token data structures, token import/export, active theme/set semantics, and schema/coercion behavior: `mem:common/tokens-schema-subtleties`. diff --git a/.serena/memories/common/uri.md b/.serena/memories/common/uri.md index 9648499409..0de8c77aaf 100644 --- a/.serena/memories/common/uri.md +++ b/.serena/memories/common/uri.md @@ -1,13 +1,4 @@ # Common URI helpers -`app.common.uri` wraps `lambdaisland.uri` and re-exports `join`, `parse`, `query-encode`, `percent-encode` and `uri?` with `dm/export`. - -## `join` resolves references, it does NOT concatenate paths - -- `lambdaisland.uri/join` implements RFC 3986 reference resolution, not path concatenation: a relative reference that does not start with `/` replaces everything after the last `/` of the path it is resolved against. Joining several segments resolves them successively, so each segment replaces the last segment of the previous result. -- `(join "https://h/" "api/teams/" "" "users/" "")` returns `https://h/api/teams/users/`, not `.../api/teams//users/`: `"users/"` replaced `""`. `(apply join base segments)` behaves the same. -- `ensure-path-slash` normalizes only the BASE to end with `/`; it does not touch the segments, so a base ending in `/` is not enough for a multi-segment append. -- To append several segments: either join them into a single relative path first (dropping empty segments and collapsing slashes), or make every non-final segment end with `/`, including the dynamic ids. Keep that normalization in the shared URL builder, not in each call site. -- A segment starting with `/` resolves against the host root and silently drops the base subpath; reject it. -- Frontend `app.config` normalizes the base (`normalize-uri`) and relies on callers passing trailing-slash segments by convention (`resolve-file-media` joins `"assets/by-file-media-id/"` then `"/thumbnail"`); it does not normalize segments. -- Backend shared builders are `app.config/join-uri` and `app.config/get-public-uri`. A past refactor moved Nitrate's per-request helper onto them without the segment normalization and broke every multi-segment Nitrate URL that passes `"api/teams/" team-id "users/" profile-id`. +- `app.common.uri/join` resolves each argument as a URI reference, not a path segment. `(join "https://h/" "api/teams/" "id" "users/" "profile")` produces `https://h/api/teams/users/profile`: `"users/"` replaces `"id"`. A leading slash drops the entire configured base subpath. +- `ensure-path-slash` normalizes only the base. Pass one relative path or make every non-final argument end in `/`, including dynamic IDs. See backend `app.config/join-uri` and the multi-segment calls in `app.nitrate`; frontend `app.config` relies on the same reference-resolution rule.