AppSurface Search
API Reference

PostgreSql

Type

PostgreSqlDurableTransactionResources

Source

Validates an exact active caller transaction and configured physical target without taking ownership.

Remarks

Shared by enqueue and handoff; preserves enqueue's resource and target exception conventions.

Method

RequireActive

NpgsqlConnection RequireActive(NpgsqlTransaction transaction, PostgreSqlDurableStoreTarget target)

Returns the supplied transaction's open connection after validating its physical store target.

Parameters

  • transaction
    The caller-owned, uncommitted transaction; this method never completes or disposes it.
  • target
    The configured PostgreSQL host, port and database identity.

Returns

The exact connection owned by the supplied transaction.

Exceptions

  • InvalidOperationException
    The transaction is inactive or does not target the configured store.
Type

PostgreSqlDurableRuntimeHealth

Source

Implements low-cardinality PostgreSQL runtime liveness, drain, and worker-generation fencing.

Method

GetWithSharedConnectionAsync

ValueTask<DurableRuntimeHealthSnapshot> GetWithSharedConnectionAsync(PostgreSqlDurableRuntimeSchemaManager schemaManager, CancellationToken cancellationToken)

Reuses the default schema manager's connection for the compatible runtime observation, halving pool acquisitions on the full health path while preserving custom-manager composition.

Method

TryBeginPassAsync

ValueTask<bool> TryBeginPassAsync(CancellationToken cancellationToken)

Preserves the legacy Boolean/exception admission behavior for internal callers and compatibility tests.

Method

TryBeginPassWithOutcomeAsync

ValueTask<PostgreSqlDurableStoreAdmission> TryBeginPassWithOutcomeAsync(CancellationToken cancellationToken)

Attempts store admission and returns typed pre-execution causes without parsing legacy exception messages.

Method

EnsureSessionAsync

ValueTask<bool> EnsureSessionAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken, bool captureAdmissionOutcome = false)

Creates or verifies this process generation while holding the worker row lock.

Returns

Whether the verified generation is currently draining.

Method

ReadObservationAsync

2 overloads
ValueTask<RuntimeObservation> ReadObservationAsync(CancellationToken cancellationToken)

Reads metadata, the optional worker generation, and due facts from one statement snapshot and one result row.

ValueTask<RuntimeObservation> ReadObservationAsync(NpgsqlConnection connection, CancellationToken cancellationToken)

Reads the one-row runtime observation through an existing compatible status connection.

Method

ReadObservationRow

RuntimeObservation ReadObservationRow(NpgsqlDataReader reader)

Validates the complete one-row provider result before any public snapshot is constructed.

Method

ReadDatabaseTimestampAsync

2 overloads
ValueTask<DateTimeOffset> ReadDatabaseTimestampAsync(CancellationToken cancellationToken)

Reads authoritative database time for a schema-only incompatibility assessment.

ValueTask<DateTimeOffset> ReadDatabaseTimestampAsync(NpgsqlConnection connection, CancellationToken cancellationToken)

Reads authoritative database time through an existing compatible status connection.

Type

PostgreSqlDurableStoreAdmission

Source

Carries a typed store-admission result and the exact legacy exception when one is required.

Method

Refused

PostgreSqlDurableStoreAdmission Refused(PostgreSqlDurableStoreAdmissionKind kind)

Creates a refusal that has no legacy exception.

Method

WithLegacyException

PostgreSqlDurableStoreAdmission WithLegacyException(PostgreSqlDurableStoreAdmissionKind kind, InvalidOperationException legacyException)

Creates a typed outcome that retains the original legacy exception.

Property

Admitted

PostgreSqlDurableStoreAdmission Admitted { get; } Source

Gets an admitted result.

Type

PostgreSqlDurableEpochMismatchSignal

Source

Internal signal that lets admission retain the exact plain legacy epoch exception.

Property

LegacyException

InvalidOperationException LegacyException { get; } Source

Gets the unmodified exception used by the legacy projection.

Type

PostgreSqlDurableWorkerGenerationSignal

Source

Internal signal that lets admission retain the exact plain legacy worker-generation exception.

Property

LegacyException

InvalidOperationException LegacyException { get; } Source

Gets the unmodified exception used by the legacy projection.

Type

PostgreSqlDurableHandoffFacts

Source

Current lease and optional deadline facts read for one invocation-bound handoff.

Parameters

  • LeaseExpiresAtUtc
    The authoritative current lease expiry from the locked Work row.
  • DeadlineUtc
    The configured immutable execution deadline for opted-in Work, when present.
  • DeadlineReached
    Whether opted-in Work permanently recorded that its deadline had elapsed.
  • UsesExecutionClock
    Whether opted-in Work uses the configured execution clock instead of the legacy PostgreSQL clock.

Remarks

These facts are reread under native row locks for each call. Lease expiry and Work revision are deliberately not cached or compared with the claim snapshot because a legitimate renewal can change them. A null deadline means either legacy Work or opted-in Work without a configured absolute deadline. A previously observed deadline remains authoritative even if the database execution clock later moves backward; the caller has already validated the active invocation and exact permit before relying on this record.

Method

ReadAsync

ValueTask<(PostgreSqlDurableHandoffFacts? Facts, string? ProblemCode)> ReadAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, PostgreSqlEffectPermit permit, CancellationToken cancellationToken)

Reads and validates the exact native authority for a caller-transaction handoff, without changing protocol state.

Parameters

  • connection
    The already-open PostgreSQL connection for the caller-owned transaction.
  • transaction
    The active caller-owned transaction used for every lock and read.
  • permit
    The exact effect permit and invocation identity being authorized.
  • cancellationToken
    Cancels database reads while the caller retains resource ownership.

Returns

Current lease/deadline facts with a null problem code when valid, or a null facts value and the first applicable bounded Durable problem code when native authority is refused. Database and cancellation exceptions propagate.

Remarks

The caller must already have validated schema and active epoch, bound the transaction-local scope, and verified that transaction belongs to connection . Reads lock in the protocol order: active scope FOR SHARE , exact Work FOR UPDATE , its dispatch row FOR UPDATE , then only the supplied permit ID FOR UPDATE . It samples authoritative time immediately after the Work checks and stops before dispatch/permit reads if the lease or deadline has elapsed, then samples again after dispatch and permit lock waits. The dispatch row must match the claim's exact dispatch ID, remain leased, and project the locked Work revision; this compares current database rows, not the possibly older revision in a permit snapshot. The lookup uses existing scope, Work, dispatch, and permit keys and never scans Work history or prior permits. It supports legacy rows explicitly and does not create a scope, consume invocation admission, mutate a permit, or complete the caller's transaction. Legacy Work uses pg_catalog.clock_timestamp() ; opted-in Work uses its configured execution clock. Refusal precedence is missing/disabled/stale scope, missing Work, Work identity, terminal state, cancellation, lease then deadline, dispatch/permit status, exact permit identity, and finally the existing invocation-admission marker for opted-in Work.

Method

SampleTimeAsync

ValueTask<DateTimeOffset> SampleTimeAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, bool usesExecutionClock, CancellationToken cancellationToken)

Samples the clock already used by the matching legacy or opted-in admission path.

Parameters

  • connection
    The open connection holding the caller-owned transaction.
  • transaction
    The caller-owned transaction after the required native locks.
  • usesExecutionClock
    True for opted-in Work; false to preserve legacy PostgreSQL clock semantics.
  • cancellationToken
    Cancels the clock query.

Returns

The current UTC time from the matching execution protocol clock.

Method

TimeProblem

string? TimeProblem(PostgreSqlDurableHandoffFacts facts, DateTimeOffset nowUtc)

Returns lease expiry before an elapsed or permanently observed opted-in deadline.

Parameters

  • facts
    The freshly locked lease and optional immutable deadline.
  • nowUtc
    Authoritative database time sampled after native lock acquisition.

Returns

DurableProblemCodes.LeaseLost , DurableProblemCodes.ExecutionDeadlineReached , or null.

Type

PostgreSqlDurableWorkOperatorClient

Source

Implements the internal PostgreSQL operator path over the landed provider contracts.

Remarks

Applications must authorize every request before this client is called.

Type

OperatorWorkSnapshot

Source
Property

SelectedPermit

PostgreSqlExecutionPermitIdentity? SelectedPermit { get; init; } Source

Latest unresolved admitted permit selected under the Work lock for exact authorized proof.

Remarks

May refer to an earlier attempt. Work projections retain their current identity; legacy rows keep null.

Type

PostgreSqlDurableWorkStore

Provides PostgreSQL persistence operations for the durable Work protocol.

Opt-in effect permits are exact fenced evidence; a separate durable marker admits invocation once.

Locked opt-in claim, lease, permit and one-use invocation admission transitions.

Opt-in acceptance freezes one post-scope-lock timestamp and preserves duplicate identity after expiry.

Classifies local observations under the exact locked fence without treating time as effect evidence.

Preserves exact invocation evidence when cancellation races an opted-in timing boundary.

Post-lock clock and persistence helpers shared by the opted-in store and audited operator protocol.

Remarks

This internal class supports controlled derived test seams. Overrides must preserve claim identity, runtime epoch and scope-generation fences, lease ownership, dispatch projection, Work history, and transaction guarantees.

Method

AcceptFlowChildAsync

ValueTask<DurableOperationResult<DurableWorkAcceptance>> AcceptFlowChildAsync(NpgsqlTransaction transaction, DurableWorkRequest request, Guid runtimeEpoch, Guid expectedStoreId, bool sendWakeNotification, string derivedActivityId, CancellationToken cancellationToken)

Accepts a Flow child Work with an immutable activity identity while retaining the ordinary Work protocol. The caller owns the surrounding transaction and must register the parent wait before commit.

Method

RenewLeaseAsync

ValueTask<PostgreSqlDurableWorkClaim?> RenewLeaseAsync(PostgreSqlDurableWorkClaim claim, CancellationToken cancellationToken = default)

Renews the active lease held by a fenced Work claim.

Parameters

  • claim
    Claim that identifies the active runtime epoch, scope, Work attempt, and lease owner.
  • cancellationToken
    Token that cancels database operations.

Returns

The renewed claim with its current revision, expiry, and cancellation state, or null when an epoch, scope, attempt, owner, or lease fence is stale.

Remarks

Overrides must preserve the current-epoch and active-scope checks, lease and dispatch consistency, durable history semantics, and transactional atomicity of the renewal attempt.

Method

ValidateSchemaAsync

ValueTask ValidateSchemaAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid? expectedStoreId, CancellationToken cancellationToken)

Validates schema compatibility and the optional store identity in the exact caller transaction.

Remarks

Handoff callers acquire the shared migration fence first; this check does not bind scope or own resources.

Method

ValidateSchemaRemovalForTestingAsync

ValueTask ValidateSchemaRemovalForTestingAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid? expectedStoreId, CancellationToken cancellationToken, Func<ValueTask> afterExistence)

Validates schema removal after the successful existence probe without relying on timing.

Parameters

  • connection
    Open connection that owns the caller transaction.
  • transaction
    Caller-owned transaction used for every validation query.
  • expectedStoreId
    Expected durable store identity, or null to omit identity validation.
  • cancellationToken
    Token that cancels validation database operations.
  • afterExistence
    Test callback invoked after the catalog probe and before metadata is read.

Remarks

This test-only seam preserves the callback-free production validation contract.

Method

CreateMissingSchemaException

DurableRuntimeSchemaException CreateMissingSchemaException(PostgresException innerException)

Preserves the PostgreSQL failure that exposed a missing schema without copying its server text.

Method

EnsureCurrentEpochAsync

ValueTask EnsureCurrentEpochAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid runtimeEpoch, CancellationToken cancellationToken)

Holds the migration fence and checks the active epoch before scoped provider operations.

Method

ValidateCurrentEpochAsync

ValueTask ValidateCurrentEpochAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid runtimeEpoch, CancellationToken cancellationToken)

Checks the active epoch after the caller has acquired the shared migration fence.

Remarks

Use EnsureCurrentEpochAsync unless schema validation requires acquiring the fence first.

Method

AcquireEpochFenceAsync

ValueTask AcquireEpochFenceAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken)

Acquires the shared migration fence before schema, store and epoch reads in a caller transaction.

Method

TryAdmitInvocationAsync

ValueTask<bool> TryAdmitInvocationAsync(PostgreSqlEffectPermit permit, CancellationToken cancellationToken = default)

Revalidates the store after permit commit and atomically consumes exact invocation admission once.

Remarks

False never authorizes an executor; a committed marker is conservative effect uncertainty even before I/O.

Method

HasExpiredOrdinaryLease

bool HasExpiredOrdinaryLease(PostgreSqlWorkExecutionRow row)

Distinguishes an independently lost lease from the immutable deadline cap.

Method

UpdateExecutionDispatchAsync

ValueTask UpdateExecutionDispatchAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, PostgreSqlWorkExecutionRow row, string state, DateTimeOffset dueAt, DateTimeOffset? expiry, long revision, bool admitted, CancellationToken cancellationToken)

Maintains eligibility separately from payload-free discovery; closed projections are excluded.

Method

AddExecutionTimeCapped

DateTimeOffset AddExecutionTimeCapped(DateTimeOffset start, TimeSpan duration, DateTimeOffset? cap = null)

Adds a positive duration only after bounding it by a representable UTC cap.

Remarks

Comparing the remaining interval first avoids overflow even when the uncapped duration is valid.

Method

InsertExecutionObservationAsync

ValueTask InsertExecutionObservationAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, PostgreSqlDurableWorkClaim claim, PostgreSqlWorkCompletion completion, string eventPrefix, string reason, DateTimeOffset observedAtUtc, CancellationToken cancellationToken)

Appends exact old-fence evidence once, retaining codec/digest/classification/retention metadata.

Remarks

The owning Work lock serializes duplicate observations; winning truth and normal results stay untouched.

Method

RecordExecutionRefusal

void RecordExecutionRefusal(string boundary, string reason)

Records only closed values after authoritative refusal; listener failure cannot change truth.

Method

ReadExecutionRowLockedAsync

ValueTask<PostgreSqlWorkExecutionRow?> ReadExecutionRowLockedAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, DurableScopeId scopeId, DurableWorkId workId, CancellationToken cancellationToken)

Returns timing facts only for an opt-in row, locking rows in separate commands before sampling.

Method

ReadInspectionExecutionSnapshot

DurableWorkExecutionSnapshot? ReadInspectionExecutionSnapshot(NpgsqlDataReader reader, int offset, DateTimeOffset acceptedAtUtc, DateTimeOffset dueAtUtc, int attemptNumber)

Projects immutable timing facts from the same Work statement snapshot used for authorized inspection.

Remarks

No dispatch/permit reads or clock sample are needed: this projection grants no admission.

Method

ReadAcceptedExecutionPolicy

DurableWorkExecutionPolicy? ReadAcceptedExecutionPolicy(NpgsqlDataReader reader, int offset)

Decodes the accepted policy column group; unknown versions fail closed.

Method

SampleExecutionTimeAsync

ValueTask<DateTimeOffset> SampleExecutionTimeAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken)

Samples the volatile authoritative clock only after callers acquire required locks.

Method

RecordAdmissionClosureAsync

ValueTask RecordAdmissionClosureAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, PostgreSqlWorkExecutionRow row, string reason, CancellationToken cancellationToken)

Persists first closure without clearing it or altering a command's revision projection.

Method

ExecutionTimingCode

string ExecutionTimingCode(PostgreSqlWorkExecutionRow row, string reason, bool uncertain)

Projects closed public problem precedence; ambiguous effects take precedence over timing.

Method

ExecutionAmbiguousState

string ExecutionAmbiguousState(DurableProviderSafety safety)

Closed safety-specific suspension for an admitted outcome that remains unknown.

Type

PostgreSqlDurableWorkClaim

Source
Property

Execution

DurableWorkExecutionSnapshot? Execution { get; init; } Source

Accepted opt-in facts; legacy claims retain a null projection.

Type

PostgreSqlDurableFlowStore

Owns scoped Flow command and query transactions. Processor transactions live in the processing partial.

Method

InsertTraceContextAsync

ValueTask<PostgreSqlDurableFlowTrace?> InsertTraceContextAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, DurableScopeId scopeId, DurableFlowInstanceId instanceId, DurableTraceContext? context, string causeKind, CancellationToken cancellationToken)

Inserts immutable trace evidence into the caller-owned Flow mutation transaction.

Remarks

The caller must set the scoped runtime context and commit or roll back the supplied transaction. A missing context produces no row and returns null . A non-null context must insert exactly one row or the method throws so the enclosing durable mutation cannot commit partial evidence.

Method

AttachTraceContextAsync

ValueTask AttachTraceContextAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, DurableScopeId scopeId, DurableFlowInstanceId instanceId, PostgreSqlDurableFlowTrace? trace, string? commandId, long revision, Guid? waitId, Guid? timerId, DurableWorkId? workId, CancellationToken cancellationToken)

Attaches inserted trace evidence to every Flow record created by the same committed transition.

Remarks

The caller must use the transaction that inserted trace . A missing trace is a no-op for an absent context. Otherwise the Flow instance and history pointer, plus every non-null command, wait, timer, or Work pointer, must each update exactly one row; any mismatch throws so the transaction rolls back rather than committing detached causal evidence.

Type

PostgreSqlDurableWorkClient

Source

Accepts durable Work in a short provider-owned PostgreSQL transaction.

Type

PostgreSqlDurableHeartbeatMaintenance

Source

Runs bounded heartbeat pruning independently of runtime pass execution.

Method

SignalAdmittedPass

void SignalAdmittedPass()

Queues maintenance without waiting for database work.

Method

StopAsync

ValueTask StopAsync(CancellationToken cancellationToken = default)

Stops scheduled maintenance during host shutdown.

Type

PostgreSqlDurableRuntimePump

Source

Runs one provider-backed PostgreSQL Pass through Work, Flow, and Schedule Turns.

Remarks

One pass is deliberately sequential and process-local. PostgreSQL retains all authoritative discovery, claim, lease, permit, completion, schedule, scope, and epoch decisions. The internal execution boundary is intentionally uninstrumented so #685 can attach Activity and ActivityLink behavior without taking ownership of this lifecycle.

Method

RunAttemptAsync

ValueTask<PostgreSqlDurablePumpOutcome> RunAttemptAsync(DurableRuntimePumpRequest request, CancellationToken cancellationToken)

Runs the sole private admission and execution state machine shared by both public projections.

Method

ClassifyPreExecutionFailure

PostgreSqlDurablePumpOutcome? ClassifyPreExecutionFailure(PostgreSqlDurableControlPlaneOperation operation, PostgreSqlDurablePumpPhase phase, Exception exception, CancellationToken cancellationToken)

Classifies only a failure that occurred before the execution boundary.

Method

TryRecordFailedPassAsync

ValueTask TryRecordFailedPassAsync(PostgreSqlDurablePumpPhase originalPhase)

Makes one fresh, bounded ownership-scoped cleanup attempt without replacing the original outcome.

Method

InvokeBoundAsync

ValueTask<DurableEncodedWorkExit> InvokeBoundAsync(DurablePreparedWorkInvocation invocation, PostgreSqlDurableWorkHandoffFence handoffFence, PostgreSqlEffectPermit permit, CancellationToken token)

Deactivates invocation authority as soon as the executor exits, independently of lease maintenance.

Method

NextRenewalAtUtc

DateTimeOffset NextRenewalAtUtc(PostgreSqlDurableWorkClaim claim, DateTimeOffset nowUtc)

Schedules opt-in lease maintenance without adding beyond its current authoritative lease bound.

Type

DurableRuntimeSchemaException

Source

Indicates a missing, incompatible, or inconsistent durable PostgreSQL schema.

Property

Status

DurableRuntimeSchemaStatus Status { get; } Source

Gets the incompatible schema status.

Type

PostgreSqlDurableFlowRepairOperatorClient

Source

Implements the preview, evidence-first Flow repair boundary for a scoped PostgreSQL durable runtime.

Remarks

Applications authorize the trusted scope before this client is invoked. The client never reads a raw Work result into its public assessment and never invokes an executor while applying a repair assertion.

Type

AppSurfaceDurablePostgreSqlOptions

Source

Configures process-local PostgreSQL durable runtime behavior.

Remarks

These options control activation only. They do not apply migrations, alter durable protocol policy, or replace PostgreSQL leases, recovery epochs, and history as the source of truth. Registering PostgreSQL storage remains passive until AppSurfaceDurablePostgreSqlBuilder.AddWorkerHost is called.

Property

WorkerId

string WorkerId { get; set; } Source

Gets or sets the privacy-safe identity written on short-lived claims and runtime heartbeats.

Remarks

Use a unique value for every concurrently live replica. It is not an authorization credential and must not contain connection details, user input, or other secrets.

Property

SendWakeNotifications

bool SendWakeNotifications { get; set; } Source

Gets or sets whether accepted commands emit metadata-only PostgreSQL wake hints.

Remarks

Polling remains authoritative when hints are disabled, lost, duplicated, delayed, or unavailable.

Property

MaximumItemsPerPass

int MaximumItemsPerPass { get; set; } Source

Gets or sets the maximum completed or committed Turns in one hosted pass.

Property

TimeBudgetPerPass

TimeSpan TimeBudgetPerPass { get; set; } Source

Gets or sets the budget for discovering and starting additional Turns in one hosted pass.

Property

HostedSurfaces

DurableRuntimeSurface HostedSurfaces { get; set; } Source

Gets or sets the durable surfaces activated by this worker instance.

Property

IdlePollingInterval

TimeSpan IdlePollingInterval { get; set; } Source

Gets or sets the maximum delay between authoritative polling passes when no work is immediately due.

Property

TransientFailureDelay

TimeSpan TransientFailureDelay { get; set; } Source

Gets or sets the bounded delay before retrying a transient store or listener failure.

Property

HeartbeatStaleAfter

TimeSpan HeartbeatStaleAfter { get; set; } Source

Gets or sets how old a heartbeat may become before health reports the worker as stale.

Property

EnableHeartbeatMaintenance

bool EnableHeartbeatMaintenance { get; set; } Source

Gets or sets whether admitted runtime passes trigger stale-heartbeat maintenance.

Remarks

Maintenance is capacity cleanup and does not affect pass readiness. It is triggered by the package PostgreSQL pump after admitted passes; a custom pump does not trigger provider maintenance. Set this to false in a new registration to pause pruning during an incident; stale identities remain until maintenance resumes or an operator cleans them.

Property

HeartbeatRetention

TimeSpan HeartbeatRetention { get; set; } Source

Gets or sets the age after which a worker heartbeat is eligible for deletion.

Remarks

Defaults to 24 hours; PostgreSQL time determines the cutoff. Values must be at least 24 hours, at most 3650 days, and greater than HeartbeatStaleAfter .

Property

HeartbeatMaintenanceCadence

TimeSpan HeartbeatMaintenanceCadence { get; set; } Source

Gets or sets the interval between ordinary heartbeat maintenance calls.

Remarks

Defaults to 24 hours. Full batches catch up no faster than one call per minute; failures retry after one hour.

Property

HeartbeatPruneBatchSize

int HeartbeatPruneBatchSize { get; set; } Source

Gets or sets the maximum number of stale heartbeat rows deleted by one maintenance call.

Remarks

Defaults to 500 and is bounded to 1–5000. At the default, catch-up is capped at 720,000 rows per day.

Property

ShutdownReserve

TimeSpan ShutdownReserve { get; set; } Source

Gets or sets one bounded host-shutdown reserve window for durable finalization or cleanup.

Remarks

Hosted startup requires TimeBudgetPerPass + (2 * ShutdownReserve) <= HostOptions.ShutdownTimeout . One fresh reserve protects terminal pass finalization and a second fresh reserve protects ownership-scoped cleanup when finalization fails. An externally activated pass retains its caller-supplied execution budget, then uses the same provider-owned finalization and cleanup reserves.

Type

IDurableRuntimeSchemaManager

Source

Provides explicit deployment operations for the AppSurface durable PostgreSQL schema.

Remarks

Use a migration-owner data source. Runtime registration may validate status but must never apply DDL.

Method

GetStatusAsync

ValueTask<DurableRuntimeSchemaStatus> GetStatusAsync(CancellationToken cancellationToken = default)

Reads installed migration metadata without modifying the database.

Parameters

  • cancellationToken
    Token that cancels the database read.

Returns

An immutable status snapshot. Missing and incompatible schemas are returned as status, not exceptions.

Exceptions

  • Npgsql.NpgsqlException
    PostgreSQL rejects the read or the connection fails.
  • OperationCanceledException
    The operation is canceled.
Method

GenerateScript

string GenerateScript(int fromVersion = 0)

Generates deterministic SQL for migrations newer than the exact reviewed fromVersion .

Parameters

  • fromVersion
    Last installed migration version, from zero through PostgreSqlDurableRuntimeSchemaManager.RequiredVersion .

Returns

A migration-owner script that acquires and releases the package advisory lock.

Exceptions

  • ArgumentOutOfRangeException
    fromVersion is outside the supported range.

Remarks

The result is forward-only and is not safe to rerun after any selected migration commits. Its advisory-lock acquisition is bounded to 30 seconds by default. If that deadline expires, the generated SQL raises PostgreSQL SQLSTATE 55P03 before migration SQL starts; retry after the active migration owner releases the lock.

Method

ApplyAsync

ValueTask<DurableRuntimeSchemaApplyResult> ApplyAsync(CancellationToken cancellationToken = default)

Applies pending migrations while holding the package session advisory lock.

Parameters

  • cancellationToken
    Token that cancels lock acquisition or migration application.

Returns

The version range observed before and after application and the ordered versions applied by this call.

Exceptions

  • DurableRuntimeSchemaException
    The installed schema is inconsistent or newer than this package.
  • Npgsql.NpgsqlException
    PostgreSQL rejects a migration or the connection fails.
  • TimeoutException
    The configured migration-lock acquisition deadline, 30 seconds by default, expires before the lock is acquired. Retry after the active migration owner releases the advisory lock.
  • OperationCanceledException
    The operation is canceled.
Method

ValidateAsync

ValueTask ValidateAsync(CancellationToken cancellationToken = default)

Fails when the installed schema cannot be used without changing it.

Parameters

  • cancellationToken
    Token that cancels the database read.

Returns

A task that completes when the installed schema is compatible.

Exceptions

  • DurableRuntimeSchemaException
    The schema is not compatible.
  • Npgsql.NpgsqlException
    PostgreSQL rejects the read or the connection fails.
  • OperationCanceledException
    The operation is canceled.
Method

InitializeRuntimeEpochAsync

ValueTask<DurableRuntimeEpochActivationResult> InitializeRuntimeEpochAsync(Guid initialEpoch, string actorId, string reasonCode, CancellationToken cancellationToken = default)

Activates the first non-empty store recovery epoch exactly once.

Parameters

  • initialEpoch
    Deployment-selected initial epoch.
  • actorId
    Privacy-safe operator code of 1-200 ASCII letters, digits, - , _ , . , or : .
  • reasonCode
    Privacy-safe activation code of 1-120 ASCII letters, digits, - , _ , . , or : .
  • cancellationToken
    Token that cancels lock acquisition or activation.

Returns

The activated epoch and database observation time.

Exceptions

  • ArgumentException
    The epoch is empty, or an operator code is empty, too long, or outside the opaque-code grammar.
  • DurableRuntimeSchemaException
    The installed schema is not compatible.
  • InvalidOperationException
    A runtime epoch is already active.
  • Npgsql.NpgsqlException
    PostgreSQL rejects the mutation or the connection fails.
  • TimeoutException
    The configured migration-lock acquisition deadline, 30 seconds by default, expires before the lock is acquired. Retry after the active migration owner releases the advisory lock.
  • OperationCanceledException
    The operation is canceled.
Method

RotateRuntimeEpochAsync

ValueTask<DurableRuntimeEpochRotationResult> RotateRuntimeEpochAsync(Guid expectedActiveEpoch, Guid newActiveEpoch, string actorId, string reasonCode, CancellationToken cancellationToken = default)

Atomically rotates the recovery epoch when the expected epoch remains active.

Parameters

  • expectedActiveEpoch
    Epoch that must still be active when the mutation commits.
  • newActiveEpoch
    Distinct, non-empty replacement epoch.
  • actorId
    Privacy-safe operator code of 1-200 ASCII letters, digits, - , _ , . , or : .
  • reasonCode
    Privacy-safe rotation code of 1-120 ASCII letters, digits, - , _ , . , or : .
  • cancellationToken
    Token that cancels lock acquisition or rotation.

Returns

The previous and active epochs and database observation time.

Exceptions

  • ArgumentException
    An epoch is empty, the epochs match, or an operator code violates its bounds or grammar.
  • DurableRuntimeSchemaException
    The installed schema is not compatible.
  • InvalidOperationException
    expectedActiveEpoch is no longer active.
  • Npgsql.NpgsqlException
    PostgreSQL rejects the mutation or the connection fails.
  • TimeoutException
    The configured migration-lock acquisition deadline, 30 seconds by default, expires before the lock is acquired. Retry after the active migration owner releases the advisory lock.
  • OperationCanceledException
    The operation is canceled.
Type

DurableRuntimeTurnScheduler

Source

Maintains process-local fair selection order for bounded runtime Turns.

Type

AppSurfaceDurablePostgreSqlServiceCollectionExtensions

Source

Registers the PostgreSQL durable runtime kernel and its separately opt-in host adapter.

Method

AddAppSurfaceDurablePostgreSql

AppSurfaceDurablePostgreSqlBuilder AddAppSurfaceDurablePostgreSql(this IServiceCollection services, NpgsqlDataSource dispatcherDataSource, NpgsqlDataSource runtimeDataSource, PostgreSqlDurableWorkOptions workOptions, PostgreSqlDurableScheduleOptions scheduleOptions, Action<AppSurfaceDurablePostgreSqlOptions>? configure = null)

Registers PostgreSQL durable clients, schema validation, health, drain, and the bounded pump without starting a background worker or applying migrations.

Parameters

  • services
    Application service collection.
  • dispatcherDataSource
    Payload-free dispatcher-role data source used for global discovery only.
  • runtimeDataSource
    Scoped runtime-role data source used for durable mutations and heartbeats.
  • workOptions
    Validated active epoch and StoreId. The configure callback selects the metadata-only wake-hint policy.
  • scheduleOptions
    Validated exact runtime role and Schedule clock/lease safety settings.
  • configure
    Optional process-local activation settings.

Returns

A builder that can explicitly add continuous host activation.

Exceptions

  • ArgumentException
    The runtime connection string does not identify a host and effective database.

Remarks

The supplied data sources must be distinct and configured with roles that are non-owner and free of BYPASSRLS . The identity check prevents reusing one data source for both roles, but cannot validate the database credentials; see the PostgreSQL role recipe . Registration validates the runtime host and effective database locally before adding services. The database may default to an explicit username, as in Npgsql; otherwise specify Database. This method performs no network I/O or DDL. Apply migrations with a separate migration-owner data source through IDurableRuntimeSchemaManager before a worker is started.

Method

ValidatePumpOverrideComposition

void ValidatePumpOverrideComposition(IServiceCollection services)

Rejects partial or visibly split opt-in admission overrides before package services are added.

Method

AddAppSurfaceDurableWorkerHost

IServiceCollection AddAppSurfaceDurableWorkerHost(this IServiceCollection services)

Adds the one critical continuous worker loop after passive PostgreSQL durable registration.

Remarks

Calling this method never applies migrations. Startup validates compatibility and the active recovery epoch, then fails closed if either is unsuitable. Repeated calls are idempotent.

Method

AddAppSurfaceDurablePostgreSqlFlowRetention

IServiceCollection AddAppSurfaceDurablePostgreSqlFlowRetention(this IServiceCollection services, NpgsqlDataSource retentionOperatorDataSource)

Adds the separately authorized verified Flow-retention client after PostgreSQL durable storage registration.

Parameters

  • services
    Application service registrations.
  • retentionOperatorDataSource
    Dedicated scope-bound retention-operator data source.

Returns

The original service collection.

Remarks

The retention operator is a fourth database role, distinct from migration owner, dispatcher, and runtime. It must not share a data source with either existing service role. This method performs no network I/O or DDL; use the schema manager to apply the explicit retention migration and authorize callers before invoking the client. See the PostgreSQL role recipe .

Type

PostgreSqlDurableRuntimeRegistration

Source

Captures the one immutable PostgreSQL durable runtime configuration for a service provider.

Parameters

  • DispatcherDataSource
    Payload-free dispatcher connection used only for global discovery.
  • RuntimeDataSource
    Scoped runtime connection used for durable mutations and heartbeats.
  • WorkOptions
    Validated active Work-store epoch and wake-hint policy.
  • ScheduleOptions
    Validated Schedule clock and lease safety configuration.
  • Options
    Validated process-local activation settings.
  • InstanceId
    Unique process-instance fence persisted with runtime heartbeats.
Type

PostgreSqlDurableHostedServiceMarker

Source

Marks that worker-host registration has occurred so repeated composition stays idempotent.

Type

PostgreSqlDurableFlowRetentionMarker

Source

Captures the retention-operator data source for duplicate registration detection.

Type

PostgreSqlDurableFlowRepairDescriptor

Source

Builds the canonical V1 descriptor digest for evidence-backed child-effect Flow repair.

Remarks

The digest binds the persisted suspension shape to the exact activity wait and child Work. Its field order and length-prefixed UTF-8 encoding are a durable compatibility contract: changing either requires a new SchemaId and a corresponding migration constraint.

Method

CreateDigest

string CreateDigest(string suspendedFromState, string code, string source, string workState, Guid waitId, DurableWorkId workId)

Creates the canonical SHA-256 digest of one child-effect suspension descriptor.

Parameters

  • suspendedFromState
    The persisted Flow state immediately before suspension.
  • code
    The stable suspension code.
  • source
    The stable suspension source.
  • workState
    The retained child Work state that caused suspension.
  • waitId
    The activity-wait identity bound to the child Work.
  • workId
    The child Work identity bound to the wait.

Returns

The lowercase hexadecimal SHA-256 descriptor digest.

Type

DurableRuntimeEpochRotationResult

Source

Reports an explicit compare-and-swap recovery-epoch rotation.

Parameters

  • PreviousEpoch
    Epoch active before rotation.
  • ActiveEpoch
    New epoch fencing prior runtimes.
  • RotatedAtUtc
    Authoritative PostgreSQL rotation timestamp.
Type

PostgreSqlDurableDiagnostics

Source

Holds canonical, value-free diagnostic destinations shared by PostgreSQL runtime components.

Type

PostgreSqlDurableFailureClassification

Source

Reports the allowlisted interpretation of one PostgreSQL control-plane failure.

Property

Diagnostic

DurableDiagnosticDescriptor? Diagnostic { get; } Source

Gets the canonical descriptor for a catalog-owned problem code, or null for unclassified failures.

Property

Propagate

PostgreSqlDurableFailureClassification Propagate { get; } Source

Gets the propagate-by-default classification.

Type

PostgreSqlDurableControlPlaneCommand

Source

Executes already-configured Npgsql commands with a cancellation sidecar derived from their inherited timeout.

Remarks

The helper does not assign NpgsqlCommand.CommandTimeout or alter connection settings. It records typed deadline evidence against the original exception before any boundary-specific translation. Non-query cancellation caused only by that package deadline becomes TimeoutException ; caller cancellation and every other failure preserve their concrete type, token, SQLSTATE, and stack. The helper is used only for schema status, health observation, and pre-execution runtime admission.

Method

ExecuteNonQueryAsync

2 overloads
ValueTask<int> ExecuteNonQueryAsync(NpgsqlCommand command, CancellationToken cancellationToken)

Executes a non-query control-plane command.

ValueTask<int> ExecuteNonQueryAsync(NpgsqlCommand command, CancellationToken cancellationToken, Func<CancellationToken, Task<int>> operation)

Executes a non-query control-plane operation and maps only package-owned deadline cancellation.

Parameters

  • command
    The configured command whose positive timeout defines the package deadline.
  • cancellationToken
    The caller-owned cancellation token.
  • operation
    The operation to execute with the effective cancellation token.

Returns

The number of rows affected by the operation.

Exceptions

  • TimeoutException
    Thrown when the package-owned command deadline expires before caller cancellation.
  • OperationCanceledException
    Propagates caller-owned cancellation without translating it.
Method

ExecuteScalarAsync

ValueTask<object?> ExecuteScalarAsync(NpgsqlCommand command, CancellationToken cancellationToken)

Executes a scalar control-plane command.

Method

ExecuteReaderAsync

ValueTask<TResult> ExecuteReaderAsync<TResult>(NpgsqlCommand command, Func<NpgsqlDataReader, CancellationToken, ValueTask<TResult>> projector, CancellationToken cancellationToken)

Executes and completely projects a control-plane reader while its deadline remains active.

Method

GetTimeoutEvidence

PostgreSqlDurableTimeoutEvidence GetTimeoutEvidence(Exception exception)

Gets deadline evidence recorded for the original exception.

Method

IsCancellationFrom

bool IsCancellationFrom(Exception exception, CancellationToken callerToken)

Reports whether the command's linked token propagated cancellation from this exact caller token.

Remarks

This provenance does not replace the original exception or its token. A doctor-owned deadline can therefore be recognized through the shared status reader while cancellation from an unrelated source still propagates.

Method

RecordTimeoutEvidence

void RecordTimeoutEvidence(Exception exception, PostgreSqlDurableTimeoutEvidence evidence)

Records package-owned deadline evidence while retaining the original exception object.

Method

ExecuteOperationAsync

ValueTask<TResult> ExecuteOperationAsync<TResult>(NpgsqlCommand command, CancellationToken cancellationToken, Func<CancellationToken, Task<TResult>> operation)

Executes one control-plane operation through the inherited command-timeout sidecar.

Remarks

This internal seam lets tests exercise cancellation precedence without depending on provider timer races. Production callers use the command-shaped helpers above.

Type

PostgreSqlDurableFailureClassifier

Source

Classifies only explicit, pre-execution PostgreSQL control-plane evidence.

Method

Classify

PostgreSqlDurableFailureClassification Classify(PostgreSqlDurableControlPlaneOperation operation, Exception exception, CancellationToken callerCancellationToken)

Returns an allowlisted unavailable or incompatible classification, otherwise the propagate result.

Method

ProblemForSchema

string ProblemForSchema(DurableRuntimeSchemaCompatibility compatibility)

Maps a schema compatibility value to its stable public problem code.

Method

DiagnosticForSchema

DurableDiagnosticDescriptor DiagnosticForSchema(DurableRuntimeSchemaCompatibility compatibility)

Gets the canonical descriptor for an existing schema-compatibility health/admission code.

Method

DiagnosticFor

DurableDiagnosticDescriptor? DiagnosticFor(string? problemCode)

Gets the canonical descriptor for a known code; unknown application codes remain unclassified.

Method

CanonicalProblemCode

string? CanonicalProblemCode(string? problemCode)

Returns a known internal health/admission code through its canonical descriptor.

Type

PostgreSqlDurableFlowActivityProjector

Source

Projects terminal or suspended child Work truth into its retained parent Flow activity wait in the same transaction.

Type

PostgreSqlDurablePumpOutcome

Source

Carries one private pump outcome, including the original exception required by the legacy projection.

Method

Completed

PostgreSqlDurablePumpOutcome Completed(DurableRuntimePumpResult result)

Creates a completed outcome with the exact provider result.

Method

Refused

PostgreSqlDurablePumpOutcome Refused(PostgreSqlDurablePumpRefusal refusal, ExceptionDispatchInfo? legacyException = null)

Creates a typed refusal, optionally retaining the exact legacy exception.

Method

Unavailable

PostgreSqlDurablePumpOutcome Unavailable(Exception exception)

Creates an unavailable result while retaining the original provider exception.

Method

Incompatible

PostgreSqlDurablePumpOutcome Incompatible(string problemCode, ExceptionDispatchInfo legacyException)

Creates an incompatible result while retaining the exact legacy exception.

Type

PostgreSqlDurablePumpFailureContext

Source

Associates an original pump exception with the phase that produced it.

Method

Mark

void Mark(Exception exception, PostgreSqlDurablePumpPhase phase)

Marks an exception without changing its type, message, token, inner exception, or stack.

Method

IsFinalizationFailure

bool IsFinalizationFailure(Exception exception)

Gets whether terminal finalization, rather than the active pass token, produced this failure.

Method

IsExecutionFailure

bool IsExecutionFailure(Exception exception)

Gets whether the sole application execution boundary produced this failure.

Type

PostgreSqlDurableAdmissionFailureContext

Source

Marks a store-admission failure that may have occurred after PostgreSQL accepted the pass-active mutation.

Method

MarkIndeterminate

void MarkIndeterminate(Exception exception)

Marks the original exception without wrapping it or changing its legacy projection.

Method

TakeIndeterminate

bool TakeIndeterminate(Exception exception)

Consumes whether ownership-scoped cleanup is required before this attempt projects the failure.

Type

PostgreSqlDurableFlowRetentionClient

Source

Implements the verified, one-Flow retention lifecycle over a scoped PostgreSQL retention-operator connection.

Remarks

The supplied connection must use the dedicated retention-operator role described by the PostgreSQL role recipe. It is not interchangeable with the runtime or dispatcher data source. The application authorizes every caller, stores archive bytes externally, and decides policy cadence; this client proves only protocol correspondence.

Method

MapManifestCreateProcedureOutcome

DurableOperationResult<DurableRetentionManifestCreateResult>? MapManifestCreateProcedureOutcome(DurableRetentionManifestCreateRequest request, string outcome)

Maps stable manifest-create procedure rejections before attempting to read a persisted manifest.

Remarks

Returns null for successful and duplicate outcomes that require a manifest read.

Method

MapLifecycleProcedureOutcome

DurableOperationResult<DurableRetentionMutationResult> MapLifecycleProcedureOutcome(DurableRetentionMutationRequest request, string outcome, string? state, long? sequence)

Maps one stable lifecycle procedure response into the public retention mutation result.

Type

PostgreSqlDurableFlowProcessorSettings

Source

Internal settings for one-transition Flow processing.

Type

IPostgreSqlDurableFlowBarrierObserver

Source

Observes committed protocol barriers used by subprocess crash certification.

Remarks

Observers run after the named database boundary commits and must preserve that ordering. They must not access the database or initiate another Flow operation, because observers exist only to certify recovery boundaries such as a deterministic subprocess termination.

Method

ObserveAsync

ValueTask ObserveAsync(string barrier, DurableScopeId scopeId, DurableFlowInstanceId instanceId, long revision, PostgreSqlFlowTelemetryEvidence? traceEvidence, CancellationToken cancellationToken)

Observes a committed Flow protocol barrier.

Parameters

  • barrier
    The stable name of the committed boundary.
  • scopeId
    The scope that owns the committed Flow transition.
  • instanceId
    The Flow instance that crossed the boundary.
  • revision
    The committed aggregate revision.
  • traceEvidence
    Value-free in-process activity evidence available at the committed boundary.
  • cancellationToken
    Cancellation for observer-only work after the commit.

Returns

A task that completes after the observer records the barrier.

Type

NoOpPostgreSqlDurableFlowBarrierObserver

Source

Provides the production barrier observer that preserves ordering without recording a checkpoint.

Type

PostgreSqlFlowDispatchCandidate

Source

Describes one payload-free Flow or timer dispatch candidate discovered by the dispatcher role.

Parameters

  • DispatchId
    The unique dispatch row identity.
  • ScopeId
    The owning durable scope.
  • Kind
    Whether the candidate evaluates a Flow or resolves a timer.
  • InstanceId
    The target Flow instance.
  • TimerId
    The timer identity for PostgreSqlFlowDispatchKind.Timer candidates.
  • DueAtUtc
    The time at which the candidate becomes eligible for processing.
  • ExpectedRevision
    The Flow revision that must still match when the candidate is claimed.
  • Priority
    The stable scheduler priority used when candidates share a due time.
Type

PostgreSqlFlowTelemetryEvidence

Source

Value-free in-process Activity evidence passed only to deterministic crash-test barriers.

Type

PostgreSqlFlowProcessingResult

Source

Reports the observable result of processing a single Flow dispatch candidate.

Parameters

  • Outcome
    The applied, terminal, fenced, or competing-transition outcome.
  • ScopeId
    The scope that owns the candidate.
  • InstanceId
    The Flow instance considered for processing.
  • State
    The resulting Flow state when a durable transition was observed.
  • Revision
    The resulting or observed Flow aggregate revision.
  • ChildWorkId
    The child Work accepted by an activity transition, when one was created.
  • ProblemCode
    The durable safety code when the Flow was suspended or rejected.
Type

PostgreSqlDurableFlowProcessor

Source

Discovers payload-free Flow/timer candidates and commits one replay-safe Flow transition at a time.

Remarks

Discovery uses only the dispatcher-role data source. Claim and mutation use only the scoped runtime-role source. Evaluation runs after the claim transaction releases every database resource.

Type

PostgreSqlDurableFlowClient

Source

Persists application-authorized durable Flow commands and payload-free queries in PostgreSQL.

Remarks

This client does not authenticate callers, apply schema migrations, or start a processor. Applications authorize the trusted DurableScopeId before calling it. The data source must use the scoped runtime role.

Method

StartAsync

ValueTask<DurableOperationResult<DurableFlowCommandResult>> StartAsync(DurableFlowStartRequest request, CancellationToken cancellationToken = default)

Remarks

Validates context through the selected allowlisted codec. Definition-owned and provider-owned views of the same captured source are compatible. Captured guards are retained if a custom registry selects that source directly; equal metadata from unrelated sources is rejected before storage.

Type

PostgreSqlDurableScheduleOptions

Source

Controls the PostgreSQL Schedule processor's runtime-role and temporal safety fences.

Remarks

The role name is checked with current_user before a Schedule processor sets its scoped RLS setting or bridges an occurrence to Work. The safety window limits how far a single database-clock observation may advance an interval cursor; a larger jump suspends rather than consumes future occurrences.

Property

RuntimeRole

string RuntimeRole { get; } Source

Gets the exact role required before Schedule bridge scope is set.

Property

MaximumClockAdvance

TimeSpan MaximumClockAdvance { get; } Source

Gets the maximum safe single-pass database-clock advance beyond a stored cursor.

Property

LeaseDuration

TimeSpan LeaseDuration { get; } Source

Gets the dispatcher-owned Schedule discovery lease duration, capped at ten minutes.

Type

PostgreSqlDurableScheduleProcessor

Source

Runs one bounded, manually invoked PostgreSQL Schedule due pass.

Remarks

The processor first claims a payload-free dispatch lease through the dispatcher data source, then opens a separate scoped runtime transaction to record and bridge Schedule facts. It does not start a loop, execute Work, invoke a provider, or start Flow targets. Cancellation is observed before each additional lease; work already committed by a prior claim remains durable.

Method

ProcessDueAsync

ValueTask<PostgreSqlDurableScheduleProcessResult> ProcessDueAsync(PostgreSqlDurableScheduleProcessRequest request, CancellationToken cancellationToken = default)

Claims and processes up to the requested number of eligible Schedule dispatch rows.

Parameters

  • request
    Bounded pass identity and maximum claim count.
  • cancellationToken
    Cancels before the next lease; it never undoes a committed Schedule fact.

Returns

Counts of claimed Schedule rows and resulting durable facts. An empty pass returns zero counts.

Type

PostgreSqlDurableProtocolCodec

Source

Centralizes fail-closed conversion between PostgreSQL protocol values and Durable contract enums.

Method

ParseWorkState

DurableWorkState ParseWorkState(string state)

Projects one persisted Work state or rejects an unknown value as corruption.

Method

FormatProviderSafety

string FormatProviderSafety(DurableProviderSafety safety)

Formats one supported provider-safety value for persistence.

Method

ParseProviderSafety

DurableProviderSafety ParseProviderSafety(string value)

Parses one persisted provider-safety value or rejects corruption.

Method

FormatClassification

string FormatClassification(DurableDataClassification classification)

Formats one supported payload classification for persistence.

Method

ParseClassification

DurableDataClassification ParseClassification(string value)

Parses one persisted payload classification or rejects corruption.

Type

AppSurfaceDurablePostgreSqlModule

Source

Declares the host-neutral durable module dependency for applications configuring PostgreSQL explicitly.

Remarks

This module does not create data sources, choose database credentials, apply migrations, or start a worker. Call AppSurfaceDurablePostgreSqlServiceCollectionExtensions.AddAppSurfaceDurablePostgreSql with the application's reviewed dispatcher and runtime data sources, then opt into AddWorkerHost only where continuous activation is intended.

Type

IDurableRuntimeExecutionBoundary

Source

Owns the per-invocation execution seam that later tracing integration instruments.

Remarks

Slice 6 deliberately makes this a no-op wrapper. Durable Flow trace context, Activities, links, tags, and exports remain #685's responsibility; its narrow integration can replace this implementation without changing claim, permit, completion, or hosted-lifecycle ownership.

Method

InvokeExitAsync

ValueTask<DurableEncodedWorkExit> InvokeExitAsync(DurablePreparedWorkInvocation invocation, CancellationToken cancellationToken)

Invokes one prepared provider operation and returns its encoded exit fact.

Remarks

Forwards cancellation to provider execution and owns no claim, permit, completion, or tracing state.

Type

PostgreSqlDurableRuntimeSchemaManager

Source

Implements explicit package-owned durable schema operations for PostgreSQL.

Remarks

Migration and epoch mutations hold one session advisory lock across their individual transactions. The session scope is required to prevent another migration owner from interleaving between migrations; lock acquisition is nevertheless bounded and cancellation-aware, and the owning connection is always disposed after the mutation so PostgreSQL releases the lock even when explicit cleanup cannot run.

Method

CanShareStatusConnectionWith

bool CanShareStatusConnectionWith(NpgsqlDataSource dataSource)

Returns whether a runtime operation may safely reuse this manager's status connection.

Parameters

  • dataSource
    The runtime data source that would reuse the connection.

Returns

true only when both operations use the same data-source instance and therefore the same credentials, pool, and connection policy.

Method

OpenStatusConnectionAsync

ValueTask<NpgsqlConnection> OpenStatusConnectionAsync(CancellationToken cancellationToken)

Opens a schema-status connection while preserving the status-acquisition observation seams.

Parameters

  • cancellationToken
    Cancels the pending pool or connection acquisition.

Returns

An open connection owned by the caller.

Method

GetStatusAsync

ValueTask<DurableRuntimeSchemaStatus> GetStatusAsync(NpgsqlConnection connection, CancellationToken cancellationToken)

Reads schema status through an existing connection so a compatible runtime observation can reuse one pool acquisition without changing the migration-fence transaction boundary.

Parameters

  • connection
    An open connection whose credentials are valid for schema status.
  • cancellationToken
    Cancels the status transaction and commands.

Returns

The installed schema compatibility status.

Method

ReadStatusInTransactionAsync

ValueTask<DurableRuntimeSchemaStatus> ReadStatusInTransactionAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken)

Reads schema compatibility and migration checksums inside a caller-owned transaction.

Parameters

  • connection
    The open connection that owns transaction .
  • transaction
    The active transaction whose snapshot must include the status read.
  • cancellationToken
    Cancels status queries; cancellation is propagated to the caller.

Returns

The same schema status produced by the manager's existing compatibility and checksum reader.

Remarks

This internal reuse seam neither opens a connection nor acquires a migration fence. It does not begin, commit, roll back, or dispose the supplied transaction or connection. The caller owns transaction boundaries, connection lifetime, fencing and snapshot selection. A canceled read may leave the caller's transaction needing rollback; this method deliberately does not perform that cleanup on the caller's behalf.

Method

ReadDoctorStatusInTransactionAsync

ValueTask<DurableRuntimeSchemaStatus> ReadDoctorStatusInTransactionAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken)

Reads the authoritative schema status for the non-mutating doctor with bounded migration-history capture.

Parameters

  • connection
    The open connection that owns transaction .
  • transaction
    The caller-owned transaction whose snapshot must include the status read.
  • cancellationToken
    Cancels status queries; cancellation is propagated to the caller.

Returns

The same authoritative schema status used by ReadStatusInTransactionAsync .

Remarks

This internal reuse seam does not open a connection or begin, commit, roll back, or dispose the supplied transaction or connection. The executing migration catalog, pending-version projection, and retained migration history are each bounded to 64 versions; a 65th history row is detected before retention. It also requires migration names and digests to have canonical, package-bounded ASCII shapes. A history or scalar that violates this doctor contract throws an InvalidOperationException with fixed, non-data-bearing text. Compatibility, contiguity, and checksum mismatches continue through the same authoritative algorithm as ReadStatusInTransactionAsync .

Method

GenerateScript

string GenerateScript(int fromVersion = 0)

Remarks

The generated script keeps a session-scoped lock because each migration has its own transaction. Lock acquisition is bounded inside a short transaction, and callers must stop on errors and close the session if a migration fails before the final explicit unlock.

Method

ApplyAsync

ValueTask<DurableRuntimeSchemaApplyResult> ApplyAsync(CancellationToken cancellationToken = default)

Remarks

Programmatic lock acquisition uses non-blocking polling with a 30-second deadline by default. Cancellation remains distinct from lock contention; a deadline failure is reported as a TimeoutException with the lock identifier and operator guidance. The lock is released explicitly on every acquired path and by disposing the owning connection as a final safety net.

Method

ValidateConnectionAsync

ValueTask ValidateConnectionAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken)

Validates schema compatibility on the connection and transaction that already hold runtime admission's migration fence.

Property

RequiredVersion

int RequiredVersion { get; } Source

Gets the schema version required by this package.

Type

DurableRuntimeSchemaApplyResult

Source

Describes one explicit migration application.

Property

PreviousVersion

int PreviousVersion { get; } Source

Gets the version before application.

Property

CurrentVersion

int CurrentVersion { get; } Source

Gets the version after application.

Property

AppliedVersions

IReadOnlyList<int> AppliedVersions { get; } Source

Gets the versions applied by this operation.

Type

PostgreSqlDurableControlClient

Source

Implements application-authorized Work inventory, cancellation, and scope fencing over PostgreSQL.

Remarks

This is an internal provider implementation of the public Provider SPI. Applications must authorize an operation before calling it; opaque scope and aggregate identities are not authorization grants.

Type

PostgreSqlDurableWorkTransactionWriter

Source

Writes durable Work directly into a caller-owned Npgsql transaction.

Type

PostgreSqlDurableScheduleProcessRequest

Source

Requests one bounded, manually invoked PostgreSQL Schedule processing pass.

Remarks

This is a passive provider operation. Applications may call it from an external trigger or test, but must not loop it in an ASP.NET request or register hosted work; hosted activation requires the explicit AddWorkerHost() opt-in.

Property

LeaseOwner

string LeaseOwner { get; } Source

Gets the opaque processor identity recorded on a transient dispatch lease.

Property

MaximumSchedules

int MaximumSchedules { get; } Source

Gets the maximum number of Schedule rows the pass may claim.

Type

PostgreSqlDurableScheduleProcessResult

Source

Reports the durable facts produced by one bounded Schedule processing pass.

Property

ClaimedSchedules

int ClaimedSchedules { get; } Source

Gets the number of payload-free dispatch rows claimed by this pass.

Property

RecordedOccurrences

int RecordedOccurrences { get; } Source

Gets the number of new or coalesced Schedule occurrence facts recorded.

Property

MaterializedWorkTargets

int MaterializedWorkTargets { get; } Source

Gets the number of Work target identities materialized by this pass.

Property

SuspendedSchedules

int SuspendedSchedules { get; } Source

Gets the number of Schedules suspended by a safety fence.

Type

DurableRuntimeAdmissionGate

Source

Coordinates process-local pass admission with synchronous shutdown initiation.

Method

TryEnter

bool TryEnter()

Returns whether a new pass may start without acquiring or reserving any separate release handle.

Remarks

A successful result permits admission only; callers must still serialize active passes independently.

Method

Close

void Close()

Rejects future admissions without waiting for or cancelling an in-flight pass.

Method

Reopen

void Reopen()

Allows future admissions after a controlled drain rollback or recovery decision.

Type

PostgreSqlExecutionOperatorDecision

Source

A closed, side-effect-free operator truth decision under already validated identity and locks.

Method

Evaluate

PostgreSqlExecutionOperatorDecision Evaluate(PostgreSqlWorkExecutionRow row, string requestedState, DurableEffectReconciliationKind? proof, bool? hasOtherUncertainEffect = null)

Checks immutable retry eligibility without granting authority or executing a projection.

Parameters

  • row
    Accepted timing and effect facts under the canonical Work lock.
  • requestedState
    Validated operator transition before timing classification.
  • proof
    Exact authorized effect proof, or null for retry/recovery.
  • hasOtherUncertainEffect
    For a selected operator permit, whether another admitted effect remains unresolved. Null preserves current-attempt classification through HasUncertainPriorEffect.

Remarks

Applied establishes existing effect truth; NotApplied clears only its selected exact permit; Unknown never expires into absence.

Type

PostgreSqlDurableExecutionCheckpointObservation

Source

Immutable payload-free facts passed to the internal execution checkpoint seam.

Type

PostgreSqlDurableExecutionCheckpointHook

Source

Observes an execution checkpoint without changing production policy or provider authority.

Remarks

The production instance has no callback and completes synchronously. Test hosts may supply one callback. Provider-call checkpoints are emitted only by an adopter-controlled fake executor that knows where its call occurs; the pump does not claim to detect arbitrary effects inside application code.

Type

PostgreSqlDurableFlowTrace

Source

Identifies transaction-local trace evidence before it is attached to its committed Flow lineage.

Type

PostgreSqlDurableScheduleWorkProjector

Source

Requeues a QueueOne Schedule when its materialized Work target reaches terminal truth.

Remarks

The Work store invokes this projector in the same transaction that commits terminal Work truth. That makes a coalesced occurrence eligible immediately, without relying on the Schedule's normal interval to wake it.

The definition row is locked before its dispatch row is updated. Schedule processing takes the same definition lock, so a terminal Work transition cannot race a pending occurrence from one active generation into a later generation.

Method

RequeuePendingOccurrenceAsync

ValueTask RequeuePendingOccurrenceAsync(NpgsqlTransaction transaction, DurableScopeId scopeId, DurableWorkId workId, CancellationToken cancellationToken)

Requeues a pending coalesced Schedule occurrence after its Work target becomes terminal.

Parameters

  • transaction
    The authoritative Work transition transaction.
  • scopeId
    The durable scope containing the completed Work target.
  • workId
    The terminal Work target that may release one QueueOne Schedule slot.
  • cancellationToken
    Cancels the database operation before it commits.
Type

DurableRuntimeSchemaStatus

Source

Reports the durable PostgreSQL schema identity, version, epoch, and compatibility.

Property

Compatibility

DurableRuntimeSchemaCompatibility Compatibility { get; } Source

Gets the compatibility verdict.

Property

StoreId

Guid StoreId { get; } Source

Gets the immutable store identity, or empty when unavailable.

Property

ActiveRuntimeEpoch

Guid? ActiveRuntimeEpoch { get; } Source

Gets the active recovery epoch, or null before explicit initialization.

Property

InstalledVersion

int InstalledVersion { get; } Source

Gets the highest installed migration version.

Property

RequiredVersion

int RequiredVersion { get; } Source

Gets the schema version required by this package.

Property

MinimumReaderVersion

int MinimumReaderVersion { get; } Source

Gets the oldest runtime protocol allowed to read.

Property

MaximumReaderVersion

int MaximumReaderVersion { get; } Source

Gets the newest runtime protocol allowed to read.

Property

MinimumWriterVersion

int MinimumWriterVersion { get; } Source

Gets the oldest runtime protocol allowed to write.

Property

MaximumWriterVersion

int MaximumWriterVersion { get; } Source

Gets the newest runtime protocol allowed to write.

Property

AppliedVersions

IReadOnlyList<int> AppliedVersions { get; } Source

Gets an immutable copy of ordered applied migration versions.

Property

PendingVersions

IReadOnlyList<int> PendingVersions { get; } Source

Gets an immutable copy of ordered pending migration versions.

Property

Problem

string? Problem { get; } Source

Gets the actionable incompatibility explanation, when present.

Property

IsCompatible

bool IsCompatible { get; } Source

Gets whether schema reads and writes may begin.

Type

DurableRuntimeEpochActivationResult

Source

Reports explicit one-time activation of a store recovery epoch.

Parameters

  • ActiveEpoch
    Epoch activated for this store.
  • ActivatedAtUtc
    Authoritative PostgreSQL activation timestamp.
Type

PostgreSqlDurableScheduleClient

Source

PostgreSQL implementation of the durable Schedule client.

Remarks

This client persists Schedule command, generation, and occurrence facts but does not start a hosted loop. Use PostgreSqlDurableScheduleProcessor to run one bounded, manually invoked due pass. The initial implementation admits Work targets only because it can atomically compose the existing caller-owned Work writer. Callers must authorize the Schedule scope before invoking this client. Configure distinct non-owner, non- BYPASSRLS dispatcher and runtime login roles with the documented PostgreSQL role recipe , and apply schema version 4 before accepting Schedule work. Hosted activation is intentionally deferred; this client and processor never register or start a background loop.

Type

PostgreSqlDurableWorkContractSelection

Source

An immutable, provider-owned snapshot of the Work contracts that a host may discover.

Remarks

This selection is created while the runtime pump is resolved. It intentionally never rereads a custom registry, so later registry mutation cannot widen a running host's discovery authority.

Method

AddDiscoveryParameters

void AddDiscoveryParameters(NpgsqlParameterCollection parameters, int maximumCandidates)

Adds the immutable selection arrays to a Work-discovery command without rebuilding them for every poll.

Property

IsEmpty

bool IsEmpty { get; } Source

Gets whether this host registered no Work contracts.

Remarks

Callers use this fail-closed gate to avoid invoking discovery with an empty contract array, which PostgreSQL rejects.

Type

AppSurfaceDurablePostgreSqlBuilder

Source

Continues PostgreSQL durable registration while keeping storage and continuous activation separate.

Method

AddWorkerHost

AppSurfaceDurablePostgreSqlBuilder AddWorkerHost()

Adds the single critical host adapter that continuously invokes the bounded runtime pump.

Remarks

Use this only in a continuously live worker process. Query-only hosts, migration tools, tests, and scale-to-zero deployments keep storage registration passive and may invoke IDurableRuntimePump from their own activator instead.

Property

Services

IServiceCollection Services { get; } Source

Gets the application service collection under configuration.

Type

PostgreSqlWorkExecutionRow

Source

Closed persisted opt-in facts read under the canonical scope/Work/dispatch/permit locks.

Remarks

NowUtc is sampled after every row lock, never before a wait. This row grants no capability.

Method

AdmissionReason

string? AdmissionReason(bool consumesNextAttempt)

Safe permanent admission refusal, or null; current-slot admission does not consume a new slot.

Method

Matches

bool Matches(PostgreSqlDurableWorkClaim claim)

Checks the exact current attempt and lease without trusting the caller's snapshot or clock.

Property

DeadlineReachedAtUtc

DateTimeOffset? DeadlineReachedAtUtc { get; init; } Source

A permanently observed absolute deadline, independent of the first admission closure reason.

Property

HasUncertainPriorEffect

bool HasUncertainPriorEffect { get; init; } Source

Unresolved admitted effects from earlier attempts cannot be cleared by a current no-effect proof.

Property

UnresolvedPermit

PostgreSqlExecutionPermitIdentity? UnresolvedPermit { get; init; } Source

The latest unresolved admitted permit, kept separate from the current Work attempt.

Property

UnresolvedPermitCount

int UnresolvedPermitCount { get; init; } Source

The number of admitted permits whose external effects remain unresolved under the Work lock.

Property

ExecutionSnapshot

DurableWorkExecutionSnapshot ExecutionSnapshot { get; } Source

Descriptive persisted timing facts for inspection; no authorization is conveyed.

Property

CutoffUtc

DateTimeOffset CutoffUtc { get; } Source

Frozen cutoff; an elapsed horizon closes admission, not a current admitted success.

Property

NextEligibilityUtc

DateTimeOffset NextEligibilityUtc { get; } Source

Next acceptance-relative eligibility; consumed attempts are never rebased or skipped.

Type

PostgreSqlExecutionPermitIdentity

Source

Exact locked identity of an admitted permit selected for authorized proof, never invocation.

Parameters

  • PermitId
    Persisted permit UUID for this exact admitted invocation.
  • AttemptNumber
    Original consumed attempt number.
  • LeaseGeneration
    Original claim lease generation.
  • ScopeGeneration
    Scope generation captured by the permit.
  • RuntimeEpoch
    Epoch recorded on the selected permit, including prior recovery epochs.
Type

IDurableWorkHandoffFence

Source

Validates the current native invocation and prepares an application handoff in its caller's transaction.

Remarks

Resolve this scoped service through AddAppSurfaceDurablePostgreSql and use it only inside the actual Work executor. The caller owns an active ReadCommitted transaction targeting the configured store. The callback must use only that transaction and connection, acquire application locks after native locks, and perform database work only. It must not complete or dispose the transaction, perform provider I/O, or escape work past invocation exit. Await the operation and complete and dispose caller resources inside the invocation before provider I/O. Preparation is provisional until caller commit; an uncertain commit requires application-ledger and existing provider-safety reconciliation. See the package's handoff reference for lock ordering, host timeout prerequisites, and cooperation limits.

Method

ExecuteAsync

ValueTask<DurableOperationResult<DurableWorkHandoffResult>> ExecuteAsync(NpgsqlTransaction transaction, Func<NpgsqlTransaction, CancellationToken, ValueTask<bool>> authorizeAndRecordHandoff, CancellationToken cancellationToken = default)

Runs one application authorization and conditional handoff write under current native fences.

Parameters

  • transaction
    Exact caller-owned, uncommitted ReadCommitted transaction on an open connection.
  • authorizeAndRecordHandoff
    Database-only callback, called at most once with the supplied resources and token.
  • cancellationToken
    Caller cancellation; observed cancellation before the final check removes operation writes.

Returns

A provisional preparation, successful denial after removing callback writes, or a bounded native refusal.

Exceptions

  • ArgumentNullException
    A required argument is null.
  • InvalidOperationException
    Resources, target or isolation are invalid, or a call overlaps or reenters.
  • OperationCanceledException
    Cancellation is observed before the final success check, or the callback throws cancellation.
  • AggregateException
    Cleanup fails after another failure; both causes are retained and outer rollback/disposal is required.

Remarks

Sequential calls are allowed; application conditional writes govern duplicates. There are no callback retries. SQL and transport exceptions propagate after feasible savepoint cleanup. Cleanup never completes the outer transaction. A cancellation signal after the last check cannot retroactively change preparation; check the token before committing and reconcile a failed or ambiguous commit before sending. An improper callback commit cannot be undone by the framework. The result is not delivery confirmation or authority transferable outside this invocation.

Type

DurableWorkHandoffResult

Source

Describes whether the callback prepared an application handoff that still requires caller commit.

Parameters

  • HandoffPrepared
    True for provisional preparation; false for application denial with callback writes removed.
Type

IDurableWorkTransactionWriter

Source

Accepts durable Work through the caller's exact active PostgreSQL transaction.

Remarks

The writer never opens, commits, rolls back, replaces, or disposes the supplied transaction. Domain state and Work acceptance therefore commit or roll back together in the same database.

Method

EnqueueAsync

ValueTask<DurableOperationResult<DurableWorkAcceptance>> EnqueueAsync(NpgsqlTransaction transaction, DurableWorkRequest request, CancellationToken cancellationToken = default)

Writes one durable acceptance without taking ownership of the transaction.

Parameters

  • transaction
    Caller-owned active Npgsql transaction.
  • request
    Validated Work request.
  • cancellationToken
    Cancellation token.

Returns

The stable new or duplicate acceptance, or an actionable domain problem.

Exceptions

  • ArgumentNullException
    Thrown when transaction or request is null.
  • InvalidOperationException
    Thrown when the transaction is disposed, inactive, closed, or targets a different PostgreSQL store.
  • DurableRuntimeSchemaException
    Thrown with safe schema status when the durable schema is absent or incompatible. When a PostgreSQL error exposed the missing schema, Exception.InnerException retains that original failure.
  • NpgsqlException
    The original PostgreSQL or transport failure. The caller must roll back the transaction.
Type

PostgreSqlDurableWorkHandoffFence

Source

Scoped, invocation-bound savepoint protocol; owns no caller resources or native transitions.

Method

EnterInvocation

IDisposable EnterInvocation(PostgreSqlEffectPermit permit)

Enters authority only around executor invocation after permit commit and existing admission.

Remarks

The immutable permit identity does not cache renewal-sensitive expiry or revision. Dispose deactivates inherited contexts.

Method

RestoreScopeAsync

ValueTask RestoreScopeAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, string? priorScope, CancellationToken token)

Restores caller scope with an intentional cleanup barrier; a failure requires caller recovery.

Method

ReleaseSavepointAsync

ValueTask ReleaseSavepointAsync(NpgsqlTransaction transaction, string savepoint, CancellationToken token)

Releases an established savepoint with an intentional cleanup barrier; owns no outer transaction.

Method

SetScopeAsync

ValueTask SetScopeAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, string? scope, CancellationToken token)

Restores effective scope including the empty/no-scope state; never changes the role or session defaults.

Type

PostgreSqlDurableHandoffCheckpointHook

Source

Intentional internal test seam; carries no payload or authority and exposes no public binder.

Type

PostgreSqlDurableHostedService

Source

Host lifecycle adapter that schedules the one authoritative bounded PostgreSQL runtime pump.

Remarks

This service is registered only by explicit worker-host composition. It does not apply schema migrations and does not own durable correctness: the store still owns claims, leases, permits, fencing, and durable history.

Method

CalculatePassShutdownWindow

TimeSpan CalculatePassShutdownWindow()

Calculates the execution window left after finalization and cleanup reserves are protected.

Method

HasProviderDeadlineEvidence

bool HasProviderDeadlineEvidence(Exception exception)

Reports whether package-owned evidence proves that the provider command deadline elapsed.

Type

PostgreSqlDurableWorkOptions

Source

Controls PostgreSQL Work acceptance for one validated store and runtime epoch.

Property

RuntimeEpoch

Guid RuntimeEpoch { get; } Source

Gets the active out-of-band recovery epoch.

Property

ExpectedStoreId

Guid ExpectedStoreId { get; } Source

Gets the expected physical durable store identity.

Property

WakeNotificationMode

PostgreSqlDurableWakeNotificationMode WakeNotificationMode { get; } Source

Gets whether acceptance emits a metadata-only PostgreSQL wake hint.

Type

DurablePostgreSqlMigration

Source

Describes one ordered, checksum-verified PostgreSQL migration and any client execution override it owns.

Parameters

  • Version
    The contiguous, one-based schema version.
  • Name
    The stable migration name parsed from the embedded resource.
  • Sql
    The normalized migration SQL.
  • Sha256
    The lowercase SHA-256 digest of Sql .
  • CommandTimeoutSeconds
    An optional positive client command timeout for migration SQL whose bounded server-side work exceeds the data source default. null preserves the configured data-source timeout.
Enum

PostgreSqlDurableStoreAdmissionKind

Source

Identifies the authoritative store-admission outcome before application execution.

Enum

PostgreSqlDurableControlPlaneOperation

Source

Identifies the bounded PostgreSQL control-plane operation that observed a failure.

Enum

PostgreSqlDurableFailureDisposition

Source

Identifies whether a control-plane failure is safe to return or must propagate.

Enum

PostgreSqlDurableUnavailableCause

Source

Identifies the fixed, value-free diagnostic cause for an unavailable store assessment.

Enum

PostgreSqlDurableTimeoutEvidence

Source

Identifies package-owned evidence that an inherited provider command deadline elapsed.

Enum

PostgreSqlDurablePumpPhase

Source

Identifies the linear phase reached by one PostgreSQL pump attempt.

Enum

PostgreSqlDurablePumpRefusal

Source

Identifies the typed pre-execution cause of a refused pump attempt.

Enum

PostgreSqlDurablePumpOutcomeKind

Source

Identifies the private outcome projected through the two public pump contracts.

Enum

PostgreSqlFlowDispatchKind

Source

Classifies the payload-free dispatch row that initiated Flow processing.

Enum

PostgreSqlFlowProcessingOutcome

Source

Describes the durable outcome of attempting to process one Flow dispatch candidate.

Enum

DurableRuntimeSchemaCompatibility

Source

Describes whether the installed durable schema can be used by this package.

Enum

PostgreSqlDurableExecutionCheckpointName

Source

Names an internal boundary in one opt-in PostgreSQL Work execution.

Enum

PostgreSqlDurableHandoffCheckpoint

Source

Internal deterministic barriers for the final decision and cleanup; production has no callback.

Enum

PostgreSqlDurableWakeNotificationMode

Source

Controls advisory PostgreSQL wake notifications after Work acceptance.