From b0c569d8917e1a7d01fe24416a679bde6a8f4910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?andr=C3=A9s=20gonz=C3=A1lez?= Date: Tue, 24 Nov 2026 22:39:35 +0100 Subject: [PATCH] :bug: Submit the import audit events from the import job (#13150) * :bug: Submit the import audit events from the import job Since 2.20 the dashboard imports .penpot files through the :import-binfile job, which submitted no audit event. The outcome of an import and the files it created were lost, so analytics could no longer tell completed imports from failed ones. The job now submits the import-binfile event with the name and props of the legacy RPC event (status, file-ids, file-count, project, version, generated-by, referer), plus the job id, the team id, the package size and the elapsed time. A cancelled job reports the cancelled status. A completed import also submits a create-file event per imported file, as the legacy RPC does. As in the RPC, an import refused by the permission check submits no event. Closes #13148 AI-assisted-by: claude-opus-5-5 * :bug: Audit import jobs at their terminal transition Run optional terminal hooks in the winning job transaction and use one for import audit events. Preserve the separate import transaction and cover cancellation, rollback, RPC paths, and dispatcher aborts. AI-assisted-by: gpt-6.1-terra * :recycle: Simplify the terminal job hook contract Pass a semantic terminal job to the hook with its final status and decoded parameters, result or error. Adapt the import audit and tests. AI-assisted-by: gpt-6.1-terra * :bug: Keep import jobs bound to their original team Freeze the destination team when creating an import job and serialize imports with project moves. Use the frozen team for audit and webhook events, and keep compatibility with existing jobs. Select import audit props explicitly to prevent new job parameters from being included in events by default. AI-assisted-by: gpt-6.1-terra * :books: Document the import team fallback removal Mark the legacy job audit fallback for removal in version 2.21.0. AI-assisted-by: gpt-6.1-terra * :wrench: Validate canonical AI model IDs in commit trailers Require bare lowercase model IDs in AI-assisted-by trailers and cover the validation with tests. Align the commit and PR workflows with the same attribution rules. AI-assisted-by: gpt-6.1-terra --------- Co-authored-by: Andrey Antukh --- .agents/skills/create-commit/SKILL.md | 6 +- .agents/skills/create-pr/SKILL.md | 6 +- .serena/memories/audit-log.md | 2 + .../auth-permissions-product-domains.md | 1 + .serena/memories/backend/core.md | 2 + .serena/memories/workflow/creating-commits.md | 4 +- .serena/memories/workflow/creating-prs.md | 3 + backend/src/app/jobs.clj | 40 ++- backend/src/app/rpc/commands/jobs.clj | 14 +- backend/src/app/rpc/commands/management.clj | 2 + backend/src/app/rpc/commands/projects.clj | 6 + backend/src/app/tasks/import_binfile.clj | 140 +++++--- .../import_team_concurrency_test.clj | 333 ++++++++++++++++++ .../import_terminal_rpc_test.clj | 230 ++++++++++++ backend/test/backend_tests/jobs_test.clj | 56 +++ .../backend_tests/rpc/commands/jobs_test.clj | 218 +++++++++++- .../backend_tests/rpc_management_test.clj | 30 ++ .../tasks/import_binfile_test.clj | 215 +++++++++++ .../backend_tests/worker_dispatcher_test.clj | 20 ++ scripts/check-commit | 24 ++ scripts/test_check_commit.py | 49 +++ 21 files changed, 1342 insertions(+), 59 deletions(-) create mode 100644 backend/test/backend_tests/import_team_concurrency_test.clj create mode 100644 backend/test/backend_tests/import_terminal_rpc_test.clj diff --git a/.agents/skills/create-commit/SKILL.md b/.agents/skills/create-commit/SKILL.md index 2a49b29dc8..f77615c8e6 100644 --- a/.agents/skills/create-commit/SKILL.md +++ b/.agents/skills/create-commit/SKILL.md @@ -47,8 +47,10 @@ hard blocker: fix the message and re-check it before reporting success. ``` If it fails, amend the message (`git commit --amend`) until it passes. Do not finish with a failing checker. -5. The `AI-assisted-by` trailer value is provided by the calling context — use - it verbatim. +5. When adding an `AI-assisted-by` trailer, use the canonical model ID from + the calling context as a bare lowercase slug (for example, + `gpt-6.1-terra`), without a provider prefix or display name. Do not guess + the ID. ## Constraints diff --git a/.agents/skills/create-pr/SKILL.md b/.agents/skills/create-pr/SKILL.md index 82ef8567e3..251c4bddf9 100644 --- a/.agents/skills/create-pr/SKILL.md +++ b/.agents/skills/create-pr/SKILL.md @@ -38,7 +38,9 @@ the user agrees. `:emoji:` title, the `**Note:**` line, and the `## What` / `## Why` / `## How` sections. Derive them from the commits and the issue body when there is one. Repeat the `AI-assisted-by:` trailer once per model that - worked on the branch. Put the body in a temp file to avoid shell quoting. + worked on the branch, using the bare canonical model ID under the rules in + `mem:workflow/creating-commits` (for example, `gpt-6.1-terra`). Put the + body in a temp file to avoid shell quoting. 2. Decide whether the PR resolves an issue. If it does, include `Closes #NNNN` in the body for human readers and pass `--issue NNNN` so the command creates the GitHub link. If the user's invocation says `no issue` @@ -67,6 +69,8 @@ error. Do not ask the user and do not add pre-flight checks for this case. 1. Identify the PR: the number given by the user, or `gh pr list --head `. 2. Write the new title and/or body following `mem:workflow/creating-prs`. + Preserve each model attribution using the same canonical model ID rules + as in Open mode. 3. Apply and verify: ```bash diff --git a/.serena/memories/audit-log.md b/.serena/memories/audit-log.md index ec9a6a6f01..67ede0afbc 100644 --- a/.serena/memories/audit-log.md +++ b/.serena/memories/audit-log.md @@ -40,6 +40,8 @@ Attribute the event to the **actor**, not an arbitrary `:profile-id` in the resp `audit/submit` propagates failures. `wrap-audit` runs **after** the command's transaction, if it has one: an audit failure can fail the response even though the business mutation is already committed. An explicit `submit` inside the caller's transaction can roll back the mutation with the event. Low-level `audit/insert` only writes a full row when persistence is on; it does not fan out to webhooks or telemetry. +The `:import-binfile` job submits `import-binfile` from its terminal hook in the transaction that records `completed`, `failed` or `cancelled`. Its props explicitly select `project-id`, `name`, `version`, `generated-by` and `referer` from job params, then add `job-id`, `team-id`, `status` and completed file ids/count; new job params do not automatically reach audit. New jobs freeze `team-id` at creation and both creation and terminal events use it for webhook routing; older jobs without it resolve the current project team as fallback. A queued cancellation also emits it; dispatcher-side `aborted` does not. The hook has no request context and omits handler-only elapsed time and package size. Import files commit earlier, and the `create-file` events use a separate transaction after that commit: a later audit or terminal failure cannot roll the files back, and a cancellation that wins late can coexist with committed files. The `job-id` joins the outcome to the job-creation event. + ### Events used to rebuild state Put the ids a projection needs in the event so the receiver does not have to join production tables. A create event needs the new entity's id. Supply `:team-id` when the command already has it; for writes the wrapper can resolve it from a project or file id, not a bare `:id`. Reads do not need that lookup. For a bulk operation whose internal calls do not emit, submit one create event per entity when full rows are persisted. Use `audit/submit-create-event` when you have the row or `audit/submit-file-created-event` when you have only a file id; the latter checks that the file exists. diff --git a/.serena/memories/backend/auth-permissions-product-domains.md b/.serena/memories/backend/auth-permissions-product-domains.md index 941358c65a..139c4488f3 100644 --- a/.serena/memories/backend/auth-permissions-product-domains.md +++ b/.serena/memories/backend/auth-permissions-product-domains.md @@ -33,6 +33,7 @@ ## Teams, projects, and invitations - Team/project commands mix DB changes, email, message bus notifications, media/storage cleanup, feature flags, quotas, and audit metadata. Keep mutations transactional when the existing command does so. +- `move-project` locks its project row before resolving the source team, checking permissions and enumerating files. Binfile job creation and import take the same lock when freezing or validating the destination team; a move can wait for the whole import transaction, subject to database timeouts. This only serializes paths that take that lock, not every file creation or legacy import. - Invitation flows validate muted/bounced emails before sending and use tokenized invitation state. Accepting an invitation is tied to the invited member identity, not just possession of a token. - The whole invitation family is team-admin only: creating, updating and deleting invitations, minting the invitation token (`get-team-invitation-token`) and listing the pending ones (`get-team-invitations`, which carries the invited email and the offered role). The token of an invitation that grants the `owner` role is restricted to the team owner, because an admin cannot create nor promote an owner invitation (`cant-promote-to-owner`). This family is the exception to the rule above: it answers `:validation` / `:insufficient-permissions` instead of `:not-found`, so the five commands speak one language. - With the `:admin-console` flag, the organization `send-invitations` policy (role value plus Nitrate `restrictions-met`, through `cto/allowed?`) gates every invitation command that hands out or manages access: create (and resend, which reuses it), `update-team-invitation-role`, `delete-team-invitation` and `get-team-invitation-token`. Only `get-team-invitations` stays on team admin alone, so a blocked admin still sees the list. The shared helper `check-send-invitations-policy` in `teams_invitations.clj` does a strict Nitrate lookup (fails closed; 404 means no organization) and runs outside a DB transaction, which is why the role and delete commands carry no `::db/transaction`. diff --git a/.serena/memories/backend/core.md b/.serena/memories/backend/core.md index 941c103403..92eeffd776 100644 --- a/.serena/memories/backend/core.md +++ b/.serena/memories/backend/core.md @@ -66,6 +66,7 @@ Every background job is a job-def: a plain `(defn execute-X [cfg params] ...)` i - 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. +- Job-defs can supply `::jobs/on-terminal`, called with the transition transaction cfg and a semantic job map after a successful `complete`, `fail` or `cancel`: `:status` is the terminal string, `:params` is decoded, `:result` is decoded for completion and `:error` is present for failure. Its writes and the transition commit together; a throw rolls both back. Dispatcher `aborted` sweeps do not call it. The import job uses the hook for its `import-binfile` audit event; the import and `create-file` writes are earlier independent transactions, so a terminal audit failure does not undo imported files. - 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. @@ -73,6 +74,7 @@ Every background job is a job-def: a plain `(defn execute-X [cfg params] ...)` i - 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. +- Import job creation freezes the project's `team-id` in its internal params while holding the project row lock and rechecking edit permission; the client cannot supply it. The import and `move-project` take the same row lock before checking team and permissions, so a move waits for an import and a queued job refuses to import after the project moves. The lock lasts through the import transaction; unrelated projects are independent. Jobs created before the field existed keep the old permission behavior and use the current project team as audit fallback. New creation and terminal audit events use the frozen team. Old workers with the former closed schema cannot process new params during a mixed-version rollout. - `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. diff --git a/.serena/memories/workflow/creating-commits.md b/.serena/memories/workflow/creating-commits.md index 6c25b175a8..53b4699403 100644 --- a/.serena/memories/workflow/creating-commits.md +++ b/.serena/memories/workflow/creating-commits.md @@ -48,8 +48,8 @@ that breaks them is wrong, even if the code is right. - Exceptions inside the body (do not wrap these): `Signed-off-by:`, `Co-authored-by:`, `AI-assisted-by:` trailers, and lines carrying a URL. **AI-assisted-by trailer rules:** -- Use only the model name, e.g. `mimo-v2.5`, `deepseek-v4-flash` -- Do NOT add prefixes like `opencode-go/` — use the bare model name +- Optional; when present, every trailer must use the bare canonical model ID as a lowercase slug, e.g. `gpt-6.1-terra`, `mimo-v2.5`, `deepseek-v4-flash`. +- Use lowercase ASCII letters and digits separated by single `-` or `.` characters; no provider prefix, display name, or guessed ID. `scripts/check-commit` checks the format, not whether the ID exists. ## Commit Type Emojis diff --git a/.serena/memories/workflow/creating-prs.md b/.serena/memories/workflow/creating-prs.md index 4eaf7f84e2..b6ed9a9647 100644 --- a/.serena/memories/workflow/creating-prs.md +++ b/.serena/memories/workflow/creating-prs.md @@ -77,6 +77,9 @@ PR descriptions follow this structure: The "Note:" line is required at the top. Adjust if this is a manual (non-AI) PR. When the PR requests a regular merge instead of a squash merge, its `**Merge:**` line goes above the `**Note:**` line (see Merge Strategy). +For AI-assisted work, include one `AI-assisted-by:` trailer per model that +worked on the branch, using the canonical model ID rules in +`mem:workflow/creating-commits`. Preserve the attributions when updating a PR. ## Writing Principles diff --git a/backend/src/app/jobs.clj b/backend/src/app/jobs.clj index cec6e8740e..99e5877dcf 100644 --- a/backend/src/app/jobs.clj +++ b/backend/src/app/jobs.clj @@ -161,6 +161,11 @@ [::handler ::sm/fn] [::decoder ::sm/fn] [::validator ::sm/fn] + ;; Runs in the winning complete/fail/cancel transaction with the cfg and + ;; a terminal job map. Params and result are decoded, status is terminal, + ;; and result or error is present only for its corresponding outcome. + ;; A throw rolls the transition back; dispatcher aborts do not invoke it. + [::on-terminal {:optional true} ::sm/fn] ;; A result crosses a plain JSON column on its way out of the job, so a ;; uuid comes back as the text it is on disk and a uuid used as a map ;; key comes back as a keyword. A def that declares the schema of its @@ -567,6 +572,20 @@ (decode-json-col :result) (decode-json-col :error))) +(defn- run-on-terminal + "Run the job definition's terminal hook in the transition transaction." + [cfg job terminal] + (when-let [job-def (get (get-defs cfg) (keyword (:name job)))] + (when-let [hook (::on-terminal job-def)] + (let [job (-> job + (dissoc :result :error) + (assoc :params (decode-params job-def (:params job))) + (merge terminal)) + job (if (contains? terminal :result) + (update job :result #(decode-result job-def %)) + job)] + (hook cfg job))))) + (defn- decode-result-of "Decode the result of a row with the decoder of the job-def that owns it. A kind the registry no longer knows (a retired job-def) answers with the @@ -1248,6 +1267,9 @@ (if (db/exec-one! conn [sql:complete-job (ct/now) (ct/now) encoded resource-id job-id]) (do + (run-on-terminal tx-cfg job (cond-> {:status "completed" + :result result} + resource-id (assoc :resource-id resource-id))) (insert-event tx-cfg job-id "end" {:outcome "completed"}) (db/after-commit @@ -1264,7 +1286,7 @@ SET status='failed', modified_at=?, error=? WHERE id=? AND status IN ('running','retry') - RETURNING id") + RETURNING *") (defn fail "Mark a running job as failed and record the `end` event. @@ -1279,12 +1301,13 @@ affected rows." [cfg job-id error] (assert (mtx/instance cfg) "missing ::mtx/metrics on the jobs cfg") - (let [job (get-job cfg job-id) - encoded (db/json (check-job-error error)) + (let [encoded (db/json (check-job-error error)) n (db/tx-run! (db/own-transaction cfg) (fn [{:keys [::db/conn] :as tx-cfg}] - (if (db/exec-one! conn [sql:fail-job (ct/now) encoded job-id]) + (if-let [job (some-> (db/exec-one! conn [sql:fail-job (ct/now) encoded job-id]) + decode-row)] (do + (run-on-terminal tx-cfg job {:status "failed" :error error}) (insert-event tx-cfg job-id "end" {:outcome "failed"}) (db/after-commit @@ -1301,7 +1324,7 @@ SET status='cancelled', modified_at=? WHERE id=? AND status IN ('new','scheduled','retry','running') - RETURNING id") + RETURNING *") (defn cancel "Cancel a pending or running job (new/scheduled/retry/running) and @@ -1313,11 +1336,12 @@ and writes no event. Returns the number of affected rows." [cfg job-id] (assert (mtx/instance cfg) "missing ::mtx/metrics on the jobs cfg") - (let [job (get-job cfg job-id) - n (db/tx-run! (db/own-transaction cfg) + (let [n (db/tx-run! (db/own-transaction cfg) (fn [{:keys [::db/conn] :as tx-cfg}] - (if (db/exec-one! conn [sql:cancel-job (ct/now) job-id]) + (if-let [job (some-> (db/exec-one! conn [sql:cancel-job (ct/now) job-id]) + decode-row)] (do + (run-on-terminal tx-cfg job {:status "cancelled"}) (insert-event tx-cfg job-id "end" {:outcome "cancelled"}) (db/after-commit diff --git a/backend/src/app/rpc/commands/jobs.clj b/backend/src/app/rpc/commands/jobs.clj index c3f590315b..31add875a6 100644 --- a/backend/src/app/rpc/commands/jobs.clj +++ b/backend/src/app/rpc/commands/jobs.clj @@ -265,10 +265,20 @@ :filename "package.penpot" :mtype "application/zip"})] (try - (let [summary (get-job-summary cfg (submit-job cfg job-def :import-binfile params profile-id - :resource-id (:resource-id staged)))] + (let [{:keys [summary team-id]} + (db/tx-run! cfg + (fn [tx-cfg] + (let [project (projects/get-project-for-update tx-cfg project-id) + _ (projects/check-edition-permissions! tx-cfg profile-id project-id) + team-id (:team-id project) + params (assoc params :team-id team-id) + job-id (submit-job tx-cfg job-def :import-binfile params profile-id + :resource-id (:resource-id staged))] + {:summary (get-job-summary tx-cfg job-id) + :team-id team-id})))] (with-meta summary {::audit/props {:job-id (:id summary) + :team-id team-id :generated-by (:generated-by manifest) :referer referer}})) diff --git a/backend/src/app/rpc/commands/management.clj b/backend/src/app/rpc/commands/management.clj index 75ee867bec..496b7aa0b6 100644 --- a/backend/src/app/rpc/commands/management.clj +++ b/backend/src/app/rpc/commands/management.clj @@ -396,6 +396,8 @@ - Permission exceptions if user lacks required permissions - Team compatibility exceptions if teams are incompatible" [{:keys [::db/conn] :as cfg} {:keys [profile-id team-id project-id] :as params}] + ;; Lock before reading or validating; retain get-by-id's not-found behavior. + (proj/get-project-for-update cfg project-id) (let [project (db/get-by-id conn :project project-id {:columns [:id :team-id]}) pids (->> (db/query conn :project {:team-id (:team-id project)} {:columns [:id]}) (map :id) diff --git a/backend/src/app/rpc/commands/projects.clj b/backend/src/app/rpc/commands/projects.clj index 18e5c282f0..f94d030561 100644 --- a/backend/src/app/rpc/commands/projects.clj +++ b/backend/src/app/rpc/commands/projects.clj @@ -80,6 +80,12 @@ (def check-read-permissions! (perms/make-check-fn has-read-permissions?)) +(defn get-project-for-update + "Lock a project against concurrent updates for the caller's transaction." + [cfg project-id] + (db/exec-one! cfg ["SELECT id, team_id FROM project WHERE id = ? FOR NO KEY UPDATE" + project-id])) + ;; --- QUERY: Get projects (def ^:private sql:projects diff --git a/backend/src/app/tasks/import_binfile.clj b/backend/src/app/tasks/import_binfile.clj index 27949b0074..04cc541d48 100644 --- a/backend/src/app/tasks/import_binfile.clj +++ b/backend/src/app/tasks/import_binfile.clj @@ -12,13 +12,17 @@ [app.binfile.jobs :as bfj] [app.binfile.v1 :as bf.v1] [app.binfile.v3 :as bf.v3] + [app.common.data :as d] [app.common.exceptions :as ex] [app.common.schema :as sm] [app.common.time :as ct] [app.db :as db] [app.jobs :as jobs] [app.jobs.storage :as js] + [app.loggers.audit :as audit] + [app.loggers.webhooks :as-alias webhooks] [app.metrics :as mtx] + [app.rpc :as-alias rpc] [app.rpc.commands.projects :as projects] [app.rpc.commands.teams :as teams] [app.storage :as sto] @@ -30,6 +34,7 @@ format version and the manifest metadata kept for audit." [:map {:title "import-binfile-params" :closed true} [:project-id ::sm/uuid] + [:team-id {:optional true} ::sm/uuid] [:name [:or [:string {:max 250}] [:map-of ::sm/uuid [:string {:max 250}]]]] [:version [:enum 1 3]] @@ -117,61 +122,111 @@ {:id project-id} {::db/return-keys false})) +(defn- import-files + "Run the core inside a transaction, so a cancellation detected between + units rolls the whole import back, and check the result against its + schema inside that same transaction: a result the contract does not + accept rolls the import back instead of leaving half of a file + imported." + [cfg context params input] + (let [profile-id (:profile-id context) + project-id (:project-id params)] + (db/tx-run! cfg (fn [tx-cfg] + (let [project (projects/get-project-for-update tx-cfg project-id) + _ (bfj/check-active tx-cfg context) + _ (projects/check-edition-permissions! tx-cfg profile-id project-id) + team (teams/get-team tx-cfg :profile-id profile-id + :project-id project-id)] + (when (and (:team-id params) + (not= (:team-id params) (:team-id project))) + (ex/raise :type :validation + :code :import-team-changed + :hint "the destination project changed teams")) + ;; the core joins this transaction: it is the one + ;; that decides whether the whole import is kept or + ;; rolled back + (-> (bfc/import-cfg tx-cfg {:profile-id profile-id + :project-id project-id + :team team + :name (:name params) + :input input}) + (bfj/check-active context) + (bfj/run context + (fn [cfg] + (let [result (case (int (:version params)) + 1 (bf.v1/import-files! cfg) + 3 (bf.v3/import-files! cfg) + (ex/raise :type :validation + :code :unsupported-version + :hint "unsupported binfile version" + :version (:version params)))] + (touch-project cfg project-id) + result))) + (assoc :name (:name params)) + (assoc :version (:version params)) + (check-result) + (as-> result {:team team :result result}))))))) + +(defn- submit-import-event + "Submit the `import-binfile` audit event with the outcome of the job. + + The event shares the terminal transition's transaction. The job runs + outside any request, so the event carries no request context." + [cfg {:keys [params status result] :as job}] + (let [{:keys [project-id team-id name version generated-by referer]} params + ;; Fallback for older jobs without a team-id; remove in 2.21.0. + team-id (or team-id (:team-id (db/get* cfg :project {:id project-id}))) + file-ids (:file-ids result) + props (cond-> {:project-id project-id + :name name + :version version + :generated-by generated-by + :referer referer + :job-id (:id job) + :team-id team-id + :status status} + (= status "completed") + (assoc :file-ids file-ids :file-count (count file-ids)))] + (audit/submit cfg {:type "command" + :name "import-binfile" + :profile-id (:profile-id job) + :props (d/without-nils props) + :context {:triggered-by "import-binfile-job"} + ::webhooks/event? true}))) + +(defn- submit-file-created-events + "The imported files get no event from their own command, so emit one per + file inside a single transaction, as the legacy RPC does." + [cfg context team file-ids] + (let [params {::rpc/profile-id (:profile-id context)}] + (db/tx-run! cfg (fn [cfg] + (doseq [file-id file-ids] + (audit/submit-file-created-event cfg params file-id + {:team-id (:id team)})))))) + (defn execute-import "Plain handler, importable and testable without integrant. The edition permission is checked again here, and not only when the job was created: it can be revoked while the job waits in its queue. The - core runs inside a transaction, so a cancellation detected between units - rolls the whole import back, and the result is checked against its schema - inside that same transaction: a result the contract does not accept rolls - the import back instead of leaving half of a file imported. The substrate - checks the result again when the job is completed, which is the only net - for a job that does not validate its own result. + substrate checks the result again when the job is completed, which is + the only net for a job that does not validate its own result. + + A completed import submits a `create-file` event per file it created. + The terminal hook submits the import outcome. The package is the input of the job: it is released and its temporary copy deleted once the job is terminal, whatever the outcome. A crash is covered by the storage GC." [cfg context params] - (let [profile-id (:profile-id context) - project-id (:project-id params) - input (js/load-input cfg context)] + (let [input (js/load-input cfg context)] (try - (projects/check-edition-permissions! cfg profile-id project-id) + (let [{:keys [team result]} (import-files cfg context params input)] + + (submit-file-created-events cfg context team (:file-ids result)) + result) - (let [team (or (teams/get-team cfg - :profile-id profile-id - :project-id project-id) - (ex/raise :type :not-found - :code :project-not-found - :hint "the destination project is not available" - :profile-id profile-id - :project-id project-id))] - (db/tx-run! cfg (fn [tx-cfg] - ;; the core joins this transaction: it - ;; is the one that decides whether the - ;; whole import is kept or rolled back - (-> (bfc/import-cfg tx-cfg {:profile-id profile-id - :project-id project-id - :team team - :name (:name params) - :input input}) - (bfj/check-active context) - (bfj/run context - (fn [cfg] - (let [result (case (int (:version params)) - 1 (bf.v1/import-files! cfg) - 3 (bf.v3/import-files! cfg) - (ex/raise :type :validation - :code :unsupported-version - :hint "unsupported binfile version" - :version (:version params)))] - (touch-project cfg project-id) - result))) - (assoc :name (:name params)) - (assoc :version (:version params)) - (check-result))))) (finally (fs/delete input) (js/release-input cfg context))))) @@ -190,6 +245,7 @@ ::jobs/schema schema:params ::jobs/handler (fn [context params] (execute-import cfg context params)) + ::jobs/on-terminal submit-import-event ::jobs/decoder (sm/decoder schema:params sm/json-transformer) ::jobs/validator (sm/validator schema:params) ;; The resolution is keyed by file id: without the result schema the diff --git a/backend/test/backend_tests/import_team_concurrency_test.clj b/backend/test/backend_tests/import_team_concurrency_test.clj new file mode 100644 index 0000000000..e8f660e790 --- /dev/null +++ b/backend/test/backend_tests/import_team_concurrency_test.clj @@ -0,0 +1,333 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS SUBSIDIARY SL + +(ns backend-tests.import-team-concurrency-test + (:require + [app.binfile.v3 :as v3] + [app.common.time :as ct] + [app.config :as cf] + [app.db :as db] + [app.jobs :as jobs] + [app.jobs.storage :as js] + [app.rpc.commands.management :as management] + [app.rpc.commands.projects :as projects] + [app.storage :as sto] + [app.worker :as worker] + [app.worker.dispatcher :as dispatcher] + [backend-tests.helpers :as th] + [clojure.java.io :as jio] + [clojure.test :as t] + [datoteka.io :as io])) + +(t/use-fixtures :once th/state-init) +(t/use-fixtures :each (th/serial th/database-reset th/clean-storage)) + +(defn- await-result + [p] + (let [value (deref p 15000 ::timeout)] + (when (= ::timeout value) + (throw (ex-info "Timed out waiting for concurrent operation" {}))) + value)) + +(defn- get-pid + [cfg] + (:pid (db/exec-one! cfg ["SELECT pg_backend_pid() AS pid"]))) + +(defn- await-blocked + [pid] + (let [deadline (+ (System/nanoTime) 10000000000)] + (loop [] + (let [row (db/exec-one! th/*system* + ["SELECT cardinality(pg_blocking_pids(?)) > 0 AS blocked" pid])] + (cond + (:blocked row) true + (< (System/nanoTime) deadline) (recur) + :else (throw (ex-info "Database operation did not block" {:pid pid}))))))) + +(defn- setup-import + [profile project-id team-id] + (let [path (-> "backend_tests/test_files/svg-attrs-camel-case.penpot" + io/resource jio/file) + staged (js/put-resource th/*system* (:id profile) + {:content (sto/content path) + :filename "package.penpot" + :mtype "application/zip"}) + params (cond-> {:project-id project-id :name "imported" :version 3} + team-id (assoc :team-id team-id)) + job-id (th/create-job* :import-binfile {:profile-id (:id profile) + :resource-id (:resource-id staged)})] + (th/db-update! :job {:params (db/json params)} {:id job-id}) + {:id job-id :params params})) + +(defn- run-import + [{:keys [id params]}] + (jobs/invoke (assoc th/*system* + ::jobs/name :import-binfile + ::jobs/params params + ::jobs/context (jobs/make-context (jobs/get-job th/*system* id))))) + +(defn- get-files + [project-id] + (th/db-exec! ["SELECT id FROM file WHERE project_id = ? AND deleted_at IS NULL" + project-id])) + +(defn- move + [cfg profile-id project-id team-id] + (management/move-project cfg {:profile-id profile-id + :project-id project-id + :team-id team-id})) + +(t/deftest move-waits-for-import-to-commit + (let [profile (th/create-profile* 1) + project (th/create-project* 1 {:profile-id (:id profile) + :team-id (:default-team-id profile)}) + destination (th/create-team* 1 {:profile-id (:id profile)}) + job (setup-import profile (:id project) (:default-team-id profile)) + entered (promise) + release (promise) + move-pid (promise) + original v3/import-files!] + (with-redefs [v3/import-files! (fn [cfg] + (deliver entered true) + (await-result release) + (original cfg))] + (let [import (future (run-import job))] + (try + (await-result entered) + (let [moving (future + (db/tx-run! th/*system* + (fn [cfg] + (deliver move-pid (get-pid cfg)) + (move cfg (:id profile) (:id project) (:id destination)))))] + (try + (t/is (true? (await-blocked (await-result move-pid)))) + (t/is (= (:default-team-id profile) + (:team-id (th/db-get :project {:id (:id project)})))) + (deliver release true) + (let [result (await-result import)] + (await-result moving) + (t/is (= (set (:file-ids result)) + (set (map :id (get-files (:id project))))))) + (t/is (= (:id destination) + (:team-id (th/db-get :project {:id (:id project)})))) + (finally + (deliver release true) + (await-result moving)))) + (finally + (deliver release true) + (await-result import))))))) + +(t/deftest import-waits-for-move-and-rejects-the-new-team + (let [profile (th/create-profile* 1) + project (th/create-project* 1 {:profile-id (:id profile) + :team-id (:default-team-id profile)}) + destination (th/create-team* 1 {:profile-id (:id profile)}) + job (setup-import profile (:id project) (:default-team-id profile)) + moved (promise) + release (promise) + import-pid (promise) + original projects/get-project-for-update + moving (future + (db/tx-run! th/*system* + (fn [cfg] + (move cfg (:id profile) (:id project) (:id destination)) + (deliver moved true) + (await-result release))))] + (try + (await-result moved) + (with-redefs [projects/get-project-for-update + (fn [cfg id] + (deliver import-pid (get-pid cfg)) + (original cfg id))] + (let [import (future (try (run-import job) + (catch Throwable cause cause)))] + (try + (t/is (true? (await-blocked (await-result import-pid)))) + (deliver release true) + (await-result moving) + (t/is (= :import-team-changed (-> (await-result import) ex-data :code))) + (t/is (empty? (get-files (:id project)))) + (finally + (deliver release true) + (await-result import))))) + (finally + (deliver release true) + (await-result moving))))) + +(t/deftest moved-import-without-destination-access-returns-not-found + (let [profile (th/create-profile* 1) + project (th/create-project* 1 {:profile-id (:id profile) + :team-id (:default-team-id profile)}) + destination (th/create-team* 1 {:profile-id (:id profile)}) + job (setup-import profile (:id project) (:default-team-id profile))] + (db/tx-run! th/*system* + #(move % (:id profile) (:id project) (:id destination))) + (th/db-exec! ["DELETE FROM team_profile_rel WHERE team_id = ? AND profile_id = ?" + (:id destination) (:id profile)]) + (let [error (try (run-import job) + (catch Throwable cause cause))] + (t/is (= :not-found (:type (ex-data error)))) + (t/is (= :object-not-found (:code (ex-data error)))) + (t/is (empty? (get-files (:id project))))))) + +(t/deftest import-waits-for-move-rollback-and-succeeds + (let [profile (th/create-profile* 1) + project (th/create-project* 1 {:profile-id (:id profile) + :team-id (:default-team-id profile)}) + destination (th/create-team* 1 {:profile-id (:id profile)}) + job (setup-import profile (:id project) (:default-team-id profile)) + moved (promise) + release (promise) + import-pid (promise) + original projects/get-project-for-update + moving (future + (try + (db/tx-run! th/*system* + (fn [cfg] + (move cfg (:id profile) (:id project) (:id destination)) + (deliver moved true) + (await-result release) + (throw (ex-info "Rollback move" {:rollback true})))) + (catch Throwable cause cause)))] + (try + (await-result moved) + (with-redefs [projects/get-project-for-update + (fn [cfg id] + (deliver import-pid (get-pid cfg)) + (original cfg id))] + (let [import (future (run-import job))] + (try + (t/is (true? (await-blocked (await-result import-pid)))) + (deliver release true) + (t/is (true? (-> (await-result moving) ex-data :rollback))) + (let [result (await-result import)] + (t/is (seq (:file-ids result))) + (t/is (= (set (:file-ids result)) + (set (map :id (get-files (:id project))))))) + (t/is (= (:default-team-id profile) + (:team-id (th/db-get :project {:id (:id project)})))) + (finally + (deliver release true) + (await-result import))))) + (finally + (deliver release true) + (await-result moving))))) + +(defn- blocked-terminal-import + [legacy terminal] + (let [profile (th/create-profile* 1) + project-id (:default-project-id profile) + job (setup-import profile project-id (when-not legacy (:default-team-id profile))) + locked (promise) + release (promise) + import-pid (promise) + original projects/get-project-for-update + holder (future + (db/tx-run! th/*system* + (fn [cfg] + (db/exec-one! cfg ["SELECT id FROM project WHERE id = ? FOR NO KEY UPDATE" + project-id]) + (deliver locked true) + (await-result release))))] + (try + (await-result locked) + (with-redefs [projects/get-project-for-update + (fn [cfg id] + (deliver import-pid (get-pid cfg)) + (original cfg id))] + (let [import (future (try (run-import job) + (catch Throwable cause cause)))] + (try + (t/is (true? (await-blocked (await-result import-pid)))) + (if (= terminal :cancelled) + (t/is (= 1 (await-result (future (jobs/cancel th/*system* (:id job)))))) + (do + (th/db-update! :job {:modified-at (ct/minus (ct/now) + (ct/plus (cf/get-jobs-lease) + (ct/duration {:minutes 1})))} + {:id (:id job)}) + (db/tx-run! th/*system* + (fn [cfg] + (#'dispatcher/mark-orphan-jobs + (assoc cfg ::dispatcher/timestamp (ct/now) + ::worker/tenant (cf/get :tenant))))))) + (t/is (= (name terminal) (:status (jobs/get-job th/*system* (:id job))))) + (deliver release true) + (await-result holder) + (t/is (= :job-interrupted (-> (await-result import) ex-data :code))) + (t/is (empty? (get-files project-id))) + (t/is (zero? (jobs/complete th/*system* :job-id (:id job) + :result {:file-ids [] :name "imported" :version 3}))) + (finally + (deliver release true) + (await-result import))))) + (finally + (deliver release true) + (await-result holder))))) + +(t/deftest cancellation-of-a-blocked-import + (blocked-terminal-import false :cancelled)) + +(t/deftest cancellation-of-a-blocked-legacy-import + (blocked-terminal-import true :cancelled)) + +(t/deftest lease-expiry-of-a-blocked-import + (blocked-terminal-import false :aborted)) + +(defn- cancel-running-import + [legacy] + (let [profile (th/create-profile* 1) + project-id (:default-project-id profile) + job (setup-import profile project-id (when-not legacy (:default-team-id profile))) + entered (promise) + release (promise) + lock-pid (promise) + original v3/import-files!] + (with-redefs [v3/import-files! + (fn [cfg] + (let [result (original cfg) + files (db/exec! cfg ["SELECT id FROM file WHERE project_id = ? AND deleted_at IS NULL" + project-id])] + (deliver entered (count files)) + (await-result release) + result))] + (let [import (future (try (run-import job) + (catch Throwable cause cause)))] + (try + (t/is (pos? (await-result entered))) + (let [waiter (future + (db/tx-run! th/*system* + (fn [cfg] + (deliver lock-pid (get-pid cfg)) + (db/exec-one! cfg ["SELECT id FROM project WHERE id = ? FOR NO KEY UPDATE" + project-id])))) + cancel (atom nil)] + (try + (t/is (true? (await-blocked (await-result lock-pid)))) + (reset! cancel (future (jobs/cancel th/*system* (:id job)))) + (t/is (= 1 (await-result @cancel))) + (t/is (= "cancelled" (:status (jobs/get-job th/*system* (:id job))))) + (deliver release true) + (let [error (await-result import)] + (t/is (= :interrupt (:type (ex-data error)))) + (t/is (= :job-interrupted (:code (ex-data error))))) + (await-result waiter) + (t/is (empty? (get-files project-id))) + (finally + (deliver release true) + (await-result import) + (await-result waiter) + (when @cancel + (await-result @cancel))))) + (finally + (deliver release true) + (await-result import))))))) + +(t/deftest cancellation-of-a-running-import + (cancel-running-import false)) + +(t/deftest cancellation-of-a-running-legacy-import + (cancel-running-import true)) diff --git a/backend/test/backend_tests/import_terminal_rpc_test.clj b/backend/test/backend_tests/import_terminal_rpc_test.clj new file mode 100644 index 0000000000..47d7c975f6 --- /dev/null +++ b/backend/test/backend_tests/import_terminal_rpc_test.clj @@ -0,0 +1,230 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC + +(ns backend-tests.import-terminal-rpc-test + (:require + [app.common.transit :as transit] + [app.config :as cf] + [app.db :as db] + [app.jobs :as jobs] + [app.jobs.storage :as js] + [app.loggers.audit :as audit] + [app.loggers.webhooks :as webhooks] + [app.rpc :as-alias rpc] + [app.rpc.commands.management :as management] + [app.storage :as sto] + [backend-tests.helpers :as th] + [clojure.java.io :as jio] + [clojure.test :as t] + [datoteka.io :as io])) + +(t/use-fixtures :once th/state-init) +(t/use-fixtures :each (th/serial th/database-reset th/clean-storage)) + +(def ^:private real-audit-submit audit/submit) + +(defn- create-import-job + [profile & {:keys [team-id]}] + (let [id (th/create-job* :import-binfile {:profile-id (:id profile)})] + (th/db-update! :job {:status "new" + :params (db/json (cond-> {:project-id (:default-project-id profile) + :name "imported" + :version 3 + :generated-by "test"} + team-id (assoc :team-id team-id)))} + {:id id}) + id)) + +(defn- get-import-events + [] + (->> (th/db-exec! ["SELECT * FROM audit_log WHERE name = 'import-binfile' AND source = 'backend'"]) + (mapv #(update % :props db/decode-transit-pgobject)))) + +(t/deftest cancelling-a-queued-import-through-rpc-persists-one-terminal-event + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true] + (let [profile (th/create-profile* 1) + job-id (create-import-job profile) + cancel #(th/command! {::th/type :cancel-job + ::rpc/profile-id (:id profile) + :id job-id})] + (t/is (th/success? (cancel))) + (t/is (th/success? (cancel))) + (t/is (= "cancelled" (:status (jobs/get-job th/*system* job-id)))) + (let [events (get-import-events) + event (first events) + props (:props event)] + (t/is (= 1 (count events))) + (t/is (= (:id profile) (:profile-id event))) + (t/is (= job-id (:job-id props))) + (t/is (= (:default-team-id profile) (:team-id props))) + (t/is (= "cancelled" (:status props))) + (t/is (= 3 (:version props))) + (t/is (= "test" (:generated-by props))) + (t/is (not (contains? props :file-ids))) + (t/is (not (contains? props :file-count))))))) + +(t/deftest management-terminal-rpcs-run-the-registered-import-hook + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true] + (let [profile (th/create-profile* 1) + completed-id (create-import-job profile) + failed-id (create-import-job profile) + result {:file-ids [] :name "imported" :version 3} + error {:type :internal :code :processing-error :hint "failed"}] + (doseq [id [completed-id failed-id]] + (t/is (pos? (jobs/claim th/*system* id (:scheduled-at (jobs/get-job th/*system* id)))))) + (let [completed (th/management-command! {::th/type :complete-job + :job-id completed-id + :result result}) + failed (th/management-command! {::th/type :fail-job + :job-id failed-id + :error error}) + events (get-import-events) + by-job (into {} (map (juxt #(get-in % [:props :job-id]) identity)) events)] + (t/is (nil? (:error completed))) + (t/is (nil? (:error failed))) + (t/is (= "completed" (:status (jobs/get-job th/*system* completed-id)))) + (t/is (= "failed" (:status (jobs/get-job th/*system* failed-id)))) + (t/is (= 2 (count events))) + (t/is (= "completed" (get-in by-job [completed-id :props :status]))) + (t/is (= 0 (get-in by-job [completed-id :props :file-count]))) + (t/is (= "failed" (get-in by-job [failed-id :props :status]))) + (t/is (not (contains? (get-in by-job [failed-id :props]) :file-ids))))))) + +(t/deftest cancelling-a-moved-import-routes-to-its-frozen-team + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/webhooks-enabled? true] + (let [profile (th/create-profile* 1) + original-id (:default-team-id profile) + destination (th/create-team* 1 {:profile-id (:id profile)}) + original (th/create-webhook* {:team-id original-id}) + _ (th/create-webhook* {:team-id (:id destination)}) + job-id (create-import-job profile :team-id original-id)] + (th/db-update! :project {:team-id (:id destination)} + {:id (:default-project-id profile)}) + (t/is (th/success? (th/command! {::th/type :cancel-job + ::rpc/profile-id (:id profile) + :id job-id}))) + (let [events (get-import-events) + event (first events) + rows (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"]) + blobs (map #(db/decode-json-pgobject (:params %)) rows) + blob (first (filter #(= "import-binfile" + (:name (transit/decode-str (:event-blob %)))) + blobs))] + (t/is (= 1 (count events))) + (t/is (= original-id (get-in event [:props :team-id]))) + (t/is (some? blob)) + (when blob + (webhooks/process-event-impl th/*system* blob) + (let [deliveries (th/db-exec! ["SELECT * FROM job WHERE name = 'run-webhook'"]) + params (map #(db/decode-json-pgobject (:params %)) deliveries) + delivery (first params) + payload (some-> delivery :event transit/decode-str)] + (t/is (= 1 (count deliveries))) + (t/is (= (str (:id original)) (get-in delivery [:config :id]))) + (t/is (= original-id (get-in payload [:props :team-id]))) + (t/is (= job-id (get-in payload [:props :job-id]))))))))) + +(t/deftest failed-import-after-move-routes-to-its-frozen-team + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/webhooks-enabled? true] + (let [profile (th/create-profile* 1) + original-id (:default-team-id profile) + project (th/create-project* 1 {:profile-id (:id profile) + :team-id original-id}) + project-id (:id project) + destination (th/create-team* 1 {:profile-id (:id profile)}) + original (th/create-webhook* {:team-id original-id}) + _ (th/create-webhook* {:team-id (:id destination)}) + path (-> "backend_tests/test_files/svg-attrs-camel-case.penpot" + io/resource jio/file) + staged (js/put-resource th/*system* (:id profile) + {:content (sto/content path) + :filename "package.penpot" + :mtype "application/zip"}) + job-id (th/create-job* :import-binfile {:profile-id (:id profile) + :resource-id (:resource-id staged)}) + params {:project-id project-id :team-id original-id + :name "imported" :version 3}] + (th/db-update! :job {:params (db/json params)} {:id job-id}) + (db/tx-run! th/*system* + #(management/move-project % {:profile-id (:id profile) + :project-id project-id + :team-id (:id destination)})) + (let [error (try + (jobs/invoke (assoc th/*system* + ::jobs/name :import-binfile + ::jobs/params params + ::jobs/context (jobs/make-context (jobs/get-job th/*system* job-id)))) + (catch Throwable cause cause))] + (t/is (= :import-team-changed (-> error ex-data :code))) + (t/is (= 1 (jobs/fail th/*system* job-id + {:type :validation :code :import-team-changed + :hint "the destination project changed teams"})))) + (t/is (= "failed" (:status (jobs/get-job th/*system* job-id)))) + (t/is (empty? (th/db-exec! ["SELECT id FROM file WHERE project_id = ? AND deleted_at IS NULL" + project-id]))) + (let [events (get-import-events) + blobs (map #(db/decode-json-pgobject (:params %)) + (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"])) + blob (first (filter #(= "import-binfile" + (:name (transit/decode-str (:event-blob %)))) + blobs))] + (t/is (= 1 (count events))) + (t/is (= "failed" (get-in (first events) [:props :status]))) + (t/is (= original-id (get-in (first events) [:props :team-id]))) + (t/is (some? blob)) + (when blob + (webhooks/process-event-impl th/*system* blob) + (let [deliveries (th/db-exec! ["SELECT * FROM job WHERE name = 'run-webhook'"]) + delivery (some-> deliveries first :params db/decode-json-pgobject) + payload (some-> delivery :event transit/decode-str)] + (t/is (= 1 (count deliveries))) + (t/is (= (str (:id original)) (get-in delivery [:config :id]))) + (t/is (= original-id (get-in payload [:props :team-id]))) + (t/is (= job-id (get-in payload [:props :job-id]))))))))) + +(t/deftest cancelling-a-legacy-moved-import-uses-the-current-team + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true] + (let [profile (th/create-profile* 1) + destination (th/create-team* 1 {:profile-id (:id profile)}) + job-id (create-import-job profile)] + (th/db-update! :project {:team-id (:id destination)} + {:id (:default-project-id profile)}) + (t/is (th/success? (th/command! {::th/type :cancel-job + ::rpc/profile-id (:id profile) + :id job-id}))) + (let [events (get-import-events)] + (t/is (= 1 (count events))) + (t/is (= (:id destination) (get-in (first events) [:props :team-id]))))))) + +(t/deftest cancelling-a-moved-import-does-not-fall-back-to-destination-webhooks + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/webhooks-enabled? true] + (let [profile (th/create-profile* 1) + destination (th/create-team* 1 {:profile-id (:id profile)}) + _ (th/create-webhook* {:team-id (:id destination)}) + job-id (create-import-job profile :team-id (:default-team-id profile))] + (th/db-update! :project {:team-id (:id destination)} + {:id (:default-project-id profile)}) + (t/is (th/success? (th/command! {::th/type :cancel-job + ::rpc/profile-id (:id profile) + :id job-id}))) + (let [rows (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"]) + blobs (map #(db/decode-json-pgobject (:params %)) rows) + blob (first (filter #(= "import-binfile" + (:name (transit/decode-str (:event-blob %)))) + blobs))] + (t/is (some? blob)) + (when blob + (webhooks/process-event-impl th/*system* blob) + (t/is (empty? (th/db-exec! ["SELECT id FROM job WHERE name = 'run-webhook'"])))))))) diff --git a/backend/test/backend_tests/jobs_test.clj b/backend/test/backend_tests/jobs_test.clj index 556a47a139..4aea6a0adb 100644 --- a/backend/test/backend_tests/jobs_test.clj +++ b/backend/test/backend_tests/jobs_test.clj @@ -163,6 +163,62 @@ nil) (-purge [_ _] nil))) +(t/deftest terminal-hooks-run-in-the-winning-transaction + (doseq [[status transition terminal-status result error] + [["running" (fn [cfg id] (jobs/complete cfg :job-id id :result {:value 1})) + "completed" {:value 1} nil] + ["running" (fn [cfg id] (jobs/fail cfg id test-error)) + "failed" nil test-error] + ["new" jobs/cancel "cancelled" nil nil]]] + (let [seen (atom []) + defs (assoc-in (get-job-defs) [:echo ::jobs/on-terminal] + (fn [tx-cfg job] + (swap! seen conj job) + (db/exec-one! tx-cfg ["UPDATE job SET label = ? WHERE id = ?" + "hook-ran" (:id job)]))) + cfg (make-cfg defs) + params (make-params) + id (jobs/submit cfg {::jobs/name :echo ::jobs/params params})] + (th/db-exec! ["UPDATE job SET status = ? WHERE id = ?" status id]) + (t/is (= 1 (transition cfg id))) + (t/is (= 0 (transition cfg id))) + (t/is (= 1 (count @seen))) + (t/is (= id (:id (first @seen)))) + (t/is (= params (:params (first @seen)))) + (t/is (= terminal-status (:status (first @seen)))) + (t/is (= result (:result (first @seen)))) + (t/is (= error (:error (first @seen)))) + (t/is (= (= terminal-status "completed") (contains? (first @seen) :result))) + (t/is (= (= terminal-status "failed") (contains? (first @seen) :error))) + (t/is (= "hook-ran" (:label (jobs/get-job cfg id))))))) + +(t/deftest terminal-hook-failure-rolls-back-transition-and-writes + (doseq [[status transition] + [["running" (fn [cfg id] (jobs/complete cfg :job-id id :result nil))] + ["running" (fn [cfg id] (jobs/fail cfg id test-error))] + ["new" jobs/cancel]]] + (let [defs (assoc-in (get-job-defs) [:echo ::jobs/on-terminal] + (fn [tx-cfg job] + (db/exec-one! tx-cfg ["UPDATE job SET label = ? WHERE id = ?" + "rolled-back" (:id job)]) + (throw (ex-info "hook failed" {})))) + cfg (make-cfg defs) + id (jobs/submit cfg {::jobs/name :echo ::jobs/params (make-params)})] + (th/db-exec! ["UPDATE job SET status = ? WHERE id = ?" status id]) + (t/is (some? (raised #(transition cfg id)))) + (t/is (= status (:status (jobs/get-job cfg id)))) + (t/is (not= "rolled-back" (:label (jobs/get-job cfg id)))) + (t/is (empty? (get-outcomes id)))))) + +(t/deftest terminal-transitions-allow-a-missing-definition-or-hook + (doseq [remove-definition [false true]] + (let [defs (get-job-defs) + cfg (make-cfg defs) + id (jobs/submit cfg {::jobs/name :echo ::jobs/params (make-params)}) + cfg (if remove-definition (assoc cfg ::jobs/defs {}) cfg)] + (t/is (= 1 (jobs/cancel cfg id))) + (t/is (= ["cancelled"] (get-outcomes id)))))) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TESTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; diff --git a/backend/test/backend_tests/rpc/commands/jobs_test.clj b/backend/test/backend_tests/rpc/commands/jobs_test.clj index 5ced5072ee..094f2cbb13 100644 --- a/backend/test/backend_tests/rpc/commands/jobs_test.clj +++ b/backend/test/backend_tests/rpc/commands/jobs_test.clj @@ -12,14 +12,19 @@ [app.binfile.v3 :as v3] [app.common.exceptions :as ex] [app.common.time :as ct] + [app.common.transit :as transit] [app.common.uuid :as uuid] [app.config :as cf] [app.db :as db] [app.jobs :as jobs] - [app.loggers.audit :as-alias audit] + [app.jobs.storage :as js] + [app.loggers.audit :as audit] + [app.loggers.webhooks :as webhooks] [app.rpc :as-alias rpc] [app.rpc.climit :as-alias climit] [app.rpc.commands.jobs :as cmd-jobs] + [app.rpc.commands.management :as management] + [app.rpc.commands.projects :as projects] [app.rpc.quotes :as-alias quotes] [app.storage :as sto] [app.storage.tmp :as tmp] @@ -42,6 +47,8 @@ "A real penpot export, the same fixture the binfile tests read." "backend_tests/test_files/svg-attrs-camel-case.penpot") +(def ^:private real-audit-submit audit/submit) + (defn- import-fixture! "A file in the default project of the profile, imported from the fixture through the core." @@ -440,6 +447,7 @@ (let [job-def (jobs/get-job-def (::jobs/defs th/*system*) :import-binfile) params (jobs/decode-params job-def (:params job))] (t/is (= (:default-project-id profile) (:project-id params))) + (t/is (= (:default-team-id profile) (:team-id params))) (t/is (= "imported" (:name params))) (t/is (= 3 (:version params))) (t/is (string? (:generated-by params))))) @@ -447,7 +455,213 @@ (t/testing "the audit points at the job and the manifest, not the package" (let [props (::audit/props (meta (:result out)))] (t/is (= (:id result) (:job-id props))) - (t/is (= #{:job-id :generated-by :referer} (set (keys props))))))))) + (t/is (= (:default-team-id profile) (:team-id props))) + (t/is (= #{:job-id :team-id :generated-by :referer} (set (keys props)))) + (t/is (not (contains? result :team-id)))))))) + +(t/deftest create-import-binfile-job-rejects-a-client-supplied-team + (let [profile (th/create-profile* 1) + session-id (upload-chunked! profile) + before (live-storage-objects) + out (create-import-binfile-job + (:id profile) (:default-project-id profile) + :upload-id session-id + :params {:project-id (:default-project-id profile) + :name "imported" + :team-id (uuid/next)})] + (t/is (not (th/success? out))) + (t/is (= :params-validation (th/ex-code (:error out)))) + (t/is (zero? (count-jobs))) + (t/is (= before (live-storage-objects))) + (t/is (nil? (:deleted-at (session-row session-id)))))) + +(t/deftest create-import-binfile-job-routes-its-audit-to-the-frozen-team + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/webhooks-enabled? true] + (let [profile (th/create-profile* 1) + original-id (:default-team-id profile) + destination (th/create-team* 1 {:profile-id (:id profile)}) + original (th/create-webhook* {:team-id original-id}) + _ (th/create-webhook* {:team-id (:id destination)}) + upload-id (upload-chunked! profile) + names {(uuid/next) "Renamed file"} + given {:project-id (:default-project-id profile) :name names} + out (create-import-binfile-job (:id profile) (:default-project-id profile) + :upload-id upload-id :params given) + job-id (:id (:result out))] + (t/is (th/success? out)) + (th/db-update! :project {:team-id (:id destination)} + {:id (:default-project-id profile)}) + ;; The test system does not install the RPC audit wrapper. Prepare the + ;; event after the move, as that wrapper does after the command returns. + (let [[mdata _] (get (::rpc/methods th/*system*) :create-import-binfile-job) + request (reify + yetti.request/IRequest + (get-header [_ _] nil) + (remote-addr [_] "127.0.0.1")) + params (with-meta {::rpc/profile-id (:id profile) + ::rpc/request-id (uuid/next) + ::rpc/request-at (ct/now) + :upload-id upload-id + :params given} + {:app.http/request request}) + event (audit/prepare-rpc-event (assoc th/*system* ::rpc/module "main" + ::rpc/type "command") + mdata params (:result out))] + (audit/submit th/*system* event)) + (let [rows (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"]) + blobs (map #(db/decode-json-pgobject (:params %)) rows) + blob (first (filter #(= "create-import-binfile-job" + (:name (transit/decode-str (:event-blob %)))) + blobs))] + (t/is (some? blob)) + (when blob + (webhooks/process-event-impl th/*system* blob) + (let [deliveries (th/db-exec! ["SELECT * FROM job WHERE name = 'run-webhook'"]) + params (map #(db/decode-json-pgobject (:params %)) deliveries) + delivery (first params) + payload (some-> delivery :event transit/decode-str) + props (:props payload)] + (t/is (= 1 (count deliveries))) + (t/is (= (str (:id original)) (get-in delivery [:config :id]))) + (t/is (= original-id (:team-id props))) + (t/is (= job-id (:job-id props))) + (t/is (= (cond-> {:upload-id upload-id + :params given + :team-id original-id + :job-id job-id} + (some? (:generated-by (::audit/props (meta (:result out))))) + (assoc :generated-by (:generated-by (::audit/props (meta (:result out))))) + (some? (:referer (::audit/props (meta (:result out))))) + (assoc :referer (:referer (::audit/props (meta (:result out)))))) + props)))))))) + +(defn- await-concurrent + [p] + (let [value (deref p 15000 ::timeout)] + (when (= ::timeout value) + (throw (ex-info "Timed out waiting for concurrent operation" {}))) + value)) + +(defn- await-db-blocked + [pid] + (let [deadline (+ (System/nanoTime) 10000000000)] + (loop [] + (cond + (:blocked (db/exec-one! th/*system* + ["SELECT cardinality(pg_blocking_pids(?)) > 0 AS blocked" pid])) + true + (< (System/nanoTime) deadline) (recur) + :else (throw (ex-info "Database operation did not block" {:pid pid})))))) + +(t/deftest create-import-after-move-rechecks-permission-and-releases-resource + (let [owner (th/create-profile* 1) + actor (th/create-profile* 2) + project (th/create-project* 1 {:profile-id (:id owner) + :team-id (:default-team-id owner)}) + destination (th/create-team* 1 {:profile-id (:id owner)}) + _ (th/db-insert! :team-profile-rel {:team-id (:default-team-id owner) + :profile-id (:id actor) + :is-owner false + :is-admin false + :can-edit true}) + upload-id (upload-chunked! actor) + before (live-storage-objects) + staged (promise) + proceed (promise) + moved (promise) + release (promise) + create-pid (promise) + put js/put-resource + lock projects/get-project-for-update] + (with-redefs [js/put-resource (fn [& args] + (let [resource (apply put args)] + (deliver staged resource) + (await-concurrent proceed) + resource)) + projects/get-project-for-update + (fn [cfg id] + (when (realized? moved) + (deliver create-pid (:pid (db/exec-one! cfg ["SELECT pg_backend_pid() AS pid"])))) + (lock cfg id))] + (let [creating (future (create-import-binfile-job (:id actor) (:id project) :upload-id upload-id))] + (try + (await-concurrent staged) + (let [moving (future + (db/tx-run! th/*system* + (fn [cfg] + (management/move-project cfg {:profile-id (:id owner) + :project-id (:id project) + :team-id (:id destination)}) + (deliver moved true) + (await-concurrent release))))] + (try + (await-concurrent moved) + (deliver proceed true) + (t/is (true? (await-db-blocked (await-concurrent create-pid)))) + (deliver release true) + (await-concurrent moving) + (let [out (await-concurrent creating)] + (t/is (not (th/success? out))) + (t/is (= :not-found (th/ex-type (:error out)))) + (t/is (zero? (count-jobs))) + (t/is (= before (live-storage-objects))) + (t/is (some? (:deleted-at (session-row upload-id))))) + (finally + (deliver proceed true) + (deliver release true) + (await-concurrent moving)))) + (finally + (deliver proceed true) + (deliver release true) + (await-concurrent creating))))))) + +(t/deftest move-waits-for-import-job-submission + (let [profile (th/create-profile* 1) + project (th/create-project* 1 {:profile-id (:id profile) + :team-id (:default-team-id profile)}) + destination (th/create-team* 1 {:profile-id (:id profile)}) + upload-id (upload-chunked! profile) + entered (promise) + release (promise) + move-pid (promise) + submit jobs/submit] + (with-redefs [jobs/submit (fn [cfg params] + (when (= :import-binfile (::jobs/name params)) + (deliver entered true) + (await-concurrent release)) + (submit cfg params))] + (let [creating (future (create-import-binfile-job (:id profile) (:id project) :upload-id upload-id))] + (try + (await-concurrent entered) + (let [moving (future + (db/tx-run! th/*system* + (fn [cfg] + (deliver move-pid (:pid (db/exec-one! cfg ["SELECT pg_backend_pid() AS pid"]))) + (management/move-project cfg {:profile-id (:id profile) + :project-id (:id project) + :team-id (:id destination)}))))] + (try + (t/is (true? (await-db-blocked (await-concurrent move-pid)))) + (deliver release true) + (let [out (await-concurrent creating) + job (jobs/get-job th/*system* (:id (:result out))) + job-def (jobs/get-job-def (::jobs/defs th/*system*) :import-binfile) + params (jobs/decode-params job-def (:params job))] + (t/is (th/success? out)) + (t/is (= (:default-team-id profile) (:team-id params))) + (t/is (= (:default-team-id profile) + (:team-id (::audit/props (meta (:result out)))))) + (t/is (some? (:resource-id job)))) + (await-concurrent moving) + (t/is (= (:id destination) (:team-id (th/db-get :project {:id (:id project)})))) + (finally + (deliver release true) + (await-concurrent moving)))) + (finally + (deliver release true) + (await-concurrent creating))))))) (t/deftest create-import-binfile-job-assembles-the-chunks-of-its-upload (let [profile (th/create-profile* 1) diff --git a/backend/test/backend_tests/rpc_management_test.clj b/backend/test/backend_tests/rpc_management_test.clj index c1b81a32d5..cbb1462422 100644 --- a/backend/test/backend_tests/rpc_management_test.clj +++ b/backend/test/backend_tests/rpc_management_test.clj @@ -16,6 +16,7 @@ [app.db :as db] [app.http :as http] [app.rpc :as-alias rpc] + [app.rpc.commands.management :as management] [app.storage :as sto] [backend-tests.helpers :as th] [backend-tests.storage-test :refer [configure-storage-backend]] @@ -671,6 +672,35 @@ (let [rows (th/db-query :file-library-rel {:file-id (:id file2)})] (t/is (zero? (count rows))))))) +(t/deftest move-project-locks-before-validating + (let [profile (th/create-profile* 1 {:is-active true}) + project-id (:default-project-id profile) + locked (promise) + release (promise) + holder (future + (db/tx-run! th/*system* + (fn [{:keys [::db/conn]}] + (db/exec-one! conn ["SELECT id FROM project WHERE id = ? FOR NO KEY UPDATE" + project-id]) + (deliver locked true) + (deref release 10000 ::timeout))))] + (try + (t/is (= true (deref locked 10000 ::timeout))) + (let [error (try + (db/tx-run! th/*system* + (fn [{:keys [::db/conn] :as cfg}] + (db/exec-one! conn ["SET LOCAL lock_timeout = '100ms'"]) + (management/move-project + cfg {:profile-id (:id profile) + :project-id project-id + :team-id (:default-team-id profile)}))) + nil + (catch java.sql.SQLException cause cause))] + (t/is (= "55P03" (some-> error .getSQLState)))) + (finally + (deliver release true) + (t/is (not= ::timeout (deref holder 10000 ::timeout))))))) + (t/deftest move-project (let [profile (th/create-profile* 1 {:is-active true}) team (th/create-team* 1 {:profile-id (:id profile)}) diff --git a/backend/test/backend_tests/tasks/import_binfile_test.clj b/backend/test/backend_tests/tasks/import_binfile_test.clj index e82d462df3..d4eb1243a2 100644 --- a/backend/test/backend_tests/tasks/import_binfile_test.clj +++ b/backend/test/backend_tests/tasks/import_binfile_test.clj @@ -9,14 +9,18 @@ it leaves behind when it fails." (:require [app.binfile.common :as bfc] + [app.binfile.jobs :as bfj] [app.binfile.v1 :as v1] [app.binfile.v3 :as v3] [app.common.uuid :as uuid] + [app.config :as cf] [app.db :as db] [app.jobs :as jobs] [app.jobs.storage :as js] + [app.loggers.audit :as audit] [app.storage :as sto] [app.storage.tmp :as tmp] + [app.tasks.import-binfile :as import-binfile] [backend-tests.helpers :as th] [clojure.java.io :as jio] [clojure.test :as t] @@ -85,6 +89,21 @@ [] (seq (.list (jio/file tmp/default-tmp-dir)))) +(def ^:private real-audit-submit audit/submit) + +(defn- get-audit-events + [event-name] + (->> (th/db-exec! ["SELECT * FROM audit_log WHERE name = ? AND source = 'backend'" + event-name]) + (mapv #(update % :props db/decode-transit-pgobject)))) + +(defn- create-import-job + [profile params resource-id] + (let [job-id (th/create-job* :import-binfile {:profile-id (:id profile) + :resource-id resource-id})] + (th/db-update! :job {:params (db/json params)} {:id job-id}) + job-id)) + (defn- project-modified-at [project-id] (:modified-at (th/db-get :project {:id project-id}))) @@ -186,6 +205,17 @@ (t/testing "and the package is released" (t/is (some? (:deleted-at (input-row (:resource-id staged)))))))) +(t/deftest an-import-refuses-a-project-that-changed-teams + (let [profile (th/create-profile* 1) + project-id (:default-project-id profile) + staged (stage-package! profile (fixture-path)) + params {:project-id project-id :team-id (uuid/next) + :name "imported" :version 3} + job-id (create-import-job profile params (:resource-id staged)) + before (project-files project-id)] + (t/is (thrown? Throwable (run-import job-id params))) + (t/is (= before (project-files project-id))))) + (t/deftest an-import-cancelled-while-it-runs-leaves-nothing-behind (let [profile (th/create-profile* 1) staged (stage-package! profile (fixture-path)) @@ -265,3 +295,188 @@ (t/testing "and the import is rolled back: the destination keeps no files" (t/is (= before (project-files project-id))))))) + +(t/deftest import-audit-excludes-unlisted-job-params + (let [profile (th/create-profile* 1) + event (atom nil) + job {:id (uuid/next) + :profile-id (:id profile) + :status "cancelled" + :params {:project-id (:default-project-id profile) + :name "imported" + :version 3 + :future-param "not for audit"}}] + (with-redefs [audit/submit (fn [_ submitted] (reset! event submitted))] + (#'import-binfile/submit-import-event th/*system* job)) + (t/is (= {:project-id (:default-project-id profile) + :name "imported" + :version 3 + :job-id (:id job) + :status "cancelled" + :team-id (:default-team-id profile)} + (:props @event))))) + +(t/deftest a-completed-import-submits-its-audit-events + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) + :name "imported" :version 3 + :referer "penpot" :generated-by "penpot/2.20.0"} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged)) + result (run-import job-id params) + file-id (first (:file-ids result))] + (t/is (empty? (get-audit-events "import-binfile"))) + (t/is (= 1 (jobs/complete th/*system* :job-id job-id :result result))) + (t/is (zero? (jobs/complete th/*system* :job-id job-id :result result))) + (let [[event :as events] (get-audit-events "import-binfile") + [created :as created-events] (get-audit-events "create-file")] + (t/is (= 1 (count events))) + (t/is (= "command" (:type event))) + (t/is (= (:id profile) (:profile-id event))) + (t/is (= {:status "completed" :job-id job-id + :project-id (:default-project-id profile) + :team-id (:default-team-id profile) + :name "imported" :version 3 :referer "penpot" + :generated-by "penpot/2.20.0" + :file-ids [file-id] :file-count 1} + (:props event))) + (t/is (= 1 (count created-events))) + (t/is (= file-id (-> created :props :id))) + (t/is (= (:id profile) (:profile-id created))) + (t/is (= (:default-team-id profile) (-> created :props :team-id))))))) + +(t/deftest a-failed-import-submits-its-terminal-outcome + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged))] + (with-redefs [v3/import-files! (fn [_] (throw (ex-info "boom" {:type :internal})))] + (t/is (thrown? Throwable (run-import job-id params)))) + (t/is (= 1 (jobs/fail th/*system* job-id {:type :internal :code :unexpected-error :hint "import failed"}))) + (t/is (zero? (jobs/fail th/*system* job-id {:type :internal :code :unexpected-error :hint "import failed"}))) + (let [[event :as events] (get-audit-events "import-binfile")] + (t/is (= 1 (count events))) + (t/is (= (:id profile) (:profile-id event))) + (t/is (= "failed" (-> event :props :status))) + (t/is (= job-id (-> event :props :job-id))) + (t/is (not (contains? (:props event) :file-ids))) + (t/is (not (contains? (:props event) :file-count)))) + (t/is (empty? (get-audit-events "create-file")))))) + +(t/deftest a-queued-cancellation-submits-one-outcome-without-loading-input + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + job-id (create-import-job profile params nil)] + (th/db-update! :job {:status "new"} {:id job-id}) + (t/is (= 1 (jobs/cancel th/*system* job-id))) + (t/is (zero? (jobs/cancel th/*system* job-id))) + (t/is (zero? (jobs/complete th/*system* :job-id job-id :result nil))) + (let [[event :as events] (get-audit-events "import-binfile")] + (t/is (= 1 (count events))) + (t/is (= (:id profile) (:profile-id event))) + (t/is (= "cancelled" (-> event :props :status))) + (t/is (= job-id (-> event :props :job-id))) + (t/is (not (contains? (:props event) :file-ids))) + (t/is (not (contains? (:props event) :file-count)))) + (t/is (empty? (get-audit-events "create-file")))))) + +(t/deftest cancellation-after-the-last-check-can-leave-imported-files + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged)) + run bfj/run + result (with-redefs [bfj/run (fn [cfg context f] + (let [result (run cfg context f)] + (jobs/cancel th/*system* job-id) + result))] + (run-import job-id params))] + (t/is (= "cancelled" (:status (jobs/get-job th/*system* job-id)))) + (t/is (zero? (jobs/complete th/*system* :job-id job-id :result result))) + (t/is (= (set (:file-ids result)) + (set (map :id (project-files (:default-project-id profile)))))) + (t/is (= ["cancelled"] (mapv #(get-in % [:props :status]) + (get-audit-events "import-binfile")))) + (t/is (= 1 (count (get-audit-events "create-file"))))))) + +(t/deftest file-created-events-require-full-audit-persistence + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? false + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged)) + result (run-import job-id params)] + (t/is (= 1 (count (:file-ids result)))) + (t/is (empty? (get-audit-events "create-file")))))) + +(t/deftest a-terminal-audit-failure-does-not-undo-the-committed-import + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged)) + result (run-import job-id params)] + (with-redefs [audit/submit (fn [cfg event] + (real-audit-submit cfg event) + (throw (ex-info "audit failure" {})))] + (t/is (thrown-with-msg? Exception #"audit failure" + (jobs/complete th/*system* :job-id job-id :result result)))) + (t/is (= "running" (:status (jobs/get-job th/*system* job-id)))) + (t/is (empty? (get-audit-events "import-binfile"))) + (t/is (= (set (:file-ids result)) + (set (map :id (project-files (:default-project-id profile)))))) + (t/is (= 1 (count (get-audit-events "create-file"))))))) + +(t/deftest a-file-created-audit-failure-leaves-the-imported-file-committed + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged))] + (with-redefs [audit/submit (fn [cfg event] + (real-audit-submit cfg event) + (throw (ex-info "audit failure" {})))] + (t/is (thrown-with-msg? Exception #"audit failure" (run-import job-id params)))) + (t/is (= 1 (count (project-files (:default-project-id profile))))) + (t/is (empty? (get-audit-events "create-file"))) + (t/is (empty? (get-audit-events "import-binfile")))))) + +(t/deftest an-aborted-import-does-not-report-a-cancellation + (with-redefs [audit/submit real-audit-submit + cf/audit-persist? true + cf/telemetry-enabled? false + cf/webhooks-enabled? false] + (let [profile (th/create-profile* 1) + params {:project-id (:default-project-id profile) :name "imported" :version 3} + staged (stage-package! profile (fixture-path)) + job-id (create-import-job profile params (:resource-id staged))] + (th/db-update! :job {:status "aborted"} {:id job-id}) + (t/is (thrown? Throwable (run-import job-id params))) + (t/is (zero? (jobs/cancel th/*system* job-id))) + (t/is (empty? (get-audit-events "import-binfile"))) + (t/is (empty? (get-audit-events "create-file")))))) diff --git a/backend/test/backend_tests/worker_dispatcher_test.clj b/backend/test/backend_tests/worker_dispatcher_test.clj index c58a8d09cb..5d5180a066 100644 --- a/backend/test/backend_tests/worker_dispatcher_test.clj +++ b/backend/test/backend_tests/worker_dispatcher_test.clj @@ -406,6 +406,26 @@ (t/testing "recent running job is not touched" (t/is (= "running" (:status (get-row fresh))))))) +(t/deftest dispatcher-aborts-do-not-run-terminal-hooks + (let [calls (atom []) + cfg (assoc (mk-cfg) + ::jobs/defs + {:test-job {::jobs/decoder identity + ::jobs/on-terminal + (fn [_ job] + (swap! calls conj job))}}) + lost (mk-job {:status "scheduled" + :modified-at (ct/minus (ct/now) + (ct/duration {:minutes 6}))}) + orphan (mk-job {:status "running" + :modified-at (ct/minus (ct/now) + (ct/plus (cf/get-jobs-lease) + (ct/duration {:minutes 1})))})] + (wdisp/run-batch cfg) + (t/is (= "aborted" (:status (get-row lost)))) + (t/is (= "aborted" (:status (get-row orphan)))) + (t/is (= [] @calls)))) + (t/deftest dispatcher-orphan-sweep-records-the-terminal-counter (let [metrics (make-orphan-metrics) cfg (assoc (mk-cfg) ::mtx/metrics metrics) diff --git a/scripts/check-commit b/scripts/check-commit index 44ed1e47fd..1a7aac5726 100755 --- a/scripts/check-commit +++ b/scripts/check-commit @@ -73,6 +73,9 @@ NON_HUMAN_COAUTHOR_PATTERN = re.compile( re.IGNORECASE, ) +AI_TRAILER_PATTERN = re.compile(r"^\s*ai-assisted-by\s*:(.*)$", re.IGNORECASE) +MODEL_ID_PATTERN = re.compile(r"[a-z0-9]+(?:[.-][a-z0-9]+)*") + URL_PATTERN = re.compile(r"https?://\S+") # ═══════════════════════════════════════════════════════════════════════════════ @@ -243,6 +246,26 @@ def check_co_authored_by(message): ) +def check_ai_assisted_by(message): + """Validate every AI-assisted-by value as a bare lowercase model ID.""" + offenders = [] + for line_number, line in enumerate(message.split("\n"), start=1): + match = AI_TRAILER_PATTERN.match(line) + if match and not MODEL_ID_PATTERN.fullmatch(match.group(1).strip()): + offenders.append((line_number, line)) + if not offenders: + return True, None + details = "\n".join( + f" line {line_number}: {line!r}" + for line_number, line in offenders + ) + return False, ( + "AI-assisted-by must use a bare lowercase canonical model ID slug " + "(for example, gpt-6.1-terra), without a provider prefix. " + "Offending line(s):\n" + details + ) + + # ═══════════════════════════════════════════════════════════════════════════════ def main(): @@ -269,6 +292,7 @@ def main(): ("Blank line after subject", check_body_blank_line), ("Body wrapped at 80 chars", check_body_line_length), ("Co-authored-by is human only", check_co_authored_by), + ("AI-assisted-by uses a model ID slug", check_ai_assisted_by), ] all_ok = True diff --git a/scripts/test_check_commit.py b/scripts/test_check_commit.py index 05cc38671d..8134ab8671 100644 --- a/scripts/test_check_commit.py +++ b/scripts/test_check_commit.py @@ -14,7 +14,9 @@ providers and bots. import importlib.machinery import importlib.util import pathlib +import subprocess import sys +import tempfile import unittest # Loading scripts/check-commit would otherwise emit scripts/__pycache__/. @@ -189,6 +191,53 @@ class CoAuthorTrailerTests(unittest.TestCase): self.assert_ok(":bug: Fix crash\n\nBody.\n\nCo-developed-by: Someone \n") +class AIAssistedTrailerTests(unittest.TestCase): + def test_valid_and_absent_trailers(self): + for trailer in ("", "AI-assisted-by: gpt-6.1-terra", + "ai-assisted-by: deepseek-v4-flash", + "AI-assisted-by: gpt-6.1-terra\nAI-assisted-by: mimo-v2.5"): + with self.subTest(trailer=trailer): + ok, error = check_commit.check_ai_assisted_by(":bug: Fix crash\n\n" + trailer) + self.assertTrue(ok, error) + + def test_invalid_values_are_reported(self): + for value in ("", "openai/gpt-6.1-terra", "GPT-6.1 Terra", + "gpt-6.1-terra extra", "-gpt", "gpt-", "gpt..6", "gpt_6"): + with self.subTest(value=value): + ok, error = check_commit.check_ai_assisted_by( + ":bug: Fix crash\n\nAI-assisted-by: " + value + ) + self.assertFalse(ok) + self.assertIn("line 3", error) + + def test_each_trailer_is_checked_and_all_offenders_reported(self): + ok, error = check_commit.check_ai_assisted_by( + ":bug: Fix crash\n\nAI-assisted-by: gpt-6.1-terra\n" + "AI-assisted-by: openai/gpt-6.1-terra\n" + "ai-assisted-by: GPT-6.1 Terra" + ) + self.assertFalse(ok) + self.assertIn("line 4", error) + self.assertIn("line 5", error) + + def test_cli_rejects_invalid_trailer(self): + with tempfile.TemporaryDirectory() as directory: + subprocess.run(["git", "init", "-q", directory], check=True) + subprocess.run( + ["git", "-C", directory, "-c", "user.name=Test", + "-c", "user.email=test@example.com", "commit", "-q", + "--allow-empty", "-m", ":bug: Fix crash", + "-m", "AI-assisted-by: openai/gpt-6.1-terra"], + check=True, + ) + result = subprocess.run( + [str(SCRIPT_PATH), "-c", "HEAD"], cwd=directory, + capture_output=True, text=True, check=False, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("AI-assisted-by", result.stderr) + + class SubjectRulesRegressionTests(unittest.TestCase): """Guard the pre-existing validators against accidental breakage."""