b5terminal

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package b5terminal contains the feature-off B5 terminal evidence, ownership, PostgreSQL wire adapter, and CancelRequest contracts.

It is deliberately not imported by a production entry point. In particular, adding the PostgreSQL adapter here does not activate a flag or replace the legacy businessdb transaction interface.

Index

Constants

View Source
const (
	TerminalEvidenceSchema       = b5.TerminalEvidenceSchemaID
	TerminalEvidenceVersion      = b5.TerminalEvidenceVersion
	NoCommitEverSentSchema       = b5.NoCommitProofSchemaID
	NoCommitEverSentVersion      = b5.NoCommitProofVersion
	ConnectionDispositionSchema  = b5.DispositionProofSchemaID
	ConnectionDispositionVersion = b5.DispositionProofVersion
)
View Source
const (
	OperationUnknown  = b5.OperationUnknown
	OperationCommit   = b5.OperationCommit
	OperationRollback = b5.OperationRollback
)
View Source
const (
	WritePhaseUnknown  = b5.WritePhaseUnknown
	WriteNotSent       = b5.WriteNotSent
	WriteZeroBytes     = b5.WriteZeroBytes
	WritePartial       = b5.WritePartial
	WriteFullFrame     = b5.WriteFullFrame
	WriteIndeterminate = b5.WriteIndeterminate
)
View Source
const (
	CorrelationUnknown                = b5.CorrelationUnknown
	CorrelationNotApplicable          = b5.CorrelationNotApplicable
	CorrelationWeakOrAbsent           = b5.CorrelationWeakOrAbsent
	CorrelationStrongCurrentOperation = b5.CorrelationStrongCurrentOperation
)
View Source
const (
	ServerStatusUnknown                = b5.ServerStatusUnknown
	ServerStatusNotObserved            = b5.ServerStatusNotObserved
	ServerReadyIdle                    = b5.ServerReadyIdle
	ServerReadyIdleInTransaction       = b5.ServerReadyIdleInTransaction
	ServerReadyFailed                  = b5.ServerReadyFailed
	ServerStatusUnknownOrContradictory = b5.ServerStatusUnknownOrContradictory
)
View Source
const (
	VerdictUnknown       = b5.EvidenceInsufficient
	VerdictConsistent    = b5.EvidenceConsistent
	VerdictContradiction = b5.EvidenceContradictory
)
View Source
const (
	FrozenEvidenceTableRows  = 5
	FrozenEvidenceTableCells = 30
)

FrozenEvidenceTableRows and FrozenEvidenceTableCells make the reviewed table shape explicit for tests and schema-freeze review.

View Source
const (
	OutcomeUnknown        = b5.OutcomeUnknown
	OutcomeCommitted      = b5.OutcomeCommitted
	OutcomeCommitRejected = b5.OutcomeNotCommitted
	OutcomeNotCommitted   = b5.OutcomeNotCommitted
)
View Source
const (
	DispositionUnknown            = b5.DispositionUnknown
	DispositionReleased           = b5.DispositionReleased
	DispositionDiscarded          = b5.DispositionDiscarded
	DispositionDiscardUnconfirmed = b5.DispositionDiscardUnconfirmed
)
View Source
const GenerationBoundCancelFence = false

GenerationBoundCancelFence is false for every v0.4 PostgreSQL path. A future true value requires a separately reviewed server protocol and attestation.

Variables

View Source
var (
	ErrStaleTerminalAttempt = errors.New("b5terminal: stale terminal attempt")
	ErrInvalidOwnerState    = errors.New("b5terminal: invalid terminal owner state")
)
View Source
var (
	ErrPGAdapterFinished        = errors.New("b5terminal: PostgreSQL adapter already finished")
	ErrPGInvalidPhysicalLease   = errors.New("b5terminal: invalid PostgreSQL physical connection lease")
	ErrPGUncleanCommandBoundary = errors.New("b5terminal: PostgreSQL connector is not at a clean command boundary")
	ErrPGTerminalWatchdog       = errors.New("b5terminal: PostgreSQL terminal watchdog expired")
	ErrPGProtocol               = errors.New("b5terminal: invalid PostgreSQL terminal protocol")
	ErrPGPoolTransfer           = errors.New("b5terminal: PostgreSQL pool transfer failed")
	ErrPGConnectionDiscarded    = errors.New("b5terminal: PostgreSQL physical connection must not be reused")
)
View Source
var ErrCancelTainted = errors.New("b5terminal: PostgreSQL connection is cancel-tainted")

Functions

This section is empty.

Types

type CancelDiagnostics

type CancelDiagnostics struct {
	ReadyForQueryIdleObserved bool
	ExecuteExited             bool
	CancelSocketClosed        bool
	StatementTimeoutObserved  bool
}

type CancelEmission

type CancelEmission uint8
const (
	CancelNotSentProven CancelEmission = iota
	CancelSendStartedOrIndeterminate
	CancelFullPacketWritten
)

type CancelGuard

type CancelGuard struct {
	// contains filtered or unexported fields
}

CancelGuard serializes the independent cancel send path with any attempt to start a new main-connection command. Standard PostgreSQL has no generation- bound cancel fence, so taint is monotonic and permanent.

func NewCancelGuard

func NewCancelGuard() *CancelGuard

func (*CancelGuard) Disposition

func (guard *CancelGuard) Disposition(backendAbsenceConfirmed bool) ConnectionDisposition

func (*CancelGuard) ObserveCancelSocketClosed

func (guard *CancelGuard) ObserveCancelSocketClosed()

func (*CancelGuard) ObserveEmission

func (guard *CancelGuard) ObserveEmission(emission CancelEmission)

func (*CancelGuard) ObserveExecuteExit

func (guard *CancelGuard) ObserveExecuteExit()

func (*CancelGuard) ObserveReadyForQueryIdle

func (guard *CancelGuard) ObserveReadyForQueryIdle()

func (*CancelGuard) ObserveStatementTimeout

func (guard *CancelGuard) ObserveStatementTimeout()

func (*CancelGuard) RecordMainSend

func (guard *CancelGuard) RecordMainSend(command MainCommand) error

func (*CancelGuard) Snapshot

func (guard *CancelGuard) Snapshot() CancelSnapshot

type CancelSnapshot

type CancelSnapshot struct {
	Emission    CancelEmission
	Tainted     bool
	Diagnostics CancelDiagnostics
	Sent        map[MainCommand]uint64
}

type CommitStage

type CommitStage uint8
const (
	CommitStageBeforeSend CommitStage = iota
	CommitStagePartialWrite
	CommitStageFullWriteAwaitingACK
	CommitStageACKObservedAwaitingRFQ
)

type ConnectionDisposition

type ConnectionDisposition = b5.ConnectionDisposition

type ConsistencyReason

type ConsistencyReason uint8
const (
	ReasonNone ConsistencyReason = iota
	ReasonUnknownSchema
	ReasonInvalidWriteAccounting
	ReasonInsufficientCorrelation
	ReasonUntypedReply
	ReasonServerStatusInsufficient
	ReasonWrongOperation
	ReasonStaleOrFutureGeneration
	ReasonDuplicateTerminalReply
	ReasonPositiveAndRejection
	ReasonDuplicateOrChangingRFQ
	ReasonReplyStatusContradiction
	ReasonExplicitLocalWriteContradiction
	ReasonInvalidStrongCorrelation
)

type ConsistencyResult

type ConsistencyResult struct {
	Verdict ConsistencyVerdict
	Reason  ConsistencyReason
}

func CheckEvidence

func CheckEvidence(e Evidence) ConsistencyResult

CheckEvidence evaluates all evidence before DB outcome or connection disposition. It never uses error text.

type ConsistencyVerdict

type ConsistencyVerdict = b5.EvidenceConsistency

type CorrelationProof

type CorrelationProof struct {
	Strength                CorrelationStrength
	CleanCommandBoundary    bool
	UniqueSocketOwner       bool
	DecoderAfterSendPermit  bool
	NoUnreadOrPendingAtSend bool
	MonotonicTranscript     bool
	TranscriptDigest        [32]byte
}

CorrelationProof records the minimum facts needed to call a PostgreSQL reply current. PostgreSQL does not put a request ID in these replies, so a strong claim is valid only from an exclusive decoder at a clean boundary.

type CorrelationStrength

type CorrelationStrength = b5.ReplyCorrelation

type DBOutcome

type DBOutcome = b5.DBOutcome

type Evidence

type Evidence struct {
	Schema                string
	SchemaVersion         uint16
	Operation             TerminalOperation
	TransactionGeneration uint64
	AttemptGeneration     uint64
	OwnerGeneration       uint64
	Write                 WriteEvidence
	Replies               []TerminalReply
	ServerStatuses        []ServerTxStatus
}

Evidence is the immutable input to CheckEvidence and ResolveTerminal.

type FaultEvent

type FaultEvent struct {
	Kind     FaultEventKind
	Command  MainCommand
	At       uint64
	Sequence uint64
}

type FaultEventKind

type FaultEventKind uint8
const (
	FaultEventCancelPacket FaultEventKind = iota
	FaultEventMainCommand
	FaultEventExecuteSuccess
	FaultEventReadyForQueryIdle
	FaultEventCancelSocketClosed
	FaultEventStatementTimeout
)

type FaultProxy

type FaultProxy struct {
	// contains filtered or unexported fields
}

FaultProxy is a deterministic, in-memory two-path proxy. Delay controls when the server observes an event; CancelGuard is updated when the client send starts, which models the dangerous interval before a delayed cancel arrives.

func NewFaultProxy

func NewFaultProxy(guard *CancelGuard) *FaultProxy

func (*FaultProxy) AdvanceTo

func (proxy *FaultProxy) AdvanceTo(at uint64) []FaultEvent

func (*FaultProxy) Delivered

func (proxy *FaultProxy) Delivered() []FaultEvent

func (*FaultProxy) Pending

func (proxy *FaultProxy) Pending() []FaultEvent

func (*FaultProxy) ScheduleServerEvent

func (proxy *FaultProxy) ScheduleServerEvent(kind FaultEventKind, delay uint64)

func (*FaultProxy) SendCancel

func (proxy *FaultProxy) SendCancel(emission CancelEmission, delay uint64)

func (*FaultProxy) SendMain

func (proxy *FaultProxy) SendMain(command MainCommand, delay uint64) error

type MainCommand

type MainCommand uint8
const (
	CommandRollback MainCommand = iota
	CommandCommit
	CommandReset
	CommandHealthProbe
	CommandStatement
)

type NoCommitEverSent

type NoCommitEverSent struct {
	Schema                     string
	SchemaVersion              uint16
	TransactionGeneration      uint64
	OwnerGeneration            uint64
	HistoryContinuous          bool
	UniqueSocketOwner          bool
	CommitSendPermitEverOpened bool
}

NoCommitEverSent is independent coordinator evidence. Connector evidence may not manufacture it, particularly when that connector is contradictory.

func (NoCommitEverSent) ValidFor

func (proof NoCommitEverSent) ValidFor(e Evidence) bool

type OwnerState

type OwnerState uint8
const (
	OwnerActive OwnerState = iota
	OwnerQuiescing
	OwnerCommitting
	OwnerRollingBack
	OwnerTerminal
)

type PGAdapterOptions

type PGAdapterOptions struct {
	WatchdogTimeout time.Duration
	ReconcileBudget time.Duration
	ResetSQL        string
	HealthSQL       string
}

type PGBackendIdentity

type PGBackendIdentity struct {
	ServerIdentity  string
	Database        string
	PID             uint32
	BackendStart    time.Time
	ConnectionNonce string
}

PGBackendIdentity is the identity passed to independent backend inventory. PID alone is intentionally insufficient because PostgreSQL can reuse it.

type PGPhysicalConnection

type PGPhysicalConnection struct {
	Conn                     net.Conn
	Identity                 PGBackendIdentity
	CleanCommandBoundary     bool
	UniqueSocketOwner        bool
	TransferToPool           func(context.Context, net.Conn, PGBackendIdentity) error
	ConfirmBackendAbsence    func(context.Context, PGBackendIdentity) (bool, error)
	OnLocalConnectionDiscard func(PGBackendIdentity, error)
}

PGPhysicalConnection transfers exclusive ownership of one already authenticated physical connection to the adapter. TransferToPool performs the pool-generation CAS and assumes ownership only when it returns nil. ConfirmBackendAbsence must use an independent connection or inventory.

type PGTerminalAdapter

type PGTerminalAdapter struct {
	// contains filtered or unexported fields
}

PGTerminalAdapter owns the physical connection from terminal-frame send through exactly one pool transfer or local destruction plus reconciliation.

func NewPGTerminalAdapter

func NewPGTerminalAdapter(lease PGPhysicalConnection, guard *CancelGuard, options PGAdapterOptions) (*PGTerminalAdapter, error)

func (*PGTerminalAdapter) FinishCommit

func (adapter *PGTerminalAdapter) FinishCommit(ctx context.Context, owner *TerminalOwner, attempt TerminalAttempt) (PGTerminalResult, error)

func (*PGTerminalAdapter) FinishRollback

func (adapter *PGTerminalAdapter) FinishRollback(ctx context.Context, owner *TerminalOwner, attempt TerminalAttempt, proof NoCommitEverSent) (PGTerminalResult, error)

func (*PGTerminalAdapter) ObserveCancelEmission

func (adapter *PGTerminalAdapter) ObserveCancelEmission(emission CancelEmission)

ObserveCancelEmission is the only supported way for the owner to publish an independently sent CancelRequest. Taint is permanent and immediately seizes the main connection, structurally preventing rollback/reset/health.

func (*PGTerminalAdapter) SendCancelRequest

func (adapter *PGTerminalAdapter) SendCancelRequest(ctx context.Context, dial func(context.Context) (net.Conn, error), pid, secret uint32) (CancelEmission, error)

SendCancelRequest emits the standard 16-byte PostgreSQL CancelRequest on an independent connection. A dial failure proves no packet was sent; once the write syscall starts the main connection is permanently tainted.

type PGTerminalResult

type PGTerminalResult struct {
	Evidence       Evidence
	Resolution     TerminalResolution
	ReleaseChecks  ReleaseChecks
	Backend        PGBackendIdentity
	WatchdogFired  bool
	CancelSnapshot CancelSnapshot
	DestroySignal  error
	LifecycleError error
}

PGTerminalResult contains the S4a total-function result plus the physical lifecycle proof. DestroySignal is ErrPGConnectionDiscarded whenever this adapter has made the connection permanently non-reusable. The businessdb capability boundary converts it to driver.ErrBadConn for physical disposal; neither signal may be used to retry a terminal operation.

type ReleaseChecks

type ReleaseChecks struct {
	DrainComplete     bool
	SessionReset      bool
	HealthCheck       bool
	StatusRecheckIdle bool
	PoolTransferCAS   bool
}

func (ReleaseChecks) AllPassed

func (checks ReleaseChecks) AllPassed() bool

type ResolutionContext

type ResolutionContext struct {
	NoCommitProof           NoCommitEverSent
	CancelEmission          CancelEmission
	ReleaseChecks           ReleaseChecks
	BackendAbsenceConfirmed bool
}

type ServerTxState

type ServerTxState = b5.ServerTxStatus

type ServerTxStatus

type ServerTxStatus struct {
	State                 ServerTxState
	TransactionGeneration uint64
	AttemptGeneration     uint64
}

ServerTxStatus is one ReadyForQuery observation. Evidence retains all observations so a duplicate RFQ or a status change is contradictory.

type TerminalAttempt

type TerminalAttempt struct {
	TransactionGeneration uint64
	OwnerGeneration       uint64
	AttemptGeneration     uint64
	Operation             TerminalOperation
	TimeoutOwner          bool
}

type TerminalOperation

type TerminalOperation = b5.TerminalOperation

TerminalOperation is the operation selected by the single terminal-owner CAS. An operation value is never inferred from a driver error string.

type TerminalOwner

type TerminalOwner struct {
	// contains filtered or unexported fields
}

TerminalOwner is a generation-bound single-owner CAS. The immutable snapshots make every race linearize at one atomic compare-and-swap.

func NewTerminalOwner

func NewTerminalOwner(transactionGeneration, ownerGeneration uint64) *TerminalOwner

func (*TerminalOwner) AdvanceCommitStage

func (owner *TerminalOwner) AdvanceCommitStage(attempt TerminalAttempt, stage CommitStage) error

func (*TerminalOwner) BeginTimeoutRollback

func (owner *TerminalOwner) BeginTimeoutRollback(attempt TerminalAttempt) error

func (*TerminalOwner) Complete

func (owner *TerminalOwner) Complete(attempt TerminalAttempt, result TerminalResolution) error

func (*TerminalOwner) NoCommitProof

func (owner *TerminalOwner) NoCommitProof(attempt TerminalAttempt) (NoCommitEverSent, bool)

NoCommitProof is emitted only for the timeout owner that won from ACTIVE. Once a commit send permit was ever opened, no API can produce a valid proof.

func (*TerminalOwner) ObserveWallDeadline

func (owner *TerminalOwner) ObserveWallDeadline(transactionGeneration, ownerGeneration uint64) TimeoutObservation

ObserveWallDeadline either wins from ACTIVE before a commit owner exists, or becomes diagnostic-only once COMMITTING has won. It never selects a timeout NOT_COMMITTED result from COMMITTING, regardless of the current write stage.

func (*TerminalOwner) OpenCommitSendPermit

func (owner *TerminalOwner) OpenCommitSendPermit(attempt TerminalAttempt) error

func (*TerminalOwner) Snapshot

func (owner *TerminalOwner) Snapshot() TerminalOwnerSnapshot

func (*TerminalOwner) TryCommit

func (owner *TerminalOwner) TryCommit(transactionGeneration, ownerGeneration uint64) (TerminalAttempt, bool)

func (*TerminalOwner) TryRollback

func (owner *TerminalOwner) TryRollback(transactionGeneration, ownerGeneration uint64) (TerminalAttempt, bool)

func (*TerminalOwner) ValidateAttempt

func (owner *TerminalOwner) ValidateAttempt(attempt TerminalAttempt) error

ValidateAttempt proves that attempt is still the generation-bound terminal owner before an adapter is allowed to touch the physical connection.

func (*TerminalOwner) Wait

type TerminalOwnerSnapshot

type TerminalOwnerSnapshot struct {
	State                      OwnerState
	TransactionGeneration      uint64
	OwnerGeneration            uint64
	AttemptGeneration          uint64
	Operation                  TerminalOperation
	CommitSendPermitEverOpened bool
	CommitStage                CommitStage
	WallDeadlineObserved       bool
}

type TerminalReply

type TerminalReply struct {
	Kind                  TerminalReplyKind
	Operation             TerminalOperation
	TransactionGeneration uint64
	AttemptGeneration     uint64
	Correlation           CorrelationProof
}

TerminalReply is one decoded terminal reply. Multiple entries in Evidence are retained so duplicate ACKs and mutually exclusive positive/rejection replies can be rejected instead of silently choosing one.

type TerminalReplyKind

type TerminalReplyKind uint8
const (
	ReplyKindUnknown TerminalReplyKind = iota
	ReplyNoReply
	ReplyCommitPositiveACK
	ReplyCommitDeferredErrorRejection
	ReplyRollbackPositiveACK
	ReplyRollbackDefinitiveRejection
	ReplyUntyped
)

type TerminalResolution

type TerminalResolution struct {
	Schema        string
	SchemaVersion uint16
	Consistency   ConsistencyResult
	Outcome       DBOutcome
	Disposition   ConnectionDisposition
}

func ResolveTerminal

func ResolveTerminal(e Evidence, context ResolutionContext) TerminalResolution

ResolveTerminal is total over every Evidence value. Contradictory and unknown-schema evidence short-circuit before nominal outcome/disposition.

type TimeoutDecision

type TimeoutDecision uint8
const (
	TimeoutLost TimeoutDecision = iota
	TimeoutWonBeforeCommit
	TimeoutFinishCommitOnly
)

type TimeoutObservation

type TimeoutObservation struct {
	Decision TimeoutDecision
	Attempt  TerminalAttempt
	Stage    CommitStage
}

type WriteEvidence

type WriteEvidence struct {
	Phase        WritePhase
	BytesWritten uint64
	FrameBytes   uint64
}

WriteEvidence binds a phase to the connector's byte accounting. FrameBytes is the complete encoded terminal-frame length. BytesWritten is exact for all phases except WriteIndeterminate, where it is only the last known count.

type WritePhase

type WritePhase = b5.WritePhase

WritePhase is connector-observed write progress for one terminal frame.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL