PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
REFACTOR (docs): Archive completed OpenSpec changes
Rostislav Dugin9d763c9bd828
diff --git a/openspec/changes/allow-manual-verification-with-disabled-schedule/.openspec.yaml b/openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/.openspec.yamlsimilarity index 100%rename from openspec/changes/allow-manual-verification-with-disabled-schedule/.openspec.yamlrename to openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/.openspec.yamldiff --git a/openspec/changes/allow-manual-verification-with-disabled-schedule/design.md b/openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/design.mdsimilarity index 100%rename from openspec/changes/allow-manual-verification-with-disabled-schedule/design.mdrename to openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/design.mddiff --git a/openspec/changes/allow-manual-verification-with-disabled-schedule/proposal.md b/openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/proposal.mdsimilarity index 100%rename from openspec/changes/allow-manual-verification-with-disabled-schedule/proposal.mdrename to openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/proposal.mddiff --git a/openspec/changes/allow-manual-verification-with-disabled-schedule/specs/backup-verification/spec.md b/openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/specs/backup-verification/spec.mdsimilarity index 100%rename from openspec/changes/allow-manual-verification-with-disabled-schedule/specs/backup-verification/spec.mdrename to openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/specs/backup-verification/spec.mddiff --git a/openspec/changes/allow-manual-verification-with-disabled-schedule/tasks.md b/openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/tasks.mdsimilarity index 100%rename from openspec/changes/allow-manual-verification-with-disabled-schedule/tasks.mdrename to openspec/changes/archive/2026-09-06-allow-manual-verification-with-disabled-schedule/tasks.mddiff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/.openspec.yaml b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/.openspec.yamlnew file mode 100644index 00000000..1a62d62b--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/.openspec.yaml@@ -0,0 +1,2 @@+schema: spec-driven+created: 2026-09-06diff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/design.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/design.mdnew file mode 100644index 00000000..9b3158c8--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/design.md@@ -0,0 +1,126 @@+## Context++See `proposal.md` for the motivation and scope.++The cache package currently constructs a process-wide Valkey client from environment settings and exposes that client to callers (`backend/internal/util/cache/cache.go:13-48`). Its typed wrapper owns JSON serialization but also embeds the Valkey client and hides write and transport failures (`backend/internal/util/cache/utils.go:19-126`). Single-use restore tokens depend on atomic read-and-delete (`backend/internal/features/backups/backups/download/restore_token/store.go:40-61`), while the download lock currently performs a non-atomic read followed by a write (`backend/internal/features/backups/backups/download/stream_guard/tracker.go:34-45`).++Publish-subscribe code shares the cache package and contains a Valkey-specific readiness handshake (`backend/internal/util/cache/pubsub.go:18-200`). Its only production consumer is task cancellation (`backend/internal/features/tasks/cancellation/cancel_manager.go:13-68`). Rate limiting also shares the cache package and represents each attempt as a separate Valkey key before scanning the namespace (`backend/internal/util/cache/rate_limiter.go:12-82`).++Valkey is part of configuration validation, application startup, healthchecks, image construction, container startup, Compose and CI (`backend/internal/config/config.go:54-67`, `backend/internal/config/config.go:215-223`, `backend/cmd/main.go:92-100`, `backend/internal/features/system/healthcheck/service.go:31-44`, `Dockerfile:112-143`, `docker/start.sh:348-374`, `docker-compose.yml:60-73`, `.github/workflows/ci-release.yml:284-299`). The embedded server is capped at 256 MiB and uses all-keys LRU eviction (`docker/start.sh:350-356`).++The Helm chart defaults to one replica but currently exposes `replicaCount` and passes it directly to the StatefulSet (`deploy/helm/values.yaml:13-14`, `deploy/helm/templates/statefulset.yaml:10`). Local transient state is correct only when one application process owns an installation.++The approach is constrained by `AGENTS.md` naming, error-handling, no-shim, security and testing rules; `backend/AGENTS.md` file organization, dependency injection, controller-test, logging and concurrency rules; `website/AGENTS.md` six-language synchronization rules; and `adr/AGENTS.md` guidance to preserve historical decisions. The user's direction to update existing ADRs without creating a new ADR is part of this change's scope.++## Goals / Non-Goals++**Goals:**++- Give cache, publish-subscribe and rate limiting separate provider contracts that do not expose Valkey types.+- Make the default providers safe under concurrent access and test their contracts independently from feature tests.+- Preserve the existing TTLs, sliding-window thresholds, task-cancellation behavior and atomic single-use token consumption.+- Make stream-lock acquisition atomic instead of carrying the current read-then-write race into the local provider.+- Bound transient cache memory without evicting live locks or tokens.+- Make one application process an enforced property of supplied deployments.++**Non-Goals:**++- Coordinate state between application processes or Kubernetes replicas.+- Persist cache entries, subscriptions or counters across process restarts.+- Ship a Valkey adapter in this change.+- Preserve old environment variables, constructors, package aliases or the Helm replica setting.+- Change public HTTP payloads, rate-limit thresholds or backup formats.++## Decisions++### Keep three narrow provider contracts++`backend/internal/util/cache` will declare a byte-oriented `Store` contract and provide `MemoryStore`. A generic `JSONStore[T]` will own namespaces, JSON encoding and the default expiration used by typed callers. The package declaration will become `cache`; the existing `cache_utils` name and Valkey-based constructors will be deleted.++`backend/internal/util/pubsub` will declare a `Broker` contract and provide `LocalBroker`. Publications will use a named `Publication` value and subscriptions will accept a `MessageHandler`. `backend/internal/util/ratelimiter` will declare a `Counter` contract and provide `MemoryCounter`. Feature constructors will accept these contracts, while each package will expose one process-wide local provider through an explicit `Get...` accessor for composition roots.++The generic `TaskCancelManager` type will be deleted. Task cancellation will separate the local `Registry`, whose methods register, unregister and cancel registered tasks, from the `Requester`, which publishes cancellation requests and the `Listener`, which delivers subscribed requests to the registry. Variables and constructor fields will keep the full domain names, such as `taskCancellationRegistry`, so the short package-local type names do not hide their responsibility.++The rejected alternative is one broad transient-state interface. Cache storage, ordered message delivery and atomic request counting have different failure and concurrency rules, so a combined interface would expose unrelated methods to every caller. Keeping pub/sub and rate limiting inside `util/cache` was also rejected because it would preserve the current misplaced responsibilities.++### Use serialized values at the cache-provider boundary++`Store` operations will accept `context.Context` and return errors. Writes will use a named entry parameter containing the key, copied payload and positive lifetime. The contract will include get, set, create-if-absent, read-and-delete, delete and clear operations. `JSONStore[T]` will translate between typed values and bytes, accept custom lifetimes through a named `ExpiringValue[T]` parameter and return serialization or provider errors to its caller.++`MemoryStore` will copy byte slices on both write and read so callers cannot mutate shared memory outside the store lock. One mutex will make create-if-absent and read-and-delete indivisible. An injected time source will make expiration-boundary tests deterministic.++The rejected alternative is storing arbitrary Go values directly. That would share mutable pointers across goroutines and would make a later remote adapter behave differently. Preserving the current methods that swallow errors was rejected because security-sensitive callers must distinguish a missing value from a failed operation and a future remote provider can fail even when the local provider normally cannot.++### Reject writes at the cache budget instead of evicting live entries++The production `MemoryStore` will use a 256 MiB payload budget, matching the current embedded Valkey ceiling. Accounting will cover stored keys and serialized values; it will not claim to reproduce allocator overhead. Reads will remove an expired requested entry. Writes will sweep expired entries before checking the budget. If the new value still does not fit, the write will return a capacity error and leave all live entries unchanged.++No cleanup goroutine is needed. Lazy expiration plus a full expired-entry sweep only when capacity is needed keeps idle behavior simple, avoids lifecycle leaks in tests and keeps memory bounded.++The rejected alternative is LRU eviction, including the current Valkey policy. A cache miss is acceptable for derived data, but silently evicting a live stream lock could admit a second stream. An unbounded map was rejected because attacker-controlled identifiers and issued tokens could grow process memory. A third-party local-cache library was rejected because the required atomic and no-live-eviction contract is small enough to implement and test without another dependency.++### Let each cache consumer choose fail-open or fail-closed behavior++Derived restore metadata may log a provider error and use the original request configuration carried into the detached restore worker. Restore-token issuance and consumption, stream-lock acquisition and rate-limit evaluation will propagate errors because treating those failures as cache misses can weaken single-use, exclusivity or request-limit guarantees. The stream guard will use create-if-absent for lock acquisition and will keep its existing heartbeat TTL behavior.++The rejected alternative is one package-wide fallback policy. The cache package cannot know whether an entry is an optimization or an authorization and concurrency guard.++### Deliver local pub/sub messages through registered subscription loops++`LocalBroker` will register a subscription before `Subscribe` returns. Each subscription will own an unbuffered mailbox and a loop that invokes its handler sequentially. Publishing will reserve matching subscriptions while holding the broker map lock, then submit the message to each mailbox while selecting on the publication context. Closing or canceling a subscription will remove it from later snapshots and drain publications already reserved for it before stopping. Close operations will return after recording closure so handlers can close their own subscription or broker without waiting on their delivery loop. A per-channel publication lock will preserve order when publishers overlap. A successful publish means every subscription active at the snapshot accepted one copy; it does not require every handler to finish.++Handler panics will be recovered at the subscription boundary so one consumer cannot terminate the process or another subscription. Canceling the subscription context, closing the subscription or closing the broker will stop later delivery. The task-cancellation requester and listener will receive `pubsub.Broker` through their constructors and retain the existing setup hook, but the Valkey readiness markers and sleeps in cancellation tests will disappear.++The rejected alternative is calling handlers synchronously inside `Publish`, because a handler cannot then be interrupted through the publication context. Starting one goroutine per message was rejected because it gives no backpressure and can reorder messages. Buffered mailboxes with silent overflow were rejected because dropping a task-cancellation message would report success without canceling the task.++### Implement rate limiting as a domain provider over the local cache++`ratelimiter.Counter` will accept a named request containing scope, identifier, maximum attempts and window duration. Its operation will be named to state both effects: it records the attempt and reports whether the request is allowed. `MemoryCounter` will use a private `JSONStore` namespace and one mutex around read, prune, append, cap and write. It will keep at most `limit + 1` recent timestamps per scope and identifier. Older timestamps cannot change an allowed result once the newest `limit + 1` attempts are still in the window.++Using the cache gives rate-limit entries the same TTL cleanup and memory budget without adding cache-specific operations to the public rate-limiter contract. If the cache cannot record the attempt, protected endpoints will fail closed and log the error without logging the identifier when it contains user data.++The rejected alternative is exposing an atomic mutation callback on `cache.Store`; a remote provider cannot execute an arbitrary Go callback atomically. A separate unbounded map was rejected because it would duplicate expiration and memory accounting. Fixed windows and token buckets were rejected because they change the current sliding-window boundary behavior. A future Valkey-backed `Counter` can implement the same contract with a server-side atomic operation without using `cache.Store`.++### Test contracts and local concurrency separately++Each utility package will have a contract test suite parameterized by a provider factory. The local provider will run through that suite and a future Valkey provider can run the same cases. Local implementation tests will use a controllable time source for exact expiration boundaries. Concurrency tests will cover one-winner cache consume and reserve operations, one remaining rate-limit allowance, ordered pub/sub delivery, cancellation, close behavior and handler panic isolation.++Feature tests will keep coverage at the observable boundary. Task-cancellation tests will create separate `Registry`, `Requester` and `Listener` instances that share one local broker and will use channels or contexts instead of sleeps. Existing user-controller rate-limit tests will verify fail-closed error handling and download and restore tests will cover atomic lock and token behavior. Focused packages will run with the Go race detector before the full backend suite.++The rejected alternative is testing only concrete maps. Those tests would not define the behavior a future provider must preserve. Keeping timing sleeps was rejected because it hides registration races and makes failures depend on machine load.++### Remove Valkey from runtime and test orchestration++The backend will remove Valkey configuration fields, validation, logical database selection, test cache namespaces, startup connection checks and external cache cleanup. Test worker slots will continue isolating PostgreSQL metadata databases, while each Go test binary will naturally own separate local transient state.++The runtime image will remove the Valkey repository and package. Container startup will proceed from storage validation to PostgreSQL bootstrap without starting a cache server. Compose and CI will remove the Valkey service and readiness wait. The deep healthcheck will stop probing an external cache connection because the local providers have no network dependency. The filesystem suite will assert that only the application and PostgreSQL run under the selected account.++The rejected alternative is leaving an unused Valkey service available for rollback. That keeps the image, CVE surface, startup dependency and configuration that this change removes. Rollback uses an earlier image that still contains its own required service.++### Enforce one replica and update current architecture notes++The Helm StatefulSet will render one replica directly. The chart will delete `replicaCount` from values and documentation rather than accepting an unsupported topology. Docker already starts one application process per container, so no new Docker setting is needed.++ADR-0006 will receive a dated note that its Valkey-based multi-node coordination is historical and that current installations use process-local providers. ADR-0013 will receive a dated note that test binaries now isolate local cache, pub/sub and rate-limit state by process, while worker slots remain responsible for metadata-database isolation. Their original decision bodies will remain unchanged and no new ADR will be created. This is an explicit user-directed exception to the default `adr/AGENTS.md` guidance to record a replacement decision in a new ADR with supersession markers.++The rejected alternative is documenting `replicaCount: 1` as a recommendation while leaving higher values valid. That permits a deployment whose cancellation messages and rate limits diverge between pods. Rewriting the ADR bodies was rejected because they record the reasoning that applied when those decisions were made.++## Risks / Trade-offs++- [A manually assembled multi-process deployment has divergent transient state] -> State the single-process contract, hard-code one Helm replica and remove supported configuration that suggests otherwise.+- [The cache reaches its payload budget] -> Reclaim expired entries, reject the new write without evicting live entries, log capacity failures and fail closed for tokens, locks and rate limits.+- [A slow pub/sub subscriber delays publication] -> Keep explicit backpressure, honor publication cancellation while submitting and keep current handlers small. A future heavy consumer must hand work to its own bounded queue.+- [Concurrent access introduces races or mutable aliases] -> Serialize state changes under package-owned locks, copy cache payloads and run focused tests with `-race`.+- [Removing the external health probe hides transient-state failure] -> Cover provider construction and contracts in process; retain deep checks for disk, tools, PostgreSQL, schedulers and verification agents.+- [Operators keep deleted Valkey or Helm values] -> Document the breaking removals. Unknown old environment values are unused and the old Helm replica value no longer changes rendered topology.+- [Rollback restores the old runtime dependency] -> Roll back with the earlier image and chart, which contain their own Valkey package and startup logic. No transient data migration is required because the production Valkey configuration disables persistence.++## Migration Plan++1. Add the three provider contracts, local implementations, contract tests and deterministic concurrency tests.+2. Move callers to the new constructors and error contracts, including atomic stream locks and fail-closed rate-limit errors.+3. Remove Valkey configuration, dependencies, healthchecks, startup code, test cleanup, Compose service and CI wait.+4. Enforce one Helm replica, update container tests, Helm documentation, all six Advanced Config pages, current OpenSpec contracts and the two relevant ADR notes.+5. Run focused race tests, the full backend suite and linter, website lint and build, strict OpenSpec validation and the Docker filesystem suite.++Deployment requires no stored-data migration. Existing cache entries, rate-limit attempts, subscriptions, locks and tokens are transient and start empty with the new process.diff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/proposal.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/proposal.mdnew file mode 100644index 00000000..003e77e0--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/proposal.md@@ -0,0 +1,38 @@+## Why++Databasus supports one application process per installation, but its transient cache, rate limiting and task-cancellation messaging still require a separate Valkey process. This adds configuration, image size, startup failure modes and test infrastructure without providing useful cross-instance coordination.++## What Changes++- Replace the Valkey-backed cache with a bounded, process-local cache behind a provider interface. Preserve expiration, invalidation, atomic consume and atomic reservation semantics.+- Move publish-subscribe behavior into a dedicated local package with its own provider interface and contract tests.+- Move rate limiting into a dedicated local package with its own provider interface, sliding-window behavior and contract tests. Feature callers no longer express limits as generic cache keys; the local implementation may privately use the typed cache provider for bounded storage and expiration.+- Keep cache, publish-subscribe and rate-limiting callers independent of their local implementations so a distributed provider can be added later without changing feature code.+- Remove the Valkey server, client dependency, health probe, environment configuration, startup orchestration, test cleanup and CI service.+- Make the supplied deployments run exactly one application process so local transient state cannot diverge between replicas.+- Update container tests and Helm documentation. Update all six Advanced Config pages to describe the single-process runtime. The English page will say `Databasus and PostgreSQL use the same non-root operating-system account named <code>databasus</code>.` English copy added or revised by this change will not use Oxford commas.+- Add short notes to relevant existing ADRs that Valkey-backed runtime state was replaced by local cache, publish-subscribe and rate-limiting providers. Preserve the original decisions as historical context.+- **BREAKING**: delete `VALKEY_HOST`, `VALKEY_PORT`, `VALKEY_USERNAME`, `VALKEY_PASSWORD` and `VALKEY_IS_SSL`. External Valkey connections and the old client-facing cache constructors are removed without aliases or fallback handling.+- **BREAKING**: delete the Helm `replicaCount` setting and render one application replica. Multi-replica installations are no longer representable by the supplied chart.++## Capabilities++### New Capabilities++- `local-cache`: Define the bounded, concurrent, process-local cache contract, including expiration and atomic operations used for locks and single-use values.+- `local-publish-subscribe`: Define process-local publication, subscription readiness, delivery, cancellation and failure isolation.+- `local-rate-limiting`: Define concurrent sliding-window request limits with deterministic expiration and independent caller scopes.+- `single-instance-runtime`: Define one application process as the supported installation topology for supplied deployment artifacts.++### Modified Capabilities++- `docker-storage-compatibility`: Remove Valkey from the bundled runtime services and from startup ordering and identity checks.+- `internal-postgresql-protection`: Describe PostgreSQL as the only embedded server and remove the obsolete Valkey port requirement.++## Impact++The change affects the backend cache and its callers, task cancellation, authentication and verification-agent rate limiting, backend configuration and dependencies, the main command, test database cleanup, Docker image construction and startup, Compose development services, release CI, Docker filesystem tests, Helm documentation, current OpenSpec contracts, ADRs and all six website Advanced Config translations.++The change answers to `AGENTS.md`, `backend/AGENTS.md`, `website/AGENTS.md` and `adr/AGENTS.md`.++Out of scope: support for multiple application processes or replicas in one installation, persistence of transient state across restarts, implementing a Valkey adapter, compatibility shims for deleted environment variables, constructors or Helm settings, changes to public HTTP APIs or configured rate-limit thresholds, creating a new ADR and rewriting historical OpenSpec archives or ADR decision bodies. Updating the two existing ADRs instead of creating a replacement ADR is an explicit scope decision for this change.diff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/docker-storage-compatibility/spec.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/docker-storage-compatibility/spec.mdnew file mode 100644index 00000000..8986f643--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/docker-storage-compatibility/spec.md@@ -0,0 +1,72 @@+## MODIFIED Requirements++### Requirement: Docker services share one configurable runtime identity++The Docker image SHALL run Databasus and embedded PostgreSQL under one non-root operating-system account named `databasus`. Operators MAY set its numeric identity with `PUID` and `PGID`. Each supplied value SHALL be a non-zero decimal Linux ID within the supported system range.++When an override is absent, startup SHALL select that ID independently from the existing PostgreSQL data owner, then the mounted backup or data-root owner and finally `999`. Root ownership SHALL NOT be selected automatically.++#### Scenario: Fresh installation uses the fallback identity++- **WHEN** an operator starts the image without identity overrides or existing non-root ownership+- **THEN** all bundled services run as user ID `999` and group ID `999` under the account name `databasus`++#### Scenario: Existing data determines the identity++- **WHEN** an existing PostgreSQL data directory has a non-root numeric owner and `PUID` or `PGID` is absent+- **THEN** startup uses the corresponding owner ID before considering other mounts or the fallback++#### Scenario: Operator supplies identity overrides++- **WHEN** an operator supplies valid `PUID` and `PGID` values+- **THEN** all bundled services run with those numeric IDs++#### Scenario: Operator overrides one identity value++- **WHEN** an operator supplies either `PUID` or `PGID` and mounted data provides the other numeric ID+- **THEN** startup combines the explicit value with the automatically selected counterpart++#### Scenario: Operator supplies an invalid identity++- **WHEN** `PUID` or `PGID` is empty, non-numeric, zero or outside the supported range+- **THEN** the container exits before starting its services+- **AND** the log identifies the invalid variable++### Requirement: Startup validates storage through required operations++Startup SHALL attempt to prepare the data root, PostgreSQL data, PostgreSQL socket, temporary and backup paths with the selected identity and required modes. A failed ownership or mode change SHALL NOT stop startup when the selected account can still perform every required operation.++Startup SHALL run the main Databasus binary with `--test-storage` under the selected account before starting PostgreSQL or the Databasus application. The storage probe SHALL save a unique file through the configured local storage and remove that file through the same storage path. Startup SHALL also verify the operations required for PostgreSQL data, its socket and Databasus control files. A failed check SHALL stop startup before PostgreSQL or the Databasus application runs. Startup SHALL NOT start or wait for a separate cache service.++#### Scenario: Filesystem denies metadata changes but permits operations++- **WHEN** a mounted filesystem rejects ownership or mode changes but the selected account can perform all required operations+- **THEN** the container starts successfully++#### Scenario: Selected identity creates missing service directories++- **WHEN** container root cannot create a required directory but the selected account can create it+- **THEN** startup creates the directory as the selected account and continues++#### Scenario: Backup publication is not permitted++- **WHEN** the selected account cannot publish a file from the temporary path to the backup path+- **THEN** the container exits before starting the application+- **AND** the English error names the affected path, required operation, effective user and group IDs and `https://databasus.com/advanced-config/#docker-storage-permissions`++#### Scenario: Mounted path is read-only++- **WHEN** any required mounted path is read-only+- **THEN** the container exits before starting PostgreSQL or the Databasus application+- **AND** the log provides the same identity and documentation details++#### Scenario: Data root cannot create control files++- **WHEN** temporary, backup, PostgreSQL data and socket paths are writable but the data root cannot create a control file+- **THEN** the container exits before starting PostgreSQL or the Databasus application+- **AND** the English error identifies the data root and required operation++#### Scenario: Container starts its bundled services++- **WHEN** storage validation succeeds+- **THEN** startup proceeds directly to embedded PostgreSQL and the Databasus application without a cache-service readiness stepdiff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/internal-postgresql-protection/spec.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/internal-postgresql-protection/spec.mdnew file mode 100644index 00000000..07e8d2f2--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/internal-postgresql-protection/spec.md@@ -0,0 +1,32 @@+## MODIFIED Requirements++### Requirement: The embedded PostgreSQL instance stays private under the shared runtime account++The embedded PostgreSQL server SHALL run under the same non-root operating-system account as the Databasus application. During bootstrap only, peer mapping SHALL allow that account to administer the PostgreSQL role named `postgres`. After bootstrap, Unix-socket database login SHALL be rejected. Loopback TCP connections SHALL require SCRAM authentication with the generated credential and replication connections to the embedded cluster SHALL be rejected.++The embedded PostgreSQL port SHALL remain unpublished by the image.++#### Scenario: Application account opens the private socket++- **WHEN** the Databasus application account attempts a Unix-socket database login after bootstrap+- **THEN** PostgreSQL authentication rejects the connection++#### Scenario: Shared runtime account performs startup administration++- **WHEN** the shared `databasus` operating-system account connects as role `postgres` during startup+- **THEN** the temporary peer mapping permits the administrative connection++#### Scenario: Loopback TCP connection without the generated password++- **WHEN** any process connects to the embedded PostgreSQL server over loopback TCP without the current generated password+- **THEN** SCRAM authentication rejects the connection++#### Scenario: Application uses the generated password++- **WHEN** Databasus connects to the embedded PostgreSQL server over loopback with the generated password+- **THEN** PostgreSQL accepts the connection++#### Scenario: Replication connection to the embedded cluster++- **WHEN** a client requests a replication connection to the embedded PostgreSQL server+- **THEN** PostgreSQL rejects itdiff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-cache/spec.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-cache/spec.mdnew file mode 100644index 00000000..bdcb3a0c--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-cache/spec.md@@ -0,0 +1,115 @@+## Purpose++Defines the transient key-value behavior that cache consumers can rely on when Databasus runs as one application process.++## ADDED Requirements++### Requirement: Cache state is process-local and volatile++The cache SHALL keep entries inside the running application process. A new process SHALL start with an empty cache and SHALL NOT require a remote cache service.++#### Scenario: Application restarts++- **WHEN** the application process stops and starts again+- **THEN** entries created by the previous process are absent++#### Scenario: Application starts without a cache service++- **WHEN** an operator starts Databasus without a remote cache endpoint+- **THEN** cache-backed features remain available++### Requirement: Namespaced entries expire and can be invalidated++Each cache entry SHALL belong to a caller-selected namespace and SHALL have a positive lifetime. A read before expiration SHALL return the stored value. A read at or after expiration SHALL report a miss and make the expired entry eligible for reclamation. Callers SHALL be able to delete one entry or clear all entries owned by the process.++#### Scenario: Entry is read before expiration++- **WHEN** a caller reads a stored entry before its lifetime ends+- **THEN** the cache returns the stored value++#### Scenario: Entry reaches its expiration time++- **WHEN** a caller reads an entry at or after its expiration time+- **THEN** the cache reports a miss++#### Scenario: Namespaces use the same key++- **WHEN** two callers store different values under the same key in different namespaces+- **THEN** each caller reads the value from its own namespace++#### Scenario: Entry is invalidated++- **WHEN** a caller invalidates a stored entry+- **THEN** subsequent reads report a miss++### Requirement: Conditional storage operations are atomic++The cache SHALL provide atomic read-and-delete and create-if-absent operations. Expired entries SHALL be treated as absent by both operations.++#### Scenario: Concurrent callers consume one value++- **WHEN** multiple callers concurrently read and delete the same live entry+- **THEN** exactly one caller receives the value+- **AND** every other caller receives a miss++#### Scenario: Concurrent callers reserve one key++- **WHEN** multiple callers concurrently create the same absent key+- **THEN** exactly one caller stores its value+- **AND** every other caller is told that a live entry already exists++#### Scenario: Caller reserves an expired key++- **WHEN** a caller conditionally creates a key whose previous entry has expired+- **THEN** the new value is stored++### Requirement: Cache memory is bounded without evicting live entries++The cache SHALL enforce its configured payload budget. Before rejecting a write, it SHALL reclaim expired entries. It SHALL NOT evict an unexpired entry to admit another value.++#### Scenario: Expired entries occupy the available budget++- **WHEN** a write needs space held by expired entries+- **THEN** the cache reclaims those entries and admits the write++#### Scenario: Live entries occupy the available budget++- **WHEN** a write would exceed the budget after expired entries are reclaimed+- **THEN** the write fails+- **AND** every unexpired entry remains available++#### Scenario: One value exceeds the budget++- **WHEN** a caller tries to store a value larger than the entire cache budget+- **THEN** the write fails without changing existing entries++### Requirement: Concurrent cache access preserves the contract++Cache operations SHALL remain safe when called concurrently. A failed or canceled operation SHALL NOT leave a partially written value.++#### Scenario: Reads and writes overlap++- **WHEN** callers read, write, invalidate, reserve and consume entries concurrently+- **THEN** every completed operation has the same result as one valid serial ordering+- **AND** no caller observes a partial value++### Requirement: Security-sensitive cache failures stop protected operations++Restore-token issuance and consumption and stream-lock acquisition SHALL fail closed when their required cache operation fails. A cache failure SHALL NOT be interpreted as an absent token or an available stream lock.++#### Scenario: Restore-token issuance cannot store the token++- **WHEN** the cache rejects or fails the write required to issue a restore token+- **THEN** token issuance returns an error without returning a usable token++#### Scenario: Restore-token consumption cannot read and delete the token++- **WHEN** the cache cannot atomically read and delete a submitted restore token+- **THEN** token consumption returns an error+- **AND** the restore operation does not start++#### Scenario: Stream-lock acquisition cannot reserve the lock++- **WHEN** the cache cannot atomically reserve the required stream lock+- **THEN** lock acquisition returns an error+- **AND** the download or restore stream does not startdiff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-publish-subscribe/spec.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-publish-subscribe/spec.mdnew file mode 100644index 00000000..41d8ed9e--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-publish-subscribe/spec.md@@ -0,0 +1,72 @@+## Purpose++Defines reliable process-local message delivery for features that coordinate work inside the single Databasus application process.++## ADDED Requirements++### Requirement: Publications stay inside the application process++The publish-subscribe provider SHALL deliver messages only to active subscriptions in the same application process. It SHALL NOT persist messages or replay publications made before a subscription became active.++#### Scenario: Message is published before subscription++- **WHEN** a message is published before a matching subscription becomes active+- **THEN** the later subscription does not receive that message++#### Scenario: Another process uses the same channel++- **WHEN** separate application processes use the same channel name+- **THEN** neither process receives the other process's publications++### Requirement: Subscription registration has no readiness race++Subscription creation SHALL return only after the subscription can accept publications. Canceling its context or closing the subscription SHALL prevent delivery of later publications.++#### Scenario: Publish follows subscription immediately++- **WHEN** a caller publishes immediately after subscription creation returns+- **THEN** the new subscription accepts the message without an additional readiness delay++#### Scenario: Subscription is canceled++- **WHEN** a subscription's context is canceled before a later publication+- **THEN** the canceled subscription does not receive that publication++### Requirement: Successful publication does not silently drop messages++A successful publication SHALL submit one copy of the message to every matching subscription that was active when publication began. Messages submitted to one subscription SHALL preserve publication order. If the publication context ends before all active subscriptions accept the message, the operation SHALL return an error instead of reporting success.++#### Scenario: Channel has multiple subscribers++- **WHEN** a caller successfully publishes to a channel with multiple active subscriptions+- **THEN** each subscription receives one copy of the message++#### Scenario: Subscriber receives consecutive publications++- **WHEN** a caller successfully publishes two messages to the same channel in sequence+- **THEN** each active subscription receives them in the same order++#### Scenario: Publication is canceled during delivery++- **WHEN** the publication context ends before every active subscription accepts the message+- **THEN** the publication returns an error++### Requirement: Subscriber failures are isolated++A subscriber failure SHALL NOT stop other subscriptions, corrupt broker state or crash the application process.++#### Scenario: Message handler panics++- **WHEN** one subscription handler panics while processing a message+- **THEN** other active subscriptions can continue receiving messages+- **AND** later publications can still use the broker++### Requirement: Broker shutdown releases subscriptions++Closing the publish-subscribe provider SHALL stop its subscriptions and reject later publications. Repeated close operations SHALL be safe.++#### Scenario: Provider closes++- **WHEN** the provider is closed while subscriptions are active+- **THEN** those subscriptions stop+- **AND** a later publication returns an errordiff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-rate-limiting/spec.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-rate-limiting/spec.mdnew file mode 100644index 00000000..ddadd1f4--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/local-rate-limiting/spec.md@@ -0,0 +1,83 @@+## Purpose++Defines process-local request limiting that protects authentication and verification endpoints without relying on a separate data service.++## ADDED Requirements++### Requirement: Rate limits use a sliding time window++The rate limiter SHALL record every request attempt for a caller-selected scope and identifier. It SHALL allow no more than the configured number of attempts whose timestamps fall inside the current window. Rejected attempts SHALL also count until they leave that window.++#### Scenario: Attempts remain below the limit++- **WHEN** an identifier makes no more than the configured number of attempts inside the window+- **THEN** every attempt is allowed++#### Scenario: Attempt exceeds the limit++- **WHEN** an identifier makes another attempt while the configured number of earlier attempts remains inside the window+- **THEN** the new attempt is rejected++#### Scenario: Old attempts leave the window++- **WHEN** enough recorded attempts reach the window boundary+- **THEN** those attempts stop contributing to the limit+- **AND** a later request is evaluated against only the remaining attempts++### Requirement: Limit scopes are independent++The rate limiter SHALL keep counts independent for each scope and identifier pair.++#### Scenario: One identifier uses two scopes++- **WHEN** the same identifier reaches the limit in one scope+- **THEN** attempts in another scope retain their own allowance++#### Scenario: Two identifiers use one scope++- **WHEN** one identifier reaches the limit in a scope+- **THEN** another identifier retains its own allowance in that scope++### Requirement: Concurrent attempts cannot exceed the allowance++Recording an attempt and deciding whether it is allowed SHALL be one atomic operation.++#### Scenario: Concurrent attempts meet one remaining allowance++- **WHEN** multiple attempts arrive concurrently and only one allowance remains+- **THEN** exactly one attempt is allowed++### Requirement: Rate-limit state is process-local and reclaimable++Rate-limit counters SHALL remain inside the running application process, start empty after restart and release state after its final recorded attempt leaves the window.++#### Scenario: Application restarts++- **WHEN** the application process restarts+- **THEN** previous rate-limit attempts no longer affect new requests++#### Scenario: Identifier becomes inactive++- **WHEN** every recorded attempt for an identifier has left the window+- **THEN** the limiter can reclaim that identifier's state++### Requirement: Invalid rate-limit settings fail explicitly++The rate limiter SHALL reject a non-positive request limit or a non-positive window without recording an attempt.++#### Scenario: Caller supplies an invalid limit++- **WHEN** a caller supplies a zero or negative request limit or window+- **THEN** the operation returns an error+- **AND** existing counters remain unchanged++### Requirement: Protected endpoints fail closed when a limit cannot be evaluated++An endpoint protected by rate limiting SHALL reject the request when the limiter cannot atomically record and evaluate the attempt. It SHALL NOT treat a limiter error as an allowed request. The endpoint SHALL log the limiter failure without including the caller identifier or other user-derived rate-limit key material.++#### Scenario: Limiter cannot record an attempt++- **WHEN** a protected endpoint receives an error from the rate limiter+- **THEN** the endpoint rejects the request+- **AND** the request does not proceed to the protected operation+- **AND** the failure is logged without the caller identifier or user-derived rate-limit key materialdiff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/single-instance-runtime/spec.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/single-instance-runtime/spec.mdnew file mode 100644index 00000000..13e27e31--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/specs/single-instance-runtime/spec.md@@ -0,0 +1,29 @@+## Purpose++Defines one application process as the supported installation topology so transient coordination remains consistent without a shared service.++## ADDED Requirements++### Requirement: Supplied deployments run one application process++Databasus installation artifacts SHALL start exactly one application process for each installation. They SHALL NOT expose a setting that increases the application replica count.++#### Scenario: Operator deploys the Helm chart++- **WHEN** an operator renders or installs the supplied Helm chart+- **THEN** the resulting workload contains exactly one application replica++#### Scenario: Operator uses the Docker image++- **WHEN** an operator starts one instance of the supplied Docker image+- **THEN** that instance runs exactly one Databasus application process++### Requirement: One process owns transient runtime state++The single application process SHALL own cache entries, publish-subscribe subscriptions and rate-limit counters for its installation. The supplied deployment SHALL NOT require another service to share that state.++#### Scenario: Installation starts normally++- **WHEN** the application process starts+- **THEN** its transient runtime providers are available inside that process+- **AND** startup does not wait for a shared transient-state servicediff --git a/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/tasks.md b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/tasks.mdnew file mode 100644index 00000000..3850b4a1--- /dev/null+++ b/openspec/changes/archive/2026-09-06-replace-valkey-with-local-runtime/tasks.md@@ -0,0 +1,40 @@+## 1. Planning checkpoint++- [x] 1.1 Run the mandatory plan reviewer against `proposal.md`, `design.md`, all delta specs, `AGENTS.md`, `backend/AGENTS.md`, `website/AGENTS.md` and `adr/AGENTS.md`; resolve every `CHANGES REQUIRED` finding before editing implementation files++## 2. Local cache++- [x] 2.1 Replace the Valkey client in `backend/internal/util/cache` with the `Store` contract and bounded `MemoryStore`; verify expiration, copied payloads, clear, capacity rejection, canceled operations and concurrent create-if-absent and read-and-delete through `go test -race ./internal/util/cache`+- [x] 2.2 Add the namespaced `JSONStore[T]` wrapper with explicit serialization and provider errors; verify its default and custom TTL, namespace isolation, malformed payload and error cases through `go test -race ./internal/util/cache`+- [x] 2.3 Move restore metadata, restore tokens and stream locks to the new cache contract, make lock acquisition atomic and verify fail-open metadata reload plus fail-closed token and lock behavior through `go test -race ./internal/features/backups/backups/download/... ./internal/features/restores/...`++## 3. Local publish-subscribe++- [x] 3.1 Create `backend/internal/util/pubsub` with the `Broker` contract and `LocalBroker`; verify immediate subscription readiness, fan-out, ordering, cancellation, publication errors, idempotent close and panic isolation through `go test -race ./internal/util/pubsub`+- [x] 3.2 Split the generic task-cancellation manager into its registration, request and listener responsibilities, inject `pubsub.Broker`, delete the Valkey-specific readiness handshake and replace timing sleeps with synchronization; verify two cancellation components sharing one broker through `go test -race ./internal/features/tasks/cancellation`++## 4. Local rate limiting++- [x] 4.1 Create `backend/internal/util/ratelimiter` with the `Counter` contract and cache-backed `MemoryCounter`; verify sliding-window boundaries, independent scopes, rejected-attempt accounting, invalid settings, expiration and one remaining concurrent allowance through `go test -race ./internal/util/ratelimiter`+- [x] 4.2 Inject `ratelimiter.Counter` into user and verification-agent request handling, propagate limiter failures as rejected requests without logging user identifiers and verify the behavior through `go test -race ./internal/features/users/controllers ./internal/features/verification/agents`++## 5. Remove Valkey infrastructure++- [x] 5.1 Delete Valkey fields and examples from `backend/internal/config`, `.env.example` and `.gitignore`; remove logical database selection, test cache namespaces, startup checks, healthcheck probes and external test cleanup while retaining PostgreSQL worker-slot isolation; verify the affected packages through `go test -race ./internal/config ./internal/features/system/healthcheck ./internal/util/testing/...`+- [x] 5.2 Remove `github.com/valkey-io/valkey-go`, run `go mod tidy` and verify active backend code has no Valkey or Redis imports or client types+- [x] 5.3 Remove the Valkey package repository and binary from `Dockerfile`, remove its startup function from `docker/start.sh` and remove the Compose service, CI readiness wait and remaining Valkey comments from `.github/workflows/ci-release.yml`; verify with `docker run --rm -v "$PWD:/mnt" koalaman/shellcheck:v0.10.0 docker/start.sh e2e/docker-storage/run.sh` and `docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.7 -color`+- [x] 5.4 Update the Docker filesystem suite to expect only Databasus and PostgreSQL processes and no cache readiness stage; build the candidate image and verify `make test-filesystems` passes++## 6. Single-instance deployment and documentation++- [x] 6.1 Delete the Helm `replicaCount` value and documentation, remove Valkey references from `deploy/helm/values.yaml` and `deploy/helm/README.md` and render one StatefulSet replica directly; run `docker run --rm -v "$PWD:/repo" -w /repo alpine/helm:3.18.6 lint deploy/helm` and verify the output of `docker run --rm -v "$PWD:/repo" -w /repo alpine/helm:3.18.6 template databasus deploy/helm` contains exactly one application replica and no supported replica-count override+- [x] 6.2 In the English Advanced Config page, replace `Databasus, PostgreSQL, and Valkey use the same non-root operating-system account named <code>databasus</code>.` with `Databasus and PostgreSQL use the same non-root operating-system account named <code>databasus</code>.` Remove Valkey from the corresponding sentence in all five translated copies. Keep English copy free of Oxford commas. Verify `npm run lint` and `npm run build` pass in `website/`+- [x] 6.3 Append dated replacement notes to ADR-0006 and ADR-0013 stating that Valkey-backed state was replaced by process-local cache, publish-subscribe and rate-limiting providers; preserve their decision bodies and verify no new ADR file is added+- [x] 6.4 Apply the delta requirements to the current OpenSpec capabilities and verify them with `npx --yes @fission-ai/[email protected] validate --specs --strict`++## 7. Final verification++- [x] 7.1 Run `go test -race ./internal/util/cache ./internal/util/pubsub ./internal/util/ratelimiter ./internal/features/tasks/cancellation ./internal/features/backups/backups/download/... ./internal/features/restores/... ./internal/features/users/controllers ./internal/features/verification/agents` in `backend/`; resolve every failure+- [x] 7.2 Run `make test` and `make lint` in `backend/`; resolve every test, formatting and lint failure+- [x] 7.3 Build the production image and verify it starts healthy without Valkey configuration, packages, processes, ports or readiness logs+- [x] 7.4 Run the mandatory post-implementation reviewer against the complete diff and every governing module document, resolve every `CHANGES REQUIRED` finding and leave the working tree ready to commitdiff --git a/openspec/specs/backup-verification/spec.md b/openspec/specs/backup-verification/spec.mdnew file mode 100644index 00000000..f25bc4f1--- /dev/null+++ b/openspec/specs/backup-verification/spec.md@@ -0,0 +1,45 @@+# Backup Verification Specification++## Purpose++Defines the relationship between on-demand backup verification and the configuration that controls automatic verification runs.++## Requirements++### Requirement: Manual verification is independent of automatic scheduling++The system SHALL allow an authorized user to enqueue and run a manual backup verification while automatic verification is disabled.++#### Scenario: Enqueue manual verification while automatic verification is disabled++- **WHEN** an authorized user requests manual verification of an eligible backup whose automatic verification is disabled and no other manual verification for that database is pending or running+- **THEN** the system accepts the request and keeps the manual verification pending for an agent++#### Scenario: Disable automatic verification while a manual verification is pending++- **WHEN** automatic verification is disabled for a database with a pending manual verification+- **THEN** the manual verification remains pending++#### Scenario: Disable automatic verification while a manual verification is running++- **WHEN** automatic verification is disabled for a database with a running manual verification+- **THEN** the manual verification remains running and can reach its normal terminal status++### Requirement: Disabling automatic verification cancels only automatic runs++The system SHALL cancel non-terminal automatic verification runs when automatic verification is disabled without canceling manual verification runs for the same database.++#### Scenario: Disable automatic verification with a time-based run++- **WHEN** automatic verification is disabled for a database with a pending or running time-based verification+- **THEN** the system cancels that automatic verification++#### Scenario: Disable automatic verification with an after-backup run++- **WHEN** automatic verification is disabled for a database with a pending or running after-backup verification+- **THEN** the system cancels that automatic verification++#### Scenario: Manual and automatic runs coexist when scheduling is disabled++- **WHEN** automatic verification is disabled for a database with both manual and automatic non-terminal verifications+- **THEN** the system cancels the automatic verifications and leaves the manual verifications unchangeddiff --git a/openspec/specs/docker-storage-compatibility/spec.md b/openspec/specs/docker-storage-compatibility/spec.mdindex 692950f0..a4d93bb1 100644--- a/openspec/specs/docker-storage-compatibility/spec.md+++ b/openspec/specs/docker-storage-compatibility/spec.md@@ -8,9 +8,9 @@ Defines the supported Docker account settings and the real-container filesystem### Requirement: Docker services share one configurable runtime identity-The Docker image SHALL run Databasus, embedded PostgreSQL, and Valkey under one non-root operating-system account named `databasus`. Operators MAY set its numeric identity with `PUID` and `PGID`. Each supplied value SHALL be a non-zero decimal Linux ID within the supported system range.+The Docker image SHALL run Databasus and embedded PostgreSQL under one non-root operating-system account named `databasus`. Operators MAY set its numeric identity with `PUID` and `PGID`. Each supplied value SHALL be a non-zero decimal Linux ID within the supported system range.-When an override is absent, startup SHALL select that ID independently from the existing PostgreSQL data owner, then the mounted backup or data-root owner, and finally `999`. Root ownership SHALL NOT be selected automatically.+When an override is absent, startup SHALL select that ID independently from the existing PostgreSQL data owner, then the mounted backup or data-root owner and finally `999`. Root ownership SHALL NOT be selected automatically.#### Scenario: Fresh installation uses the fallback identity@@ -34,15 +34,15 @@ When an override is absent, startup SHALL select that ID independently from the#### Scenario: Operator supplies an invalid identity-- **WHEN** `PUID` or `PGID` is empty, non-numeric, zero, or outside the supported range+- **WHEN** `PUID` or `PGID` is empty, non-numeric, zero or outside the supported range- **THEN** the container exits before starting its services- **AND** the log identifies the invalid variable### Requirement: Startup validates storage through required operations-Startup SHALL attempt to prepare the data root, PostgreSQL data, PostgreSQL socket, temporary, and backup paths with the selected identity and required modes. A failed ownership or mode change SHALL NOT stop startup when the selected account can still perform every required operation.+Startup SHALL attempt to prepare the data root, PostgreSQL data, PostgreSQL socket, temporary and backup paths with the selected identity and required modes. A failed ownership or mode change SHALL NOT stop startup when the selected account can still perform every required operation.-Startup SHALL start Valkey and wait for readiness before running the main Databasus binary with `--test-storage` under the selected account. The command SHALL save a unique file through `LocalStorage.SaveFile` and remove it through `LocalStorage.DeleteFile`. Startup SHALL also verify the operations required for PostgreSQL data, its socket, and Databasus control files. A failed check SHALL stop startup before PostgreSQL or the Databasus application runs.+Startup SHALL run the main Databasus binary with `--test-storage` under the selected account before starting PostgreSQL or the Databasus application. The storage probe SHALL save a unique file through the configured local storage and remove that file through the same storage path. Startup SHALL also verify the operations required for PostgreSQL data, its socket and Databasus control files. A failed check SHALL stop startup before PostgreSQL or the Databasus application runs. Startup SHALL NOT start or wait for a separate cache service.#### Scenario: Filesystem denies metadata changes but permits operations@@ -58,7 +58,7 @@ Startup SHALL start Valkey and wait for readiness before running the main Databa- **WHEN** the selected account cannot publish a file from the temporary path to the backup path- **THEN** the container exits before starting the application-- **AND** the English error names the affected path, required operation, effective user and group IDs, and `https://databasus.com/advanced-config/#docker-storage-permissions`+- **AND** the English error names the affected path, required operation, effective user and group IDs and `https://databasus.com/advanced-config/#docker-storage-permissions`#### Scenario: Mounted path is read-only@@ -68,10 +68,15 @@ Startup SHALL start Valkey and wait for readiness before running the main Databa#### Scenario: Data root cannot create control files-- **WHEN** temporary, backup, PostgreSQL data, and socket paths are writable but the data root cannot create a control file+- **WHEN** temporary, backup, PostgreSQL data and socket paths are writable but the data root cannot create a control file- **THEN** the container exits before starting PostgreSQL or the Databasus application- **AND** the English error identifies the data root and required operation+#### Scenario: Container starts its bundled services++- **WHEN** storage validation succeeds+- **THEN** startup proceeds directly to embedded PostgreSQL and the Databasus application without a cache-service readiness step+### Requirement: Existing Docker data remains usable after an image updateThe current image SHALL start with persistent data created by versions `v3.54.0`, `v3.55.0`, `v3.55.1`, and `v3.56.0` when the mounted filesystem permits the selected account's required operations. Startup SHALL preserve the metadata database, secret key, application log, existing backup files, resumable nested WAL queues, and the existing PostgreSQL cluster. It SHALL prepare an existing WAL queue recursively and verify directory creation plus non-mutating file opens under the selected account before PostgreSQL or the Databasus application starts.diff --git a/openspec/specs/internal-postgresql-protection/spec.md b/openspec/specs/internal-postgresql-protection/spec.mdindex b8ba7a23..69e815e2 100644--- a/openspec/specs/internal-postgresql-protection/spec.md+++ b/openspec/specs/internal-postgresql-protection/spec.md@@ -166,9 +166,9 @@ Scheduled healthchecks SHALL test a database already loaded by the system withou### Requirement: The embedded PostgreSQL instance stays private under the shared runtime account-The embedded PostgreSQL server SHALL run under the same non-root operating-system account as the Databasus application and Valkey. During bootstrap only, peer mapping SHALL allow that account to administer the PostgreSQL role named `postgres`. After bootstrap, Unix-socket database login SHALL be rejected. Loopback TCP connections SHALL require SCRAM authentication with the generated credential, and replication connections to the embedded cluster SHALL be rejected.+The embedded PostgreSQL server SHALL run under the same non-root operating-system account as the Databasus application. During bootstrap only, peer mapping SHALL allow that account to administer the PostgreSQL role named `postgres`. After bootstrap, Unix-socket database login SHALL be rejected. Loopback TCP connections SHALL require SCRAM authentication with the generated credential and replication connections to the embedded cluster SHALL be rejected.-The embedded PostgreSQL and Valkey ports SHALL remain unpublished by the image.+The embedded PostgreSQL port SHALL remain unpublished by the image.#### Scenario: Application account opens the private socketdiff --git a/openspec/specs/local-cache/spec.md b/openspec/specs/local-cache/spec.mdnew file mode 100644index 00000000..10465e8b--- /dev/null+++ b/openspec/specs/local-cache/spec.md@@ -0,0 +1,117 @@+# Local Cache Specification++## Purpose++Defines the transient key-value behavior that cache consumers can rely on when Databasus runs as one application process.++## Requirements++### Requirement: Cache state is process-local and volatile++The cache SHALL keep entries inside the running application process. A new process SHALL start with an empty cache and SHALL NOT require a remote cache service.++#### Scenario: Application restarts++- **WHEN** the application process stops and starts again+- **THEN** entries created by the previous process are absent++#### Scenario: Application starts without a cache service++- **WHEN** an operator starts Databasus without a remote cache endpoint+- **THEN** cache-backed features remain available++### Requirement: Namespaced entries expire and can be invalidated++Each cache entry SHALL belong to a caller-selected namespace and SHALL have a positive lifetime. A read before expiration SHALL return the stored value. A read at or after expiration SHALL report a miss and make the expired entry eligible for reclamation. Callers SHALL be able to delete one entry or clear all entries owned by the process.++#### Scenario: Entry is read before expiration++- **WHEN** a caller reads a stored entry before its lifetime ends+- **THEN** the cache returns the stored value++#### Scenario: Entry reaches its expiration time++- **WHEN** a caller reads an entry at or after its expiration time+- **THEN** the cache reports a miss++#### Scenario: Namespaces use the same key++- **WHEN** two callers store different values under the same key in different namespaces+- **THEN** each caller reads the value from its own namespace++#### Scenario: Entry is invalidated++- **WHEN** a caller invalidates a stored entry+- **THEN** subsequent reads report a miss++### Requirement: Conditional storage operations are atomic++The cache SHALL provide atomic read-and-delete and create-if-absent operations. Expired entries SHALL be treated as absent by both operations.++#### Scenario: Concurrent callers consume one value++- **WHEN** multiple callers concurrently read and delete the same live entry+- **THEN** exactly one caller receives the value+- **AND** every other caller receives a miss++#### Scenario: Concurrent callers reserve one key++- **WHEN** multiple callers concurrently create the same absent key+- **THEN** exactly one caller stores its value+- **AND** every other caller is told that a live entry already exists++#### Scenario: Caller reserves an expired key++- **WHEN** a caller conditionally creates a key whose previous entry has expired+- **THEN** the new value is stored++### Requirement: Cache memory is bounded without evicting live entries++The cache SHALL enforce its configured payload budget. Before rejecting a write, it SHALL reclaim expired entries. It SHALL NOT evict an unexpired entry to admit another value.++#### Scenario: Expired entries occupy the available budget++- **WHEN** a write needs space held by expired entries+- **THEN** the cache reclaims those entries and admits the write++#### Scenario: Live entries occupy the available budget++- **WHEN** a write would exceed the budget after expired entries are reclaimed+- **THEN** the write fails+- **AND** every unexpired entry remains available++#### Scenario: One value exceeds the budget++- **WHEN** a caller tries to store a value larger than the entire cache budget+- **THEN** the write fails without changing existing entries++### Requirement: Concurrent cache access preserves the contract++Cache operations SHALL remain safe when called concurrently. A failed or canceled operation SHALL NOT leave a partially written value.++#### Scenario: Reads and writes overlap++- **WHEN** callers read, write, invalidate, reserve and consume entries concurrently+- **THEN** every completed operation has the same result as one valid serial ordering+- **AND** no caller observes a partial value++### Requirement: Security-sensitive cache failures stop protected operations++Restore-token issuance and consumption and stream-lock acquisition SHALL fail closed when their required cache operation fails. A cache failure SHALL NOT be interpreted as an absent token or an available stream lock.++#### Scenario: Restore-token issuance cannot store the token++- **WHEN** the cache rejects or fails the write required to issue a restore token+- **THEN** token issuance returns an error without returning a usable token++#### Scenario: Restore-token consumption cannot read and delete the token++- **WHEN** the cache cannot atomically read and delete a submitted restore token+- **THEN** token consumption returns an error+- **AND** the restore operation does not start++#### Scenario: Stream-lock acquisition cannot reserve the lock++- **WHEN** the cache cannot atomically reserve the required stream lock+- **THEN** lock acquisition returns an error+- **AND** the download or restore stream does not startdiff --git a/openspec/specs/local-publish-subscribe/spec.md b/openspec/specs/local-publish-subscribe/spec.mdnew file mode 100644index 00000000..b71b4f4b--- /dev/null+++ b/openspec/specs/local-publish-subscribe/spec.md@@ -0,0 +1,74 @@+# Local Publish-Subscribe Specification++## Purpose++Defines reliable process-local message delivery for features that coordinate work inside the single Databasus application process.++## Requirements++### Requirement: Publications stay inside the application process++The publish-subscribe provider SHALL deliver messages only to active subscriptions in the same application process. It SHALL NOT persist messages or replay publications made before a subscription became active.++#### Scenario: Message is published before subscription++- **WHEN** a message is published before a matching subscription becomes active+- **THEN** the later subscription does not receive that message++#### Scenario: Another process uses the same channel++- **WHEN** separate application processes use the same channel name+- **THEN** neither process receives the other process's publications++### Requirement: Subscription registration has no readiness race++Subscription creation SHALL return only after the subscription can accept publications. Canceling its context or closing the subscription SHALL prevent delivery of later publications.++#### Scenario: Publish follows subscription immediately++- **WHEN** a caller publishes immediately after subscription creation returns+- **THEN** the new subscription accepts the message without an additional readiness delay++#### Scenario: Subscription is canceled++- **WHEN** a subscription's context is canceled before a later publication+- **THEN** the canceled subscription does not receive that publication++### Requirement: Successful publication does not silently drop messages++A successful publication SHALL submit one copy of the message to every matching subscription that was active when publication began. Messages submitted to one subscription SHALL preserve publication order. If the publication context ends before all active subscriptions accept the message, the operation SHALL return an error instead of reporting success.++#### Scenario: Channel has multiple subscribers++- **WHEN** a caller successfully publishes to a channel with multiple active subscriptions+- **THEN** each subscription receives one copy of the message++#### Scenario: Subscriber receives consecutive publications++- **WHEN** a caller successfully publishes two messages to the same channel in sequence+- **THEN** each active subscription receives them in the same order++#### Scenario: Publication is canceled during delivery++- **WHEN** the publication context ends before every active subscription accepts the message+- **THEN** the publication returns an error++### Requirement: Subscriber failures are isolated++A subscriber failure SHALL NOT stop other subscriptions, corrupt broker state or crash the application process.++#### Scenario: Message handler panics++- **WHEN** one subscription handler panics while processing a message+- **THEN** other active subscriptions can continue receiving messages+- **AND** later publications can still use the broker++### Requirement: Broker shutdown releases subscriptions++Closing the publish-subscribe provider SHALL stop its subscriptions and reject later publications. Repeated close operations SHALL be safe.++#### Scenario: Provider closes++- **WHEN** the provider is closed while subscriptions are active+- **THEN** those subscriptions stop+- **AND** a later publication returns an errordiff --git a/openspec/specs/local-rate-limiting/spec.md b/openspec/specs/local-rate-limiting/spec.mdnew file mode 100644index 00000000..74c24bc7--- /dev/null+++ b/openspec/specs/local-rate-limiting/spec.md@@ -0,0 +1,85 @@+# Local Rate Limiting Specification++## Purpose++Defines process-local request limiting that protects authentication and verification endpoints without relying on a separate data service.++## Requirements++### Requirement: Rate limits use a sliding time window++The rate limiter SHALL record every request attempt for a caller-selected scope and identifier. It SHALL allow no more than the configured number of attempts whose timestamps fall inside the current window. Rejected attempts SHALL also count until they leave that window.++#### Scenario: Attempts remain below the limit++- **WHEN** an identifier makes no more than the configured number of attempts inside the window+- **THEN** every attempt is allowed++#### Scenario: Attempt exceeds the limit++- **WHEN** an identifier makes another attempt while the configured number of earlier attempts remains inside the window+- **THEN** the new attempt is rejected++#### Scenario: Old attempts leave the window++- **WHEN** enough recorded attempts reach the window boundary+- **THEN** those attempts stop contributing to the limit+- **AND** a later request is evaluated against only the remaining attempts++### Requirement: Limit scopes are independent++The rate limiter SHALL keep counts independent for each scope and identifier pair.++#### Scenario: One identifier uses two scopes++- **WHEN** the same identifier reaches the limit in one scope+- **THEN** attempts in another scope retain their own allowance++#### Scenario: Two identifiers use one scope++- **WHEN** one identifier reaches the limit in a scope+- **THEN** another identifier retains its own allowance in that scope++### Requirement: Concurrent attempts cannot exceed the allowance++Recording an attempt and deciding whether it is allowed SHALL be one atomic operation.++#### Scenario: Concurrent attempts meet one remaining allowance++- **WHEN** multiple attempts arrive concurrently and only one allowance remains+- **THEN** exactly one attempt is allowed++### Requirement: Rate-limit state is process-local and reclaimable++Rate-limit counters SHALL remain inside the running application process, start empty after restart and release state after its final recorded attempt leaves the window.++#### Scenario: Application restarts++- **WHEN** the application process restarts+- **THEN** previous rate-limit attempts no longer affect new requests++#### Scenario: Identifier becomes inactive++- **WHEN** every recorded attempt for an identifier has left the window+- **THEN** the limiter can reclaim that identifier's state++### Requirement: Invalid rate-limit settings fail explicitly++The rate limiter SHALL reject a non-positive request limit or a non-positive window without recording an attempt.++#### Scenario: Caller supplies an invalid limit++- **WHEN** a caller supplies a zero or negative request limit or window+- **THEN** the operation returns an error+- **AND** existing counters remain unchanged++### Requirement: Protected endpoints fail closed when a limit cannot be evaluated++An endpoint protected by rate limiting SHALL reject the request when the limiter cannot atomically record and evaluate the attempt. It SHALL NOT treat a limiter error as an allowed request. The endpoint SHALL log the limiter failure without including the caller identifier or other user-derived rate-limit key material.++#### Scenario: Limiter cannot record an attempt++- **WHEN** a protected endpoint receives an error from the rate limiter+- **THEN** the endpoint rejects the request+- **AND** the request does not proceed to the protected operation+- **AND** the failure is logged without the caller identifier or user-derived rate-limit key materialdiff --git a/openspec/specs/single-instance-runtime/spec.md b/openspec/specs/single-instance-runtime/spec.mdnew file mode 100644index 00000000..c9675f15--- /dev/null+++ b/openspec/specs/single-instance-runtime/spec.md@@ -0,0 +1,31 @@+# Single-Instance Runtime Specification++## Purpose++Defines one application process as the supported installation topology so transient coordination remains consistent without a shared service.++## Requirements++### Requirement: Supplied deployments run one application process++Databasus installation artifacts SHALL start exactly one application process for each installation. They SHALL NOT expose a setting that increases the application replica count.++#### Scenario: Operator deploys the Helm chart++- **WHEN** an operator renders or installs the supplied Helm chart+- **THEN** the resulting workload contains exactly one application replica++#### Scenario: Operator uses the Docker image++- **WHEN** an operator starts one instance of the supplied Docker image+- **THEN** that instance runs exactly one Databasus application process++### Requirement: One process owns transient runtime state++The single application process SHALL own cache entries, publish-subscribe subscriptions and rate-limit counters for its installation. The supplied deployment SHALL NOT require another service to share that state.++#### Scenario: Installation starts normally++- **WHEN** the application process starts+- **THEN** its transient runtime providers are available inside that process+- **AND** startup does not wait for a shared transient-state service