@dbsp/adapter-pgsql 7.3.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { C as ChangeKind, G as GeneratedPostconditionSession, S as SqlIdentifier, a as CompilerContext, b as CompilerState, D as Decision, P as ProjectionEnvelope, T as TransitionJournalQueryable, c as PgLockedRun, d as PgOutcomeCheckpointObserver, e as ConvergePgOptions$1, f as PgPhysicalModel, g as PgConvergeResult, h as PgConvergeCheckResult, i as PgLedgerScopeCurrency, r as readTransitionJournal } from './outcome-protocol-BhYhYQPC.js';
2
- export { A as AddedEnumValue, j as AutoIncrementTransitionUnsupportedError, k as CanonicalizeCheckConstraintsOptions, l as CheckConstraintCanonicalizationError, m as CheckConstraintCanonicalizationWarning, n as CheckConstraintNewEnumValueError, o as ColumnDefaultCanonicalizationError, p as ColumnDefaultCanonicalizationWarning, q as ComparePgDatabaseSchemaOptions, s as CompareSchemataOptions, t as DEFAULT_PK_COLUMN, u as DetectedHierarchy, v as DiffSummary, E as ExpressionCanonicalizationUnavailableError, w as ExpressionCanonicalizationWarning, x as ExpressionHandler, y as ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError, F as FkColumnDerivation, z as GenerateDDLOptions, B as GeneratedPostcondition, H as GeneratedPostconditionBindingAddress, I as GeneratedPostconditionBindingResolutionError, J as GeneratedPostconditionProofInFlightError, K as GeneratedPostconditionReplanRequiredError, L as GeneratedPostconditionSessionDeactivatedError, M as GeneratedPostconditionWorkInFlightError, N as IncludeHandler, O as IncludeResult, Q as IndexCapabilityContext, R as IndexFeatureUnsupportedError, U as IndexPredicateCanonicalizationError, V as IndexRenderSpec, W as IntrospectedModelIR, X as IntrospectionOptions, Y as MigrationSQLOptions, Z as NonConvergentSchemaDiffError, _ as NonConvergentSchemaDiffSurface, $ as PG_LEDGER_SHAPE_VERSION, a0 as PartialIndexPredicateNewEnumValueError, a1 as PgAdapter, a2 as PgAdapterOptions, a3 as PgAdmittedOperation, a4 as PgAdmittedOperationResult, a5 as PgAdvisoryLockKey, a6 as PgAdvisoryLockOptionsError, a7 as PgAdvisoryLockResult, a8 as PgApplicationStepOwnedState, a9 as PgApplicationStepTx, aa as PgBorrowedClientAdapterOptions, ab as PgCatalogueIdentityQueryable, ac as PgCompileOnlyAdapterOptions, ad as PgConvergeApplicationStep, ae as PgConvergeAssertStep, af as PgConvergeInitializationFailure, ag as PgConvergeOnceStep, ah as PgConvergePlannedStep, ai as PgConvergeRefusal, aj as PgConvergeRefusalChange, ak as PgConvergeRefusalError, al as PgLedgerLockResult, am as PgLedgerStorageUnsupportedError, an as PgLedgerTarget, ao as PgOutcomeCheckpoint, ap as PgOutcomeClaimRequest, aq as PgOutcomeExecutionRequest, ar as PgOutcomeNonTransactionalRequest, as as PgOutcomeReadBackFactory, at as PgOutcomeRecoveryRequest, au as PgOutcomeRecoveryResult, av as PgOutcomeResolution, aw as PgOutcomeResolutionAppendResult, ax as PgOutcomeResult, ay as PgOutcomeTransactionalRequest, az as PgOwnedCheckState, aA as PgPhysicalModelInput, aB as PgPhysicalModelInputError, aC as PgPhysicalNameClaim, aD as PgPhysicalNameCollision, aE as PgPhysicalNameCollisionError, aF as PgPhysicalNamespace, aG as PgPinnedConnectionAbortSignalError, aH as PgPoolAdapterOptions, aI as PgPreparedStatementReplayError, aJ as PgPreparedStatementsOptions, aK as PgRawSqlTransactionControlError, aL as PgReinitializePreflightOptions, aM as PgReinitializePreflightPool, aN as PgRollbackOnlyScope, aO as PgSchemaDiff, aP as PgTransactionAbortSignalError, aQ as PgTransactionAbortedCommitError, aR as PgTransactionAbortedError, aS as PgTransactionOptionsError, aT as PgTransactionTimeoutError, aU as RawIndexPredicateFallbackError, aV as ReferencedKeyKind, aW as ReferencedKeyRemovalConflict, aX as ReferencedKeyRemovalError, aY as SchemaChange, aZ as SchemaDiff, a_ as SchemaScopeOptions, a$ as TransitionRunIdentityMismatchError, b0 as WhereDispatcher, b1 as WhereHandler, b2 as acquirePgLedgerLocks, b3 as appendIntentJournal, b4 as appendTransitionAuthorization, b5 as assertCreateIndexSupported, b6 as assertCreateIndexesSupported, b7 as assertDeclarableChangeKind, b8 as assertGeneratedPostconditionSession, b9 as assertNoRepeatedExpressionSurfaceDrift, ba as canGenerateCreateIndex, bb as canonicalizeCheckConstraints, bc as comparePgDatabaseSchema, bd as compareSchemata, be as createPgAdapter, bf as createPgCompileOnlyAdapter, bg as createPgGeneratedManagedStep, bh as createPgPhysicalModel, bi as createPgTransitionRunPersister, bj as decodeGeneratedPostcondition, bk as decodeGeneratedPostconditionPayload, bl as defaultFkDerivation, bm as ensureDbspMetaLedger, bn as ensurePgLedger, bo as ensurePgLedgerStorageVersion, bp as ensureTransitionJournal, bq as executePgAdmittedOperation, br as generateCreateIndex, bs as generateDDL, bt as generateDownSQL, bu as generateMigrationSQL, bv as generatedPostconditionDigest, bw as generatedPostconditionForChange, bx as introspect, by as readPgCatalogueIdentity, bz as readPgLedgerMarker, bA as readPgLedgerReservationsForExecution, bB as readPgLedgerScopeCurrency, bC as readPgOutcomeRecoveryReadBack, bD as readVerifiedPgLedgerReservationsForPair, bE as recordPgLedgerIdentity, bF as renderCreateDbspMetaSchemaSql, bG as renderCreateIndex, bH as renderCreateLedgerEventTableSql, bI as renderCreateLedgerIdentityTableSql, bJ as renderCreateLedgerImmutabilityFunctionSql, bK as renderCreateLedgerImmutabilityTriggerSql, bL as renderCreateLedgerMarkerTableSql, bM as renderCreateLedgerReservationTableSql, bN as renderCreateLedgerTerminalMemberIndexSql, bO as renderCreateTransitionAuthorizationTableSql, bP as renderCreateTransitionJournalTableSql, bQ as renderCreateTransitionRunPlanTableSql, bR as renderCreateTransitionRunTableSql, bS as runPgReinitializePreflight, bT as toGeneratedPostconditionBindingAddress, bU as validatePgLedgerRuntimeIntegrity, bV as verifyGeneratedCheckPostcondition, bW as verifyGeneratedColumnPostcondition, bX as verifyGeneratedIdentityPostcondition, bY as verifyGeneratedIndexPostcondition, bZ as verifyGeneratedTablePostcondition, b_ as withGeneratedPostconditionSession } from './outcome-protocol-BhYhYQPC.js';
3
- import { ExpressionRef, ModelIR } from '@dbsp/core';
1
+ import { C as ChangeKind, G as GeneratedPostconditionSession, S as SqlIdentifier, a as CompilerContext, b as CompilerState, D as Decision, T as TransitionJournalQueryable, P as PgLockedRun, c as PgOutcomeCheckpointObserver, d as ConvergePgOptions$1, e as PgPhysicalModel, f as PgConvergeResult, g as PgConvergeCheckResult, h as PgLedgerScopeCurrency, r as readTransitionJournal } from './outcome-protocol-SJC5Zk63.js';
2
+ export { A as AddedEnumValue, i as AutoIncrementTransitionUnsupportedError, j as CanonicalizeCheckConstraintsOptions, k as CheckConstraintCanonicalizationError, l as CheckConstraintCanonicalizationWarning, m as CheckConstraintNewEnumValueError, n as ColumnDefaultCanonicalizationError, o as ColumnDefaultCanonicalizationWarning, p as ComparePgDatabaseSchemaOptions, q as CompareSchemataOptions, s as DEFAULT_PK_COLUMN, t as DetectedHierarchy, u as DiffSummary, E as ExpressionCanonicalizationUnavailableError, v as ExpressionCanonicalizationWarning, w as ExpressionHandler, x as ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError, F as FkColumnDerivation, y as GenerateDDLOptions, z as GeneratedPostcondition, B as GeneratedPostconditionBindingAddress, H as GeneratedPostconditionBindingResolutionError, I as GeneratedPostconditionProofInFlightError, J as GeneratedPostconditionReplanRequiredError, K as GeneratedPostconditionSessionDeactivatedError, L as GeneratedPostconditionWorkInFlightError, M as IncludeHandler, N as IncludeResult, O as IndexCapabilityContext, Q as IndexFeatureUnsupportedError, R as IndexPredicateCanonicalizationError, U as IndexRenderSpec, V as IntrospectedModelIR, W as IntrospectionOptions, X as MigrationSQLOptions, Y as NonConvergentSchemaDiffError, Z as NonConvergentSchemaDiffSurface, _ as PG_LEDGER_SHAPE_VERSION, $ as PartialIndexPredicateNewEnumValueError, a0 as PgAdapter, a1 as PgAdapterOptions, a2 as PgAdmittedOperation, a3 as PgAdmittedOperationResult, a4 as PgAdvisoryLockKey, a5 as PgAdvisoryLockOptionsError, a6 as PgAdvisoryLockResult, a7 as PgApplicationStepOwnedState, a8 as PgApplicationStepTx, a9 as PgBorrowedClientAdapterOptions, aa as PgCatalogueIdentityQueryable, ab as PgCompileOnlyAdapterOptions, ac as PgConvergeApplicationStep, ad as PgConvergeAssertStep, ae as PgConvergeInitializationFailure, af as PgConvergeOnceStep, ag as PgConvergePlannedStep, ah as PgConvergeRefusal, ai as PgConvergeRefusalChange, aj as PgConvergeRefusalError, ak as PgLedgerLockResult, al as PgLedgerStorageUnsupportedError, am as PgLedgerTarget, an as PgOutcomeCheckpoint, ao as PgOutcomeClaimRequest, ap as PgOutcomeExecutionRequest, aq as PgOutcomeNonTransactionalRequest, ar as PgOutcomeReadBackFactory, as as PgOutcomeRecoveryRequest, at as PgOutcomeRecoveryResult, au as PgOutcomeResolution, av as PgOutcomeResolutionAppendResult, aw as PgOutcomeResult, ax as PgOutcomeTransactionalRequest, ay as PgOwnedCheckState, az as PgPhysicalModelInput, aA as PgPhysicalModelInputError, aB as PgPhysicalNameClaim, aC as PgPhysicalNameCollision, aD as PgPhysicalNameCollisionError, aE as PgPhysicalNamespace, aF as PgPinnedConnectionAbortSignalError, aG as PgPoolAdapterOptions, aH as PgPreparedStatementReplayError, aI as PgPreparedStatementsOptions, aJ as PgRawSqlTransactionControlError, aK as PgReinitializePreflightOptions, aL as PgReinitializePreflightPool, aM as PgRollbackOnlyScope, aN as PgSchemaDiff, aO as PgTransactionAbortSignalError, aP as PgTransactionAbortedCommitError, aQ as PgTransactionAbortedError, aR as PgTransactionOptionsError, aS as PgTransactionTimeoutError, aT as RawIndexPredicateFallbackError, aU as ReferencedKeyKind, aV as ReferencedKeyRemovalConflict, aW as ReferencedKeyRemovalError, aX as SchemaChange, aY as SchemaDiff, aZ as SchemaScopeOptions, a_ as TransitionRunIdentityMismatchError, a$ as WhereDispatcher, b0 as WhereHandler, b1 as acquirePgLedgerLocks, b2 as appendIntentJournal, b3 as appendTransitionAuthorization, b4 as assertCreateIndexSupported, b5 as assertCreateIndexesSupported, b6 as assertDeclarableChangeKind, b7 as assertGeneratedPostconditionSession, b8 as assertNoRepeatedExpressionSurfaceDrift, b9 as canGenerateCreateIndex, ba as canonicalizeCheckConstraints, bb as comparePgDatabaseSchema, bc as compareSchemata, bd as createPgAdapter, be as createPgCompileOnlyAdapter, bf as createPgGeneratedManagedStep, bg as createPgPhysicalModel, bh as createPgTransitionRunPersister, bi as decodeGeneratedPostcondition, bj as decodeGeneratedPostconditionPayload, bk as defaultFkDerivation, bl as ensureDbspMetaLedger, bm as ensurePgLedger, bn as ensurePgLedgerStorageVersion, bo as ensureTransitionJournal, bp as executePgAdmittedOperation, bq as generateCreateIndex, br as generateDDL, bs as generateDownSQL, bt as generateMigrationSQL, bu as generatedPostconditionDigest, bv as generatedPostconditionForChange, bw as introspect, bx as readPgCatalogueIdentity, by as readPgLedgerMarker, bz as readPgLedgerReservationsForExecution, bA as readPgLedgerScopeCurrency, bB as readPgOutcomeRecoveryReadBack, bC as readVerifiedPgLedgerReservationsForPair, bD as recordPgLedgerIdentity, bE as renderCreateDbspMetaSchemaSql, bF as renderCreateIndex, bG as renderCreateLedgerEventTableSql, bH as renderCreateLedgerIdentityTableSql, bI as renderCreateLedgerImmutabilityFunctionSql, bJ as renderCreateLedgerImmutabilityTriggerSql, bK as renderCreateLedgerMarkerTableSql, bL as renderCreateLedgerReservationTableSql, bM as renderCreateLedgerTerminalMemberIndexSql, bN as renderCreateTransitionAuthorizationTableSql, bO as renderCreateTransitionJournalTableSql, bP as renderCreateTransitionRunPlanTableSql, bQ as renderCreateTransitionRunTableSql, bR as runPgReinitializePreflight, bS as toGeneratedPostconditionBindingAddress, bT as validatePgLedgerRuntimeIntegrity, bU as verifyGeneratedCheckPostcondition, bV as verifyGeneratedColumnPostcondition, bW as verifyGeneratedIdentityPostcondition, bX as verifyGeneratedIndexPostcondition, bY as verifyGeneratedTablePostcondition, bZ as withGeneratedPostconditionSession } from './outcome-protocol-SJC5Zk63.js';
3
+ import { ExpressionRef } from '@dbsp/core';
4
4
  export { normalizeSQL } from '@dbsp/core';
5
5
  import * as _dbsp_types from '@dbsp/types';
6
- import { LedgerPayload, LedgerAddress, NormalizedManagedStep, ColumnIR, MutationReturningItem, WhereIntent, DialectCapabilities, QueryIntent, CompiledQuery, SetOperationIntent, PlanReport, CompileOptions, LedgerHome, LedgerChainMember, OperationKindRef, SemanticArtifactRef, ProvenPlanShape, ExecutionContract, TransitionSessionClient, TransitionLessor, ExclusiveTransitionTarget, ObservationIssuer, ObservationRequest, ObservationContext, EvidenceObservation, ExpressionValue, LogicalIdentity, PhysicalOperation, OperationEffectAssessment, FingerprintManifest, DurableIntentRecord, IssuedObservation, ApplyGuard, AdvisoryObservation, TransactionalCompletionRecord, StepJournal, ResourceAddress, Assumption, TransitionRule, TransitionCompositionFact, ModelIR as ModelIR$1, TrustRoot, TableReaddressDeclaration, LedgerClaimKind } from '@dbsp/types';
6
+ import { LedgerPayload, LedgerAddress, NormalizedManagedStep, ColumnIR, MutationReturningItem, WhereIntent, DialectCapabilities, CompiledQuery, LedgerHome, LedgerChainMember, OperationKindRef, SemanticArtifactRef, ProvenPlanShape, ExecutionContract, TransitionSessionClient, TransitionLessor, ExclusiveTransitionTarget, ObservationIssuer, ObservationRequest, ObservationContext, EvidenceObservation, ExpressionValue, LogicalIdentity, PhysicalOperation, OperationEffectAssessment, FingerprintManifest, DurableIntentRecord, IssuedObservation, ApplyGuard, AdvisoryObservation, TransactionalCompletionRecord, StepJournal, ResourceAddress, Assumption, TransitionRule, TransitionCompositionFact, ModelIR, TrustRoot, TableReaddressDeclaration, LedgerClaimKind } from '@dbsp/types';
7
7
  import { Node, OnConflictClause, ParamRef } from '@pgsql/types';
8
8
  import { ScopedApprovalSet, PostgreSqlObservationTargetIdentity, TypeRef, CollationRef, UnsafeNativeFragment, ExecutableAssertion, NamingPlugin, RequiredEnumLabelIR, LedgerReservationRow, LedgerRefusal, ContainmentClosureDestructiveOutcome } from '@dbsp/types/internal';
9
9
  export { CamelCaseNamingPlugin, IdentityNamingPlugin, NamingPlugin, camelCaseNaming, getNamingPluginForDbCasing, identityNaming } from '@dbsp/types/internal';
@@ -697,61 +697,16 @@ declare function redactParams(params: readonly unknown[], config: RedactionConfi
697
697
  /**
698
698
  * Set operation compiler (UNION / INTERSECT / EXCEPT)
699
699
  *
700
- * Recursively compiles a SetOperationIntent tree into a single SQL string
701
- * with correctly renumbered positional parameters ($1, $2, ...).
700
+ * Compiles a SetOperationIntent tree into one `SelectStmt` tree whose operands
701
+ * are the leaves' trees, then deparses it once. Each operand numbers its
702
+ * parameters from $1; the right operand's `ParamRef` nodes are shifted in the
703
+ * tree by the left operand's parameter count (ADR 0012).
702
704
  */
703
705
 
704
706
  /**
705
707
  * Compiled set-operation SQL with positional parameters.
706
708
  */
707
709
  type SetOperationResult<T = unknown> = CompiledQuery<T>;
708
- /**
709
- * Function that compiles a single QueryIntent leaf to a projection envelope, or
710
- * a compiled query that can be bridged into one.
711
- * Provided by the caller to decouple from adapter internals.
712
- */
713
- type LeafCompileResult = ProjectionEnvelope | CompiledQuery;
714
- type LeafCompileFn = (query: QueryIntent) => LeafCompileResult;
715
- /**
716
- * Recursively compile a SetOperationIntent to SQL with merged parameters.
717
- *
718
- * Each leaf QueryIntent is compiled via `compileFn` to a projection envelope.
719
- * When merging left and right branches, the right side's `$N` placeholders are
720
- * renumbered so they don't collide with the left side's parameters. The final
721
- * set operation drops positional projection provenance through the envelope so
722
- * `finalizeEnvelope` owns the set-operation `js` fail-loud behavior.
723
- *
724
- * @param intent - The set operation intent (recursive tree)
725
- * @param compileFn - Compiles a single QueryIntent to an envelope-compatible result
726
- * @returns Combined SQL string and merged parameter array
727
- *
728
- * @example
729
- * ```typescript
730
- * const compileFn = createLeafCompileFn(adapter, model, plan);
731
- * const result = compileSetOperation(setOpIntent, compileFn);
732
- * console.log(result.sql); // (SELECT ...) UNION (SELECT ...)
733
- * console.log(result.parameters); // [...leftParams, ...rightParams]
734
- * ```
735
- */
736
- declare function compileSetOperation(intent: SetOperationIntent, compileFn: LeafCompileFn): SetOperationResult;
737
- /**
738
- * Create a leaf compile function from adapter + model + capabilities.
739
- *
740
- * Convenience factory for the common case where you have a PgAdapter
741
- * and need a compileFn for `compileSetOperation`.
742
- *
743
- * @param adapter - Adapter with compile() and dialectCapabilities
744
- * @param model - ModelIR schema
745
- * @param planFn - The plan() function from @dbsp/core
746
- */
747
- declare function createLeafCompileFn(adapter: {
748
- compile(plan: PlanReport, options: CompileOptions & {
749
- model: ModelIR;
750
- }): CompiledQuery;
751
- dialectCapabilities: DialectCapabilities;
752
- }, model: ModelIR, planFn: (intent: QueryIntent, model: ModelIR, options: {
753
- dialectCapabilities: DialectCapabilities;
754
- }) => PlanReport, options?: CompileOptions): LeafCompileFn;
755
710
 
756
711
  /**
757
712
  * Cursor-Based Streaming Support
@@ -1472,7 +1427,7 @@ interface EnumAddValueRuleOptions {
1472
1427
  */
1473
1428
  readonly naming?: NamingPlugin;
1474
1429
  }
1475
- declare function satisfiesPgEnumLabelVisibleCompositionFact(fact: TransitionCompositionFact, current: ModelIR$1, _context: ObservationContext): boolean;
1430
+ declare function satisfiesPgEnumLabelVisibleCompositionFact(fact: TransitionCompositionFact, current: ModelIR, _context: ObservationContext): boolean;
1476
1431
  declare function createEnumAddValueRule(options?: EnumAddValueRuleOptions): TransitionRule<EnumAddValueMatch>;
1477
1432
 
1478
1433
  interface CreateUniqueIndexConcurrentlyMatch {
@@ -2177,4 +2132,4 @@ declare function sanitizeForDisplay(value: string): string;
2177
2132
  */
2178
2133
  declare function validateSqlExpression(sql: string, context: string): void;
2179
2134
 
2180
- export { ADD_CHECK_RULE_ID, ALTER_AUTHORITY_OBSERVATION, ALTER_COLUMN_SET_NOT_NULL_OPERATION_KIND, ALTER_TYPE_ADD_VALUE_OPERATION_KIND, ATTACH_LOGICAL_IDENTITY_OPERATION_KIND, type AlterColumnSetNotNullPayload, type AlterTypeAddValuePayload, type AttachLogicalIdentityPayload, COLUMN_EXISTS_OBSERVATION, ChangeKind, CompilerContext, CompilerState, type ConflictAction, type ConflictTarget, type ConvergePgBaseOptions, type ConvergePgCheckOptions, type ConvergePgOptions, type CursorHoldOption, type CursorOptions, type CursorScrollOption, DATABASE_READ_ONLY_OUTCOME, DBSP_LEDGER_EVENT_TABLE, DBSP_LEDGER_IDENTITY_TABLE, DBSP_LEDGER_MARKER_TABLE, DBSP_LEDGER_RESERVATION_TABLE, DBSP_LOGICAL_IDENTITY_TABLE, DBSP_META_SCHEMA, DBSP_TRANSITION_AUTHORIZATION_TABLE, DBSP_TRANSITION_JOURNAL_TABLE, DBSP_TRANSITION_RUN_PLAN_TABLE, DBSP_TRANSITION_RUN_TABLE, DEFAULT_REDACTION_PATTERNS, Decision, type DeleteConfig, ENGINE_VERSION_OBSERVATION, ENUM_ADD_VALUE_RULE_ID, ENUM_LABEL_VISIBLE_OBSERVATION, ENUM_TYPE_EXISTS_OBSERVATION, type EnumAddValueMatch, type EnumAddValueRuleOptions, type ExplainFormat, type ExplainOptions, type ExplainPlan, type FetchDirection, type FetchOptions, type GeneratedIdentityObservation, type GeneratedMutationClassification, type GeneratedPostconditionObservation, type GeneratedPostconditionReadBack, GeneratedPostconditionSession, type GeneratedStructuralObservation, type IdentityAdoptionAsserter, type InsertConfig, InvalidIdentifierError, LOGICAL_IDENTITY_ADOPTION_RULE_ID, LOGICAL_IDENTITY_CARRIER_OBSERVATION, type LeafCompileFn, type LogicalIdentityAdoptionMatch, type LogicalIdentityAdoptionRuleOptions, MANUAL_SQL_OPERATION_KIND, type ManualSqlPayload, NO_NULLS_GUARD, PG_INTROSPECTION_ARTIFACT, PG_OPERATION_PACK_ARTIFACT, PG_RULE_PACK_ARTIFACT, type ParamRefValidationResult, type PgAdoptionPreflightResult, type PgAdoptionResult, PgConvergeCheckResult, PgConvergeResult, PgDatabaseReadOnlyError, type PgDatabaseWritability, type PgDeclaredAdoptionInput, PgExecutionContractDerivationError, type PgLedgerAddressChain, PgLedgerScopeCurrency, PgLockedRun, PgOutcomeCheckpointObserver, type PgPersistedDeclaredAdoptionInput, type PgPersistedReaddressInput, PgPhysicalModel, type PgReaddressPairRecoveryResult, type PgReconcileFailureStage, type PgReconcileRecoveryFailureCause, type PgReconcileRecoveryOutcome, type PgReconcileRecoveryReport, type PgReconcileSelectedIssue, PgReconcileTransitionRunError, type PgReconcileTransitionRunResult, type PgReleaseResult, type PgRemovalEffectAddress, type PgRemovalEffectsClosure, type PgTransitionClientLease, type PgTransitionPackOptions, type RedactionConfig, type RedactionPattern, SET_NOT_NULL_RULE_ID, type SetNotNullMatch, type SetOperationResult, type StreamConfig, type UpdateConfig, type UpsertConfig, acquirePgTransitionClient, assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid, assertPgDatabaseWritable, bm25Search, booleanSearch, boost, buildCloseCursor, buildDeclareCursor, buildExplain, buildExplainAnalyzeJson, buildExplainPlan, buildExplainVerbose, buildFetch, buildFetchAll, buildFetchFirst, buildFetchForward, buildFetchNext, buildOnConflictClause, buildStreamingStatements, classifyGeneratedMutation, classifyPgDatabaseWritability, classifyPgReaddressRecovery, classifyPgReaddressSupport, classifyPgWrite, classifyRemovalEffectsClosure, collectAndValidateParamRefs, compileDelete, compileInsert, compileMutation, compileSetOperation, compileUpdate, compileUpsert, conditionalUpdate, containmentAuthorityOutcome, convergePg, cosineDistance, createAlterColumnSetNotNullOperationRuntime, createAlterTypeAddValueOperationRuntime, createAnyExpr, createAttachLogicalIdentityOperationRuntime, createEnumAddValueRule, createEqualityExpr, createLeafCompileFn, createLogicalIdentityAdoptionRule, createManualSqlOperationRuntime, createParamRef, createPgExecutionContract, createPgObservationIssuer, createPgTransitionLessor, createPgTransitionPack, createSetNotNullRule, createTypeCastParamRef, dbTypesEqual, derivePgCapabilitiesForVersion, evaluatePgExecutionContract, excludedRef, executePgDeclaredAdoption, executePgObservationFromLessor, executePgPersistedTableReaddress, executionIdsForRun, findPgLedgerTerminalMember, generateCursorName, generateSeries, getRowEstimates, getTotalExecutionTime, innerProduct, isGeneratedMutationDestructive, isPgDatabaseReadOnlyError, isReservedKeyword, l2Distance, mapColumnType, mapOnDeleteAction, nextval, normalizeManualSqlPayload, parse, parseExplainJson, pgTargetIdentityMismatch, preflightPgDeclaredAdoption, preparePgExecutionSession, preparePgRecoveryAdmission, rawDistance, readGeneratedPostcondition, readGeneratedPostconditionReadBack, readPgExecutionTargetFromClient, readPgLedgerAddressChain, readPgLedgerControllerOid, readPgObservationContextFromClient, readPgObservationContextFromLessor, readPgRemovalEffectsClosure, readTransitionJournal, reconcilePgTransitionRun, recoverPgReaddressPair, redactParams, refusesRecordedPlanRemoval, releasePgManagedAddress, renderAlterColumnSetNotNullSql, renderAlterTypeAddValueSql, renderAttachLogicalIdentityLockSql, renderCreateLogicalIdentityIndexesSql, renderCreateLogicalIdentitySideTableSql, renderInsertLogicalIdentitySql, renderNoNullsCheckSql, renderPgTableReaddressStatements, renderSetNotNullLockSql, reservationsForRemovalClosure, sanitizeForDisplay, score, validateIdentifier, validateIdentifiers, validateParamRef, validatePgManagedLedgerCurrency, validateQualifiedIdentifier, validateSqlExpression, vectorDims, withPgTransitionRunLock };
2135
+ export { ADD_CHECK_RULE_ID, ALTER_AUTHORITY_OBSERVATION, ALTER_COLUMN_SET_NOT_NULL_OPERATION_KIND, ALTER_TYPE_ADD_VALUE_OPERATION_KIND, ATTACH_LOGICAL_IDENTITY_OPERATION_KIND, type AlterColumnSetNotNullPayload, type AlterTypeAddValuePayload, type AttachLogicalIdentityPayload, COLUMN_EXISTS_OBSERVATION, ChangeKind, CompilerContext, CompilerState, type ConflictAction, type ConflictTarget, type ConvergePgBaseOptions, type ConvergePgCheckOptions, type ConvergePgOptions, type CursorHoldOption, type CursorOptions, type CursorScrollOption, DATABASE_READ_ONLY_OUTCOME, DBSP_LEDGER_EVENT_TABLE, DBSP_LEDGER_IDENTITY_TABLE, DBSP_LEDGER_MARKER_TABLE, DBSP_LEDGER_RESERVATION_TABLE, DBSP_LOGICAL_IDENTITY_TABLE, DBSP_META_SCHEMA, DBSP_TRANSITION_AUTHORIZATION_TABLE, DBSP_TRANSITION_JOURNAL_TABLE, DBSP_TRANSITION_RUN_PLAN_TABLE, DBSP_TRANSITION_RUN_TABLE, DEFAULT_REDACTION_PATTERNS, Decision, type DeleteConfig, ENGINE_VERSION_OBSERVATION, ENUM_ADD_VALUE_RULE_ID, ENUM_LABEL_VISIBLE_OBSERVATION, ENUM_TYPE_EXISTS_OBSERVATION, type EnumAddValueMatch, type EnumAddValueRuleOptions, type ExplainFormat, type ExplainOptions, type ExplainPlan, type FetchDirection, type FetchOptions, type GeneratedIdentityObservation, type GeneratedMutationClassification, type GeneratedPostconditionObservation, type GeneratedPostconditionReadBack, GeneratedPostconditionSession, type GeneratedStructuralObservation, type IdentityAdoptionAsserter, type InsertConfig, InvalidIdentifierError, LOGICAL_IDENTITY_ADOPTION_RULE_ID, LOGICAL_IDENTITY_CARRIER_OBSERVATION, type LogicalIdentityAdoptionMatch, type LogicalIdentityAdoptionRuleOptions, MANUAL_SQL_OPERATION_KIND, type ManualSqlPayload, NO_NULLS_GUARD, PG_INTROSPECTION_ARTIFACT, PG_OPERATION_PACK_ARTIFACT, PG_RULE_PACK_ARTIFACT, type ParamRefValidationResult, type PgAdoptionPreflightResult, type PgAdoptionResult, PgConvergeCheckResult, PgConvergeResult, PgDatabaseReadOnlyError, type PgDatabaseWritability, type PgDeclaredAdoptionInput, PgExecutionContractDerivationError, type PgLedgerAddressChain, PgLedgerScopeCurrency, PgLockedRun, PgOutcomeCheckpointObserver, type PgPersistedDeclaredAdoptionInput, type PgPersistedReaddressInput, PgPhysicalModel, type PgReaddressPairRecoveryResult, type PgReconcileFailureStage, type PgReconcileRecoveryFailureCause, type PgReconcileRecoveryOutcome, type PgReconcileRecoveryReport, type PgReconcileSelectedIssue, PgReconcileTransitionRunError, type PgReconcileTransitionRunResult, type PgReleaseResult, type PgRemovalEffectAddress, type PgRemovalEffectsClosure, type PgTransitionClientLease, type PgTransitionPackOptions, type RedactionConfig, type RedactionPattern, SET_NOT_NULL_RULE_ID, type SetNotNullMatch, type SetOperationResult, type StreamConfig, type UpdateConfig, type UpsertConfig, acquirePgTransitionClient, assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid, assertPgDatabaseWritable, bm25Search, booleanSearch, boost, buildCloseCursor, buildDeclareCursor, buildExplain, buildExplainAnalyzeJson, buildExplainPlan, buildExplainVerbose, buildFetch, buildFetchAll, buildFetchFirst, buildFetchForward, buildFetchNext, buildOnConflictClause, buildStreamingStatements, classifyGeneratedMutation, classifyPgDatabaseWritability, classifyPgReaddressRecovery, classifyPgReaddressSupport, classifyPgWrite, classifyRemovalEffectsClosure, collectAndValidateParamRefs, compileDelete, compileInsert, compileMutation, compileUpdate, compileUpsert, conditionalUpdate, containmentAuthorityOutcome, convergePg, cosineDistance, createAlterColumnSetNotNullOperationRuntime, createAlterTypeAddValueOperationRuntime, createAnyExpr, createAttachLogicalIdentityOperationRuntime, createEnumAddValueRule, createEqualityExpr, createLogicalIdentityAdoptionRule, createManualSqlOperationRuntime, createParamRef, createPgExecutionContract, createPgObservationIssuer, createPgTransitionLessor, createPgTransitionPack, createSetNotNullRule, createTypeCastParamRef, dbTypesEqual, derivePgCapabilitiesForVersion, evaluatePgExecutionContract, excludedRef, executePgDeclaredAdoption, executePgObservationFromLessor, executePgPersistedTableReaddress, executionIdsForRun, findPgLedgerTerminalMember, generateCursorName, generateSeries, getRowEstimates, getTotalExecutionTime, innerProduct, isGeneratedMutationDestructive, isPgDatabaseReadOnlyError, isReservedKeyword, l2Distance, mapColumnType, mapOnDeleteAction, nextval, normalizeManualSqlPayload, parse, parseExplainJson, pgTargetIdentityMismatch, preflightPgDeclaredAdoption, preparePgExecutionSession, preparePgRecoveryAdmission, rawDistance, readGeneratedPostcondition, readGeneratedPostconditionReadBack, readPgExecutionTargetFromClient, readPgLedgerAddressChain, readPgLedgerControllerOid, readPgObservationContextFromClient, readPgObservationContextFromLessor, readPgRemovalEffectsClosure, readTransitionJournal, reconcilePgTransitionRun, recoverPgReaddressPair, redactParams, refusesRecordedPlanRemoval, releasePgManagedAddress, renderAlterColumnSetNotNullSql, renderAlterTypeAddValueSql, renderAttachLogicalIdentityLockSql, renderCreateLogicalIdentityIndexesSql, renderCreateLogicalIdentitySideTableSql, renderInsertLogicalIdentitySql, renderNoNullsCheckSql, renderPgTableReaddressStatements, renderSetNotNullLockSql, reservationsForRemovalClosure, sanitizeForDisplay, score, validateIdentifier, validateIdentifiers, validateParamRef, validatePgManagedLedgerCurrency, validateQualifiedIdentifier, validateSqlExpression, vectorDims, withPgTransitionRunLock };
package/dist/index.js CHANGED
@@ -104,7 +104,6 @@ import {
104
104
  compileDelete,
105
105
  compileInsert,
106
106
  compileMutation,
107
- compileSetOperation,
108
107
  compileUpdate,
109
108
  compileUpsert,
110
109
  conditionalUpdate,
@@ -116,7 +115,6 @@ import {
116
115
  createAttachLogicalIdentityOperationRuntime,
117
116
  createEnumAddValueRule,
118
117
  createEqualityExpr,
119
- createLeafCompileFn,
120
118
  createLogicalIdentityAdoptionRule,
121
119
  createManualSqlOperationRuntime,
122
120
  createParamRef,
@@ -234,7 +232,7 @@ import {
234
232
  withGeneratedPostconditionSession,
235
233
  withPgTransitionRunLock,
236
234
  withPgTransitionTransaction
237
- } from "./chunk-CQSIDXP5.js";
235
+ } from "./chunk-GTX6FAK2.js";
238
236
 
239
237
  // src/explain/explain.ts
240
238
  function buildExplain(query, options = {}) {
@@ -1203,7 +1201,6 @@ export {
1203
1201
  compileDelete,
1204
1202
  compileInsert,
1205
1203
  compileMutation,
1206
- compileSetOperation,
1207
1204
  compileUpdate,
1208
1205
  compileUpsert,
1209
1206
  conditionalUpdate,
@@ -1216,7 +1213,6 @@ export {
1216
1213
  createAttachLogicalIdentityOperationRuntime,
1217
1214
  createEnumAddValueRule,
1218
1215
  createEqualityExpr,
1219
- createLeafCompileFn,
1220
1216
  createLogicalIdentityAdoptionRule,
1221
1217
  createManualSqlOperationRuntime,
1222
1218
  createParamRef,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/explain/explain.ts","../src/extensions/paradedb.ts","../src/extensions/pgsql-builtins.ts","../src/extensions/pgvector.ts","../src/redact-params.ts","../src/transition/release.ts","../src/transition/public-api.ts","../src/transition/reconcile.ts"],"sourcesContent":["/**\n * EXPLAIN Statement Compiler\n *\n * Generates PostgreSQL EXPLAIN statements with various options.\n * Supports:\n * - ANALYZE (execute and show actual run times)\n * - FORMAT (text, json, xml, yaml)\n * - VERBOSE, COSTS, BUFFERS, TIMING, SETTINGS\n */\n\nimport type { Node } from '@pgsql/types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Output format for EXPLAIN results.\n */\nexport type ExplainFormat = 'text' | 'json' | 'xml' | 'yaml';\n\n/**\n * Options for EXPLAIN statement.\n */\nexport interface ExplainOptions {\n\t/** Execute the query and show actual run times */\n\tanalyze?: boolean;\n\t/** Show more detailed output */\n\tverbose?: boolean;\n\t/** Show cost estimates (default: true) */\n\tcosts?: boolean;\n\t/** Show buffer usage (requires analyze) */\n\tbuffers?: boolean;\n\t/** Show actual timing (requires analyze) */\n\ttiming?: boolean;\n\t/** Show non-default settings */\n\tsettings?: boolean;\n\t/** Output format */\n\tformat?: ExplainFormat;\n}\n\n// ============================================================================\n// EXPLAIN Builder\n// ============================================================================\n\n/**\n * Build an EXPLAIN statement wrapping a query.\n *\n * @param query - The query to explain (SelectStmt, InsertStmt, etc.)\n * @param options - EXPLAIN options\n * @returns ExplainStmt AST node\n *\n * @example\n * ```typescript\n * const selectAst = { SelectStmt: { ... } };\n * const explainAst = buildExplain(selectAst, { analyze: true, format: 'json' });\n * // Produces: EXPLAIN (ANALYZE, FORMAT JSON) SELECT ...\n * ```\n */\nexport function buildExplain(query: Node, options: ExplainOptions = {}): Node {\n\tconst defElems: Node[] = [];\n\n\t// Add options in standard order\n\tif (options.analyze !== undefined) {\n\t\tdefElems.push(buildDefElem('analyze', options.analyze));\n\t}\n\n\tif (options.verbose !== undefined) {\n\t\tdefElems.push(buildDefElem('verbose', options.verbose));\n\t}\n\n\tif (options.costs !== undefined) {\n\t\tdefElems.push(buildDefElem('costs', options.costs));\n\t}\n\n\tif (options.buffers !== undefined) {\n\t\tdefElems.push(buildDefElem('buffers', options.buffers));\n\t}\n\n\tif (options.timing !== undefined) {\n\t\tdefElems.push(buildDefElem('timing', options.timing));\n\t}\n\n\tif (options.settings !== undefined) {\n\t\tdefElems.push(buildDefElem('settings', options.settings));\n\t}\n\n\tif (options.format) {\n\t\tdefElems.push(buildDefElem('format', options.format));\n\t}\n\n\tconst explainStmt: { query: Node; options?: Node[] } = { query };\n\tif (defElems.length > 0) {\n\t\texplainStmt.options = defElems;\n\t}\n\n\treturn { ExplainStmt: explainStmt };\n}\n\n/**\n * Build EXPLAIN ANALYZE with JSON format (common pattern).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with ANALYZE and JSON format\n */\nexport function buildExplainAnalyzeJson(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tformat: 'json',\n\t});\n}\n\n/**\n * Build simple EXPLAIN (plan only, no execution).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with default options\n */\nexport function buildExplainPlan(query: Node): Node {\n\treturn buildExplain(query);\n}\n\n/**\n * Build verbose EXPLAIN with costs and buffers.\n *\n * @param query - The query to explain\n * @returns ExplainStmt with verbose options\n */\nexport function buildExplainVerbose(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tverbose: true,\n\t\tbuffers: true,\n\t\ttiming: true,\n\t});\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Build a DefElem node for EXPLAIN options.\n *\n * @param name - Option name (analyze, verbose, format, etc.)\n * @param value - Option value (boolean or string)\n * @returns DefElem AST node\n */\nfunction buildDefElem(name: string, value: boolean | string): Node {\n\tlet arg: Node | undefined;\n\n\tif (typeof value === 'boolean') {\n\t\t// Boolean options: ANALYZE TRUE/FALSE\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value ? 'true' : 'false',\n\t\t\t},\n\t\t};\n\t} else {\n\t\t// String options: FORMAT json\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tDefElem: {\n\t\t\tdefname: name,\n\t\t\targ,\n\t\t\tdefaction: 'DEFELEM_UNSPEC',\n\t\t},\n\t};\n}\n\n/**\n * Parse EXPLAIN JSON output to get execution statistics.\n *\n * @param jsonOutput - The JSON string from EXPLAIN (ANALYZE, FORMAT JSON)\n * @returns Parsed plan with execution statistics\n */\nexport function parseExplainJson(jsonOutput: string): ExplainPlan[] {\n\ttry {\n\t\tconst parsed = JSON.parse(jsonOutput);\n\t\treturn Array.isArray(parsed) ? parsed : [parsed];\n\t} catch {\n\t\tthrow new Error('Failed to parse EXPLAIN JSON output');\n\t}\n}\n\n/**\n * Parsed EXPLAIN plan structure (simplified).\n */\nexport interface ExplainPlan {\n\tPlan: {\n\t\t'Node Type': string;\n\t\t'Relation Name'?: string;\n\t\tAlias?: string;\n\t\t'Startup Cost'?: number;\n\t\t'Total Cost'?: number;\n\t\t'Plan Rows'?: number;\n\t\t'Plan Width'?: number;\n\t\t'Actual Startup Time'?: number;\n\t\t'Actual Total Time'?: number;\n\t\t'Actual Rows'?: number;\n\t\t'Actual Loops'?: number;\n\t\tPlans?: ExplainPlan['Plan'][];\n\t};\n\t'Planning Time'?: number;\n\t'Execution Time'?: number;\n\tTriggers?: unknown[];\n}\n\n/**\n * Extract total execution time from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Total execution time in milliseconds\n */\nexport function getTotalExecutionTime(plans: ExplainPlan[]): number {\n\tif (plans.length === 0) return 0;\n\n\tconst plan = plans[0]!;\n\tconst planning = plan['Planning Time'] ?? 0;\n\tconst execution = plan['Execution Time'] ?? 0;\n\n\treturn planning + execution;\n}\n\n/**\n * Extract row counts from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Object with estimated and actual row counts\n */\nexport function getRowEstimates(plans: ExplainPlan[]): {\n\testimated: number;\n\tactual: number;\n} {\n\tif (plans.length === 0) return { estimated: 0, actual: 0 };\n\n\tconst rootPlan = plans[0]?.Plan;\n\tif (!rootPlan) return { estimated: 0, actual: 0 };\n\n\treturn {\n\t\testimated: rootPlan['Plan Rows'] ?? 0,\n\t\tactual: rootPlan['Actual Rows'] ?? 0,\n\t};\n}\n","/**\n * ParadeDB Extension Wrappers\n *\n * Type-safe query builders for ParadeDB BM25 full-text search.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(score('id').as('score'))\n * - WHERE: .where(bm25Search('symbols', query, { name: 3.0, doc: 1.0 }))\n * - ORDER BY: .orderBy(score('id'), 'desc')\n *\n * @remarks\n * ParadeDB functions accept both named and positional arguments.\n * This module uses named args via namedArg() for parse(), which produces:\n * paradedb.parse(field => 'field_name', query_string => $1)\n * Named parameter syntax is supported via the NamedArgExpressionIntent (EXT-NAMED-PARAMS).\n */\n\nimport {\n\tarray,\n\tExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\tnamedArg,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * BM25 relevance score for a row.\n *\n * Use in SELECT and ORDER BY to retrieve and sort by full-text relevance.\n * Requires a BM25 index on the table.\n *\n * @param keyField - The key field of the BM25 index (typically the primary key, e.g. 'id')\n * @returns ExpressionRef that compiles to: paradedb.score(\"keyField\")\n *\n * @example\n * orm.select('symbols').column(score('id').as('score')).orderBy(score('id'), 'desc')\n * // → paradedb.score(\"id\") AS \"score\"\n */\nexport function score(keyField: string): ExpressionRef {\n\treturn fn('paradedb.score', exprRef(keyField));\n}\n\n/**\n * Parse a single-field BM25 query expression.\n *\n * Compiles to: paradedb.parse(field => 'field_name', query_string => $N)\n *\n * @param field - Column name to search in (must be indexed in the BM25 index)\n * @param query - Query string value (will be bound as a parameter)\n * @returns ExpressionRef for use with boost() or booleanSearch()\n *\n * @example\n * parse('name', 'hello world')\n * // → paradedb.parse(field => 'name', query_string => $1)\n */\nexport function parse(\n\tfield: string,\n\tquery: ExpressionRef | unknown,\n): ExpressionRef {\n\t// If query is already an ExpressionRef, pass it directly so fn() unwraps .intent.\n\t// Otherwise, wrap it in param() so it becomes a bound $N parameter.\n\tconst queryExpr: ExpressionRef =\n\t\tquery instanceof ExpressionRef ? query : param(query);\n\treturn fn(\n\t\t'paradedb.parse',\n\t\tnamedArg('field', literal(field)),\n\t\tnamedArg('query_string', queryExpr),\n\t);\n}\n\n/**\n * Apply a boost multiplier to a BM25 sub-expression.\n *\n * Compiles to: paradedb.boost(factor, expr)\n *\n * @param factor - Boost multiplier (e.g. 3.0 for 3x weight)\n * @param expr - Expression to boost (typically a parse() call)\n * @returns ExpressionRef for use with booleanSearch()\n *\n * @example\n * boost(3.0, parse('name', 'hello'))\n * // → paradedb.boost(3.0, paradedb.parse('name', $1))\n */\nexport function boost(factor: number, expr: ExpressionRef): ExpressionRef {\n\treturn fn('paradedb.boost', literal(factor), expr);\n}\n\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(expr1, expr2, ...)\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(paradedb.boost(3.0, ...), paradedb.boost(1.0, ...))\n */\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(should => ARRAY[expr1, expr2, ...])\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(should => ARRAY[paradedb.boost(3.0, ...), paradedb.boost(1.0, ...)])\n */\nexport function booleanSearch(exprs: ExpressionRef[]): ExpressionRef {\n\treturn fn('paradedb.boolean', namedArg('should', array(...exprs)));\n}\n\n/**\n * Full BM25 multi-field search with per-field boost weights.\n *\n * Produces: table @@@ paradedb.boolean(boost1, boost2, ...)\n *\n * Each field in `fieldBoosts` generates a `paradedb.boost(weight, paradedb.parse(field, $N))`\n * sub-expression. The same query string is used for all fields (single parameter binding).\n *\n * @param table - Table alias for the left side of the @@@ operator\n * @param query - Query string (bound as a single $N parameter, shared across all fields)\n * @param fieldBoosts - Map of column name → boost weight\n * @returns ExpressionRef for use in .where()\n *\n * @example\n * bm25Search('s', searchTerm, {\n * name_searchable: 3.0,\n * name: 1.0,\n * signature: 1.5,\n * doc_searchable: 1.0,\n * })\n * // → s @@@ paradedb.boolean(\n * // paradedb.boost(3.0, paradedb.parse('name_searchable', $1)),\n * // paradedb.boost(1.0, paradedb.parse('name', $1)),\n * // paradedb.boost(1.5, paradedb.parse('signature', $1)),\n * // paradedb.boost(1.0, paradedb.parse('doc_searchable', $1))\n * // )\n *\n * @remarks\n * The query parameter is shared: all parse() calls reference the same $N slot.\n * If you need different query strings per field, compose parse()/boost()/booleanSearch() manually.\n *\n * @remarks\n * ParadeDB's boolean() function accepts both positional args and the named\n * `should => ARRAY[...]` syntax. This wrapper uses positional args.\n * Named parameter syntax is deferred to EXT-NAMED-PARAMS.\n */\nexport function bm25Search(\n\ttable: string,\n\tquery: unknown,\n\tfieldBoosts: Record<string, number>,\n): ExpressionRef {\n\tconst queryParam = param(query);\n\tconst boostExprs = Object.entries(fieldBoosts).map(([field, weight]) =>\n\t\tboost(weight, fn('paradedb.parse', literal(field), queryParam)),\n\t);\n\tconst booleanExpr = booleanSearch(boostExprs);\n\treturn op('@@@', exprRef(table), booleanExpr);\n}\n","/**\n * PostgreSQL built-in function helpers.\n *\n * Thin wrappers around core expression primitives for common PostgreSQL functions.\n * Same pattern as pgvector.ts and paradedb.ts.\n */\nimport { type ExpressionRef, fn, literal } from '@dbsp/core';\n\n/**\n * Generate a series of values: generate_series(start, stop[, step])\n *\n * Returns a set of values from start to stop (inclusive), with an optional step.\n * Commonly used with CTE for batch operations.\n *\n * @example generateSeries(1, 100) → generate_series(1, 100)\n * @example generateSeries(0, 50, 5) → generate_series(0, 50, 5)\n */\nexport function generateSeries(\n\tstart: number,\n\tstop: number,\n\tstep?: number,\n): ExpressionRef {\n\tconst args: ExpressionRef[] = [literal(start), literal(stop)];\n\tif (step !== undefined) {\n\t\targs.push(literal(step));\n\t}\n\treturn fn('generate_series', ...args);\n}\n\n/**\n * Get next value from a sequence: nextval('sequence_name')\n *\n * @example nextval('order_id_seq') → nextval('order_id_seq')\n */\nexport function nextval(sequenceName: string): ExpressionRef {\n\treturn fn('nextval', literal(sequenceName));\n}\n","/**\n * pgvector Extension Wrappers\n *\n * Type-safe query builders for pgvector distance operators.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(cosineDistance('vector', qv).as('score'))\n * - WHERE: .where(cosineDistance('vector', qv).gte(0.5))\n * - ORDER BY: .orderBy(rawDistance('vector', qv), 'asc')\n */\n\nimport {\n\tcast,\n\ttype ExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * Cosine similarity: 1 - (col <=> vector)\n *\n * Score in [0, 1], higher = more similar.\n * Use in SELECT to get a similarity score.\n *\n * @example\n * orm.select('embeddings').column(cosineDistance('vector', qv).as('score'))\n */\nexport function cosineDistance(\n\tcolumn: string,\n\tvector: number[],\n): ExpressionRef {\n\treturn op(\n\t\t'-',\n\t\tliteral(1),\n\t\top('<=>', exprRef(column), cast(param(vector), 'vector')),\n\t);\n}\n\n/**\n * Raw cosine distance: col <=> vector\n *\n * Lower = closer. Index-friendly — use in ORDER BY for ANN search.\n * Do NOT use in SELECT as a similarity score (lower = closer is counterintuitive).\n *\n * @example\n * orm.select('embeddings').orderBy(rawDistance('vector', qv), 'asc')\n */\nexport function rawDistance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<=>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * L2 (Euclidean) distance: col <-> vector\n *\n * @example\n * orm.select('embeddings').orderBy(l2Distance('vector', qv), 'asc')\n */\nexport function l2Distance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<->', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Inner product distance: col <#> vector (negative inner product)\n *\n * For maximum inner product search: ORDER BY innerProduct('vector', qv) ASC.\n *\n * @example\n * orm.select('embeddings').orderBy(innerProduct('vector', qv), 'asc')\n */\nexport function innerProduct(column: string, vector: number[]): ExpressionRef {\n\treturn op('<#>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Get the number of dimensions of a vector column: vector_dims(col)\n *\n * Returns an integer — the dimension count of the stored vector.\n * Useful for sanity-checking that embeddings match the expected model dimension.\n *\n * @example\n * orm.from(embeddings).columns([vectorDims('vector').as('dim')]).first()\n * // → SELECT vector_dims(\"t0\".\"vector\") AS \"dim\" FROM \"embeddings\" AS \"t0\"\n */\nexport function vectorDims(column: string): ExpressionRef {\n\treturn fn('vector_dims', exprRef(column));\n}\n","/**\n * Redact sensitive values in a query dump's `params` array before logging.\n *\n * Defense-in-depth helper: when application code may have inserted PII as\n * literal parameter values (e.g. an email in a WHERE clause), this replaces\n * any string value matching a configured pattern with the `replacement`\n * placeholder. Non-string values are passed through unchanged.\n */\n\nexport type RedactionPattern = string | RegExp;\n\nexport type RedactionConfig = {\n\t/** Patterns to match against string param values. String = substring (case-insensitive); RegExp = `.test()`. */\n\treadonly patterns: ReadonlyArray<RedactionPattern>;\n\t/** Placeholder substituted for matched values. Default `'[REDACTED]'`. */\n\treadonly replacement?: string;\n};\n\n/**\n * Curated regex set for common PII shapes. Match against the value itself\n * (not the column name), so they detect data shaped like an email / token /\n * credit-card / SSN regardless of which `$N` slot it landed in.\n *\n * @stable Adding entries is non-breaking; removing one is a semver-major change\n * because callers may rely on a specific shape being redacted.\n */\nexport const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp> = Object.freeze([\n\t/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/, // email\n\t/^Bearer\\s+[A-Za-z0-9._-]+$/i, // bearer token\n\t/^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, // JWT\n\t/^\\d{3}-\\d{2}-\\d{4}$/, // US SSN\n\t/^\\d(?:[ -]?\\d){12,18}$/, // credit card (13-19 digits, optional spaces/dashes between)\n\t/^sk-[A-Za-z0-9]{20,}$/, // OpenAI-style API key\n]);\n\nconst DEFAULT_REPLACEMENT = '[REDACTED]';\n\n/**\n * Returns a NEW array of params with sensitive string values replaced.\n * The input array is never mutated. Non-string values pass through unchanged.\n */\nexport function redactParams(\n\tparams: readonly unknown[],\n\tconfig: RedactionConfig,\n): readonly unknown[] {\n\tconst replacement = config.replacement ?? DEFAULT_REPLACEMENT;\n\treturn params.map((value) =>\n\t\tmatchesAnyPattern(value, config.patterns) ? replacement : value,\n\t);\n}\n\nfunction matchesAnyPattern(\n\tvalue: unknown,\n\tpatterns: ReadonlyArray<RedactionPattern>,\n): boolean {\n\tif (typeof value !== 'string') return false;\n\tconst lowerValue = value.toLowerCase();\n\tfor (const pattern of patterns) {\n\t\tif (typeof pattern === 'string') {\n\t\t\tif (pattern.length > 0 && lowerValue.includes(pattern.toLowerCase()))\n\t\t\t\treturn true;\n\t\t} else {\n\t\t\tconst re =\n\t\t\t\tpattern.global || pattern.sticky\n\t\t\t\t\t? new RegExp(pattern.source, pattern.flags)\n\t\t\t\t\t: pattern;\n\t\t\tif (re.test(value)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n","/** End management without issuing DDL or accepting a caller-supplied controller. */\nimport { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport { projectLedgerChain } from '@dbsp/core/internal';\nimport type { LedgerAddress, LedgerHome } from '@dbsp/types';\nimport * as transitionTypes from '@dbsp/types';\nimport { refusalFor } from '@dbsp/types';\nimport type { LedgerRefusal } from '@dbsp/types/internal';\nimport type { readPgCatalogueIdentity } from './catalogue-identity.js';\nimport {\n\treadPgLedgerAddressChain,\n\treadPgLedgerControllerOid,\n} from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport type { TransitionJournalQueryable } from './journal.js';\nimport {\n\tacquirePgLedgerLocks,\n\tappendPgLedgerRelease,\n\ttype PgLedgerTarget,\n} from './ledger.js';\nimport {\n\tformatPgTransitionUnknownError,\n\tPgResolvableRelationIdentityReadError,\n\treadPgCatalogueIdentityWithResolvableRelationLock,\n} from './lock-relation.js';\nimport {\n\tsetPgTransitionLockTimeout,\n\twithPgTransitionTransaction,\n} from './outcome-protocol.js';\nimport { createPostLockAdmissionEvidence } from './post-lock-admission-evidence.js';\nimport { readPgLedgerScopeCurrency } from './reinitialize-preflight.js';\n\ntype ControllerIdentity = { readonly name: string; readonly oid: string };\ntype ControllerIdentityHelper = (\n\trecorded: ControllerIdentity,\n\tcurrent: ControllerIdentity,\n) => boolean;\n\nconst sameControllerIdentity =\n\t(\n\t\ttransitionTypes as typeof transitionTypes & {\n\t\t\treadonly sameControllerIdentity?: ControllerIdentityHelper;\n\t\t}\n\t).sameControllerIdentity ??\n\t((recorded, current) =>\n\t\trecorded.name === current.name && recorded.oid === current.oid);\n\nexport type PgReleaseResult =\n\t| { readonly outcome: 'released' }\n\t| {\n\t\t\t/** A managed mutation must name a non-writable target before any release read. */\n\t\t\treadonly outcome: 'database-read-only';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\t/** Transport/query/read-only failure; never mislabel it malformed chain. */\n\t\t\treadonly outcome: 'release-unavailable';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\treadonly outcome: 'release-refused';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t\t\treadonly refusal: LedgerRefusal;\n\t };\n\nfunction releaseRefusal(\n\taddress: LedgerAddress,\n\tcode: 'ERR-02' | 'ERR-05' | 'ERR-06' | 'ERR-08' | 'ERR-09',\n\tstate: LedgerRefusal['state'],\n): Extract<PgReleaseResult, { readonly outcome: 'release-refused' }> {\n\tconst refusal = refusalFor(code, { address, state });\n\treturn {\n\t\toutcome: 'release-refused',\n\t\tdetail: refusal.cause,\n\t\taddress,\n\t\trefusal,\n\t};\n}\n\nfunction target(home: LedgerHome): PgLedgerTarget {\n\tif (home.scope === 'database') return { scope: 'database' };\n\tif (!home.schema) throw new Error('schema release requires a schema ledger');\n\treturn { scope: 'schema', schema: home.schema };\n}\n\n/**\n * Refuse from the live subject before opening a release transaction.\n *\n * This is intentionally only an early refusal pass: success still repeats\n * every fact under the ledger lock below. It means a pending, blocked,\n * foreign-controller, or stale-lineage address keeps its classified refusal\n * even when a subsequently unnecessary transaction cleanup loses transport.\n */\nasync function preflightReleaseRefusal(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult | undefined> {\n\tconst currency = await readPgLedgerScopeCurrency(input.executor, input.home);\n\tif (currency.kind !== 'current')\n\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\tconst chain = await readPgLedgerAddressChain(\n\t\tinput.executor,\n\t\tinput.home,\n\t\tinput.address,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\tif (projection.openClaim !== undefined)\n\t\treturn releaseRefusal(input.address, 'ERR-08', projection.stableState);\n\tif (projection.stableState !== 'managed' || !chain.terminalMember)\n\t\treturn releaseRefusal(input.address, 'ERR-02', projection.stableState);\n\tconst user = await input.executor.query(\n\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t);\n\tconst currentUser = user.rows[0]?.current_user;\n\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\tif (typeof currentUser !== 'string' || typeof currentUserOid !== 'string')\n\t\tthrow new Error('current_user role identity is unreadable');\n\tconst controllerOid =\n\t\t(\n\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\treadonly controllerOid?: string;\n\t\t\t}\n\t\t).controllerOid ??\n\t\t(await readPgLedgerControllerOid(\n\t\t\tinput.executor,\n\t\t\tinput.home,\n\t\t\tinput.address,\n\t\t\tchain.terminalMember.eventId,\n\t\t));\n\tif (\n\t\t!sameControllerIdentity(\n\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t)\n\t)\n\t\treturn releaseRefusal(input.address, 'ERR-05', projection.stableState);\n\treturn undefined;\n}\n\nexport async function releasePgManagedAddress(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult> {\n\ttry {\n\t\ttry {\n\t\t\tawait assertPgDatabaseWritable(input.executor);\n\t\t} catch (error) {\n\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'database-read-only',\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\tdetail: error.message,\n\t\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t\tconst earlyRefusal = await preflightReleaseRefusal(input);\n\t\tif (earlyRefusal) return earlyRefusal;\n\t\treturn await withPgTransitionTransaction(\n\t\t\tinput.executor,\n\t\t\tasync (executor) => {\n\t\t\t\tawait setPgTransitionLockTimeout(executor);\n\t\t\t\tconst lock = await acquirePgLedgerLocks(executor, [input.home]);\n\t\t\t\tif (lock.kind !== 'acquired') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait createPostLockAdmissionEvidence(executor, lock.proof);\n\t\t\t\t} catch {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\t\t\t\t}\n\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\texecutor,\n\t\t\t\t\tinput.home,\n\t\t\t\t\tinput.address,\n\t\t\t\t);\n\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\tif (projection.kind !== 'projected-ledger-chain') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\tif (projection.openClaim !== undefined) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-08',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (projection.stableState !== 'managed' || !chain.terminalMember) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-02',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst user = await executor.query(\n\t\t\t\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t\t\t\t);\n\t\t\t\tconst currentUser = user.rows[0]?.current_user;\n\t\t\t\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\t\t\t\tif (\n\t\t\t\t\ttypeof currentUser !== 'string' ||\n\t\t\t\t\ttypeof currentUserOid !== 'string'\n\t\t\t\t)\n\t\t\t\t\tthrow new Error('current_user role identity is unreadable');\n\t\t\t\tconst controllerOid =\n\t\t\t\t\t(\n\t\t\t\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\t\t\t\treadonly controllerOid?: string;\n\t\t\t\t\t\t}\n\t\t\t\t\t).controllerOid ??\n\t\t\t\t\t(await readPgLedgerControllerOid(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.home,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\tchain.terminalMember.eventId,\n\t\t\t\t\t));\n\t\t\t\tif (\n\t\t\t\t\t!sameControllerIdentity(\n\t\t\t\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet live: Awaited<ReturnType<typeof readPgCatalogueIdentity>>;\n\t\t\t\ttry {\n\t\t\t\t\tlive = await readPgCatalogueIdentityWithResolvableRelationLock(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'release',\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof PgResolvableRelationIdentityReadError))\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-09',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!live?.catalogueIdentity ||\n\t\t\t\t\t!chain.terminalMember.catalogueIdentity ||\n\t\t\t\t\t!isDeepStrictEqual(\n\t\t\t\t\t\tlive.catalogueIdentity,\n\t\t\t\t\t\tchain.terminalMember.catalogueIdentity,\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t// Kinds without a lockable relation retain the narrow window after this\n\t\t\t\t// final identity read and before their release append.\n\t\t\t\tconst eventId = `dbsp.release.${randomUUID()}`;\n\t\t\t\tawait appendPgLedgerRelease(executor, target(input.home), {\n\t\t\t\t\teventId,\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\teventKind: 'released',\n\t\t\t\t\tpredecessor: chain.terminalMember.eventId,\n\t\t\t\t});\n\t\t\t\treturn { outcome: 'released' };\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'release-unavailable',\n\t\t\taddress: input.address,\n\t\t\tdetail: formatPgTransitionUnknownError(error),\n\t\t};\n\t}\n}\n","import type { Pool } from 'pg';\nimport type { PgPhysicalModel } from '../physical-model/index.js';\nimport { escapeDiagnosticText, validateIdentifier } from '../validate.js';\nimport {\n\tconvergePgPhysical,\n\ttype ConvergePgOptions as InternalConvergePgOptions,\n\ttype PgConvergeCheckResult,\n\tPgConvergeRefusalError,\n\ttype PgConvergeResult,\n\tphysicalConvergeOptions,\n} from './converge.js';\n\nexport interface ConvergePgBaseOptions\n\textends Omit<\n\t\tInternalConvergePgOptions,\n\t\t'schema' | 'dbCasing' | 'mode' | 'declaredSequenceNames' | 'fkAutoIndex'\n\t> {}\nexport interface ConvergePgOptions extends ConvergePgBaseOptions {\n\treadonly mode?: 'apply';\n}\n\nexport interface ConvergePgCheckOptions extends ConvergePgBaseOptions {\n\treadonly mode: 'check';\n}\n\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions?: ConvergePgOptions,\n): Promise<PgConvergeResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgCheckOptions,\n): Promise<PgConvergeCheckResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgOptions | ConvergePgCheckOptions = {},\n): Promise<PgConvergeResult | PgConvergeCheckResult> {\n\ttry {\n\t\tvalidateIdentifier(physical.schema, 'schema');\n\t} catch (error) {\n\t\tthrow new PgConvergeRefusalError(\n\t\t\t'invalid-options',\n\t\t\t[],\n\t\t\t`converge refuses physical schema ${escapeDiagnosticText(String(physical.schema))}: ${escapeDiagnosticText(error instanceof Error ? error.message : String(error))}`,\n\t\t);\n\t}\n\treturn convergePgPhysical(\n\t\tpool,\n\t\tphysical,\n\t\tphysicalConvergeOptions(physical, options),\n\t);\n}\n","import { createHash } from 'node:crypto';\nimport {\n\tacquireExclusiveTransitionLease,\n\tassumptionAccepted,\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\tresourceScopeCovers,\n\ttransitionPlanDigest,\n} from '@dbsp/core/internal';\nimport type {\n\tLedgerAddress,\n\tLedgerHome,\n\tLedgerPayload,\n\tResourceAddress,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport type {\n\tLedgerReservationRow,\n\tOutcomeIndeterminateRecoveryEvidence,\n} from '@dbsp/types/internal';\nimport type { Pool } from 'pg';\nimport { readPgLedgerAddressChain } from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport { readTransitionJournal } from './journal.js';\nimport { readPgLedgerReservationsForExecution } from './ledger.js';\nimport { withPgTransitionRunLock } from './lessor.js';\nimport { assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid } from './operations/create-unique-index-concurrently.js';\nimport { recoverPgOutcomeClaim } from './outcome-protocol.js';\nimport { recoverPgReaddressPair } from './readdress.js';\nimport {\n\ttype PgLedgerScopeCurrency,\n\treadPgLedgerScopeCurrency,\n\treadVerifiedPgLedgerReservationsForPair,\n} from './reinitialize-preflight.js';\n\nexport type PgReconcileRecoveryOutcome =\n\t| 'appended'\n\t| 'already-appended'\n\t| 'indeterminate-appended'\n\t| 'no-open-claim'\n\t| 'pending'\n\t| 'blocked'\n\t| 'malformed-chain'\n\t| 'protocol-refused'\n\t| 'transport-ambiguous'\n\t| 'refused-pair'\n\t| 'indeterminate-pair';\n\nexport type PgReconcileRecoveryFailureCause =\n\t| 'catalogue'\n\t| 'malformed-journal'\n\t| 'transport';\n\n/** One ordered recovery attempt; diagnostics are raw and presentation-free. */\nexport interface PgReconcileRecoveryReport {\n\treadonly address: LedgerAddress;\n\treadonly outcome: PgReconcileRecoveryOutcome;\n\treadonly reason?: string;\n\treadonly pairId?: string;\n\treadonly failureCause?: PgReconcileRecoveryFailureCause;\n}\n\n/** The selected semantic refusal condition, never a CLI refusal document. */\nexport type PgReconcileSelectedIssue =\n\t| {\n\t\t\treadonly kind: 'ledger-not-current';\n\t\t\treadonly currency: Exclude<\n\t\t\t\tPgLedgerScopeCurrency,\n\t\t\t\t{ readonly kind: 'current' }\n\t\t\t>;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly reason: string;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'catalogue-unavailable';\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\treadonly kind: 'malformed-chain';\n\t\t\treadonly address: LedgerAddress;\n\t };\n\ninterface PgReconcileBaseResult {\n\treadonly runId: string;\n\treadonly addresses: readonly ResourceAddress[];\n\treadonly recovery?: readonly PgReconcileRecoveryReport[];\n\treadonly selectedIssue?: PgReconcileSelectedIssue;\n}\n\nexport type PgReconcileTransitionRunResult =\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'completed';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'unresolved';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'selection-unavailable';\n\t\t\treadonly detail?: string;\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly selectedIssue: Extract<\n\t\t\t\tPgReconcileSelectedIssue,\n\t\t\t\t{ readonly kind: 'database-read-only' }\n\t\t\t>;\n\t })\n\t| {\n\t\t\treadonly kind: 'busy';\n\t\t\treadonly runId: string;\n\t\t\treadonly addresses: readonly ResourceAddress[];\n\t };\n\nexport type PgReconcileFailureStage = 'reconcile' | 'journal' | 'catalogue';\n\n/** A read/recovery failure whose original cause remains available to callers. */\nexport class PgReconcileTransitionRunError extends Error {\n\tconstructor(\n\t\treadonly stage: PgReconcileFailureStage,\n\t\treadonly originalCause: unknown,\n\t) {\n\t\tsuper('PostgreSQL transition-run reconciliation failed', {\n\t\t\tcause: originalCause,\n\t\t});\n\t\tthis.name = 'PgReconcileTransitionRunError';\n\t}\n}\n\nfunction ledgerHome(address: LedgerAddress): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped managed claim ${address.name} has no schema`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\n/** Canonicalizes catalogue identity for an outcome resolution payload. */\nexport function recoveryPayload(\n\tidentity: Parameters<\n\t\tNonNullable<Parameters<typeof recoverPgOutcomeClaim>[1]['readBack']>\n\t>[2],\n): LedgerPayload {\n\tconst value = JSON.parse(\n\t\tcanonicalJson({\n\t\t\t...(identity === undefined ? {} : { catalogueIdentity: identity }),\n\t\t}),\n\t) as LedgerPayload['value'];\n\treturn { value, digest: canonicalJsonDigest(value) };\n}\n\nfunction recoveryReport(\n\taddress: LedgerAddress,\n\tresult: Awaited<ReturnType<typeof recoverPgOutcomeClaim>>,\n): PgReconcileRecoveryReport {\n\tif (result.kind === 'outcome-recovery-appended') {\n\t\tconst indeterminate =\n\t\t\tresult.classification.resolution.eventKind === 'indeterminate';\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: indeterminate\n\t\t\t\t? 'indeterminate-appended'\n\t\t\t\t: result.append.kind === 'already-appended-outcome-resolution'\n\t\t\t\t\t? 'already-appended'\n\t\t\t\t\t: 'appended',\n\t\t\treason: result.classification.resolution.reason,\n\t\t};\n\t}\n\tif (result.kind === 'outcome-recovery-no-open-claim')\n\t\treturn { address, outcome: 'no-open-claim' };\n\tif (result.kind === 'outcome-recovery-pending')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'pending',\n\t\t\treason: result.reason,\n\t\t\t...(result.reasonCode === 'catalogue-unavailable'\n\t\t\t\t? { failureCause: 'catalogue' as const }\n\t\t\t\t: {}),\n\t\t};\n\tif (result.kind === 'outcome-recovery-blocked')\n\t\treturn { address, outcome: 'blocked', reason: result.reason };\n\tif (result.kind === 'outcome-recovery-malformed-chain')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'malformed-chain',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'malformed-journal',\n\t\t};\n\tif (result.kind === 'outcome-transport-ambiguous')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t};\n\treturn { address, outcome: 'protocol-refused', reason: result.reason };\n}\n\nfunction readdressRecoveryReport(\n\treservations: readonly LedgerReservationRow[],\n\tresult: Awaited<ReturnType<typeof recoverPgReaddressPair>>,\n): PgReconcileRecoveryReport {\n\tconst first = reservations[0];\n\tif (!first) throw new Error('re-address recovery has no reservation');\n\tif (result.kind === 'readdress-recovery-refused-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'refused-pair',\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-indeterminate-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'indeterminate-pair',\n\t\t\treason: result.reason,\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-transport-ambiguous-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t\tpairId: result.pairId,\n\t\t};\n\treturn {\n\t\taddress: first.address,\n\t\toutcome: 'pending',\n\t\treason: result.reason,\n\t\tpairId: result.pairId,\n\t};\n}\n\nfunction isUnresolvedRecoveryOutcome(\n\treport: PgReconcileRecoveryReport,\n): boolean {\n\treturn [\n\t\t'pending',\n\t\t'blocked',\n\t\t'malformed-chain',\n\t\t'protocol-refused',\n\t\t'transport-ambiguous',\n\t\t'no-open-claim',\n\t\t'indeterminate-appended',\n\t\t'indeterminate-pair',\n\t].includes(report.outcome);\n}\n\nfunction selectedRecoveryIssue(\n\treports: readonly PgReconcileRecoveryReport[],\n): PgReconcileSelectedIssue | undefined {\n\tfor (const report of reports) {\n\t\tif (report.failureCause === 'malformed-journal')\n\t\t\treturn { kind: 'malformed-chain', address: report.address };\n\t\tif (report.failureCause === 'catalogue')\n\t\t\treturn { kind: 'catalogue-unavailable', address: report.address };\n\t}\n\treturn undefined;\n}\n\nfunction statementBundleDigest(\n\tstatements: readonly { readonly ordinal: number; readonly sql: string }[],\n): string {\n\treturn createHash('sha256')\n\t\t.update(\n\t\t\tJSON.stringify(statements.map(({ ordinal, sql }) => [ordinal, sql])),\n\t\t)\n\t\t.digest('hex');\n}\n\nfunction recoveryEvidenceForClaim(input: {\n\treadonly journal: Awaited<ReturnType<typeof readTransitionJournal>>;\n\treadonly row: LedgerReservationRow;\n\treadonly plannedClaimKey: string;\n\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n}): OutcomeIndeterminateRecoveryEvidence | undefined {\n\tif (transitionPlanDigest(input.journal.plan) !== input.journal.run.planDigest)\n\t\treturn undefined;\n\tconst step = input.journal.plan.steps.find(\n\t\t(candidate) =>\n\t\t\tcandidate.managedClaim?.plannedClaimKey === input.plannedClaimKey,\n\t);\n\tconst claim = step?.managedClaim;\n\tif (\n\t\t!step ||\n\t\t!claim ||\n\t\t!sameLedgerAddress(claim.address, input.row.address) ||\n\t\toutcomeClaimId(\n\t\t\tinput.row.executionId,\n\t\t\tinput.plannedClaimKey,\n\t\t\tinput.row.address,\n\t\t) !== input.row.rootClaimId\n\t)\n\t\treturn undefined;\n\tconst binding = step.guards.find(\n\t\t(guard) =>\n\t\t\tguard.protocol.binding.kind === 'external-ddl-exclusion' &&\n\t\t\tresourceScopeCovers(guard.protocol.binding.scope, [input.row.address]),\n\t)?.protocol.binding;\n\tif (binding?.kind !== 'external-ddl-exclusion') return undefined;\n\tconst assumption = input.journal.plan.assumptions.find(\n\t\t(candidate) =>\n\t\t\tcandidate.id === binding.assumption &&\n\t\t\tcandidate.class === 'external-ddl-exclusion' &&\n\t\t\tstep.restsOnAssumptions.includes(candidate.id) &&\n\t\t\tresourceScopeCovers(candidate.scope, [input.row.address]),\n\t);\n\tif (!assumption) return undefined;\n\tconst accepted = input.journal.authorizations?.some((authorization) => {\n\t\tconst grant = authorization.grants.find(\n\t\t\t(candidate) => candidate.assumptionId === assumption.id,\n\t\t);\n\t\tif (!grant) return false;\n\t\tconst acceptance = authorization.policy[grant.grant];\n\t\treturn (\n\t\t\tacceptance !== undefined &&\n\t\t\tassumptionAccepted(assumption, { accepts: [acceptance] })\n\t\t);\n\t});\n\tif (!accepted) return undefined;\n\tconst bundleDigest = statementBundleDigest(claim.statementBundle.statements);\n\treturn {\n\t\trunId: input.journal.run.runId,\n\t\tplanDigest: input.journal.run.planDigest,\n\t\texecutionId: input.row.executionId,\n\t\tclaimId: input.row.rootClaimId,\n\t\tplannedClaimKey: input.plannedClaimKey,\n\t\tadmittedBundleDigest: bundleDigest,\n\t\tpersistedBundleDigest: bundleDigest,\n\t\trecordedPreState: input.stableStateBeforeClaim,\n\t\texternalDdlExclusion: {\n\t\t\tplanDigest: input.journal.run.planDigest,\n\t\t\taddress: input.row.address,\n\t\t\ttrustRoot: JSON.stringify(assumption.asserter),\n\t\t},\n\t};\n}\n\n/**\n * Returns recovery decisions for one durable run without reissuing DDL.\n *\n * Reconciliation keeps the run-lock session while `recoverPgOutcomeClaim`\n * acquires its own outcome session. The supplied pool must allow at least two\n * concurrent connections: a pool with `max: 1` waits forever under the lock.\n */\nexport async function reconcilePgTransitionRun(\n\tpool: Pool,\n\trunId: string,\n): Promise<PgReconcileTransitionRunResult> {\n\tlet stage: PgReconcileFailureStage = 'reconcile';\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\tpool,\n\t\t\trunId,\n\t\t\tasync (target) => {\n\t\t\t\tconst lease = await acquireExclusiveTransitionLease(target);\n\t\t\t\ttry {\n\t\t\t\t\tstage = 'journal';\n\t\t\t\t\tconst journal = await readTransitionJournal(lease.session, runId, {\n\t\t\t\t\t\tensure: false,\n\t\t\t\t\t});\n\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\tconst material: Array<{\n\t\t\t\t\t\treadonly address: LedgerAddress;\n\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t}> = journal.plan.steps\n\t\t\t\t\t\t.map((step) => {\n\t\t\t\t\t\t\tconst generatedStep = step as {\n\t\t\t\t\t\t\t\treadonly address?: LedgerAddress;\n\t\t\t\t\t\t\t\treadonly plannedClaimKeys?: readonly string[];\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst generated = generatedStep.address;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tstep.managedClaim ??\n\t\t\t\t\t\t\t\t(generated === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\taddress: generated,\n\t\t\t\t\t\t\t\t\t\t\t...(generatedStep.plannedClaimKeys?.[0] === undefined\n\t\t\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: generatedStep.plannedClaimKeys[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t(claim): claim is NonNullable<typeof claim> =>\n\t\t\t\t\t\t\t\tclaim !== undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait assertPgDatabaseWritable(lease.session);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (isPgDatabaseReadOnlyError(error)) {\n\t\t\t\t\t\t\tconst addresses = material.map((claim) => claim.address);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses,\n\t\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\t\treason: error.message,\n\t\t\t\t\t\t\t\t\taffectedAddresses: addresses,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (material.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\taddresses:\n\t\t\t\t\t\t\t\tjournal.plan.declarations?.declarations.map(\n\t\t\t\t\t\t\t\t\t(declaration) => declaration.address,\n\t\t\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\t};\n\t\t\t\t\tconst homes = new Map<string, LedgerHome>();\n\t\t\t\t\tfor (const claim of material) {\n\t\t\t\t\t\tconst home = ledgerHome(claim.address);\n\t\t\t\t\t\thomes.set(`${home.scope}:${home.schema ?? ''}`, home);\n\t\t\t\t\t}\n\t\t\t\t\tfor (const home of homes.values()) {\n\t\t\t\t\t\tconst currency = await readPgLedgerScopeCurrency(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (currency.kind === 'current') continue;\n\t\t\t\t\t\tconst affectedAddresses = material\n\t\t\t\t\t\t\t.filter((claim) => {\n\t\t\t\t\t\t\t\tconst claimHome = ledgerHome(claim.address);\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\tclaimHome.scope === home.scope &&\n\t\t\t\t\t\t\t\t\tclaimHome.schema === home.schema\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.map((claim) => claim.address);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\taddresses: affectedAddresses,\n\t\t\t\t\t\t\trecovery: affectedAddresses.map((address) => ({\n\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\toutcome: 'blocked' as const,\n\t\t\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\t\tcurrency.kind === 'not-current'\n\t\t\t\t\t\t\t\t\t\t? currency.reason\n\t\t\t\t\t\t\t\t\t\t: currency.kind,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\tkind: 'ledger-not-current' as const,\n\t\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t\t\taffectedAddresses,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst executionIds = executionIdsForRun(journal);\n\t\t\t\t\tconst reservations = (\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\t[...homes.values()].flatMap((home) =>\n\t\t\t\t\t\t\t\texecutionIds.map((executionId) =>\n\t\t\t\t\t\t\t\t\treadPgLedgerReservationsForExecution(\n\t\t\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t).flat();\n\t\t\t\t\tif (reservations.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\taddresses: material.map((claim) => claim.address),\n\t\t\t\t\t\t};\n\t\t\t\t\tconst readdressPairs = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tconst byRoot = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tfor (const row of reservations) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trow.claimKind === 'readdress-intent' &&\n\t\t\t\t\t\t\trow.pairId !== undefined\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst pairKey = `${row.executionId}:${row.pairId}`;\n\t\t\t\t\t\t\treaddressPairs.set(pairKey, [\n\t\t\t\t\t\t\t\t...(readdressPairs.get(pairKey) ?? []),\n\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbyRoot.set(row.rootClaimId, [\n\t\t\t\t\t\t\t...(byRoot.get(row.rootClaimId) ?? []),\n\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tconst recovery: PgReconcileRecoveryReport[] = [];\n\t\t\t\t\tfor (const pairRows of readdressPairs.values()) {\n\t\t\t\t\t\tconst pairId = pairRows[0]?.pairId;\n\t\t\t\t\t\tconst executionId = pairRows[0]?.executionId;\n\t\t\t\t\t\tif (!pairId || !executionId) continue;\n\t\t\t\t\t\tconst closure = await readVerifiedPgLedgerReservationsForPair(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\t[...homes.values()],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst recovered = await recoverPgReaddressPair(lease.session, {\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\treservations: closure,\n\t\t\t\t\t\t});\n\t\t\t\t\t\trecovery.push(readdressRecoveryReport(closure, recovered));\n\t\t\t\t\t}\n\t\t\t\t\tfor (const rows of byRoot.values()) {\n\t\t\t\t\t\tconst rootClaimId = rows[0]?.rootClaimId;\n\t\t\t\t\t\tif (!rootClaimId) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trows.some(\n\t\t\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t\t\t!executionIds.includes(row.executionId) ||\n\t\t\t\t\t\t\t\t\trow.rootClaimId !== rootClaimId,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `reservation disagreement for root claim ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst rootCandidates: Array<{\n\t\t\t\t\t\t\treadonly row: LedgerReservationRow;\n\t\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t\t\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n\t\t\t\t\t\t}> = [];\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tstage = 'catalogue';\n\t\t\t\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\tledgerHome(row.address),\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tprojection.kind !== 'projected-ledger-chain' ||\n\t\t\t\t\t\t\t\tprojection.openClaim === undefined\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tconst open = projection.openClaim.event;\n\t\t\t\t\t\t\tconst openRoot = open.rootClaimId ?? open.eventId;\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\topen.executionId !== row.executionId ||\n\t\t\t\t\t\t\t\topenRoot !== rootClaimId\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\t\taddresses: rows.map((item) => item.address),\n\t\t\t\t\t\t\t\t\tdetail: `open chain member disagrees with reservation root ${rootClaimId}`,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (open.eventId === rootClaimId)\n\t\t\t\t\t\t\t\trootCandidates.push({\n\t\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t\t\tstableStateBeforeClaim:\n\t\t\t\t\t\t\t\t\t\tprojection.openClaim.stableStateBeforeClaim,\n\t\t\t\t\t\t\t\t\t...(open.plannedClaimKey === undefined\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: { plannedClaimKey: open.plannedClaimKey }),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rootCandidates.length !== 1)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `execution ${runId} has ${rootCandidates.length} open root members for ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst selected = rootCandidates[0];\n\t\t\t\t\t\tif (!selected) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!selected.plannedClaimKey ||\n\t\t\t\t\t\t\t!material.some(\n\t\t\t\t\t\t\t\t(claim) => claim.plannedClaimKey === selected.plannedClaimKey,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `open root ${rootClaimId} has no matching persisted managed step`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst step = journal.plan.steps.find(\n\t\t\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t\t\tcandidate.managedClaim?.plannedClaimKey ===\n\t\t\t\t\t\t\t\t\tselected.plannedClaimKey ||\n\t\t\t\t\t\t\t\t('plannedClaimKeys' in candidate &&\n\t\t\t\t\t\t\t\t\tArray.isArray(candidate.plannedClaimKeys) &&\n\t\t\t\t\t\t\t\t\tcandidate.plannedClaimKeys.includes(\n\t\t\t\t\t\t\t\t\t\tselected.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst operationReadBack =\n\t\t\t\t\t\t\tstep?.operation?.operationKind.name ===\n\t\t\t\t\t\t\t'CreateUniqueIndexConcurrently'\n\t\t\t\t\t\t\t\t? async (\n\t\t\t\t\t\t\t\t\t\texecutor: Parameters<\n\t\t\t\t\t\t\t\t\t\t\ttypeof assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid\n\t\t\t\t\t\t\t\t\t\t>[0],\n\t\t\t\t\t\t\t\t\t\t_address: LedgerAddress,\n\t\t\t\t\t\t\t\t\t\tidentity: Parameters<typeof recoveryPayload>[0],\n\t\t\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\t\t\tawait assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid(\n\t\t\t\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\t\t\t\tstep.operation,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tobserved: recoveryPayload(identity),\n\t\t\t\t\t\t\t\t\t\t\teffect: 'unverifiable' as const,\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst indeterminateEvidence = recoveryEvidenceForClaim({\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\trow: selected.row,\n\t\t\t\t\t\t\tplannedClaimKey: selected.plannedClaimKey,\n\t\t\t\t\t\t\tstableStateBeforeClaim: selected.stableStateBeforeClaim,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tconst isRoot = sameLedgerAddress(\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t\tselected.row.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst recovered = await recoverPgOutcomeClaim(pool, {\n\t\t\t\t\t\t\t\taddress: row.address,\n\t\t\t\t\t\t\t\treservations: [row],\n\t\t\t\t\t\t\t\tresolutionEventId: isRoot\n\t\t\t\t\t\t\t\t\t? `${rootClaimId}:reconcile:${runId}`\n\t\t\t\t\t\t\t\t\t: `${rootClaimId}:reconcile:${runId}:${row.address.kind}:${row.address.name}`,\n\t\t\t\t\t\t\t\tacceptedExternalDdlExclusion:\n\t\t\t\t\t\t\t\t\tisRoot && indeterminateEvidence !== undefined,\n\t\t\t\t\t\t\t\tresolveIndeterminate: true,\n\t\t\t\t\t\t\t\treadBack: async (_executor, _address, identity) =>\n\t\t\t\t\t\t\t\t\trecoveryPayload(identity),\n\t\t\t\t\t\t\t\t...(isRoot && indeterminateEvidence !== undefined\n\t\t\t\t\t\t\t\t\t? { indeterminateEvidence }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t...(isRoot && operationReadBack !== undefined\n\t\t\t\t\t\t\t\t\t? { operationReadBack }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\trecovery.push(recoveryReport(row.address, recovered));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst unresolved = recovery.some(isUnresolvedRecoveryOutcome);\n\t\t\t\t\tconst issue = selectedRecoveryIssue(recovery);\n\t\t\t\t\treturn unresolved\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t\t\t...(issue === undefined ? {} : { selectedIssue: issue }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t\t};\n\t\t\t\t} finally {\n\t\t\t\t\tawait lease.release();\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tif (locked.kind === 'busy') return { kind: 'busy', runId, addresses: [] };\n\t\treturn locked.value;\n\t} catch (error) {\n\t\tthrow new PgReconcileTransitionRunError(stage, error);\n\t}\n}\n\n/** Finds every execution id durably attributable to one transition run. */\nexport function executionIdsForRun(\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n): readonly string[] {\n\tconst executionIds = new Set<string>([journal.run.runId]);\n\tfor (const event of journal.events) {\n\t\tconst record = event.record;\n\t\tif (\n\t\t\tevent.event === 'intent' &&\n\t\t\t'executionId' in record &&\n\t\t\ttypeof record.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.executionId);\n\t\tif (\n\t\t\tevent.event === 'observed' &&\n\t\t\t'intent' in record &&\n\t\t\trecord.intent &&\n\t\t\ttypeof record.intent.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.intent.executionId);\n\t}\n\tif ('generator' in journal.plan)\n\t\texecutionIds.add(`dbsp.generator.execution.${journal.run.runId}`);\n\treturn [...executionIds];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAU,YAChB,iBAAiB,UACjB,OAAO,OAAO,gBAAgB;AAE9B,mBAAa,IAAI,OAAO,WAAW;AACpC,QACC,MAAM,UAAU,cAChB,YAAY,UACZ,OAAO,UACP,OAAO,OAAO,OAAO,gBAAgB;AAErC,mBAAa,IAAI,OAAO,OAAO,WAAW;AAAA,EAC5C;AACA,MAAI,eAAe,QAAQ;AAC1B,iBAAa,IAAI,4BAA4B,QAAQ,IAAI,KAAK,EAAE;AACjE,SAAO,CAAC,GAAG,YAAY;AACxB;","names":["fn","literal","exprRef","fn","literal","op","param","sameControllerIdentity","projectLedgerChain","target","projectLedgerChain"]}
1
+ {"version":3,"sources":["../src/explain/explain.ts","../src/extensions/paradedb.ts","../src/extensions/pgsql-builtins.ts","../src/extensions/pgvector.ts","../src/redact-params.ts","../src/transition/release.ts","../src/transition/public-api.ts","../src/transition/reconcile.ts"],"sourcesContent":["/**\n * EXPLAIN Statement Compiler\n *\n * Generates PostgreSQL EXPLAIN statements with various options.\n * Supports:\n * - ANALYZE (execute and show actual run times)\n * - FORMAT (text, json, xml, yaml)\n * - VERBOSE, COSTS, BUFFERS, TIMING, SETTINGS\n */\n\nimport type { Node } from '@pgsql/types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Output format for EXPLAIN results.\n */\nexport type ExplainFormat = 'text' | 'json' | 'xml' | 'yaml';\n\n/**\n * Options for EXPLAIN statement.\n */\nexport interface ExplainOptions {\n\t/** Execute the query and show actual run times */\n\tanalyze?: boolean;\n\t/** Show more detailed output */\n\tverbose?: boolean;\n\t/** Show cost estimates (default: true) */\n\tcosts?: boolean;\n\t/** Show buffer usage (requires analyze) */\n\tbuffers?: boolean;\n\t/** Show actual timing (requires analyze) */\n\ttiming?: boolean;\n\t/** Show non-default settings */\n\tsettings?: boolean;\n\t/** Output format */\n\tformat?: ExplainFormat;\n}\n\n// ============================================================================\n// EXPLAIN Builder\n// ============================================================================\n\n/**\n * Build an EXPLAIN statement wrapping a query.\n *\n * @param query - The query to explain (SelectStmt, InsertStmt, etc.)\n * @param options - EXPLAIN options\n * @returns ExplainStmt AST node\n *\n * @example\n * ```typescript\n * const selectAst = { SelectStmt: { ... } };\n * const explainAst = buildExplain(selectAst, { analyze: true, format: 'json' });\n * // Produces: EXPLAIN (ANALYZE, FORMAT JSON) SELECT ...\n * ```\n */\nexport function buildExplain(query: Node, options: ExplainOptions = {}): Node {\n\tconst defElems: Node[] = [];\n\n\t// Add options in standard order\n\tif (options.analyze !== undefined) {\n\t\tdefElems.push(buildDefElem('analyze', options.analyze));\n\t}\n\n\tif (options.verbose !== undefined) {\n\t\tdefElems.push(buildDefElem('verbose', options.verbose));\n\t}\n\n\tif (options.costs !== undefined) {\n\t\tdefElems.push(buildDefElem('costs', options.costs));\n\t}\n\n\tif (options.buffers !== undefined) {\n\t\tdefElems.push(buildDefElem('buffers', options.buffers));\n\t}\n\n\tif (options.timing !== undefined) {\n\t\tdefElems.push(buildDefElem('timing', options.timing));\n\t}\n\n\tif (options.settings !== undefined) {\n\t\tdefElems.push(buildDefElem('settings', options.settings));\n\t}\n\n\tif (options.format) {\n\t\tdefElems.push(buildDefElem('format', options.format));\n\t}\n\n\tconst explainStmt: { query: Node; options?: Node[] } = { query };\n\tif (defElems.length > 0) {\n\t\texplainStmt.options = defElems;\n\t}\n\n\treturn { ExplainStmt: explainStmt };\n}\n\n/**\n * Build EXPLAIN ANALYZE with JSON format (common pattern).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with ANALYZE and JSON format\n */\nexport function buildExplainAnalyzeJson(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tformat: 'json',\n\t});\n}\n\n/**\n * Build simple EXPLAIN (plan only, no execution).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with default options\n */\nexport function buildExplainPlan(query: Node): Node {\n\treturn buildExplain(query);\n}\n\n/**\n * Build verbose EXPLAIN with costs and buffers.\n *\n * @param query - The query to explain\n * @returns ExplainStmt with verbose options\n */\nexport function buildExplainVerbose(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tverbose: true,\n\t\tbuffers: true,\n\t\ttiming: true,\n\t});\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Build a DefElem node for EXPLAIN options.\n *\n * @param name - Option name (analyze, verbose, format, etc.)\n * @param value - Option value (boolean or string)\n * @returns DefElem AST node\n */\nfunction buildDefElem(name: string, value: boolean | string): Node {\n\tlet arg: Node | undefined;\n\n\tif (typeof value === 'boolean') {\n\t\t// Boolean options: ANALYZE TRUE/FALSE\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value ? 'true' : 'false',\n\t\t\t},\n\t\t};\n\t} else {\n\t\t// String options: FORMAT json\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tDefElem: {\n\t\t\tdefname: name,\n\t\t\targ,\n\t\t\tdefaction: 'DEFELEM_UNSPEC',\n\t\t},\n\t};\n}\n\n/**\n * Parse EXPLAIN JSON output to get execution statistics.\n *\n * @param jsonOutput - The JSON string from EXPLAIN (ANALYZE, FORMAT JSON)\n * @returns Parsed plan with execution statistics\n */\nexport function parseExplainJson(jsonOutput: string): ExplainPlan[] {\n\ttry {\n\t\tconst parsed = JSON.parse(jsonOutput);\n\t\treturn Array.isArray(parsed) ? parsed : [parsed];\n\t} catch {\n\t\tthrow new Error('Failed to parse EXPLAIN JSON output');\n\t}\n}\n\n/**\n * Parsed EXPLAIN plan structure (simplified).\n */\nexport interface ExplainPlan {\n\tPlan: {\n\t\t'Node Type': string;\n\t\t'Relation Name'?: string;\n\t\tAlias?: string;\n\t\t'Startup Cost'?: number;\n\t\t'Total Cost'?: number;\n\t\t'Plan Rows'?: number;\n\t\t'Plan Width'?: number;\n\t\t'Actual Startup Time'?: number;\n\t\t'Actual Total Time'?: number;\n\t\t'Actual Rows'?: number;\n\t\t'Actual Loops'?: number;\n\t\tPlans?: ExplainPlan['Plan'][];\n\t};\n\t'Planning Time'?: number;\n\t'Execution Time'?: number;\n\tTriggers?: unknown[];\n}\n\n/**\n * Extract total execution time from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Total execution time in milliseconds\n */\nexport function getTotalExecutionTime(plans: ExplainPlan[]): number {\n\tif (plans.length === 0) return 0;\n\n\tconst plan = plans[0]!;\n\tconst planning = plan['Planning Time'] ?? 0;\n\tconst execution = plan['Execution Time'] ?? 0;\n\n\treturn planning + execution;\n}\n\n/**\n * Extract row counts from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Object with estimated and actual row counts\n */\nexport function getRowEstimates(plans: ExplainPlan[]): {\n\testimated: number;\n\tactual: number;\n} {\n\tif (plans.length === 0) return { estimated: 0, actual: 0 };\n\n\tconst rootPlan = plans[0]?.Plan;\n\tif (!rootPlan) return { estimated: 0, actual: 0 };\n\n\treturn {\n\t\testimated: rootPlan['Plan Rows'] ?? 0,\n\t\tactual: rootPlan['Actual Rows'] ?? 0,\n\t};\n}\n","/**\n * ParadeDB Extension Wrappers\n *\n * Type-safe query builders for ParadeDB BM25 full-text search.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(score('id').as('score'))\n * - WHERE: .where(bm25Search('symbols', query, { name: 3.0, doc: 1.0 }))\n * - ORDER BY: .orderBy(score('id'), 'desc')\n *\n * @remarks\n * ParadeDB functions accept both named and positional arguments.\n * This module uses named args via namedArg() for parse(), which produces:\n * paradedb.parse(field => 'field_name', query_string => $1)\n * Named parameter syntax is supported via the NamedArgExpressionIntent (EXT-NAMED-PARAMS).\n */\n\nimport {\n\tarray,\n\tExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\tnamedArg,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * BM25 relevance score for a row.\n *\n * Use in SELECT and ORDER BY to retrieve and sort by full-text relevance.\n * Requires a BM25 index on the table.\n *\n * @param keyField - The key field of the BM25 index (typically the primary key, e.g. 'id')\n * @returns ExpressionRef that compiles to: paradedb.score(\"keyField\")\n *\n * @example\n * orm.select('symbols').column(score('id').as('score')).orderBy(score('id'), 'desc')\n * // → paradedb.score(\"id\") AS \"score\"\n */\nexport function score(keyField: string): ExpressionRef {\n\treturn fn('paradedb.score', exprRef(keyField));\n}\n\n/**\n * Parse a single-field BM25 query expression.\n *\n * Compiles to: paradedb.parse(field => 'field_name', query_string => $N)\n *\n * @param field - Column name to search in (must be indexed in the BM25 index)\n * @param query - Query string value (will be bound as a parameter)\n * @returns ExpressionRef for use with boost() or booleanSearch()\n *\n * @example\n * parse('name', 'hello world')\n * // → paradedb.parse(field => 'name', query_string => $1)\n */\nexport function parse(\n\tfield: string,\n\tquery: ExpressionRef | unknown,\n): ExpressionRef {\n\t// If query is already an ExpressionRef, pass it directly so fn() unwraps .intent.\n\t// Otherwise, wrap it in param() so it becomes a bound $N parameter.\n\tconst queryExpr: ExpressionRef =\n\t\tquery instanceof ExpressionRef ? query : param(query);\n\treturn fn(\n\t\t'paradedb.parse',\n\t\tnamedArg('field', literal(field)),\n\t\tnamedArg('query_string', queryExpr),\n\t);\n}\n\n/**\n * Apply a boost multiplier to a BM25 sub-expression.\n *\n * Compiles to: paradedb.boost(factor, expr)\n *\n * @param factor - Boost multiplier (e.g. 3.0 for 3x weight)\n * @param expr - Expression to boost (typically a parse() call)\n * @returns ExpressionRef for use with booleanSearch()\n *\n * @example\n * boost(3.0, parse('name', 'hello'))\n * // → paradedb.boost(3.0, paradedb.parse('name', $1))\n */\nexport function boost(factor: number, expr: ExpressionRef): ExpressionRef {\n\treturn fn('paradedb.boost', literal(factor), expr);\n}\n\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(expr1, expr2, ...)\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(paradedb.boost(3.0, ...), paradedb.boost(1.0, ...))\n */\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(should => ARRAY[expr1, expr2, ...])\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(should => ARRAY[paradedb.boost(3.0, ...), paradedb.boost(1.0, ...)])\n */\nexport function booleanSearch(exprs: ExpressionRef[]): ExpressionRef {\n\treturn fn('paradedb.boolean', namedArg('should', array(...exprs)));\n}\n\n/**\n * Full BM25 multi-field search with per-field boost weights.\n *\n * Produces: table @@@ paradedb.boolean(boost1, boost2, ...)\n *\n * Each field in `fieldBoosts` generates a `paradedb.boost(weight, paradedb.parse(field, $N))`\n * sub-expression. The same query string is used for all fields (single parameter binding).\n *\n * @param table - Table alias for the left side of the @@@ operator\n * @param query - Query string (bound as a single $N parameter, shared across all fields)\n * @param fieldBoosts - Map of column name → boost weight\n * @returns ExpressionRef for use in .where()\n *\n * @example\n * bm25Search('s', searchTerm, {\n * name_searchable: 3.0,\n * name: 1.0,\n * signature: 1.5,\n * doc_searchable: 1.0,\n * })\n * // → s @@@ paradedb.boolean(\n * // paradedb.boost(3.0, paradedb.parse('name_searchable', $1)),\n * // paradedb.boost(1.0, paradedb.parse('name', $1)),\n * // paradedb.boost(1.5, paradedb.parse('signature', $1)),\n * // paradedb.boost(1.0, paradedb.parse('doc_searchable', $1))\n * // )\n *\n * @remarks\n * The query parameter is shared: all parse() calls reference the same $N slot.\n * If you need different query strings per field, compose parse()/boost()/booleanSearch() manually.\n *\n * @remarks\n * ParadeDB's boolean() function accepts both positional args and the named\n * `should => ARRAY[...]` syntax. This wrapper uses positional args.\n * Named parameter syntax is deferred to EXT-NAMED-PARAMS.\n */\nexport function bm25Search(\n\ttable: string,\n\tquery: unknown,\n\tfieldBoosts: Record<string, number>,\n): ExpressionRef {\n\tconst queryParam = param(query);\n\tconst boostExprs = Object.entries(fieldBoosts).map(([field, weight]) =>\n\t\tboost(weight, fn('paradedb.parse', literal(field), queryParam)),\n\t);\n\tconst booleanExpr = booleanSearch(boostExprs);\n\treturn op('@@@', exprRef(table), booleanExpr);\n}\n","/**\n * PostgreSQL built-in function helpers.\n *\n * Thin wrappers around core expression primitives for common PostgreSQL functions.\n * Same pattern as pgvector.ts and paradedb.ts.\n */\nimport { type ExpressionRef, fn, literal } from '@dbsp/core';\n\n/**\n * Generate a series of values: generate_series(start, stop[, step])\n *\n * Returns a set of values from start to stop (inclusive), with an optional step.\n * Commonly used with CTE for batch operations.\n *\n * @example generateSeries(1, 100) → generate_series(1, 100)\n * @example generateSeries(0, 50, 5) → generate_series(0, 50, 5)\n */\nexport function generateSeries(\n\tstart: number,\n\tstop: number,\n\tstep?: number,\n): ExpressionRef {\n\tconst args: ExpressionRef[] = [literal(start), literal(stop)];\n\tif (step !== undefined) {\n\t\targs.push(literal(step));\n\t}\n\treturn fn('generate_series', ...args);\n}\n\n/**\n * Get next value from a sequence: nextval('sequence_name')\n *\n * @example nextval('order_id_seq') → nextval('order_id_seq')\n */\nexport function nextval(sequenceName: string): ExpressionRef {\n\treturn fn('nextval', literal(sequenceName));\n}\n","/**\n * pgvector Extension Wrappers\n *\n * Type-safe query builders for pgvector distance operators.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(cosineDistance('vector', qv).as('score'))\n * - WHERE: .where(cosineDistance('vector', qv).gte(0.5))\n * - ORDER BY: .orderBy(rawDistance('vector', qv), 'asc')\n */\n\nimport {\n\tcast,\n\ttype ExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * Cosine similarity: 1 - (col <=> vector)\n *\n * Score in [0, 1], higher = more similar.\n * Use in SELECT to get a similarity score.\n *\n * @example\n * orm.select('embeddings').column(cosineDistance('vector', qv).as('score'))\n */\nexport function cosineDistance(\n\tcolumn: string,\n\tvector: number[],\n): ExpressionRef {\n\treturn op(\n\t\t'-',\n\t\tliteral(1),\n\t\top('<=>', exprRef(column), cast(param(vector), 'vector')),\n\t);\n}\n\n/**\n * Raw cosine distance: col <=> vector\n *\n * Lower = closer. Index-friendly — use in ORDER BY for ANN search.\n * Do NOT use in SELECT as a similarity score (lower = closer is counterintuitive).\n *\n * @example\n * orm.select('embeddings').orderBy(rawDistance('vector', qv), 'asc')\n */\nexport function rawDistance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<=>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * L2 (Euclidean) distance: col <-> vector\n *\n * @example\n * orm.select('embeddings').orderBy(l2Distance('vector', qv), 'asc')\n */\nexport function l2Distance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<->', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Inner product distance: col <#> vector (negative inner product)\n *\n * For maximum inner product search: ORDER BY innerProduct('vector', qv) ASC.\n *\n * @example\n * orm.select('embeddings').orderBy(innerProduct('vector', qv), 'asc')\n */\nexport function innerProduct(column: string, vector: number[]): ExpressionRef {\n\treturn op('<#>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Get the number of dimensions of a vector column: vector_dims(col)\n *\n * Returns an integer — the dimension count of the stored vector.\n * Useful for sanity-checking that embeddings match the expected model dimension.\n *\n * @example\n * orm.from(embeddings).columns([vectorDims('vector').as('dim')]).first()\n * // → SELECT vector_dims(\"t0\".\"vector\") AS \"dim\" FROM \"embeddings\" AS \"t0\"\n */\nexport function vectorDims(column: string): ExpressionRef {\n\treturn fn('vector_dims', exprRef(column));\n}\n","/**\n * Redact sensitive values in a query dump's `params` array before logging.\n *\n * Defense-in-depth helper: when application code may have inserted PII as\n * literal parameter values (e.g. an email in a WHERE clause), this replaces\n * any string value matching a configured pattern with the `replacement`\n * placeholder. Non-string values are passed through unchanged.\n */\n\nexport type RedactionPattern = string | RegExp;\n\nexport type RedactionConfig = {\n\t/** Patterns to match against string param values. String = substring (case-insensitive); RegExp = `.test()`. */\n\treadonly patterns: ReadonlyArray<RedactionPattern>;\n\t/** Placeholder substituted for matched values. Default `'[REDACTED]'`. */\n\treadonly replacement?: string;\n};\n\n/**\n * Curated regex set for common PII shapes. Match against the value itself\n * (not the column name), so they detect data shaped like an email / token /\n * credit-card / SSN regardless of which `$N` slot it landed in.\n *\n * @stable Adding entries is non-breaking; removing one is a semver-major change\n * because callers may rely on a specific shape being redacted.\n */\nexport const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp> = Object.freeze([\n\t/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/, // email\n\t/^Bearer\\s+[A-Za-z0-9._-]+$/i, // bearer token\n\t/^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, // JWT\n\t/^\\d{3}-\\d{2}-\\d{4}$/, // US SSN\n\t/^\\d(?:[ -]?\\d){12,18}$/, // credit card (13-19 digits, optional spaces/dashes between)\n\t/^sk-[A-Za-z0-9]{20,}$/, // OpenAI-style API key\n]);\n\nconst DEFAULT_REPLACEMENT = '[REDACTED]';\n\n/**\n * Returns a NEW array of params with sensitive string values replaced.\n * The input array is never mutated. Non-string values pass through unchanged.\n */\nexport function redactParams(\n\tparams: readonly unknown[],\n\tconfig: RedactionConfig,\n): readonly unknown[] {\n\tconst replacement = config.replacement ?? DEFAULT_REPLACEMENT;\n\treturn params.map((value) =>\n\t\tmatchesAnyPattern(value, config.patterns) ? replacement : value,\n\t);\n}\n\nfunction matchesAnyPattern(\n\tvalue: unknown,\n\tpatterns: ReadonlyArray<RedactionPattern>,\n): boolean {\n\tif (typeof value !== 'string') return false;\n\tconst lowerValue = value.toLowerCase();\n\tfor (const pattern of patterns) {\n\t\tif (typeof pattern === 'string') {\n\t\t\tif (pattern.length > 0 && lowerValue.includes(pattern.toLowerCase()))\n\t\t\t\treturn true;\n\t\t} else {\n\t\t\tconst re =\n\t\t\t\tpattern.global || pattern.sticky\n\t\t\t\t\t? new RegExp(pattern.source, pattern.flags)\n\t\t\t\t\t: pattern;\n\t\t\tif (re.test(value)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n","/** End management without issuing DDL or accepting a caller-supplied controller. */\nimport { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport { projectLedgerChain } from '@dbsp/core/internal';\nimport type { LedgerAddress, LedgerHome } from '@dbsp/types';\nimport * as transitionTypes from '@dbsp/types';\nimport { refusalFor } from '@dbsp/types';\nimport type { LedgerRefusal } from '@dbsp/types/internal';\nimport type { readPgCatalogueIdentity } from './catalogue-identity.js';\nimport {\n\treadPgLedgerAddressChain,\n\treadPgLedgerControllerOid,\n} from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport type { TransitionJournalQueryable } from './journal.js';\nimport {\n\tacquirePgLedgerLocks,\n\tappendPgLedgerRelease,\n\ttype PgLedgerTarget,\n} from './ledger.js';\nimport {\n\tformatPgTransitionUnknownError,\n\tPgResolvableRelationIdentityReadError,\n\treadPgCatalogueIdentityWithResolvableRelationLock,\n} from './lock-relation.js';\nimport {\n\tsetPgTransitionLockTimeout,\n\twithPgTransitionTransaction,\n} from './outcome-protocol.js';\nimport { createPostLockAdmissionEvidence } from './post-lock-admission-evidence.js';\nimport { readPgLedgerScopeCurrency } from './reinitialize-preflight.js';\n\ntype ControllerIdentity = { readonly name: string; readonly oid: string };\ntype ControllerIdentityHelper = (\n\trecorded: ControllerIdentity,\n\tcurrent: ControllerIdentity,\n) => boolean;\n\nconst sameControllerIdentity =\n\t(\n\t\ttransitionTypes as typeof transitionTypes & {\n\t\t\treadonly sameControllerIdentity?: ControllerIdentityHelper;\n\t\t}\n\t).sameControllerIdentity ??\n\t((recorded, current) =>\n\t\trecorded.name === current.name && recorded.oid === current.oid);\n\nexport type PgReleaseResult =\n\t| { readonly outcome: 'released' }\n\t| {\n\t\t\t/** A managed mutation must name a non-writable target before any release read. */\n\t\t\treadonly outcome: 'database-read-only';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\t/** Transport/query/read-only failure; never mislabel it malformed chain. */\n\t\t\treadonly outcome: 'release-unavailable';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\treadonly outcome: 'release-refused';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t\t\treadonly refusal: LedgerRefusal;\n\t };\n\nfunction releaseRefusal(\n\taddress: LedgerAddress,\n\tcode: 'ERR-02' | 'ERR-05' | 'ERR-06' | 'ERR-08' | 'ERR-09',\n\tstate: LedgerRefusal['state'],\n): Extract<PgReleaseResult, { readonly outcome: 'release-refused' }> {\n\tconst refusal = refusalFor(code, { address, state });\n\treturn {\n\t\toutcome: 'release-refused',\n\t\tdetail: refusal.cause,\n\t\taddress,\n\t\trefusal,\n\t};\n}\n\nfunction target(home: LedgerHome): PgLedgerTarget {\n\tif (home.scope === 'database') return { scope: 'database' };\n\tif (!home.schema) throw new Error('schema release requires a schema ledger');\n\treturn { scope: 'schema', schema: home.schema };\n}\n\n/**\n * Refuse from the live subject before opening a release transaction.\n *\n * This is intentionally only an early refusal pass: success still repeats\n * every fact under the ledger lock below. It means a pending, blocked,\n * foreign-controller, or stale-lineage address keeps its classified refusal\n * even when a subsequently unnecessary transaction cleanup loses transport.\n */\nasync function preflightReleaseRefusal(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult | undefined> {\n\tconst currency = await readPgLedgerScopeCurrency(input.executor, input.home);\n\tif (currency.kind !== 'current')\n\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\tconst chain = await readPgLedgerAddressChain(\n\t\tinput.executor,\n\t\tinput.home,\n\t\tinput.address,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\tif (projection.openClaim !== undefined)\n\t\treturn releaseRefusal(input.address, 'ERR-08', projection.stableState);\n\tif (projection.stableState !== 'managed' || !chain.terminalMember)\n\t\treturn releaseRefusal(input.address, 'ERR-02', projection.stableState);\n\tconst user = await input.executor.query(\n\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t);\n\tconst currentUser = user.rows[0]?.current_user;\n\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\tif (typeof currentUser !== 'string' || typeof currentUserOid !== 'string')\n\t\tthrow new Error('current_user role identity is unreadable');\n\tconst controllerOid =\n\t\t(\n\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\treadonly controllerOid?: string;\n\t\t\t}\n\t\t).controllerOid ??\n\t\t(await readPgLedgerControllerOid(\n\t\t\tinput.executor,\n\t\t\tinput.home,\n\t\t\tinput.address,\n\t\t\tchain.terminalMember.eventId,\n\t\t));\n\tif (\n\t\t!sameControllerIdentity(\n\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t)\n\t)\n\t\treturn releaseRefusal(input.address, 'ERR-05', projection.stableState);\n\treturn undefined;\n}\n\nexport async function releasePgManagedAddress(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult> {\n\ttry {\n\t\ttry {\n\t\t\tawait assertPgDatabaseWritable(input.executor);\n\t\t} catch (error) {\n\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'database-read-only',\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\tdetail: error.message,\n\t\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t\tconst earlyRefusal = await preflightReleaseRefusal(input);\n\t\tif (earlyRefusal) return earlyRefusal;\n\t\treturn await withPgTransitionTransaction(\n\t\t\tinput.executor,\n\t\t\tasync (executor) => {\n\t\t\t\tawait setPgTransitionLockTimeout(executor);\n\t\t\t\tconst lock = await acquirePgLedgerLocks(executor, [input.home]);\n\t\t\t\tif (lock.kind !== 'acquired') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait createPostLockAdmissionEvidence(executor, lock.proof);\n\t\t\t\t} catch {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\t\t\t\t}\n\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\texecutor,\n\t\t\t\t\tinput.home,\n\t\t\t\t\tinput.address,\n\t\t\t\t);\n\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\tif (projection.kind !== 'projected-ledger-chain') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\tif (projection.openClaim !== undefined) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-08',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (projection.stableState !== 'managed' || !chain.terminalMember) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-02',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst user = await executor.query(\n\t\t\t\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t\t\t\t);\n\t\t\t\tconst currentUser = user.rows[0]?.current_user;\n\t\t\t\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\t\t\t\tif (\n\t\t\t\t\ttypeof currentUser !== 'string' ||\n\t\t\t\t\ttypeof currentUserOid !== 'string'\n\t\t\t\t)\n\t\t\t\t\tthrow new Error('current_user role identity is unreadable');\n\t\t\t\tconst controllerOid =\n\t\t\t\t\t(\n\t\t\t\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\t\t\t\treadonly controllerOid?: string;\n\t\t\t\t\t\t}\n\t\t\t\t\t).controllerOid ??\n\t\t\t\t\t(await readPgLedgerControllerOid(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.home,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\tchain.terminalMember.eventId,\n\t\t\t\t\t));\n\t\t\t\tif (\n\t\t\t\t\t!sameControllerIdentity(\n\t\t\t\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet live: Awaited<ReturnType<typeof readPgCatalogueIdentity>>;\n\t\t\t\ttry {\n\t\t\t\t\tlive = await readPgCatalogueIdentityWithResolvableRelationLock(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'release',\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof PgResolvableRelationIdentityReadError))\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-09',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!live?.catalogueIdentity ||\n\t\t\t\t\t!chain.terminalMember.catalogueIdentity ||\n\t\t\t\t\t!isDeepStrictEqual(\n\t\t\t\t\t\tlive.catalogueIdentity,\n\t\t\t\t\t\tchain.terminalMember.catalogueIdentity,\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t// Kinds without a lockable relation retain the narrow window after this\n\t\t\t\t// final identity read and before their release append.\n\t\t\t\tconst eventId = `dbsp.release.${randomUUID()}`;\n\t\t\t\tawait appendPgLedgerRelease(executor, target(input.home), {\n\t\t\t\t\teventId,\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\teventKind: 'released',\n\t\t\t\t\tpredecessor: chain.terminalMember.eventId,\n\t\t\t\t});\n\t\t\t\treturn { outcome: 'released' };\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'release-unavailable',\n\t\t\taddress: input.address,\n\t\t\tdetail: formatPgTransitionUnknownError(error),\n\t\t};\n\t}\n}\n","import type { Pool } from 'pg';\nimport type { PgPhysicalModel } from '../physical-model/index.js';\nimport { escapeDiagnosticText, validateIdentifier } from '../validate.js';\nimport {\n\tconvergePgPhysical,\n\ttype ConvergePgOptions as InternalConvergePgOptions,\n\ttype PgConvergeCheckResult,\n\tPgConvergeRefusalError,\n\ttype PgConvergeResult,\n\tphysicalConvergeOptions,\n} from './converge.js';\n\nexport interface ConvergePgBaseOptions\n\textends Omit<\n\t\tInternalConvergePgOptions,\n\t\t'schema' | 'dbCasing' | 'mode' | 'declaredSequenceNames' | 'fkAutoIndex'\n\t> {}\nexport interface ConvergePgOptions extends ConvergePgBaseOptions {\n\treadonly mode?: 'apply';\n}\n\nexport interface ConvergePgCheckOptions extends ConvergePgBaseOptions {\n\treadonly mode: 'check';\n}\n\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions?: ConvergePgOptions,\n): Promise<PgConvergeResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgCheckOptions,\n): Promise<PgConvergeCheckResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgOptions | ConvergePgCheckOptions = {},\n): Promise<PgConvergeResult | PgConvergeCheckResult> {\n\ttry {\n\t\tvalidateIdentifier(physical.schema, 'schema');\n\t} catch (error) {\n\t\tthrow new PgConvergeRefusalError(\n\t\t\t'invalid-options',\n\t\t\t[],\n\t\t\t`converge refuses physical schema ${escapeDiagnosticText(String(physical.schema))}: ${escapeDiagnosticText(error instanceof Error ? error.message : String(error))}`,\n\t\t);\n\t}\n\treturn convergePgPhysical(\n\t\tpool,\n\t\tphysical,\n\t\tphysicalConvergeOptions(physical, options),\n\t);\n}\n","import { createHash } from 'node:crypto';\nimport {\n\tacquireExclusiveTransitionLease,\n\tassumptionAccepted,\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\tresourceScopeCovers,\n\ttransitionPlanDigest,\n} from '@dbsp/core/internal';\nimport type {\n\tLedgerAddress,\n\tLedgerHome,\n\tLedgerPayload,\n\tResourceAddress,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport type {\n\tLedgerReservationRow,\n\tOutcomeIndeterminateRecoveryEvidence,\n} from '@dbsp/types/internal';\nimport type { Pool } from 'pg';\nimport { readPgLedgerAddressChain } from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport { readTransitionJournal } from './journal.js';\nimport { readPgLedgerReservationsForExecution } from './ledger.js';\nimport { withPgTransitionRunLock } from './lessor.js';\nimport { assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid } from './operations/create-unique-index-concurrently.js';\nimport { recoverPgOutcomeClaim } from './outcome-protocol.js';\nimport { recoverPgReaddressPair } from './readdress.js';\nimport {\n\ttype PgLedgerScopeCurrency,\n\treadPgLedgerScopeCurrency,\n\treadVerifiedPgLedgerReservationsForPair,\n} from './reinitialize-preflight.js';\n\nexport type PgReconcileRecoveryOutcome =\n\t| 'appended'\n\t| 'already-appended'\n\t| 'indeterminate-appended'\n\t| 'no-open-claim'\n\t| 'pending'\n\t| 'blocked'\n\t| 'malformed-chain'\n\t| 'protocol-refused'\n\t| 'transport-ambiguous'\n\t| 'refused-pair'\n\t| 'indeterminate-pair';\n\nexport type PgReconcileRecoveryFailureCause =\n\t| 'catalogue'\n\t| 'malformed-journal'\n\t| 'transport';\n\n/** One ordered recovery attempt; diagnostics are raw and presentation-free. */\nexport interface PgReconcileRecoveryReport {\n\treadonly address: LedgerAddress;\n\treadonly outcome: PgReconcileRecoveryOutcome;\n\treadonly reason?: string;\n\treadonly pairId?: string;\n\treadonly failureCause?: PgReconcileRecoveryFailureCause;\n}\n\n/** The selected semantic refusal condition, never a CLI refusal document. */\nexport type PgReconcileSelectedIssue =\n\t| {\n\t\t\treadonly kind: 'ledger-not-current';\n\t\t\treadonly currency: Exclude<\n\t\t\t\tPgLedgerScopeCurrency,\n\t\t\t\t{ readonly kind: 'current' }\n\t\t\t>;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly reason: string;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'catalogue-unavailable';\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\treadonly kind: 'malformed-chain';\n\t\t\treadonly address: LedgerAddress;\n\t };\n\ninterface PgReconcileBaseResult {\n\treadonly runId: string;\n\treadonly addresses: readonly ResourceAddress[];\n\treadonly recovery?: readonly PgReconcileRecoveryReport[];\n\treadonly selectedIssue?: PgReconcileSelectedIssue;\n}\n\nexport type PgReconcileTransitionRunResult =\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'completed';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'unresolved';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'selection-unavailable';\n\t\t\treadonly detail?: string;\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly selectedIssue: Extract<\n\t\t\t\tPgReconcileSelectedIssue,\n\t\t\t\t{ readonly kind: 'database-read-only' }\n\t\t\t>;\n\t })\n\t| {\n\t\t\treadonly kind: 'busy';\n\t\t\treadonly runId: string;\n\t\t\treadonly addresses: readonly ResourceAddress[];\n\t };\n\nexport type PgReconcileFailureStage = 'reconcile' | 'journal' | 'catalogue';\n\n/** A read/recovery failure whose original cause remains available to callers. */\nexport class PgReconcileTransitionRunError extends Error {\n\tconstructor(\n\t\treadonly stage: PgReconcileFailureStage,\n\t\treadonly originalCause: unknown,\n\t) {\n\t\tsuper('PostgreSQL transition-run reconciliation failed', {\n\t\t\tcause: originalCause,\n\t\t});\n\t\tthis.name = 'PgReconcileTransitionRunError';\n\t}\n}\n\nfunction ledgerHome(address: LedgerAddress): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped managed claim ${address.name} has no schema`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\n/** Canonicalizes catalogue identity for an outcome resolution payload. */\nexport function recoveryPayload(\n\tidentity: Parameters<\n\t\tNonNullable<Parameters<typeof recoverPgOutcomeClaim>[1]['readBack']>\n\t>[2],\n): LedgerPayload {\n\tconst value = JSON.parse(\n\t\tcanonicalJson({\n\t\t\t...(identity === undefined ? {} : { catalogueIdentity: identity }),\n\t\t}),\n\t) as LedgerPayload['value'];\n\treturn { value, digest: canonicalJsonDigest(value) };\n}\n\nfunction recoveryReport(\n\taddress: LedgerAddress,\n\tresult: Awaited<ReturnType<typeof recoverPgOutcomeClaim>>,\n): PgReconcileRecoveryReport {\n\tif (result.kind === 'outcome-recovery-appended') {\n\t\tconst indeterminate =\n\t\t\tresult.classification.resolution.eventKind === 'indeterminate';\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: indeterminate\n\t\t\t\t? 'indeterminate-appended'\n\t\t\t\t: result.append.kind === 'already-appended-outcome-resolution'\n\t\t\t\t\t? 'already-appended'\n\t\t\t\t\t: 'appended',\n\t\t\treason: result.classification.resolution.reason,\n\t\t};\n\t}\n\tif (result.kind === 'outcome-recovery-no-open-claim')\n\t\treturn { address, outcome: 'no-open-claim' };\n\tif (result.kind === 'outcome-recovery-pending')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'pending',\n\t\t\treason: result.reason,\n\t\t\t...(result.reasonCode === 'catalogue-unavailable'\n\t\t\t\t? { failureCause: 'catalogue' as const }\n\t\t\t\t: {}),\n\t\t};\n\tif (result.kind === 'outcome-recovery-blocked')\n\t\treturn { address, outcome: 'blocked', reason: result.reason };\n\tif (result.kind === 'outcome-recovery-malformed-chain')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'malformed-chain',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'malformed-journal',\n\t\t};\n\tif (result.kind === 'outcome-transport-ambiguous')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t};\n\treturn { address, outcome: 'protocol-refused', reason: result.reason };\n}\n\nfunction readdressRecoveryReport(\n\treservations: readonly LedgerReservationRow[],\n\tresult: Awaited<ReturnType<typeof recoverPgReaddressPair>>,\n): PgReconcileRecoveryReport {\n\tconst first = reservations[0];\n\tif (!first) throw new Error('re-address recovery has no reservation');\n\tif (result.kind === 'readdress-recovery-refused-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'refused-pair',\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-indeterminate-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'indeterminate-pair',\n\t\t\treason: result.reason,\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-transport-ambiguous-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t\tpairId: result.pairId,\n\t\t};\n\treturn {\n\t\taddress: first.address,\n\t\toutcome: 'pending',\n\t\treason: result.reason,\n\t\tpairId: result.pairId,\n\t};\n}\n\nfunction isUnresolvedRecoveryOutcome(\n\treport: PgReconcileRecoveryReport,\n): boolean {\n\treturn [\n\t\t'pending',\n\t\t'blocked',\n\t\t'malformed-chain',\n\t\t'protocol-refused',\n\t\t'transport-ambiguous',\n\t\t'no-open-claim',\n\t\t'indeterminate-appended',\n\t\t'indeterminate-pair',\n\t].includes(report.outcome);\n}\n\nfunction selectedRecoveryIssue(\n\treports: readonly PgReconcileRecoveryReport[],\n): PgReconcileSelectedIssue | undefined {\n\tfor (const report of reports) {\n\t\tif (report.failureCause === 'malformed-journal')\n\t\t\treturn { kind: 'malformed-chain', address: report.address };\n\t\tif (report.failureCause === 'catalogue')\n\t\t\treturn { kind: 'catalogue-unavailable', address: report.address };\n\t}\n\treturn undefined;\n}\n\nfunction statementBundleDigest(\n\tstatements: readonly { readonly ordinal: number; readonly sql: string }[],\n): string {\n\treturn createHash('sha256')\n\t\t.update(\n\t\t\tJSON.stringify(statements.map(({ ordinal, sql }) => [ordinal, sql])),\n\t\t)\n\t\t.digest('hex');\n}\n\nfunction recoveryEvidenceForClaim(input: {\n\treadonly journal: Awaited<ReturnType<typeof readTransitionJournal>>;\n\treadonly row: LedgerReservationRow;\n\treadonly plannedClaimKey: string;\n\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n}): OutcomeIndeterminateRecoveryEvidence | undefined {\n\tif (transitionPlanDigest(input.journal.plan) !== input.journal.run.planDigest)\n\t\treturn undefined;\n\tconst step = input.journal.plan.steps.find(\n\t\t(candidate) =>\n\t\t\tcandidate.managedClaim?.plannedClaimKey === input.plannedClaimKey,\n\t);\n\tconst claim = step?.managedClaim;\n\tif (\n\t\t!step ||\n\t\t!claim ||\n\t\t!sameLedgerAddress(claim.address, input.row.address) ||\n\t\toutcomeClaimId(\n\t\t\tinput.row.executionId,\n\t\t\tinput.plannedClaimKey,\n\t\t\tinput.row.address,\n\t\t) !== input.row.rootClaimId\n\t)\n\t\treturn undefined;\n\tconst binding = step.guards.find(\n\t\t(guard) =>\n\t\t\tguard.protocol.binding.kind === 'external-ddl-exclusion' &&\n\t\t\tresourceScopeCovers(guard.protocol.binding.scope, [input.row.address]),\n\t)?.protocol.binding;\n\tif (binding?.kind !== 'external-ddl-exclusion') return undefined;\n\tconst assumption = input.journal.plan.assumptions.find(\n\t\t(candidate) =>\n\t\t\tcandidate.id === binding.assumption &&\n\t\t\tcandidate.class === 'external-ddl-exclusion' &&\n\t\t\tstep.restsOnAssumptions.includes(candidate.id) &&\n\t\t\tresourceScopeCovers(candidate.scope, [input.row.address]),\n\t);\n\tif (!assumption) return undefined;\n\tconst accepted = input.journal.authorizations?.some((authorization) => {\n\t\tconst grant = authorization.grants.find(\n\t\t\t(candidate) => candidate.assumptionId === assumption.id,\n\t\t);\n\t\tif (!grant) return false;\n\t\tconst acceptance = authorization.policy[grant.grant];\n\t\treturn (\n\t\t\tacceptance !== undefined &&\n\t\t\tassumptionAccepted(assumption, { accepts: [acceptance] })\n\t\t);\n\t});\n\tif (!accepted) return undefined;\n\tconst bundleDigest = statementBundleDigest(claim.statementBundle.statements);\n\treturn {\n\t\trunId: input.journal.run.runId,\n\t\tplanDigest: input.journal.run.planDigest,\n\t\texecutionId: input.row.executionId,\n\t\tclaimId: input.row.rootClaimId,\n\t\tplannedClaimKey: input.plannedClaimKey,\n\t\tadmittedBundleDigest: bundleDigest,\n\t\tpersistedBundleDigest: bundleDigest,\n\t\trecordedPreState: input.stableStateBeforeClaim,\n\t\texternalDdlExclusion: {\n\t\t\tplanDigest: input.journal.run.planDigest,\n\t\t\taddress: input.row.address,\n\t\t\ttrustRoot: JSON.stringify(assumption.asserter),\n\t\t},\n\t};\n}\n\n/**\n * Returns recovery decisions for one durable run without reissuing DDL.\n *\n * Reconciliation keeps the run-lock session while `recoverPgOutcomeClaim`\n * acquires its own outcome session. The supplied pool must allow at least two\n * concurrent connections: a pool with `max: 1` waits forever under the lock.\n */\nexport async function reconcilePgTransitionRun(\n\tpool: Pool,\n\trunId: string,\n): Promise<PgReconcileTransitionRunResult> {\n\tlet stage: PgReconcileFailureStage = 'reconcile';\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\tpool,\n\t\t\trunId,\n\t\t\tasync (target) => {\n\t\t\t\tconst lease = await acquireExclusiveTransitionLease(target);\n\t\t\t\ttry {\n\t\t\t\t\tstage = 'journal';\n\t\t\t\t\tconst journal = await readTransitionJournal(lease.session, runId, {\n\t\t\t\t\t\tensure: false,\n\t\t\t\t\t});\n\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\tconst material: Array<{\n\t\t\t\t\t\treadonly address: LedgerAddress;\n\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t}> = journal.plan.steps\n\t\t\t\t\t\t.map((step) => {\n\t\t\t\t\t\t\tconst generatedStep = step as {\n\t\t\t\t\t\t\t\treadonly address?: LedgerAddress;\n\t\t\t\t\t\t\t\treadonly plannedClaimKeys?: readonly string[];\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst generated = generatedStep.address;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tstep.managedClaim ??\n\t\t\t\t\t\t\t\t(generated === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\taddress: generated,\n\t\t\t\t\t\t\t\t\t\t\t...(generatedStep.plannedClaimKeys?.[0] === undefined\n\t\t\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: generatedStep.plannedClaimKeys[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t(claim): claim is NonNullable<typeof claim> =>\n\t\t\t\t\t\t\t\tclaim !== undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait assertPgDatabaseWritable(lease.session);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (isPgDatabaseReadOnlyError(error)) {\n\t\t\t\t\t\t\tconst addresses = material.map((claim) => claim.address);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses,\n\t\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\t\treason: error.message,\n\t\t\t\t\t\t\t\t\taffectedAddresses: addresses,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (material.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\taddresses:\n\t\t\t\t\t\t\t\tjournal.plan.declarations?.declarations.map(\n\t\t\t\t\t\t\t\t\t(declaration) => declaration.address,\n\t\t\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\t};\n\t\t\t\t\tconst homes = new Map<string, LedgerHome>();\n\t\t\t\t\tfor (const claim of material) {\n\t\t\t\t\t\tconst home = ledgerHome(claim.address);\n\t\t\t\t\t\thomes.set(`${home.scope}:${home.schema ?? ''}`, home);\n\t\t\t\t\t}\n\t\t\t\t\tfor (const home of homes.values()) {\n\t\t\t\t\t\tconst currency = await readPgLedgerScopeCurrency(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (currency.kind === 'current') continue;\n\t\t\t\t\t\tconst affectedAddresses = material\n\t\t\t\t\t\t\t.filter((claim) => {\n\t\t\t\t\t\t\t\tconst claimHome = ledgerHome(claim.address);\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\tclaimHome.scope === home.scope &&\n\t\t\t\t\t\t\t\t\tclaimHome.schema === home.schema\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.map((claim) => claim.address);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\taddresses: affectedAddresses,\n\t\t\t\t\t\t\trecovery: affectedAddresses.map((address) => ({\n\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\toutcome: 'blocked' as const,\n\t\t\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\t\tcurrency.kind === 'not-current'\n\t\t\t\t\t\t\t\t\t\t? currency.reason\n\t\t\t\t\t\t\t\t\t\t: currency.kind,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\tkind: 'ledger-not-current' as const,\n\t\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t\t\taffectedAddresses,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst executionIds = executionIdsForRun(journal);\n\t\t\t\t\tconst reservations = (\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\t[...homes.values()].flatMap((home) =>\n\t\t\t\t\t\t\t\texecutionIds.map((executionId) =>\n\t\t\t\t\t\t\t\t\treadPgLedgerReservationsForExecution(\n\t\t\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t).flat();\n\t\t\t\t\tif (reservations.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\taddresses: material.map((claim) => claim.address),\n\t\t\t\t\t\t};\n\t\t\t\t\tconst readdressPairs = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tconst byRoot = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tfor (const row of reservations) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trow.claimKind === 'readdress-intent' &&\n\t\t\t\t\t\t\trow.pairId !== undefined\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst pairKey = `${row.executionId}:${row.pairId}`;\n\t\t\t\t\t\t\treaddressPairs.set(pairKey, [\n\t\t\t\t\t\t\t\t...(readdressPairs.get(pairKey) ?? []),\n\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbyRoot.set(row.rootClaimId, [\n\t\t\t\t\t\t\t...(byRoot.get(row.rootClaimId) ?? []),\n\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tconst recovery: PgReconcileRecoveryReport[] = [];\n\t\t\t\t\tfor (const pairRows of readdressPairs.values()) {\n\t\t\t\t\t\tconst pairId = pairRows[0]?.pairId;\n\t\t\t\t\t\tconst executionId = pairRows[0]?.executionId;\n\t\t\t\t\t\tif (!pairId || !executionId) continue;\n\t\t\t\t\t\tconst closure = await readVerifiedPgLedgerReservationsForPair(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\t[...homes.values()],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst recovered = await recoverPgReaddressPair(lease.session, {\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\treservations: closure,\n\t\t\t\t\t\t});\n\t\t\t\t\t\trecovery.push(readdressRecoveryReport(closure, recovered));\n\t\t\t\t\t}\n\t\t\t\t\tfor (const rows of byRoot.values()) {\n\t\t\t\t\t\tconst rootClaimId = rows[0]?.rootClaimId;\n\t\t\t\t\t\tif (!rootClaimId) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trows.some(\n\t\t\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t\t\t!executionIds.includes(row.executionId) ||\n\t\t\t\t\t\t\t\t\trow.rootClaimId !== rootClaimId,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `reservation disagreement for root claim ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst rootCandidates: Array<{\n\t\t\t\t\t\t\treadonly row: LedgerReservationRow;\n\t\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t\t\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n\t\t\t\t\t\t}> = [];\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tstage = 'catalogue';\n\t\t\t\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\tledgerHome(row.address),\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tprojection.kind !== 'projected-ledger-chain' ||\n\t\t\t\t\t\t\t\tprojection.openClaim === undefined\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tconst open = projection.openClaim.event;\n\t\t\t\t\t\t\tconst openRoot = open.rootClaimId ?? open.eventId;\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\topen.executionId !== row.executionId ||\n\t\t\t\t\t\t\t\topenRoot !== rootClaimId\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\t\taddresses: rows.map((item) => item.address),\n\t\t\t\t\t\t\t\t\tdetail: `open chain member disagrees with reservation root ${rootClaimId}`,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (open.eventId === rootClaimId)\n\t\t\t\t\t\t\t\trootCandidates.push({\n\t\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t\t\tstableStateBeforeClaim:\n\t\t\t\t\t\t\t\t\t\tprojection.openClaim.stableStateBeforeClaim,\n\t\t\t\t\t\t\t\t\t...(open.plannedClaimKey === undefined\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: { plannedClaimKey: open.plannedClaimKey }),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rootCandidates.length !== 1)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `execution ${runId} has ${rootCandidates.length} open root members for ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst selected = rootCandidates[0];\n\t\t\t\t\t\tif (!selected) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!selected.plannedClaimKey ||\n\t\t\t\t\t\t\t!material.some(\n\t\t\t\t\t\t\t\t(claim) => claim.plannedClaimKey === selected.plannedClaimKey,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `open root ${rootClaimId} has no matching persisted managed step`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst step = journal.plan.steps.find(\n\t\t\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t\t\tcandidate.managedClaim?.plannedClaimKey ===\n\t\t\t\t\t\t\t\t\tselected.plannedClaimKey ||\n\t\t\t\t\t\t\t\t('plannedClaimKeys' in candidate &&\n\t\t\t\t\t\t\t\t\tArray.isArray(candidate.plannedClaimKeys) &&\n\t\t\t\t\t\t\t\t\tcandidate.plannedClaimKeys.includes(\n\t\t\t\t\t\t\t\t\t\tselected.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst operationReadBack =\n\t\t\t\t\t\t\tstep?.operation?.operationKind.name ===\n\t\t\t\t\t\t\t'CreateUniqueIndexConcurrently'\n\t\t\t\t\t\t\t\t? async (\n\t\t\t\t\t\t\t\t\t\texecutor: Parameters<\n\t\t\t\t\t\t\t\t\t\t\ttypeof assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid\n\t\t\t\t\t\t\t\t\t\t>[0],\n\t\t\t\t\t\t\t\t\t\t_address: LedgerAddress,\n\t\t\t\t\t\t\t\t\t\tidentity: Parameters<typeof recoveryPayload>[0],\n\t\t\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\t\t\tawait assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid(\n\t\t\t\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\t\t\t\tstep.operation,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tobserved: recoveryPayload(identity),\n\t\t\t\t\t\t\t\t\t\t\teffect: 'unverifiable' as const,\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst indeterminateEvidence = recoveryEvidenceForClaim({\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\trow: selected.row,\n\t\t\t\t\t\t\tplannedClaimKey: selected.plannedClaimKey,\n\t\t\t\t\t\t\tstableStateBeforeClaim: selected.stableStateBeforeClaim,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tconst isRoot = sameLedgerAddress(\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t\tselected.row.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst recovered = await recoverPgOutcomeClaim(pool, {\n\t\t\t\t\t\t\t\taddress: row.address,\n\t\t\t\t\t\t\t\treservations: [row],\n\t\t\t\t\t\t\t\tresolutionEventId: isRoot\n\t\t\t\t\t\t\t\t\t? `${rootClaimId}:reconcile:${runId}`\n\t\t\t\t\t\t\t\t\t: `${rootClaimId}:reconcile:${runId}:${row.address.kind}:${row.address.name}`,\n\t\t\t\t\t\t\t\tacceptedExternalDdlExclusion:\n\t\t\t\t\t\t\t\t\tisRoot && indeterminateEvidence !== undefined,\n\t\t\t\t\t\t\t\tresolveIndeterminate: true,\n\t\t\t\t\t\t\t\treadBack: async (_executor, _address, identity) =>\n\t\t\t\t\t\t\t\t\trecoveryPayload(identity),\n\t\t\t\t\t\t\t\t...(isRoot && indeterminateEvidence !== undefined\n\t\t\t\t\t\t\t\t\t? { indeterminateEvidence }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t...(isRoot && operationReadBack !== undefined\n\t\t\t\t\t\t\t\t\t? { operationReadBack }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\trecovery.push(recoveryReport(row.address, recovered));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst unresolved = recovery.some(isUnresolvedRecoveryOutcome);\n\t\t\t\t\tconst issue = selectedRecoveryIssue(recovery);\n\t\t\t\t\treturn unresolved\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t\t\t...(issue === undefined ? {} : { selectedIssue: issue }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t\t};\n\t\t\t\t} finally {\n\t\t\t\t\tawait lease.release();\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tif (locked.kind === 'busy') return { kind: 'busy', runId, addresses: [] };\n\t\treturn locked.value;\n\t} catch (error) {\n\t\tthrow new PgReconcileTransitionRunError(stage, error);\n\t}\n}\n\n/** Finds every execution id durably attributable to one transition run. */\nexport function executionIdsForRun(\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n): readonly string[] {\n\tconst executionIds = new Set<string>([journal.run.runId]);\n\tfor (const event of journal.events) {\n\t\tconst record = event.record;\n\t\tif (\n\t\t\tevent.event === 'intent' &&\n\t\t\t'executionId' in record &&\n\t\t\ttypeof record.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.executionId);\n\t\tif (\n\t\t\tevent.event === 'observed' &&\n\t\t\t'intent' in record &&\n\t\t\trecord.intent &&\n\t\t\ttypeof record.intent.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.intent.executionId);\n\t}\n\tif ('generator' in journal.plan)\n\t\texecutionIds.add(`dbsp.generator.execution.${journal.run.runId}`);\n\treturn [...executionIds];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DO,SAAS,aAAa,OAAa,UAA0B,CAAC,GAAS;AAC7E,QAAM,WAAmB,CAAC;AAG1B,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WAAW,QAAQ,OAAO,CAAC;AAAA,EACvD;AAEA,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WAAW,QAAQ,OAAO,CAAC;AAAA,EACvD;AAEA,MAAI,QAAQ,UAAU,QAAW;AAChC,aAAS,KAAK,aAAa,SAAS,QAAQ,KAAK,CAAC;AAAA,EACnD;AAEA,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WAAW,QAAQ,OAAO,CAAC;AAAA,EACvD;AAEA,MAAI,QAAQ,WAAW,QAAW;AACjC,aAAS,KAAK,aAAa,UAAU,QAAQ,MAAM,CAAC;AAAA,EACrD;AAEA,MAAI,QAAQ,aAAa,QAAW;AACnC,aAAS,KAAK,aAAa,YAAY,QAAQ,QAAQ,CAAC;AAAA,EACzD;AAEA,MAAI,QAAQ,QAAQ;AACnB,aAAS,KAAK,aAAa,UAAU,QAAQ,MAAM,CAAC;AAAA,EACrD;AAEA,QAAM,cAAiD,EAAE,MAAM;AAC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CAAC,EAAE;AACxE,WAAO,OAAO;AAAA,EACf,SAAS,OAAO;AACf,UAAM,IAAI,8BAA8B,OAAO,KAAK;AAAA,EACrD;AACD;AAGO,SAAS,mBACf,SACoB;AACpB,QAAM,eAAe,oBAAI,IAAY,CAAC,QAAQ,IAAI,KAAK,CAAC;AACxD,aAAW,SAAS,QAAQ,QAAQ;AACnC,UAAM,SAAS,MAAM;AACrB,QACC,MAAM,UAAU,YAChB,iBAAiB,UACjB,OAAO,OAAO,gBAAgB;AAE9B,mBAAa,IAAI,OAAO,WAAW;AACpC,QACC,MAAM,UAAU,cAChB,YAAY,UACZ,OAAO,UACP,OAAO,OAAO,OAAO,gBAAgB;AAErC,mBAAa,IAAI,OAAO,OAAO,WAAW;AAAA,EAC5C;AACA,MAAI,eAAe,QAAQ;AAC1B,iBAAa,IAAI,4BAA4B,QAAQ,IAAI,KAAK,EAAE;AACjE,SAAO,CAAC,GAAG,YAAY;AACxB;","names":["fn","literal","exprRef","fn","literal","op","param","sameControllerIdentity","projectLedgerChain","target","projectLedgerChain"]}
@@ -1,8 +1,8 @@
1
1
  import * as _dbsp_types from '@dbsp/types';
2
2
  import { TransitionRunMetadata, ProvenPlanShape, TransitionRunJournal, TransitionSessionClient, ModelIR, CompareOutcome, PlanAssessment, ObservationContext, ApplyResult, ApplyPolicy, ColumnListInput, ParamIntent, DialectCapabilities, WhereIntent, ExpressionIntent, NormalizedManagedStep } from '@dbsp/types';
3
3
  import { Node } from '@pgsql/types';
4
- import { an as PgLedgerTarget, T as TransitionJournalQueryable, b$ as PgOrderedLedgerLocks, c0 as PgLedgerShapeAllowance, c1 as PgLedgerPhysicalShapeOutcome, bB as readPgLedgerScopeCurrency, f as PgPhysicalModel, c2 as DeclaredNameResolver, F as FkColumnDerivation, c3 as BindingNameRegistry, c4 as QueryScope, c5 as RelationTargetProjectionRegistry, c6 as NestedSelectCompiler, a as CompilerContext, c as PgLockedRun, d as PgOutcomeCheckpointObserver } from './outcome-protocol-BhYhYQPC.js';
5
- export { c7 as ComparePgDatabaseSchemaOptions, c8 as ComparePgDeclaredAdoptionSchemaInput, c9 as CompareSchemataOptions, ca as ConvergePgBaseOptions, cb as ConvergePgCheckOptions, e as ConvergePgOptions, cc as GenerateDDLOptions, cd as MigrationSQLOptions, ce as PgAdoptionComparisonExecutor, a9 as PgApplicationStepTx, cf as PgCommitAcknowledgementAmbiguousError, ad as PgConvergeApplicationStep, ae as PgConvergeAssertStep, h as PgConvergeCheckResult, af as PgConvergeInitializationFailure, ag as PgConvergeOnceStep, ah as PgConvergePlannedStep, aj as PgConvergeRefusalChange, ak as PgConvergeRefusalError, g as PgConvergeResult, cg as appendPgLedgerClaim, ch as appendPgLedgerClaimGroup, ci as appendPgLedgerProgress, cj as appendPgLedgerRelease, ck as appendPgLedgerResolution, cl as appendPgLedgerResolutionGroup, cm as appendPgOutcomeResolution, cn as classifyPgLedgerPhysicalShape, co as collectReferencedKeyRemovalConflicts, cp as comparePgDatabaseSchema, cq as comparePgDeclaredAdoptionSchema, cr as compareSchemata, cs as convergePg, ct as createPgDeclaredAdoptionStep, cu as createPgDeclaredSequenceAdoptionStep, cv as createPgLedgerShapeAllowance, cw as executePgDestructiveOutcome, cx as generateDDL, cy as generateDownSQL, cz as generateMigrationSQL, cA as lockPgJournalRun, cB as modelForDeclaredAdoption, cC as openPgOutcomeClaim, cD as openPgOutcomeClaimGroup, cE as pgDeclaredAdoptionDeclaration, cF as pgDeclaredSequenceAdoptionDeclaration, cG as readPgLedgerReservationsForPair, cH as recoverPgAdmittedReaddressPair, cI as recoverPgOutcomeClaim, cJ as resolvePgDestructiveOutcome, cK as resolvePgOutcomeClaimGroup } from './outcome-protocol-BhYhYQPC.js';
4
+ import { am as PgLedgerTarget, T as TransitionJournalQueryable, b_ as PgOrderedLedgerLocks, b$ as PgLedgerShapeAllowance, c0 as PgLedgerPhysicalShapeOutcome, bA as readPgLedgerScopeCurrency, e as PgPhysicalModel, c1 as DeclaredNameResolver, F as FkColumnDerivation, c2 as BindingNameRegistry, c3 as QueryScope, c4 as RelationTargetProjectionRegistry, c5 as NestedSelectCompiler, a as CompilerContext, P as PgLockedRun, c as PgOutcomeCheckpointObserver } from './outcome-protocol-SJC5Zk63.js';
5
+ export { c6 as ComparePgDatabaseSchemaOptions, c7 as ComparePgDeclaredAdoptionSchemaInput, c8 as CompareSchemataOptions, c9 as ConvergePgBaseOptions, ca as ConvergePgCheckOptions, d as ConvergePgOptions, cb as GenerateDDLOptions, cc as MigrationSQLOptions, cd as PgAdoptionComparisonExecutor, a8 as PgApplicationStepTx, ce as PgCommitAcknowledgementAmbiguousError, ac as PgConvergeApplicationStep, ad as PgConvergeAssertStep, g as PgConvergeCheckResult, ae as PgConvergeInitializationFailure, af as PgConvergeOnceStep, ag as PgConvergePlannedStep, ai as PgConvergeRefusalChange, aj as PgConvergeRefusalError, f as PgConvergeResult, cf as appendPgLedgerClaim, cg as appendPgLedgerClaimGroup, ch as appendPgLedgerProgress, ci as appendPgLedgerRelease, cj as appendPgLedgerResolution, ck as appendPgLedgerResolutionGroup, cl as appendPgOutcomeResolution, cm as classifyPgLedgerPhysicalShape, cn as collectReferencedKeyRemovalConflicts, co as comparePgDatabaseSchema, cp as comparePgDeclaredAdoptionSchema, cq as compareSchemata, cr as convergePg, cs as createPgDeclaredAdoptionStep, ct as createPgDeclaredSequenceAdoptionStep, cu as createPgLedgerShapeAllowance, cv as executePgDestructiveOutcome, cw as generateDDL, cx as generateDownSQL, cy as generateMigrationSQL, cz as lockPgJournalRun, cA as modelForDeclaredAdoption, cB as openPgOutcomeClaim, cC as openPgOutcomeClaimGroup, cD as pgDeclaredAdoptionDeclaration, cE as pgDeclaredSequenceAdoptionDeclaration, cF as readPgLedgerReservationsForPair, cG as recoverPgAdmittedReaddressPair, cH as recoverPgOutcomeClaim, cI as resolvePgDestructiveOutcome, cJ as resolvePgOutcomeClaimGroup } from './outcome-protocol-SJC5Zk63.js';
6
6
  import { TransitionRunAuthorization, JsonAggOrderByEntry, ScopedApprovalSet } from '@dbsp/types/internal';
7
7
  import { InProcessProvenPlan, ValidatedManagedStepManifest } from '@dbsp/core/internal';
8
8
  import { Pool, PoolClient } from 'pg';
package/dist/internal.js CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  recoverPgOutcomeClaim,
44
44
  resolvePgDestructiveOutcome,
45
45
  resolvePgOutcomeClaimGroup
46
- } from "./chunk-CQSIDXP5.js";
46
+ } from "./chunk-GTX6FAK2.js";
47
47
  export {
48
48
  PgCommitAcknowledgementAmbiguousError,
49
49
  PgConvergeRefusalError,