You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(plugins): keep one installation per plugin - #4525
Other clients: N/A (no client-visible change: plugin installation is a web admin feature, and the Apple, Android and Roku apps don't call the plugin install or upload endpoints)
A plugin could end up with two installation rows, and from then on every install or update of that plugin failed with a server error. Nothing in the database stopped it: installs read plugin_installations to decide between creating and replacing, then inserted without a lock. Two API servers auto-installing a default plugin at startup, or an admin install racing that auto-install, could both insert. An install from a direct archive_url never looked for an existing row at all, so installing an already-installed plugin that way always added a second one. Once two rows exist, existingInstallationByPluginID refuses with "multiple existing installations", which the API returns as a 500.
This change enforces one installation per plugin in Postgres and cleans up deployments that already have duplicates.
Approach
Unique index. A migration adds a unique index on plugin_id for ordinary plugins (kind = 'plugin'; the builtin row keeps its own index). It first takes an EXCLUSIVE lock on the table, so a server still on the previous release can't add a duplicate mid-migration; this mode also waits out row locks such as a settings save's, which would otherwise deadlock with the cleanup. It then deletes duplicates, keeping per plugin a row with an enabled sign-in binding, then one with linked sign-in identities, then one an admin configured (settings or a sign-in binding), then one with a stored package, then an enabled one, then the oldest. Request connections and linked sign-in identities on a deleted row move to the kept one, and the kept row takes any library chain placement, task binding or saved task schedule it lacks from the best-ranked duplicate, and a stored package from a duplicate of the same version. When a duplicate identity can't move because the kept row links the same subject, its same-user sessions and device approvals move to the kept identity, and for a different user every session is revoked, their API keys are deleted and device sign-ins approved for the identity are canceled, so that account signs in again. The deleted rows' settings, sign-in bindings, remaining chain entries and state go with them: settings are encrypted under the installation id, and a delivered event leaves no delivery row, so moving a pending delivery could deliver it to the kept row twice. Events still pending only for a deleted row are dropped.
One write per create.InstallationStore.Create now writes the row, capabilities, signature and stored package in one transaction, with the row enabled. A create that hits the new index returns ErrPluginAlreadyInstalled. The create paths in the installer extract files before writing the row. They no longer save the package, enable the row, or delete it after a later failure as separate steps, so a concurrent replacement can no longer have its package overwritten or its row deleted by a create that started first.
Direct archive links.Service.InstallRemote takes the same create-or-replace decision as an upload, so a direct archive link for an installed plugin replaces it through fix(plugins): refuse a plugin update that another install overtook during its download #4509's guarded replacement path. Because the plugin is known only after the download, it reads the installations before downloading, as installCatalog does: another install of the plugin that lands during the download makes this one answer 409 instead of replacing the newer release.
Validation
Postgres test: installing one plugin twice through a direct archive link leaves one installation, replaced in place under the same id. A second create for the installed plugin is refused and leaves the stored package unchanged. An archive link overtaken by another install during its download is refused and the newer release stays. The test failed on main (4102bca) for the reported reason (the second archive link added a second row), and its overtaken-download case failed on this PR's first head before the fix.
Migration: run on a main-migrated database seeded with duplicates (no package versus package, disabled versus enabled, an older row versus a newer one holding an admin setting, a configured row without a package versus an unconfigured one with one, a request connection naming a duplicate, three duplicates where two hold the same chain placement, task bindings and saved schedules, and sign-in plugins whose duplicates hold different bindings and linked identities). It kept the expected row for each plugin (for sign-in plugins, the one with the enabled binding), moved the request connection and linked identities to it, gave it the missing chain placement, task binding and saved schedules without touching its own, left the builtin row and single installations alone, and the index then refused a new duplicate. Run against an in-flight settings save on a duplicate it deletes, the migration deadlocked with the earlier SHARE ROW EXCLUSIVE lock and waited and finished with EXCLUSIVE.
make test-go, go vet ./..., make lint-changed, go mod tidy -diff, make migrate-validate, and the generated-contract, route-inventory, size-ratchet, local-path and case-collision checks pass.
make test-db-contracts: every listed test that ran passed. The 45 backup tests that need pg_dump/pg_restore skipped on the build host; go test ./internal/backup/ passed there against the branch's database. make lint-router-recovery was not run (no golangci-lint on the build host; no router code changed).
Not reproduced on a running deployment: the proof is the test and the migration run above.
The migration deletes data on deployments that already have duplicate installations: the dropped rows' plugin settings, sign-in bindings, chain entries and state. The ranking keeps the configured row where one exists. When both rows were configured, the older one wins and the other's settings are lost; when the kept configured row has no stored package and no duplicate of the same version had one, the admin installs the plugin again, which replaces that row in place and keeps its settings. Install directories of deleted rows stay on disk.
During a rolling upgrade, a server still on the previous release that hits the new index (an archive-link install of an installed plugin, or a lost race) returns a 500 instead of a 409 until it is upgraded.
The migration briefly blocks writes and row locks on plugin_installations while it runs; plain reads continue.
Checklist
I read and can explain the complete diff.
This pull request addresses one concern.
Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
The Evidence section shows every change a user can see, or how I checked a change nobody sees.
AI Disclosure
Harness: Claude Code in T3 Code
Tool(s): Claude Code; Codex (plan review)
Model(s): claude-opus-5-5 (implementation, plan cut, code review), claude-sonnet-5-5 (code review cleanup finder and validation check), gpt-6.2-sol (plan attack)
Involvement: Fully AI-generated; not yet human verified
Adversarial review: before implementation, gpt-6.2-sol attacked the plan and claude-opus-5-5 cut it. That changed which duplicate the migration keeps (stored package and admin configuration before enabled and age, instead of the oldest row), added the write lock, and reused fix(plugins): refuse a plugin update that another install overtook during its download #4509's ArchiveInput and saveArchive. A high code review (three finders and a validation check) led to the admin-configuration ranking and the 409 wording in the operation summaries, and removed an interface method the installer no longer calls. A simplify pass changed nothing. Kody's review moved admin configuration ahead of the stored package in that ranking and added the request-connection, chain-placement and task-binding moves; Codex's reviews added the saved-schedule and sign-in identity moves and the sign-in ranking. The background adversarial review (gpt-6.2-sol, reviewed a1b9f75) found two problems, both fixed: the migration's lock mode could deadlock with a settings save from a server on the previous release, and a slow archive-link install could replace a newer install that landed during its download. It posted nothing because the head moved before it published.
Enforce one installation per plugin with unique index and ErrPluginAlreadyInstalled
Adds a partial unique index on plugin_id for plugin-kind rows and a new sentinel error ErrPluginAlreadyInstalled returned by InstallationStore.Create on a constraint violation, in installation.go and migration
Installer.installBinary and Installer.installArchive now store the archive and enabled state inside the creation transaction, removing separate save/enable/compensating-delete steps
Concurrent races are handled: admin installs that lose the race return a 409 conflict, and auto-update installs treat it as a skip instead of an error
Service.InstallRemote snapshots installed plugins before download, so a replacement overtaken during download is handled against the earlier installation state rather than blindly creating a new row
Risk: the migration locks plugin_installations during consolidation, merging duplicates by enabled/sign-in binding priority and transferring integrations, identities, sessions, API keys, schedules, and archives to the kept row. Check duplicate-row handling carefully if you rely on multiple installations per plugin.
No actionable comments were generated in the recent review.
Walkthrough
The database now enforces one plugin installation per plugin ID. Installation creation stores archives transactionally, and local, remote, and automatic install paths handle replacements and creation races.
The migration keeps one installation per plugin ID, redirects or copies related records, and adds a partial unique index. Create stores the archive in the same transaction as the installation and capabilities, and maps a matching unique-index violation to ErrPluginAlreadyInstalled. The database contract test covers replacement and duplicate creation. Backup tests no longer include duplicate local installations.
Archive installation and replacement internal/plugins/installer.go, internal/plugins/installer_replace_test.go, cmd/silo/marker_plugin_migration_test.go, internal/plugins/installation_paths_test.go
Binary and archive installers include archive data when creating enabled installations. Archive files are extracted before the installation record is created. Tests and fixtures now supply or verify archive data during creation.
Service installation and race checks internal/plugins/service.go, internal/plugins/service_install_unique_db_test.go
Local and remote archive installs use a shared service path. Remote installs snapshot installations before downloading and use that snapshot to select an existing installation. Database tests cover replacement and a delayed install returning ErrInstallationChanged after a newer installation completes.
Creation-race handling and API descriptions internal/plugins/auto_update.go, internal/apiv2/admin_plugin_configuration.go, internal/apiv2/admin_plugin_lifecycle.go, internal/apiv2/admin_plugin_uploads.go, docs/admin-api.md, contracts/api/v2/openapi.json, web/src/api/v2/schema.ts
Automatic updates skip a plugin that was already installed. The admin API returns a conflict for duplicate creation, and API descriptions document the 409 race outcome for installs and uploads.
sequenceDiagram
participant PluginService
participant InstallationStore
participant ArchiveURL
participant Installer
participant PostgreSQL
PluginService->>InstallationStore: List installations before download
PluginService->>ArchiveURL: Download archive
ArchiveURL-->>PluginService: Return archive
PluginService->>PluginService: Validate archive and select from installation snapshot
PluginService->>Installer: Install archive when no snapshot match exists
Installer->>InstallationStore: Create installation with archive
InstallationStore->>PostgreSQL: Store installation, capabilities, and archive in one transaction
Loading
Merge Risk: Low · up to 82562
The change enforces one installation per plugin and handles install races. Two minor residual concerns remain: a brief window during migration where a connection could reference a removed duplicate installation, and a test that could hang until the runner timeout. Neither is likely to cause serious production impact, so the change is mergeable with owner awareness.
Security architecture risk: Moderate · up to 82562
The installation changes improve consistency, but duplicate cleanup can delete a working sign-in provider’s user identity links. Existing API credentials can then lose provider-based revocation, and rolling back the index does not restore those links.
Retained concerns
Medium · security · inferred: Automatic deduplication can remove the installation anchoring external-auth enforcement. An older settings-only installation can outrank a duplicate holding the active sign-in binding because both count as configured. Deleting the latter cascades through its external identities without preserving their enforcement role or revoking affected credentials. Users whose only identity is deleted can retain API keys and Audiobookshelf sessions that no longer receive provider-driven revocation. This is newly reachable through upgrade cleanup rather than an explicit uninstall, and the down migration cannot restore the deleted state.
Security review details
Security Blast Radius
inferred — The retained concern is limited to upgraded databases containing duplicates whose discarded installation owns external identities. Affected credentials retain their existing account authority; exploiting lost provider enforcement requires possession of an existing valid credential, not permission to install plugins.
Security Findings and Attack Paths
inferred — A settings-bearing older installation and an active sign-in installation can tie on configuration, archive presence, and enablement, causing the older row to win. Cleanup deletes the active provider’s identities. Because scheduled revocation starts from existing identity rows, a holder of an affected API key or Audiobookshelf session can retain access after a subsequent upstream disablement that previously would have been checked. Independent expiry, local account disablement, manual revocation, or another surviving identity can still constrain that access.
Trust Boundaries and Controls
observed — The inspected install and upload routes remain acting-admin operations. Their middleware chain requires authentication, viewer access, and acting-admin authorization. The routed TestPluginInstallKeepsOneInstallationPerPluginDB symbol is a database test using a local HTTP test server, not a newly exposed production endpoint.
Hardening Proposals
proposed — Before deleting an identity-bearing duplicate, require an explicit reconciliation policy that preserves provider enforcement or revokes affected credentials. Active sign-in authority should not lose solely to unrelated settings and age; ambiguous authentication ownership can instead require operator resolution before destructive cleanup.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title "fix(plugins): keep one installation per plugin" matches the main change. The changeset adds a unique partial index on plugin_installations for plugin-kind rows, routes installs through a si…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description is specific and on-topic. It explains the problem (duplicate plugin installation rows and resulting 500 errors), the approach (a unique index on plugin_id, a cleanup migration, one-tra…
Full details: Title check
Explanation
The title "fix(plugins): keep one installation per plugin" matches the main change. The changeset adds a unique partial index on plugin_installations for plugin-kind rows, routes installs through a single atomic Create path, maps lost races to 409, and cleans up duplicate rows in a migration. The title is short, specific, and uses a conventional commit prefix that names the affected area.
Full details: Description check
Explanation
The description is specific and on-topic. It explains the problem (duplicate plugin installation rows and resulting 500 errors), the approach (a unique index on plugin_id, a cleanup migration, one-transaction creates, 409 responses for losing creates, and InstallRemote for direct archive links), the validation performed, and the risks. Every section relates directly to the changeset.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Fix failing CI checks
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 01867db8-058d-44e7-ab98-c60c0ee1e508
Commits
Reviewing files that changed from the base of the PR and between 64d6716 and 8256221.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Deleting duplicate plugin_installations cascades pending plugin_event_deliveries rows, permanently discarding undelivered events. Reassign pending deliveries to the retained installation before deleting duplicates.
Prompt for LLM
File migrations/sql/20261118203050_unique_plugin_installation_per_plugin.sql, lines 39-41:
Duplicate cleanup discards pending plugin event deliveries
Deleting a duplicate cascades pending `plugin_event_deliveries` rows, permanently discarding events that have not yet been delivered to the plugin. Reassign pending deliveries to the retained installation before deleting the duplicate.
The reason will be displayed to describe this comment to others. Learn more.
Leaving this one as is. EventDeliveryStore.Enqueue writes one delivery per subscribing installation for each event, so the kept installation already has its own pending row for every event the duplicate was due. Moving the duplicate's rows onto it would deliver those events twice. The migration comment now says so.
The reason will be displayed to describe this comment to others. Learn more.
Leaving the migration as is may be reasonable, but the fact that Enqueue creates one delivery per subscribing installation does not by itself establish that the retained installation has a pending delivery for every event owed to the duplicate. The installations could have subscribed at different times, or their delivery statuses could differ.
Moving every row could indeed cause duplicate deliveries. Before relying on the migration comment, I’d verify those cases and clarify whether losing events pending only on the deleted installation is acceptable.
The reason will be displayed to describe this comment to others. Learn more.
Agreed that the kept row may not have a pending delivery for every event the duplicate was owed. A delivery row is deleted once it is delivered or given up (EventDeliveryStore.Delete), so a missing row on the kept installation can mean it already received the event, and moving the duplicate's row could deliver it twice. Dropping loses only events still pending for the deleted row, once, during this migration. I prefer that loss to a possible double delivery, such as a second scrobble. The migration comment now states that tradeoff (pushed with the next commit).
The reason will be displayed to describe this comment to others. Learn more.
That tradeoff is reasonable. Since a missing delivery row can mean the event was already delivered, blindly moving pending rows could cause duplicate side effects. Accepting a one-time loss of deliveries pending on deleted installations is a defensible choice.
I withdraw the recommendation to reassign the pending deliveries. The migration comment should make the potential loss clear to reviewers and operators.
The reason will be displayed to describe this comment to others. Learn more.
Duplicate cleanup discards resident plugin instance state
Deleting a duplicate cascades its plugin_instance_state, losing resident network providers' overlay node keys even when the retained installation has no corresponding state. Decrypt and re-encrypt nonconflicting state for the retained installation before deleting the duplicate.
Prompt for LLM
File migrations/sql/20261118203050_unique_plugin_installation_per_plugin.sql, lines 41-43:
Duplicate cleanup discards resident plugin instance state
Deleting a duplicate also cascades its `plugin_instance_state`, including resident network providers' overlay node keys, even when the retained installation has no corresponding state. Preserve nonconflicting state by decrypting and re-encrypting it for the retained installation before deleting the duplicate.
The reason will be displayed to describe this comment to others. Learn more.
Leaving this one as is. plugin_instance_state is encrypted with the installation id in its AAD (instanceStateAAD), so moving it to the kept row would mean a Go migration that decrypts and re-encrypts it, which is more than this cleanup should carry. The ranking keeps the row an admin configured first, and for a resident network provider that is normally the row whose plugin ran and wrote the state. When a dropped duplicate held the only state, the plugin starts without it, as after a fresh install; I haven't checked how each network provider recovers from that. The PR's Risks section lists the deleted rows' state as lost.
The reason will be displayed to describe this comment to others. Learn more.
Understood. Leaving the migration as is is a reasonable tradeoff given the installation-bound encryption and the recovery path you described.
The remaining risk is that a dropped duplicate may hold the only resident provider state, causing the node to register again on restart. The PR’s Risks section already discloses that the deleted rows’ state is lost.
This assertion accepts any error, including an unmapped PostgreSQL uniqueness error. That error would leave the API returning a server error and automatic installation reporting a failure.
Use errors.Is(err, ErrPluginAlreadyInstalled) here. The existing row and archive assertions can remain.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: a953caaa-b0e5-4477-95ce-2d3477b1b464
Commits
Reviewing files that changed from the base of the PR and between d4a2117 and 64d6716.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Lock the parent installation in the connection save transaction.
A connection save writes the submitted installation_id without checking the parent row. The migration deletes duplicate plugin_installations rows in its own transaction. Its EXCLUSIVE table lock does not block writes to request_integrations. A save that carries a duplicate ID can therefore commit after the redirect at lines 39-43. The connection then references a deleted installation.
Before writing installation_id, the save transaction must lock the parent row with FOR SHARE and reject the save with ErrInvalidInput when that row no longer exists. The plain update path must do the same. A plain read without a lock does not close this race.
The reason will be displayed to describe this comment to others. Learn more.
Leaving this out of this PR. During the migration the servers still saving connections run the previous release, so a parent-row check added to the save path here would not close this window; it only helps once every server runs the new code. Outside the migration the same gap is a connection save racing an ordinary uninstall, which exists on main and isn't changed by this PR. The connection then shows as not bound to an installation until it is saved again (routedServerProblem). That belongs in its own change to the requests save path.
#!/bin/bashset -u
if [ -f internal/requests/AGENTS.md ];then cat internal/requests/AGENTS.md;fiprintf'\n--- integration writes ---\n'
rg -n -C 4 'INSERT INTO request_integrations|UPDATE request_integrations|func .*Integration' internal/requests -g '*.go'| grep -E -C 5 'INSERT INTO request_integrations|UPDATE request_integrations|UpdateIntegration|SaveIntegration|CreateIntegration'| head -n 220
printf'\n--- routedServerProblem outline and source ---\n'
ast-grep outline internal/requests/routes_admin.go --match 'routedServerProblem'
cat -n internal/requests/routes_admin.go | sed -n '360,405p'printf'\n--- conditional save outline and source ---\n'
ast-grep outline internal/requests/editor_concurrency.go --items all --match 'Integration'
cat -n internal/requests/editor_concurrency.go | sed -n '80,135p'printf'\n--- request change status against base if available ---\n'
git diff --stat origin/main...HEAD -- internal/requests 2>/dev/null ||true
Length of output: 22123
@Quick104 You’re right. My proposed save-path lock would not protect the migration from writes by older servers.
The migration race remains possible, but I accept deferring the save-path change. I’m not marking the finding as addressed.
Learnings added
Learnt from: Quick104
Repo: Silo-Server/silo-server PR: 4525
File: migrations/sql/20261118203050_unique_plugin_installation_per_plugin.sql:39-43
Timestamp: 2026-11-18T21:46:08.501Z
Learning: Within repository "Silo-Server/silo-server", only for files matching one of ["migrations/sql/20261118203050_unique_plugin_installation_per_plugin.sql"]: For migrations/sql/20261118203050_unique_plugin_installation_per_plugin.sql, request_integrations.installation_id has no foreign key, and older servers can save connections while the migration redirects references and deletes duplicate installations. A parent-row check added only to the new server's save path cannot by itself protect this migration from older writers. Do not present that check as a complete fix for the migration race.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
A plugin could get a second plugin_installations row: installs chose between
creating and replacing by reading the table and then inserted without a lock,
and a direct archive_url install never looked for an existing row at all. Two
servers auto-installing a default plugin at startup, or an admin install racing
that, could both insert. Once two rows existed, every later install or update
of the plugin failed with a server error.
- A partial unique index on plugin_id (kind 'plugin') enforces one row per
plugin. Its migration first removes duplicates, keeping a row with a stored
package, then an enabled one, then the oldest.
- InstallationStore.Create writes the row, capabilities, signature and package
in one transaction, enabled, and answers ErrPluginAlreadyInstalled when
another install created the plugin first. The create paths extract files
before the row and no longer delete a row on a later failure.
- The admin API answers that with 409 conflict; the auto-install skips it.
- InstallRemote downloads the archive and replaces an installed plugin the
same way an upload does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
Deduplication can disable an active plugin
A disabled configured installation outranks an enabled unconfigured duplicate, so cleanup can leave an active plugin disabled after upgrade. Preserve i.enabled when consolidating duplicates, subject to the intended administrative policy.
Prompt for LLM
File migrations/sql/20261118203050_unique_plugin_installation_per_plugin.sql, lines 33-36:
Deduplication can disable an active plugin
A disabled configured installation outranks an enabled unconfigured duplicate, so cleanup deletes the running installation and leaves the plugin disabled after upgrade. Preserve the enabled state when consolidating duplicates, subject to the intended administrative policy.
The reason will be displayed to describe this comment to others. Learn more.
Leaving this as is. A configured row was set up by an admin, so its disabled state is an admin's choice, while an enabled duplicate with no configuration is usually the second automatic install from the startup race this PR fixes. Turning the kept row on whenever any duplicate was enabled would override that choice, and enabling is the riskier direction to guess in: a disabled plugin is one switch away from running again, and nothing runs that an admin turned off.
The reason will be displayed to describe this comment to others. Learn more.
That reasoning makes sense. Preserving the selected row’s disabled state avoids potentially running a plugin that an admin intentionally disabled. The tradeoff is that an enabled duplicate may be removed and the plugin may need to be re-enabled manually.
I agree with leaving the migration as is and withdrawing the suggestion.
A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
Security: Revoke every bearer for displaced auth users
Required condition: an upgrade has duplicate plugin rows where one external subject maps to different users and the displaced user still holds an ABS token or impersonation session. Fresh evidence after the prior fix is that this branch revokes only sessions whose user_id matches and deletes API keys. It leaves abs_sessions live and misses sessions where the user appears only as impersonator_user_id; the repository's account-wide revocation handles both. After identity deletion, provider rechecks cannot revoke these bearers. Revoke every sign-in type and both sides of impersonation before deleting the identity.
Useful? React with 👍 / 👎.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codeimpact: usabilityCore flow broken or severely blockedpriority: P1Core-path bug; painful workaround — next after P0size/L200–499 added + deleted lines (all files); change volume, not priority.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: changes #1224 C1; changes #1225 C1
Other clients: N/A (no client-visible change: plugin installation is a web admin feature, and the Apple, Android and Roku apps don't call the plugin install or upload endpoints)
A plugin could end up with two installation rows, and from then on every install or update of that plugin failed with a server error. Nothing in the database stopped it: installs read
plugin_installationsto decide between creating and replacing, then inserted without a lock. Two API servers auto-installing a default plugin at startup, or an admin install racing that auto-install, could both insert. An install from a directarchive_urlnever looked for an existing row at all, so installing an already-installed plugin that way always added a second one. Once two rows exist,existingInstallationByPluginIDrefuses with "multiple existing installations", which the API returns as a 500.This change enforces one installation per plugin in Postgres and cleans up deployments that already have duplicates.
Approach
plugin_idfor ordinary plugins (kind = 'plugin'; the builtin row keeps its own index). It first takes anEXCLUSIVElock on the table, so a server still on the previous release can't add a duplicate mid-migration; this mode also waits out row locks such as a settings save's, which would otherwise deadlock with the cleanup. It then deletes duplicates, keeping per plugin a row with an enabled sign-in binding, then one with linked sign-in identities, then one an admin configured (settings or a sign-in binding), then one with a stored package, then an enabled one, then the oldest. Request connections and linked sign-in identities on a deleted row move to the kept one, and the kept row takes any library chain placement, task binding or saved task schedule it lacks from the best-ranked duplicate, and a stored package from a duplicate of the same version. When a duplicate identity can't move because the kept row links the same subject, its same-user sessions and device approvals move to the kept identity, and for a different user every session is revoked, their API keys are deleted and device sign-ins approved for the identity are canceled, so that account signs in again. The deleted rows' settings, sign-in bindings, remaining chain entries and state go with them: settings are encrypted under the installation id, and a delivered event leaves no delivery row, so moving a pending delivery could deliver it to the kept row twice. Events still pending only for a deleted row are dropped.InstallationStore.Createnow writes the row, capabilities, signature and stored package in one transaction, with the row enabled. A create that hits the new index returnsErrPluginAlreadyInstalled. The create paths in the installer extract files before writing the row. They no longer save the package, enable the row, or delete it after a later failure as separate steps, so a concurrent replacement can no longer have its package overwritten or its row deleted by a create that started first.conflict, for installs and uploads. Both operations already declared 409 after fix(plugins): refuse a plugin update that another install overtook during its download #4509, and their summaries now mention this case. The default-plugin auto-install logs and skips it instead of recording a failure.Service.InstallRemotetakes the same create-or-replace decision as an upload, so a direct archive link for an installed plugin replaces it through fix(plugins): refuse a plugin update that another install overtook during its download #4509's guarded replacement path. Because the plugin is known only after the download, it reads the installations before downloading, asinstallCatalogdoes: another install of the plugin that lands during the download makes this one answer 409 instead of replacing the newer release.Validation
SHARE ROW EXCLUSIVElock and waited and finished withEXCLUSIVE.make test-go,go vet ./...,make lint-changed,go mod tidy -diff,make migrate-validate, and the generated-contract, route-inventory, size-ratchet, local-path and case-collision checks pass.make test-db-contracts: every listed test that ran passed. The 45 backup tests that needpg_dump/pg_restoreskipped on the build host;go test ./internal/backup/passed there against the branch's database.make lint-router-recoverywas not run (nogolangci-linton the build host; no router code changed).Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/plugin-unique-install/
Risks
plugin_installationswhile it runs; plain reads continue.Checklist
AI Disclosure
ArchiveInputandsaveArchive. Ahighcode review (three finders and a validation check) led to the admin-configuration ranking and the 409 wording in the operation summaries, and removed an interface method the installer no longer calls. A simplify pass changed nothing. Kody's review moved admin configuration ahead of the stored package in that ranking and added the request-connection, chain-placement and task-binding moves; Codex's reviews added the saved-schedule and sign-in identity moves and the sign-in ranking. The background adversarial review (gpt-6.2-sol, reviewed a1b9f75) found two problems, both fixed: the migration's lock mode could deadlock with a settings save from a server on the previous release, and a slow archive-link install could replace a newer install that landed during its download. It posted nothing because the head moved before it published.🤖 Generated with Claude Code
Note
Enforce one installation per plugin with unique index and
ErrPluginAlreadyInstalledplugin_idfor plugin-kind rows and a new sentinel errorErrPluginAlreadyInstalledreturned byInstallationStore.Createon a constraint violation, in installation.go and migrationInstaller.installBinaryandInstaller.installArchivenow store the archive and enabled state inside the creation transaction, removing separate save/enable/compensating-delete stepsService.InstallRemotesnapshots installed plugins before download, so a replacement overtaken during download is handled against the earlier installation state rather than blindly creating a new rowplugin_installationsduring consolidation, merging duplicates by enabled/sign-in binding priority and transferring integrations, identities, sessions, API keys, schedules, and archives to the kept row. Check duplicate-row handling carefully if you rely on multiple installations per plugin.Macroscope summarized d94f686.