Skip to content

feat(storage): serve storage from a configured adapter - #1462

Draft
Robbie Cronin (robert-cronin) wants to merge 14 commits into
stack/512/29-gateway-wirefrom
stack/512/30-adapter-dial
Draft

Robbie Cronin (robert-cronin) wants to merge 14 commits into
stack/512/29-gateway-wirefrom
stack/512/30-adapter-dial

Conversation

@robert-cronin

@robert-cronin Robbie Cronin (robert-cronin) commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Stacked on the gateway layer. Until this layer the controller refused any storage binding other than embedded SQLite at startup (RequireEmbeddedSQLite returned AdapterTransportUnavailable), so a configured adapter could never be used. This layer dials the adapter and serves both contracts from it. It is the layer that lets Orka run on an out-of-tree PostgreSQL adapter.

Base is stack/512/29-gateway-wire; the diff below is this layer only. The regenerated wire provider and staging chart are in their own commit.

What changes

  • internal/storageclient/remote connects to an adapter. remote.Open:
    • dials a control connection and a bulk connection with wire.Dial: TLS 1.3 with the resolved CA bundle and server name, which for a serviceRef defaults to <service>.<namespace>.svc;
    • sends per-call credentials that require transport security. StaticToken holds a resolved bearer token; FileToken reads the projected ServiceAccount token on every call, so rotation needs no restart. A token that can't be read fails the call before it is sent. A ServiceAccount token is only ever sent to the serviceRef target;
    • calls DescribeServer, then builds wire.NewClient bound to the described dataset, the server's protocol revision, the families the server declares, the bulk connection and the provider's limits.
  • Stable startup reasons, checked in order: AdapterUnavailable (no answer before --storage-adapter-connect-timeout, two minutes by default, retried with backoff), AdapterTLSFailed, AdapterAuthRefused, AdapterIncompatible (contract version or revision, protocol revision, dataset, or no declared families), AdapterContractMissing and AdapterWireIncomplete (a required family the adapter doesn't implement, or an incomplete wire without the flag). Only AdapterUnavailable is retried. A TLS alert from the adapter, such as one that refuses TLS 1.3, is AdapterTLSFailed, not AdapterUnavailable. AdapterTransportUnavailable is gone.
  • wire.Provider in pkg/storage serves both contracts from one connection. It embeds *wire.Client, and wiregen now writes zz_generated.provider.go with a stub for every contract method that has no RPC yet, returning wire.UnservedFamilyError, which matches ErrIncompatible so callers never requeue it as temporary. A client bound to an older server refuses a method newer than the server's revision the same way. Wiring a family removes its stubs on the next generation, and a stale stub is a compile error. It lives in pkg/storage because that is the module wiregen writes into.
  • Declared families: the protocol revision says which families the wire carries, not which ones an adapter implements, so an adapter on the current revision that stubs whole families used to pass startup and fail on the first call. Describe now carries ServerInfo.families, the families whose methods the server's providers all implement. wire.NewServer derives it: a provider that stubs methods implements wire.PartialProvider, whose UnimplementedMethods names them, and one stubbed method withholds its whole family. adapterkit.Serve passes its providers straight to NewServer, so an adapter names the methods it stubs and never keeps a family list; a name that isn't a contract method fails NewServer. The controller treats as unserved the union of the families newer than the server's revision and the families the server doesn't declare, and the client refuses a method of an undeclared family without sending it.
  • Required families: every family on the wire is required (remote.RequiredFamilies) except the gateway's delivery and cleanup families (remote.OptionalFamilies), which only --gateway-enabled uses. That covers what the Task and Session paths always touch, such as outbox projections for ACP dispatch, Task data fences, session turns, sealed execution snapshots and usage. GatewayEventStore is required because every Task read looks up the Task's gateway identity. RepositoryMonitorStore is required because the RepositoryMonitor reconciler always runs and no flag turns it off. A family added to the wire later is required until it is listed as optional and mapped to the flag that uses it, and a test fails if an optional family belongs to no feature flag.
  • An adapter that declares nothing is refused with AdapterIncompatible. Such a server was built before the declaration existed, so the controller can't tell what it stubs, and reading silence as "implements everything" would bring back the call-time failures the declaration exists to prevent. Failing closed breaks no released adapter: the only released wire library, pkg/storage/v0.4.0, serves protocol revision 2, which the controller already refuses. An adapter built against an earlier head of this stack needs a rebuild.
  • Partial wire, off by default: --storage-allow-partial-wire (Helm: storage.experimental.allowPartialWire) lets the controller start on an adapter that serves only some families, and logs a warning. Families not yet on the wire (AHP, auth sessions, memory, connectors, security) and optional families the adapter doesn't declare then answer UnservedFamilyError. Startup still refuses each enabled feature whose families aren't served, for example --enable-ahp-api, --github-sign-in-enabled, --connectors-enabled and --gateway-enabled. Required families are never waived. Without the flag, any unserved family stops startup with AdapterWireIncomplete.
  • Startup on an adapter (cmd/storage_adapter.go): storageconfig.Plan() replaces RequireEmbeddedSQLite and picks embedded SQLite or one adapter; contracts on different backends stop with SplitBindingUnsupported. On an adapter the controller loads the snapshot key, minting one only for a dataset the adapter created empty and hasn't finished bootstrapping, activates it, completes the dataset bootstrap over the wire, and runs the connection as a runnable that reports orka_storage_adapter_up{contract,backend} and closes both connections on shutdown. The embedded SQLite path is unchanged.
  • Server description: by default the server still describes its provider before every read, so a read for a dataset the provider no longer serves is refused before it reaches the provider. An adapter whose dataset can't change while it serves can set adapterkit.Config.DescriptionMaxAge (ServerConfig.DescriptionMaxAge in the wire library). A read that names the dataset the server last described then reuses that description while it is younger than the age, so an out-of-tree adapter whose Describe takes several database round trips no longer pays for one on every read. A failed description is never reused, and Refresh (which adapterkit runs on its readiness interval) and every Describe renew it. A read is refused as unavailable when a description that started after its own failed, even if the dataset ID didn't change. Within the age, a read after a dataset switch can reach the new dataset; storage-contracts.md documents that window, and it is why the age is opt-in. A server whose two contract parts share one provider describes it once. Writes stay fenced by their envelope's dataset, and administrative calls still describe every time. When the client has gone before the response headers can be sent, the server reports the call as cancelled rather than logging a provider error.
  • API: storageHTTPError is the one mapping from storage errors. ErrNotReady and ErrUnavailable answer 503 with Retry-After, ErrOutcomeUnknown answers 409, and UnservedFamilyError answers 501 naming the family. About 90 handler sites now use it. Where a handler fails after it has already committed a write (a monitor command's workflow action, a security finding, patch proposal or scan status after its Task), a temporary error answers 500 without retry advice, because a retry would repeat the committed write.
  • Helm gains storage.experimental.allowPartialWire and the token path wiring for the dial; docs cover the operator side in configuration.md and troubleshooting.md, and the dial and declared families in storage-contracts.md ("Connecting to an adapter").

Orka doesn't call BindDataset yet. A dataset's owning installation comes from AdvanceControllerEpoch, which records the installation on an unbound dataset and refuses any other with ErrFenced; a test proves a second installation is refused.

Testing

  • go test ./internal/storageclient/remote/...:
    • TestStateProviderConformanceThroughAdapter and TestArtifactProviderConformanceThroughAdapter: the SQLite provider passes the whole storagetest suite through remote.Open and wire.Provider over TLS, the path production uses.
    • TestOpenFailureReasons covers every startup reason, including an adapter that only speaks TLS 1.2, an older protocol revision on a partial wire, an adapter that declares no families, and an adapter that stubs one method of a required family (EnqueueOutboxProjectionRecord), which is refused with AdapterWireIncomplete naming OutboxPersistenceStore. TestOpenGivesUpOnAnUnreachableAdapter, TestOpenRetriesUntilTheAdapterAnswers, TestOpenReportsAnUnreadableToken and TestOpenRefusesAnIncompleteWireWithoutTheFlag cover the rest.
    • TestOpenAcceptsAStubbedOptionalFamilyOnlyOnAPartialWire: a stubbed gateway delivery method is refused without the flag; with it the family is unserved and the client refuses its methods without sending them. TestRequiredFamiliesCoverEveryWiredFamilyButTheOptionalOnes pins the split.
    • TestFileTokenIsReadForEveryCall, TestConnectionReportsHealthAndClosesOnShutdown, TestASecondInstallationCannotAdvanceTheDataset and TestSnapshotKeyActivationSkipsUnservedFamiliesOnlyOnAPartialWire.
  • go test ./cmd/...: the snapshot key bootstrap matrix (mint for a new empty dataset, refuse a non-empty dataset without a key, activate an existing key), the startup refusals for an incomplete wire and for features with unserved families, TestControllerAdapterStartupRefusesTheGatewayWhenTheAdapterStubsItsFamilies (refused with the gateway on, starts with it off), and TestEveryOptionalFamilyBelongsToAFeature. The expected refusals come from wire.UnservedFamilies, so they stay right as families are wired.
  • go -C pkg/storage test ./...: TestProviderRefusesFamiliesWithoutRPCs, TestProviderRefusesFamiliesNewerThanTheServer, TestModelListsUnservedFamilies, TestServerDeclaresTheFamiliesItsProvidersImplement, TestServerRefusesAnUnknownUnimplementedMethod, TestClientRefusesFamiliesTheServerDoesNotDeclare, TestEveryWiredMethodIsAContractMethod, TestServerInfoFamiliesAreSortedBoundedAndClean, TestServerRechecksTheDatasetBeforeEachReadByDefault, TestServeDescribesBeforeEveryReadUnlessGivenADescriptionAge, TestServerChecksReadsAgainstAFreshDescription, TestServerDescribesAgainOnceTheDescriptionIsOld, TestServerKeepsADescriptionThatFailedLaterStale, TestServerRefusesAReadWhoseDescriptionAFailedRefreshSuperseded, TestAFreshDescriptionVouchesOnlyForItsOwnDataset, TestAReadAdmittedOnAFreshDescriptionAnswersForThatDescriptionsDataset and TestServerReportsACallTheClientAbandonedAsCancelled.
  • go test ./internal/api/...: TestStorageFailureMapsAdapterErrors, the retry-hint tests, TestStorageFailureAfterCommitNeverAsksForARetry, TestGenerateSecurityPatchDoesNotAskForARetryOnceTheProposalExists and TestRepositoryMonitorCommandDoesNotAskForARetryOnceTheCommandExists.
  • make test, full golangci-lint on the root and pkg/storage modules, go test ./internal/storageconfig/... ./cmd/build/helmify/..., make verify-generated, go test ./hack/repocheck, go build ./... and go vet: pass.

Part of #512.

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
…e adapter dial

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
@coderabbitai

coderabbitai Bot commented Nov 30, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…the controller needs

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
… it serves

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
…escribe

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
…d calls as cancelled

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical flaws can duplicate already-committed operations on retry and serve records under the wrong dataset identity.

4 open issues
What changed in this PR

Enables Orka to serve both storage contracts through a configured external adapter, advancing #512 while preserving embedded SQLite as the default. Adapter use remains experimental until all contract families are available over the wire.

Changes:

  • Adds authenticated TLS connections, startup compatibility checks, snapshot-key bootstrap, and adapter health reporting.
  • Adds declared-family negotiation, generated unsupported-method stubs, and centralized HTTP storage-error mapping.
  • Adds Helm configuration, operator documentation, and coverage for adapter startup, protocol behavior, and provider conformance.
File Description
website/​docs/​reference/​configuration.md Documents adapter configuration and startup failures.
website/​docs/​operations/​troubleshooting.md Adds adapter snapshot-key recovery guidance.
pkg/​storage/​v1/​wire/​zz_generated.provider.go Generates family metadata and unsupported-method stubs.
pkg/​storage/​v1/​wire/​wiretest/​wiretest.go Adjusts default server metadata initialization.
pkg/​storage/​v1/​wire/​storagepb/​common.pb.go Regenerates protobuf family declarations.
pkg/​storage/​v1/​wire/​server.go Adds family advertisement and description caching.
pkg/​storage/​v1/​wire/​server_test.go Updates per-read dataset validation coverage.
pkg/​storage/​v1/​wire/​provider.go Implements the combined wire provider and family errors.
pkg/​storage/​v1/​wire/​provider_test.go Tests unsupported methods and older servers.
pkg/​storage/​v1/​wire/​protocol.go Adds bounded, sanitized family metadata.
pkg/​storage/​v1/​wire/​internal/​wiregen/​render.go Generates provider stubs and method-family mappings.
pkg/​storage/​v1/​wire/​internal/​wiregen/​model.go Derives contract families and protocol requirements.
pkg/​storage/​v1/​wire/​internal/​wiregen/​generator_test.go Tests generated family completeness.
pkg/​storage/​v1/​wire/​families_test.go Tests family declarations and client refusals.
pkg/​storage/​v1/​wire/​families_internal_test.go Validates method membership and metadata sanitization.
pkg/​storage/​v1/​wire/​description_test.go Tests description caching, refresh, and cancellation.
pkg/​storage/​v1/​wire/​dataset_test.go Adjusts dataset tests for description reuse.
pkg/​storage/​v1/​wire/​client.go Rejects calls to undeclared or newer methods.
pkg/​storage/​v1/​wire/​admit_test.go Updates dataset publication test setup.
pkg/​storage/​proto/​orka/​storage/​v1/​common.proto Adds declared families to server metadata.
manifest_staging/​charts/​orka/​values.yaml Adds generated partial-wire settings.
manifest_staging/​charts/​orka/​templates/​deployment.yaml Passes the generated partial-wire flag.
manifest_staging/​charts/​orka/​templates/​_helpers.tpl Validates generated experimental settings.
internal/​storageconfig/​load.go Loads adapter timeout and partial-wire flags.
internal/​storageconfig/​load_test.go Tests backend planning and new flags.
internal/​storageconfig/​config.go Selects one backend and defines startup reasons.
internal/​storageconfig/​client_auth_test.go Tests ServiceAccount-authenticated adapter planning.
internal/​storageclient/​remote/​remotetest/​remotetest.go Adds a TLS adapter test harness.
internal/​storageclient/​remote/​remote.go Implements adapter connection, validation, and lifecycle.
internal/​storageclient/​remote/​remote_test.go Tests startup, credentials, health, and ownership.
internal/​storageclient/​remote/​options_test.go Tests endpoint resolution and token restrictions.
internal/​storageclient/​remote/​credentials.go Implements token sources and TLS failure classification.
internal/​storageclient/​remote/​conformance_test.go Exercises provider conformance through the adapter.
internal/​storageclient/​custody.go Supports partial-wire snapshot verification.
internal/​storageclient/​connector.go Handles unserved connector verification families.
internal/​storageclient/​client.go Carries the partial-wire option.
internal/​metrics/​metrics.go Registers adapter availability metrics.
internal/​api/​usage_handlers.go Maps usage storage failures consistently.
internal/​api/​task_transcript_search.go Maps transcript authorization storage failures.
internal/​api/​task_access.go Maps gateway ownership storage failures.
internal/​api/​storage_errors.go Centralizes storage-error HTTP responses.
internal/​api/​storage_errors_test.go Tests status codes and retry hints.
internal/​api/​server.go Applies centralized storage-error mapping.
internal/​api/​security_handlers.go Applies storage-error mapping to security workflows.
internal/​api/​monitor_handlers.go Applies storage-error mapping to monitor workflows.
internal/​api/​memory_handlers.go Maps unsupported memory families.
internal/​api/​internal_task_mutation.go Uses centralized mutation-error mapping.
internal/​api/​internal_handlers.go Updates message retrieval error mapping.
internal/​api/​internal_execution_event_handlers.go Updates execution-event write error mapping.
internal/​api/​handlers.go Maps task, session, and artifact storage failures.
internal/​api/​gateway_handlers.go Updates gateway storage-error mapping.
internal/​api/​execution_event_handlers.go Maps event retrieval storage failures.
internal/​api/​attention_handlers.go Maps attention-query storage failures.
docs/​development/​storage-contracts.md Documents adapter negotiation and dataset behavior.
cmd/​storage_adapter.go Implements adapter startup and feature-family checks.
cmd/​storage_adapter_test.go Tests bootstrap and startup refusals.
cmd/​main.go Selects SQLite or adapter-backed storage.
cmd/​build/​helmify/​storage_service_account_token_test.go Updates split-binding expectations.
cmd/​build/​helmify/​storage_config_test.go Tests chart planning and partial-wire settings.
cmd/​build/​helmify/​static/​values.yaml Defines partial-wire defaults and adapter guidance.
cmd/​build/​helmify/​static/​templates/​deployment.yaml Passes the partial-wire controller flag.
cmd/​build/​helmify/​static/​templates/​_helpers.tpl Validates experimental storage values.
cmd/​agent_execution_snapshot_secret.go Generalizes snapshot-key bootstrap across backends.

Review effort: Balanced

Comment thread internal/api/monitor_handlers.go Resolved
Comment thread internal/api/security_handlers.go Resolved
Comment thread pkg/storage/v1/wire/server.go Resolved
Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
…describes

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The default validation gap can allow records from the wrong dataset to be accepted, while partially committed scan admission can incorrectly advertise a safe retry.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Avoid retryable responses after partially committed scan admission

internal/​api/​security_handlers.go:458

CreateScanRun has already committed, and CreateInitialScanTask can also create the Task before validation fails. If validation and cancellation both return ErrUnavailable, this mapping sends 503 with Retry-After even though the run and Task remain. Use storageFailureAfterCommit here unless rollback is confirmed, so partially committed admission does not advertise a safe retry.

4 resolved since last review

Review effort: Balanced

Comment thread pkg/storage/v1/wire/server.go Resolved
…scription age

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The handler can return a retryable 503 after scan effects are committed without confirmed rollback, encouraging callers to repeat a POST and duplicate those effects.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Avoid retrying POST after scan task creation has committed

internal/​api/​security_handlers.go:458

The scan run has already committed here, and CreateInitialScanTask can also create the Task before its final storage-backed validation fails. If that validation and cancellation encounter ErrUnavailable, this returns 503 with Retry-After and explicitly asks the caller to repeat a POST whose effects already exist. Use the post-commit mapping here unless rollback is confirmed, as the later status-update failure already does.

1 resolved since last review

Review effort: Balanced

…rseded

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Out-of-order description completion can discard failure tracking, allowing an older read to bypass the fence and reach the provider.

1 open issue

Review effort: Balanced

Comment thread pkg/storage/v1/wire/server.go Resolved
…dy succeeded

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>
…r reads

Signed-off-by: Robert Cronin <robert.owen.cronin@gmail.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate retry safety when storage failures occur after scan creation has committed and rollback is not guaranteed.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants