{"modulePath":"github.com/diffsec/agentmon","version":"v0.0.0-20261111001054-230ac962f687","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package statemachine\n\nPackage statemachine implements the PostgreSQL proxy's Extended Query and transaction state machine per docs/agentmon-db-access-spec.md §14 and the design doc 2026-05-11-db-plan-05-pg-extended-tx-design.md §4.\n\nTransition is a pure function: it consumes (state, frame, cache, rules, service) and returns (nextState, \\[]Action). It mutates the CacheView directly (for Put/Delete/Clear) so the Action stream is I/O-only.\n\n## Functions\n\n```go\nfunc Transition(\n\ts ConnState,\n\tframe Frame,\n\tcache CacheView,\n\trules *policy.RuleSet,\n\tsvc policy.ServiceID,\n) (ConnState, []Action)\n```\nTransition is the pure state-transition function. It consumes the current ConnState, the next inbound frontend frame, a CacheView (mutated directly for Put/Delete/Clear), the active RuleSet, and the per-connection service identifier (used to scope policy evaluation). Returns the next state and the Action stream the dispatcher must execute.\n\nPlan 05a implements: Sync, Parse, Bind, Describe, Execute, Flush, Close, Query (Simple Query), Terminate. Other frame kinds fall through to a default-deny path that produces SynthError(0A000) + Close. Plan 05b lifts FunctionCall and SQL prepared interception; Plan 05c lifts COPY frames and the approval-wait variant.\n\n```go\nfunc TransitionWithParser(\n\ts ConnState,\n\tframe Frame,\n\tcache CacheView,\n\trules *policy.RuleSet,\n\tsvc policy.ServiceID,\n\tparser PolicyClassifier,\n\topts classify_pg.Options,\n) (ConnState, []Action)\n```\nTransitionWithParser is the parser-injected variant; tests use it when they need to assert against a non-postgres dialect or a mock classifier.\n\n## Types\n\n```go\ntype Action interface {\n\t// contains filtered or unexported methods\n}\n```\nAction is a single thing the dispatcher must execute after a Transition. Concrete types are sealed via the private isAction() method so the dispatcher can rely on a closed sum type. Cache mutations are NOT Actions — Transition mutates the CacheView directly.\n\n```go\nfunc DenyRoute(s ConnState, rule policy.StatementRule, msg, sqlstate string) []Action\n```\nDenyRoute returns the Action sequence implementing the spec §14.3 + §14.4 deny path. Callers pass the rendered deny message (already templated) and the SQLSTATE chosen by the rule kind.\n\n  - Out-of-tx (lastUpstreamRFQ in {0, 'I'}) and not dirty: \\[SynthError, SynthReadyForQuery(I)]\n  - Out-of-tx and dirty: \\[SynthError, DrainUntilRFQ]\n  - In-tx (lastUpstreamRFQ in {'T', 'E'}), terminate (default or explicit): \\[SynthError(Severity=FATAL), Close]\n  - In-tx, rollback\\_then\\_continue: \\[SynthError, InjectRollback, DrainUntilRFQ, SynthReadyForQuery(I)]\n\n```go\ntype ActionApproverWait struct {\n\tTimeout time.Duration\n\tStmt    effects.ClassifiedStatement\n\tRule    policy.StatementRule\n}\n```\nActionApproverWait instructs the dispatcher to invoke the configured Approver and wait up to Timeout before either forwarding or routing a deny.\n\n```go\ntype ActionClose struct{}\n```\nActionClose tears down both client and upstream connections. After this the dispatcher returns from the per-connection driver.\n\n```go\ntype ActionDrainUntilRFQ struct{}\n```\nActionDrainUntilRFQ reads upstream frames and forwards them to the client (subject to the per-row demux for counters in upstreamread.go) until an upstream ReadyForQuery is observed. Updates LastUpstreamRFQ on the way.\n\n```go\ntype ActionForward struct{}\n```\nActionForward emits the original frontend frame to upstream unchanged. The dispatcher reads pc.lastFrame and forwards via upstream framer.\n\n```go\ntype ActionInjectRollback struct{}\n```\nActionInjectRollback sends a synthetic \"ROLLBACK\" Simple Query upstream as if from the client. Used by the rollback\\_then\\_continue deny mode. The dispatcher composes a 'Q' frame with body \"ROLLBACK\".\n\n```go\ntype ActionSuppress struct{}\n```\nActionSuppress instructs the dispatcher to drop the current frontend frame without forwarding upstream and without responding to client. Used inside an absorbing-deny window.\n\n```go\ntype ActionSynthBindComplete struct{}\n```\nActionSynthBindComplete mirrors ActionSynthParseComplete for Bind.\n\n```go\ntype ActionSynthError struct {\n\tSQLState string\n\tMessage  string\n\t// Severity overrides \"ERROR\" when non-empty. The terminate-in-tx path\n\t// uses Severity=\"FATAL\" so libpq clients surface the SQLSTATE alongside\n\t// the EOF that follows.\n\tSeverity string\n}\n```\nActionSynthError synthesizes ErrorResponse to the client. The dispatcher chooses Severity based on the deny path (ERROR for resumable; FATAL for terminate). SQLState is the §10 / §13 / §14 SQLSTATE.\n\n```go\ntype ActionSynthParseComplete struct{}\n```\nActionSynthParseComplete synthesizes a ParseComplete frame to the client (used in absorbing-window denies to satisfy clients expecting one frame per Parse). Plan 05a does not emit this in standard paths; reserved for future tightening.\n\n```go\ntype ActionSynthReadyForQuery struct {\n\tStatus byte // 'I' | 'T' | 'E'\n}\n```\nActionSynthReadyForQuery synthesizes ReadyForQuery to the client.\n\n```go\ntype ActionTrackUpstreamRFQ struct {\n\tStatus byte\n}\n```\nActionTrackUpstreamRFQ updates ConnState.LastUpstreamRFQ and Phase to match Status. Emitted when the dispatcher observes an upstream 'Z' frame during normal forwarding.\n\n```go\ntype BindFrame struct {\n\tPortal    string\n\tStatement string // prepared-statement name\n}\n```\n\n```go\nfunc (*BindFrame) Kind() FrameKind\n```\n\n```go\ntype CacheOp struct {\n\tMethod string // \"Get\" | \"Put\" | \"Delete\" | \"Clear\"\n\tKey    string\n\tValue  CacheValue\n\tHit    bool // only meaningful for \"Get\"\n}\n```\nCacheOp records one observation against a FakeCacheView.\n\n```go\ntype CacheValue struct {\n\tVerb                     string // RawVerb from effects.ClassifiedStatement\n\tGroupID                  uint8  // primary effect group_id; used for re-evaluate at Execute\n\tOpaqueID                 string // optional: spine-test correlation\n\tCatalogRefreshSearchPath bool\n\tCatalogRefreshSnapshot   bool\n}\n```\nCacheValue is the value stored in a CacheView. The transition logic reads/writes this type; production wraps it around a preparedcache.Entry at the dispatcher boundary so the state-machine package stays decoupled from the cache implementation.\n\n```go\ntype CacheView interface {\n\tGet(name string) (CacheValue, bool)\n\tPut(name string, v CacheValue)\n\tDelete(name string)\n\tClear()\n}\n```\nCacheView is the subset of preparedcache.Cache that Transition consumes. Implementations must be safe for concurrent reads with one writer per connection (the per-conn goroutine).\n\n```go\ntype CloseFrame struct {\n\tObjectType byte // 'S' (statement) or 'P' (portal)\n\tName       string\n}\n```\n\n```go\nfunc (*CloseFrame) Kind() FrameKind\n```\n\n```go\ntype ConnState struct {\n\t// Phase reflects the per-connection lifecycle position.\n\tPhase Phase\n\n\t// LastUpstreamRFQ is the most recent ReadyForQuery status byte observed\n\t// from upstream. Zero (0x00) means pre-auth. Otherwise 'I', 'T', or 'E'.\n\tLastUpstreamRFQ byte\n\n\t// Absorbing is true when a previous Parse/Bind/Execute denied within\n\t// the current Sync window. Subsequent non-Sync frames are suppressed\n\t// until the next Sync resolves the window.\n\tAbsorbing bool\n\n\t// UpstreamDirtySinceSync is true once any Parse/Bind/Execute/Describe/\n\t// Close has been forwarded upstream in the current Sync window. Reset\n\t// on the next observed upstream RFQ.\n\tUpstreamDirtySinceSync bool\n\n\t// TxStartedAt is the local timestamp the proxy observed transitioning\n\t// into 'T' (in-tx) state on a fresh transaction. Cleared when the next\n\t// observed upstream RFQ is 'I'. Used by the DBEvent tx_context schema.\n\tTxStartedAt time.Time\n}\n```\nConnState is the per-connection state the Extended Query and transaction state machine carries. All fields are exported so the dispatcher can read them after Transition returns; mutations happen only through Transition (or through the dispatcher updating LastUpstreamRFQ + Phase when an upstream 'Z' arrives during forwarding).\n\n```go\ntype CopyDataFrame struct {\n\tBody []byte // borrowed; do not retain past the Transition call\n}\n```\n\n```go\nfunc (*CopyDataFrame) Kind() FrameKind\n```\n\n```go\ntype CopyDoneFrame struct{}\n```\n\n```go\nfunc (*CopyDoneFrame) Kind() FrameKind\n```\n\n```go\ntype CopyFailFrame struct {\n\tMessage string\n}\n```\n\n```go\nfunc (*CopyFailFrame) Kind() FrameKind\n```\n\n```go\ntype DescribeFrame struct {\n\tObjectType byte // 'S' (statement) or 'P' (portal)\n\tName       string\n}\n```\n\n```go\nfunc (*DescribeFrame) Kind() FrameKind\n```\n\n```go\ntype ExecuteFrame struct {\n\tPortal string\n}\n```\n\n```go\nfunc (*ExecuteFrame) Kind() FrameKind\n```\n\n```go\ntype FakeCacheView struct {\n\t// contains filtered or unexported fields\n}\n```\nFakeCacheView records every operation and is safe for unit tests. NOT for production.\n\n```go\nfunc NewFakeCacheView() *FakeCacheView\n```\nNewFakeCacheView returns an empty fake.\n\n```go\nfunc (f *FakeCacheView) Clear()\n```\n\n```go\nfunc (f *FakeCacheView) Delete(name string)\n```\n\n```go\nfunc (f *FakeCacheView) Get(name string) (CacheValue, bool)\n```\n\n```go\nfunc (f *FakeCacheView) Put(name string, v CacheValue)\n```\n\n```go\nfunc (f *FakeCacheView) Recorded() []CacheOp\n```\nRecorded returns the operation history.\n\n```go\ntype FlushFrame struct{}\n```\n\n```go\nfunc (*FlushFrame) Kind() FrameKind\n```\n\n```go\ntype Frame interface {\n\tKind() FrameKind\n}\n```\nFrame is a thin protocol-level view of one PostgreSQL frontend message. The dispatcher constructs concrete adapters from pgproto3.FrontendMessage before calling Transition. The state machine does not depend on pgproto3.\n\n```go\ntype FrameKind uint8\n```\nFrameKind enumerates the per-frame kinds Transition dispatches on.\n\n```go\nconst (\n\tFrameKindQuery FrameKind = iota\n\tFrameKindParse\n\tFrameKindBind\n\tFrameKindDescribe\n\tFrameKindExecute\n\tFrameKindSync\n\tFrameKindFlush\n\tFrameKindClose\n\tFrameKindTerminate\n\tFrameKindFunctionCall // Plan 05b live; Plan 05a falls through to default-deny\n\tFrameKindCopyData\n\tFrameKindCopyDone\n\tFrameKindCopyFail\n)\n```\n\n```go\ntype FunctionCallFrame struct {\n\tFunctionOID uint32\n}\n```\n\n```go\nfunc (*FunctionCallFrame) Kind() FrameKind\n```\n\n```go\ntype ParseFrame struct {\n\tName string // empty string is unnamed prepared statement\n\tSQL  string\n}\n```\n\n```go\nfunc (*ParseFrame) Kind() FrameKind\n```\n\n```go\ntype Phase uint8\n```\nPhase enumerates the per-connection lifecycle phases. The state machine tracks both Phase (for human-readable invariants) and LastUpstreamRFQ (the on-wire 'Z' status byte) because the two convey slightly different information — Phase encodes COPY-in/COPY-out which RFQ cannot represent.\n\n```go\nconst (\n\tPhasePreAuth Phase = iota\n\tPhaseIdle\n\tPhaseInQuery\n\tPhaseInTx\n\tPhaseInTxError\n\tPhaseInCopyIn\n\tPhaseInCopyOut\n)\n```\n\n```go\nfunc (p Phase) String() string\n```\n\n```go\ntype PolicyClassifier interface {\n\tClassify(sql string, sess classify_pg.SessionState, opts classify_pg.Options) ([]effects.ClassifiedStatement, error)\n}\n```\nPolicyClassifier is the minimal classifier surface Transition needs at the state-machine boundary. The dispatcher injects a real classify\\_pg.Parser via TransitionWithParser; transition\\_test.go uses the live parser via classify\\_pg.New(classify\\_pg.DialectPostgres).\n\n```go\ntype QueryFrame struct {\n\tSQL string\n}\n```\n\n```go\nfunc (*QueryFrame) Kind() FrameKind\n```\n\n```go\ntype SyncFrame struct{}\n```\n\n```go\nfunc (*SyncFrame) Kind() FrameKind\n```\n\n```go\ntype TerminateFrame struct{}\n```\n\n```go\nfunc (*TerminateFrame) Kind() FrameKind\n```\n\n","path":"github.com/diffsec/agentmon/internal/db/proxy/postgres/statemachine","name":"statemachine","synopsis":"Package statemachine implements the PostgreSQL proxy's Extended Query and transaction state machine per docs/agentmon-db-access-spec.md §14 and the design doc 2026-05-11-db-plan-05-pg-extended-tx-design.md §4.","isRedistributable":true}
