From 81336278469179a311081e9bf72a79e6897769fb Mon Sep 17 00:00:00 2001 From: Proview-China Date: Fri, 31 Jul 2026 08:43:02 +0800 Subject: [PATCH] feat(praxis): add governed model turn v3 pre-invoke boundary --- .../governed-model-turn-v3-actual-boundary.md | 42 + ...-governed-model-turn-v3-actual-boundary.md | 17 + .../governed-model-turn-v3-actual-boundary.md | 21 + .../governed-model-turn-v3-actual-boundary.md | 27 + .../governed_model_turn_actual_boundary_v3.go | 121 ++ ...overned_model_turn_provider_boundary_v3.go | 21 +- .../model-invoker/invocation_material_v2.go | 70 +- .../model-invoker/routegateway/gateway.go | 43 +- .../governed_v3_actual_boundary.go | 439 +++++ .../model-invoker/routegateway/pool.go | 66 +- ...overned_model_turn_provider_boundary_v3.go | 39 + ...governed_v3_actual_boundary_import_test.go | 52 + .../governed_v3_actual_boundary_test.go | 1685 +++++++++++++++++ 13 files changed, 2595 insertions(+), 48 deletions(-) create mode 100644 .properties.rax/design/model-invoker/governed-model-turn-v3-actual-boundary.md create mode 100644 .properties.rax/memory/model-invoker/20260731-055700-governed-model-turn-v3-actual-boundary.md create mode 100644 .properties.rax/module/model-invoker/governed-model-turn-v3-actual-boundary.md create mode 100644 .properties.rax/plan/model-invoker/governed-model-turn-v3-actual-boundary.md create mode 100644 ExecutionRuntime/model-invoker/governed_model_turn_actual_boundary_v3.go create mode 100644 ExecutionRuntime/model-invoker/routegateway/governed_v3_actual_boundary.go create mode 100644 ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_import_test.go create mode 100644 ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_test.go diff --git a/.properties.rax/design/model-invoker/governed-model-turn-v3-actual-boundary.md b/.properties.rax/design/model-invoker/governed-model-turn-v3-actual-boundary.md new file mode 100644 index 0000000..b2abd52 --- /dev/null +++ b/.properties.rax/design/model-invoker/governed-model-turn-v3-actual-boundary.md @@ -0,0 +1,42 @@ +# Governed Model Turn V3 Actual Boundary + +## 冻结目标 + +本切片只把已存在的 `GovernedModelTurnV3` 与 `InvocationMaterialV2` 串进 routegateway 的可逆 pre-invoke 路径。由于 credential exact current、实际 Provider request canonical 和 durable Provider Attempt 尚未冻结,它在 `prepareAt` 后、任何 Boundary 写入前确定性 Fail Closed。 + +## 固定顺序 + +```text +exact Turn +→ historical Boundary early Inspect +→ authoritative Context/Tool pair S1 +→ Prepared/Current/ACK S1/S2 +→ reversible Provider prepare +→ deterministic Fail Closed +``` + +历史 Boundary 通过同一复合 Store 在 Binding、Secret 和 Factory 前 early Inspect;所有新调用都保持 Boundary、Provider 与 Observation 写入为零。 + +## 边界 + +- `ContextFrame/ContextMaterial`与`ToolInjectionMaterial/ToolSurface`必须通过`InvocationMaterialAuthorizerV2`的paired-reader ports再次验证。 +- caller传入的非零`ModelBoundary`必须与历史winner exact一致;只有零值可由历史winner补全。 +- S1/S2分别用一次权威paired-reader读取同时生成Authorization与完整Context/Tool projection;每条source的Ref、Checked、TTL、Digest及projection body必须exact一致,不能二次读取拼接快照,也不能只比较聚合最短TTL。 +- Commit ACK在S1/S2都必须重新验证current、Prepared/Current绑定和完整body;expiry equality、same-Ref body splice及重封后的Ref漂移均在Provider prepare前拒绝。 +- exact Turn Reader返回值必须同时通过完整`Validate`和Ref equality,不能用保持Ref的State/Created/Updated/Expires splice绕过。 +- routegateway不生成Context、Tool、Runtime或Harness事实。 +- Provider prepare可逆;确定性 Fail Closed 必须释放adapter lease。 +- adapter lease的release/retire终态与调用顺序无关;最终stale且refs为零时Closer恰执行一次,release错误保留在返回因果链。 +- 当前切片不跨 Runtime guard、不调用 Provider,也不产生 Provider Observation。 +- 同版本、同expiry但credential material generation变化不能由现有`SecretResolver`证明,因此不得通过二次Resolve解锁Provider。 +- direct `Invoke`、V1、V2路径不因本切片获得V3治理语义。 + +## Production NO-GO + +当前同时缺少: + +- 将`prepareAt`产生的实际Provider request形状重算并闭合到`ActualProviderInjectionDigest`的公开canonical; +- V3 Provider Attempt/Observation的持久化与exact Inspect合同。 +- Model-owned exact `CredentialMaterialCurrentRef`、`ResolvedCredentialHandle`与`CurrentReader`,并让pool key和`preparedCall`绑定该exact ref,在invoke前fresh exact Inspect。 + +所以本切片只能证明pre-invoke读取、准备与Fail Closed;测试中的工具alias和compiled digest仍是fixture材料,不是Tool Owner authoritative compiled material。Host availability只能由Runtime guard的权威reader提供,caller不得伪造。 diff --git a/.properties.rax/memory/model-invoker/20260731-055700-governed-model-turn-v3-actual-boundary.md b/.properties.rax/memory/model-invoker/20260731-055700-governed-model-turn-v3-actual-boundary.md new file mode 100644 index 0000000..205f463 --- /dev/null +++ b/.properties.rax/memory/model-invoker/20260731-055700-governed-model-turn-v3-actual-boundary.md @@ -0,0 +1,17 @@ +# Governed Model Turn V3 Actual Boundary 施工中 + +## 当前事实 + +- worktree已rebase基线:`origin/main@5e491e9450b76a3f488cf14703b9d4396dc670bc` +- 分支:`agent/governed-model-turn-v3-routegateway-actual-boundary` +- V3 routegateway pre-invoke路径已形成未提交候选。 +- authoritative Context/Tool pair会在S1/S2各读取一次,并由同次读取同时产生Authorization与完整projection;非min source TTL/Checked漂移不会被二次读取TOCTOU或聚合最短TTL掩盖。 +- Commit ACK在S1/S2按完整body与currentness复检;exact Turn保持Ref的body splice也会Fail Closed。 +- 现有`SecretResolver`无法证明同version/expiry下的material generation exact current,因此本切片在prepare后、Boundary前Fail Closed。 +- caller Boundary exact匹配/冲突、source TTL缩短/延长与Checked漂移、ACK expiry/body漂移、Turn body splice、S2 clock regression、Runtime draft preflight与Provider lease release error chain均已补门禁。 +- adapter lease release/retire改为顺序无关终态,stale且refs为零时Closer恰一次。 +- 已有64并发、same-coordinate material drift与重放门禁测试,Boundary/Provider均为0。 + +## NO-GO + +尚无credential exact current/handle/reader、实际Provider request→`ActualProviderInjectionDigest`公开canonical,也无V3 Provider Attempt/Observation持久化与exact Inspect;当前仅证明Boundary/Provider/Observation=0的pre-invoke reference路径。 diff --git a/.properties.rax/module/model-invoker/governed-model-turn-v3-actual-boundary.md b/.properties.rax/module/model-invoker/governed-model-turn-v3-actual-boundary.md new file mode 100644 index 0000000..fe8b05e --- /dev/null +++ b/.properties.rax/module/model-invoker/governed-model-turn-v3-actual-boundary.md @@ -0,0 +1,21 @@ +# Module: Governed Model Turn V3 Actual Boundary + +## 作用 + +该模块是Model Invoker中V3 pre-provider facts到routegateway物理调用的窄接线。它复用公开Owner ports,不复制Context、Tool、Runtime或Harness语义。 + +## Public surface + +- `InspectCurrentInvocationMaterialAuthorizationV2` +- `InspectCurrentInvocationMaterialAuthorizationClosureV3` +- `ValidateModelProviderActualPointRequestDraftV3` +- `GovernedModelTurnProviderBoundaryTurnAttemptReaderV3` +- `routegateway.GovernedModelTurnActualBoundaryDependenciesV3` +- `routegateway.GovernedModelTurnActualBoundaryCommandV3` +- `routegateway.GovernedModelTurnActualBoundaryResultV3` +- `routegateway.WithGovernedModelTurnActualBoundaryV3` +- `routegateway.Gateway.InvokeGovernedModelTurnActualBoundaryV3` + +## Current status + +Owner-local pre-invoke candidate。它以完整Context/Tool paired projection、完整ACK snapshot和已验证Turn body执行S1/S2;在adapter prepare后、Boundary写入前确定性Fail Closed。无credential exact current、实际Provider request canonical闭包与持久Provider Observation,Provider调用固定为0,production仍为NO-GO。 diff --git a/.properties.rax/plan/model-invoker/governed-model-turn-v3-actual-boundary.md b/.properties.rax/plan/model-invoker/governed-model-turn-v3-actual-boundary.md new file mode 100644 index 0000000..a165f46 --- /dev/null +++ b/.properties.rax/plan/model-invoker/governed-model-turn-v3-actual-boundary.md @@ -0,0 +1,27 @@ +# Governed Model Turn V3 Actual Boundary Plan + +## 实施 + +1. 增加已持久化`InvocationMaterialV2`的authoritative pair复读helper;Authorizer每个阶段只读每个Pair一次,并从同次读取同时生成Authorization与完整current projection。 +2. 为Gateway增加独立V3 dependencies与Option,不修改V1/V2。 +3. 实现S1/S2与可逆Provider prepare。 +4. 在任何Boundary写入前因credential exact current合同缺失而确定性Fail Closed。 +5. 在任何Provider prepare前校验Runtime actual-point draft;历史replay拒绝caller Boundary splice。 +6. 增加64并发、same-version/same-expiry material drift、非min source TTL/Checked漂移、ACK current/body漂移、Turn body splice、pair unavailable、clock drift和replay测试。 +7. 收紧adapter lease终态:release/retire并发或任意先后顺序不丢失Closer与错误。 + +## 验收 + +- Boundary、Provider与Observation写入均为0。 +- 64并发同Turn/attempt保持Boundary=0、Provider=0。 +- 同版本同expiry但material generation变化仍Provider=0。 +- 任一authoritative source或ACK在S1/S2发生完整projection/body漂移时,Binding、Secret、Factory、Boundary、Provider与Observation均为0。 +- 交替Reader不能利用同阶段二次读取制造Authorization/Pair混合快照;每个Pair在每个阶段恰读一次。 +- exact Turn保持Ref但修改State/Created/Updated/Expires时,Provider prepare为0。 +- authoritative pair未配置时Gateway无法启用。 +- V1/V2、direct Invoke、Provider实现、Runtime/Harness/Context/Tool目录零修改。 +- ordinary、race、vet、diff/import boundary通过。 + +## 后续 + +另行冻结Provider request canonical→`ActualProviderInjectionDigest`闭包、V3 Provider Attempt/Observation history与lost-reply exact Inspect,以及credential exact current/handle/reader;本计划不生成production Outcome。 diff --git a/ExecutionRuntime/model-invoker/governed_model_turn_actual_boundary_v3.go b/ExecutionRuntime/model-invoker/governed_model_turn_actual_boundary_v3.go new file mode 100644 index 0000000..96ef8b9 --- /dev/null +++ b/ExecutionRuntime/model-invoker/governed_model_turn_actual_boundary_v3.go @@ -0,0 +1,121 @@ +package modelinvoker + +import ( + "context" + "time" +) + +// InvocationMaterialCurrentAuthorizationClosureV3 freezes the complete +// authoritative Context and Tool pair projections observed with one current +// material authorization check. Aggregate authorization expiry alone cannot +// prove that a non-minimum source did not drift between S1 and S2. +type InvocationMaterialCurrentAuthorizationClosureV3 struct { + Authorization InvocationMaterialAuthorizationV2 + ContextPair InvocationMaterialContextPairProjectionV2 + ToolPair InvocationMaterialToolPairProjectionV2 +} + +// InspectCurrentInvocationMaterialAuthorizationV2 replays the five exact +// Model-owned reader checks for an already persisted InvocationMaterialV2. +// It does not create another material, cross a commit gate, prepare a Provider, +// or grant dispatch authority. Route gateways use it at S1/S2/S3 so the stored +// RouteCall bytes cannot outlive their authoritative Context and Tool pairs. +func InspectCurrentInvocationMaterialAuthorizationV2( + ctx context.Context, + authorizer *InvocationMaterialAuthorizerV2, + prepared PreparedModelInvocationFactV1, + current PreparedModelInvocationCurrentProjectionV1, + material InvocationMaterialV2, + now time.Time, +) (InvocationMaterialAuthorizationV2, error) { + if ctx == nil || ctx.Err() != nil || authorizer == nil || now.IsZero() || + material.ValidateAgainstPreparedV2(prepared, current, now) != nil { + return InvocationMaterialAuthorizationV2{}, governedInvalidV1( + "invocation material V2 current authorization inputs are invalid", + ) + } + closure := InvocationMaterialExactClosureV2{ + SourceLineage: material.Authorization.SourceLineage, + ProviderInjection: material.Authorization.ProviderInjectionRef, + Route: material.Authorization.RouteRef, + Profile: material.Authorization.ProfileRef, + } + observed, err := authorizer.authorizeV2( + ctx, + prepared, + current, + material.Call, + closure, + now, + ) + if err != nil { + return InvocationMaterialAuthorizationV2{}, err + } + if !sameInvocationMaterialAuthorizationClosureV2( + observed, + material.Authorization, + ) || + observed.AuthorizedUnixNano < material.Authorization.AuthorizedUnixNano || + observed.ExpiresUnixNano != material.Authorization.ExpiresUnixNano { + return InvocationMaterialAuthorizationV2{}, governedConflictV1( + "invocation material V2 current authorization drifted", + ) + } + return observed, nil +} + +// InspectCurrentInvocationMaterialAuthorizationClosureV3 additionally freezes +// the full paired Context and Tool current projections. It performs no writes, +// gate crossing, Provider preparation, or dispatch authorization. +func InspectCurrentInvocationMaterialAuthorizationClosureV3( + ctx context.Context, + authorizer *InvocationMaterialAuthorizerV2, + prepared PreparedModelInvocationFactV1, + current PreparedModelInvocationCurrentProjectionV1, + material InvocationMaterialV2, + now time.Time, +) (InvocationMaterialCurrentAuthorizationClosureV3, error) { + var closure InvocationMaterialCurrentAuthorizationClosureV3 + if ctx == nil || ctx.Err() != nil || authorizer == nil || now.IsZero() || + material.ValidateAgainstPreparedV2(prepared, current, now) != nil { + return closure, governedInvalidV1( + "invocation material V3 current authorization closure inputs are invalid", + ) + } + expected := InvocationMaterialExactClosureV2{ + SourceLineage: material.Authorization.SourceLineage, + ProviderInjection: material.Authorization.ProviderInjectionRef, + Route: material.Authorization.RouteRef, + Profile: material.Authorization.ProfileRef, + } + observed, err := authorizer.authorizeClosureV3( + ctx, + prepared, + current, + material.Call, + expected, + now, + ) + if err != nil { + return closure, err + } + authorization := observed.authorization + if !sameInvocationMaterialAuthorizationClosureV2( + authorization, + material.Authorization, + ) || + authorization.AuthorizedUnixNano < + material.Authorization.AuthorizedUnixNano || + authorization.ExpiresUnixNano != + material.Authorization.ExpiresUnixNano { + return closure, governedConflictV1( + "invocation material V2 current authorization drifted", + ) + } + closure = InvocationMaterialCurrentAuthorizationClosureV3{ + Authorization: authorization, + ContextPair: observed.contextPair, + ToolPair: observed.toolPair, + } + return closure, nil +} diff --git a/ExecutionRuntime/model-invoker/governed_model_turn_provider_boundary_v3.go b/ExecutionRuntime/model-invoker/governed_model_turn_provider_boundary_v3.go index 9c45d83..30f3dc2 100644 --- a/ExecutionRuntime/model-invoker/governed_model_turn_provider_boundary_v3.go +++ b/ExecutionRuntime/model-invoker/governed_model_turn_provider_boundary_v3.go @@ -136,6 +136,16 @@ type GovernedModelTurnProviderBoundaryRepositoryV3 interface { ) (GovernedModelTurnProviderBoundaryFactV3, error) } +// GovernedModelTurnProviderBoundaryTurnAttemptReaderV3 exposes the immutable +// winner for an original V3 Turn attempt. It lets a physical gateway reject a +// replay before resolving credentials or preparing a Provider adapter. +type GovernedModelTurnProviderBoundaryTurnAttemptReaderV3 interface { + InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + context.Context, + GovernedModelTurnAttemptRefV3, + ) (GovernedModelTurnProviderBoundaryFactV3, error) +} + func GovernedModelTurnProviderBoundaryOwnerV3() core.OwnerRef { return core.OwnerRef{ Domain: governedModelTurnProviderBoundaryOwnerDomainV3, @@ -321,7 +331,7 @@ func DeriveGovernedModelTurnProviderBoundaryRefV3( "governed model turn provider boundary V3 lineage drifted", ) } - if err := validateRuntimeRequestWithoutBoundaryV3(request); err != nil { + if err := ValidateModelProviderActualPointRequestDraftV3(request); err != nil { return GovernedModelTurnProviderBoundaryRefV3{}, err } operationDigest, err := request.Operation.DigestV3() @@ -422,9 +432,9 @@ func BuildGovernedModelTurnProviderBoundaryFactV3( if err != nil { return GovernedModelTurnProviderBoundaryFactV3{}, err } - if turn.RefV3() != draft.TurnRef { + if turn.Validate() != nil || turn.RefV3() != draft.TurnRef { return GovernedModelTurnProviderBoundaryFactV3{}, governedConflictV1( - "governed model turn provider boundary V3 Turn exact Reader drifted", + "governed model turn provider boundary V3 Turn exact Reader returned invalid or drifted content", ) } if _, err := validateCurrentGovernedModelTurnWinnerV3( @@ -690,7 +700,10 @@ func validateGovernedModelTurnProviderBoundaryLineageV3( return nil } -func validateRuntimeRequestWithoutBoundaryV3( +// ValidateModelProviderActualPointRequestDraftV3 validates every Runtime +// actual-point coordinate that exists before Model derives ModelBoundary. It +// performs no reads and does not grant dispatch authority. +func ValidateModelProviderActualPointRequestDraftV3( request runtimeports.InspectCurrentModelProviderActualPointRequestV1, ) error { boundary := request.ModelBoundary diff --git a/ExecutionRuntime/model-invoker/invocation_material_v2.go b/ExecutionRuntime/model-invoker/invocation_material_v2.go index a9b6c2a..7489d91 100644 --- a/ExecutionRuntime/model-invoker/invocation_material_v2.go +++ b/ExecutionRuntime/model-invoker/invocation_material_v2.go @@ -159,6 +159,12 @@ func SealInvocationMaterialAuthorizationV2(a InvocationMaterialAuthorizationV2) return a, a.Validate() } +type invocationMaterialAuthorizationClosureV3 struct { + authorization InvocationMaterialAuthorizationV2 + contextPair InvocationMaterialContextPairProjectionV2 + toolPair InvocationMaterialToolPairProjectionV2 +} + func (a *InvocationMaterialAuthorizerV2) authorizeV2( ctx context.Context, prepared PreparedModelInvocationFactV1, @@ -167,23 +173,50 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( expected InvocationMaterialExactClosureV2, now time.Time, ) (InvocationMaterialAuthorizationV2, error) { + closure, err := a.authorizeClosureV3( + ctx, + prepared, + current, + call, + expected, + now, + ) + if err != nil { + return InvocationMaterialAuthorizationV2{}, err + } + return closure.authorization, nil +} + +// authorizeClosureV3 derives the authorization and the complete Context/Tool +// projections from the same authoritative reads. Its compatibility wrapper +// above preserves the V2 contract while V3 S1/S2 callers can freeze the exact +// source bodies without a second-read TOCTOU window. +func (a *InvocationMaterialAuthorizerV2) authorizeClosureV3( + ctx context.Context, + prepared PreparedModelInvocationFactV1, + current PreparedModelInvocationCurrentProjectionV1, + call RouteCall, + expected InvocationMaterialExactClosureV2, + now time.Time, +) (invocationMaterialAuthorizationClosureV3, error) { + var closure invocationMaterialAuthorizationClosureV3 if a == nil || ctx == nil || ctx.Err() != nil || now.IsZero() || expected.ValidateAgainstPreparedV2(prepared) != nil || current.ValidateAgainstFact(prepared) != nil || current.ValidateCurrent(current.Ref(), now) != nil { - return InvocationMaterialAuthorizationV2{}, governedInvalidV1("invocation material V2 Authorizer input is invalid") + return closure, governedInvalidV1("invocation material V2 Authorizer input is invalid") } contextDigest, err := DigestGovernedModelTurnContextV2(call) if err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } requestToolsDigest, err := DigestGovernedModelTurnRequestToolsV2(call) if err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } if contextDigest != expected.SourceLineage.ContextMappedInputDigest || requestToolsDigest != expected.SourceLineage.RequestToolsDigest { - return InvocationMaterialAuthorizationV2{}, governedConflictV1("RouteCall bytes differ from expected source lineage") + return closure, governedConflictV1("RouteCall bytes differ from expected source lineage") } contextPair, err := a.config.ContextPair.InspectExactInvocationContextPairV2( ctx, @@ -192,7 +225,7 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( contextDigest, ) if err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } if err := contextPair.ValidateCurrentV2( expected.SourceLineage.ContextFrame, @@ -200,7 +233,7 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( contextDigest, now, ); err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } toolPair, err := a.config.ToolPair.InspectExactInvocationToolPairV2( ctx, @@ -209,7 +242,7 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( requestToolsDigest, ) if err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } if err := toolPair.ValidateCurrentV2( expected.SourceLineage.ToolInjectionMaterial, @@ -219,28 +252,28 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( requestToolsDigest, now, ); err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } provider, err := a.config.ProviderInjection.InspectExactInvocationProviderInjectionV1(ctx, expected.ProviderInjection) if err != nil || provider.ValidateCurrentV1(expected.ProviderInjection, now) != nil { if err == nil { err = governedConflictV1("invocation material V2 ProviderInjection source is not current") } - return InvocationMaterialAuthorizationV2{}, err + return closure, err } route, err := a.config.Route.InspectExactInvocationRouteV1(ctx, expected.Route) if err != nil || route.ValidateCurrentV1(expected.Route, now) != nil { if err == nil { err = governedConflictV1("invocation material V2 Route source is not current") } - return InvocationMaterialAuthorizationV2{}, err + return closure, err } profile, err := a.config.Profile.InspectExactInvocationProfileV1(ctx, expected.Profile) if err != nil || profile.ValidateCurrentV1(expected.Profile, now) != nil { if err == nil { err = governedConflictV1("invocation material V2 Profile source is not current") } - return InvocationMaterialAuthorizationV2{}, err + return closure, err } observed, err := SealInvocationMaterialSourceLineageV2(InvocationMaterialSourceLineageV2{ ContextFrame: contextPair.ContextFrame, @@ -255,13 +288,13 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( if err != nil || observed != expected.SourceLineage || provider.Ref != expected.ProviderInjection || route.Ref != expected.Route || profile.Ref != expected.Profile { - return InvocationMaterialAuthorizationV2{}, governedConflictV1("invocation material V2 exact Owner readers drifted") + return closure, governedConflictV1("invocation material V2 exact Owner readers drifted") } routeCallDigest, err := DigestGovernedModelTurnRouteCallV2(call) if err != nil { - return InvocationMaterialAuthorizationV2{}, err + return closure, err } - return SealInvocationMaterialAuthorizationV2(InvocationMaterialAuthorizationV2{ + authorization, err := SealInvocationMaterialAuthorizationV2(InvocationMaterialAuthorizationV2{ PreparedRef: prepared.Ref(), CurrentRef: current.Ref(), RouteCallDigest: routeCallDigest, @@ -280,6 +313,15 @@ func (a *InvocationMaterialAuthorizerV2) authorizeV2( profile.ExpiresUnixNano, ), }) + if err != nil { + return closure, err + } + closure = invocationMaterialAuthorizationClosureV3{ + authorization: authorization, + contextPair: contextPair, + toolPair: toolPair, + } + return closure, nil } type InvocationMaterialRefV2 struct { diff --git a/ExecutionRuntime/model-invoker/routegateway/gateway.go b/ExecutionRuntime/model-invoker/routegateway/gateway.go index 67dafb8..47ba52a 100644 --- a/ExecutionRuntime/model-invoker/routegateway/gateway.go +++ b/ExecutionRuntime/model-invoker/routegateway/gateway.go @@ -74,20 +74,37 @@ func WithGovernedModelTurnsV2(dependencies GovernedModelTurnDependenciesV2) Opti } } +// WithGovernedModelTurnActualBoundaryV3 enables only the additive V3 +// pre-invoke reference path. It does not alter V1/V2, write a new Provider +// boundary, or make direct Invoke governed. +func WithGovernedModelTurnActualBoundaryV3( + dependencies GovernedModelTurnActualBoundaryDependenciesV3, +) Option { + return func(gateway *Gateway) error { + if err := dependencies.validate(); err != nil { + return err + } + copy := dependencies + gateway.governedTurnActualBoundaryV3 = © + return nil + } +} + type Gateway struct { - catalog *catalog.Catalog - policy *modelinvoker.RouteInvoker - bindings RuntimeBindingResolver - secrets SecretResolver - factories *FactoryRegistry - pool *adapterPool - now func() time.Time - httpClient *http.Client - subscriptionAuthorization modelinvoker.SubscriptionAuthorizationResolver - governedV1 *GovernedModelInvocationDependenciesV1 - governedTurnV2 *GovernedModelTurnDependenciesV2 - closeOnce sync.Once - closeErr error + catalog *catalog.Catalog + policy *modelinvoker.RouteInvoker + bindings RuntimeBindingResolver + secrets SecretResolver + factories *FactoryRegistry + pool *adapterPool + now func() time.Time + httpClient *http.Client + subscriptionAuthorization modelinvoker.SubscriptionAuthorizationResolver + governedV1 *GovernedModelInvocationDependenciesV1 + governedTurnV2 *GovernedModelTurnDependenciesV2 + governedTurnActualBoundaryV3 *GovernedModelTurnActualBoundaryDependenciesV3 + closeOnce sync.Once + closeErr error } func New(routeCatalog *catalog.Catalog, bindings RuntimeBindingResolver, secrets SecretResolver, factories *FactoryRegistry, options ...Option) (*Gateway, error) { diff --git a/ExecutionRuntime/model-invoker/routegateway/governed_v3_actual_boundary.go b/ExecutionRuntime/model-invoker/routegateway/governed_v3_actual_boundary.go new file mode 100644 index 0000000..fc82275 --- /dev/null +++ b/ExecutionRuntime/model-invoker/routegateway/governed_v3_actual_boundary.go @@ -0,0 +1,439 @@ +package routegateway + +import ( + "context" + "errors" + "reflect" + "time" + + modelinvoker "github.com/Proview-China/rax/ExecutionRuntime/model-invoker" + runtimeports "github.com/Proview-China/rax/ExecutionRuntime/runtime/ports" +) + +// GovernedModelTurnActualBoundaryDependenciesV3 is deliberately closed over +// public, read-only Owner ports plus one composite Boundary store. +// Missing authoritative Context/Tool pair readers make Authorizer construction +// fail, so this path cannot silently fall back to stored RouteCall bytes. +type GovernedModelTurnProviderBoundaryStoreV3 interface { + modelinvoker.GovernedModelTurnProviderBoundaryRepositoryV3 + modelinvoker.GovernedModelTurnProviderBoundaryTurnAttemptReaderV3 +} + +type GovernedModelTurnActualBoundaryDependenciesV3 struct { + preparedHistory modelinvoker.PreparedModelInvocationReaderV1 + preparedCurrent modelinvoker.PreparedModelInvocationCurrentReaderV1 + commitGate modelinvoker.PreparedModelInvocationCommitGateV1 + materials modelinvoker.InvocationMaterialReaderV2 + authorizer *modelinvoker.InvocationMaterialAuthorizerV2 + turns modelinvoker.GovernedModelTurnRepositoryV3 + boundaries GovernedModelTurnProviderBoundaryStoreV3 +} + +func NewGovernedModelTurnActualBoundaryDependenciesV3( + preparedHistory modelinvoker.PreparedModelInvocationReaderV1, + preparedCurrent modelinvoker.PreparedModelInvocationCurrentReaderV1, + commitGate modelinvoker.PreparedModelInvocationCommitGateV1, + materials modelinvoker.InvocationMaterialReaderV2, + authorizer *modelinvoker.InvocationMaterialAuthorizerV2, + turns modelinvoker.GovernedModelTurnRepositoryV3, + boundaries GovernedModelTurnProviderBoundaryStoreV3, +) (GovernedModelTurnActualBoundaryDependenciesV3, error) { + dependencies := GovernedModelTurnActualBoundaryDependenciesV3{ + preparedHistory: preparedHistory, + preparedCurrent: preparedCurrent, + commitGate: commitGate, + materials: materials, + authorizer: authorizer, + turns: turns, + boundaries: boundaries, + } + if err := dependencies.validate(); err != nil { + return GovernedModelTurnActualBoundaryDependenciesV3{}, err + } + return dependencies, nil +} + +func (d GovernedModelTurnActualBoundaryDependenciesV3) validate() error { + for _, dependency := range []any{ + d.preparedHistory, + d.preparedCurrent, + d.commitGate, + d.materials, + d.authorizer, + d.turns, + d.boundaries, + } { + if nilInterface(dependency) { + return gatewayError( + modelinvoker.ErrorInvalidRequest, + "governed_turn_v3_actual_boundary_dependencies_required", + "governed model turn V3 actual boundary requires every exact Owner reader", + nil, + ) + } + } + return nil +} + +// GovernedModelTurnActualBoundaryCommandV3 starts from an already persisted, +// exact V3 Turn winner. RuntimeRequest may omit ModelBoundary on its first +// call; the Model boundary builder derives and seals it. +type GovernedModelTurnActualBoundaryCommandV3 struct { + TurnRef modelinvoker.GovernedModelTurnRefV3 + RuntimeRequest runtimeports.InspectCurrentModelProviderActualPointRequestV1 +} + +// GovernedModelTurnActualBoundaryResultV3 is an in-process pre-invoke result. +// Until exact credential current, prepared injection, and durable Provider +// attempt contracts exist, Boundary and Invoke remain zero. +type GovernedModelTurnActualBoundaryResultV3 struct { + Turn modelinvoker.GovernedModelTurnOutcomeV3 + Boundary modelinvoker.GovernedModelTurnProviderBoundaryPersistenceResultV3 + Invoke InvokeResult +} + +// InvokeGovernedModelTurnActualBoundaryV3 currently proves only the reversible +// pre-invoke coordinator. It replays exact Turn/Context/Tool/ACK inputs and +// prepares an adapter, then deterministically fails closed before writing a +// Boundary or invoking a Provider. This is not a production dispatch port. +func (g *Gateway) InvokeGovernedModelTurnActualBoundaryV3( + ctx context.Context, + command GovernedModelTurnActualBoundaryCommandV3, +) ( + result GovernedModelTurnActualBoundaryResultV3, + err error, +) { + if g == nil || g.now == nil || g.governedTurnActualBoundaryV3 == nil { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorUnavailable, + "turn_v3_actual_boundary", + "governed model turn V3 actual boundary is unavailable", + nil, + ) + } + if ctx == nil || ctx.Err() != nil || command.TurnRef.Validate() != nil { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorInvalid, + "turn_v3_actual_boundary", + "live context and exact V3 Turn Ref are required", + nil, + ) + } + dependencies := g.governedTurnActualBoundaryV3 + + turn, err := dependencies.turns.InspectExactGovernedModelTurnV3(ctx, command.TurnRef) + if err != nil { + return result, err + } + if turn.Validate() != nil || turn.RefV3() != command.TurnRef { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_exact", + "V3 Turn exact reader returned invalid or drifted content", + nil, + ) + } + result.Turn = turn.CloneV3() + + // Inspect the original Turn attempt before crossing Commit or resolving any + // Provider credential/factory. A replay never re-prepares a Provider, even + // when its caller only retained the original command without ModelBoundary. + existing, inspectErr := + dependencies.boundaries.InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + ctx, + turn.AttemptRefV3(), + ) + if inspectErr == nil { + expectedRequest := command.RuntimeRequest + if reflect.DeepEqual( + expectedRequest.ModelBoundary, + runtimeports.ModelProviderBoundaryCurrentRefV1{}, + ) { + expectedRequest.ModelBoundary = existing.RuntimeRequest.ModelBoundary + } else if expectedRequest.ModelBoundary.Validate() != nil || + !runtimeports.SameModelProviderBoundaryCurrentRefV1( + expectedRequest.ModelBoundary, + existing.RuntimeRequest.ModelBoundary, + ) { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_boundary_existing", + "caller V3 provider boundary differs from the immutable winner", + nil, + ) + } + if existing.Validate() != nil || + existing.TurnRef != turn.RefV3() || + !reflect.DeepEqual(existing.RuntimeRequest, expectedRequest) { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_boundary_existing", + "existing V3 provider boundary belongs to another exact request", + nil, + ) + } + result.Boundary = modelinvoker.GovernedModelTurnProviderBoundaryPersistenceResultV3{ + Fact: existing, + Disposition: modelinvoker.GovernedModelTurnProviderBoundaryPersistenceExistingV3, + } + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorIndeterminate, + "turn_v3_boundary_existing", + "original V3 provider boundary already exists; Provider replay is forbidden", + nil, + ) + } + if modelinvoker.GovernedModelInvocationErrorKindOfV1(inspectErr) != + modelinvoker.GovernedModelInvocationErrorNotFound { + return result, inspectErr + } + if err := modelinvoker.ValidateModelProviderActualPointRequestDraftV3( + command.RuntimeRequest, + ); err != nil { + return result, err + } + + s1 := g.now() + prepared1, current1, material1, err := + g.readGovernedModelTurnInputsV3(ctx, turn, s1) + if err != nil { + return result, err + } + authorization1, err := + modelinvoker.InspectCurrentInvocationMaterialAuthorizationClosureV3( + ctx, + dependencies.authorizer, + prepared1, + current1, + material1, + s1, + ) + if err != nil { + return result, err + } + ack1, err := modelinvoker.CrossPreparedModelInvocationCommitGateV1( + ctx, + dependencies.commitGate, + turn.PreparedRef, + turn.CurrentRef, + ) + if err != nil { + return result, err + } + if ack1.PreparedRef != turn.PreparedRef || + ack1.CurrentRef != turn.CurrentRef || + ack1.ValidateCurrent(current1, s1) != nil { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_s1_ack", + "V3 S1 Commit ACK is not exact and current", + nil, + ) + } + + s2 := g.now() + if s2.IsZero() || s2.Before(s1) { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_s2_clock", + "clock regressed before V3 S2", + nil, + ) + } + prepared2, current2, material2, err := + g.readGovernedModelTurnInputsV3(ctx, turn, s2) + if err != nil { + return result, err + } + authorization2, err := + modelinvoker.InspectCurrentInvocationMaterialAuthorizationClosureV3( + ctx, + dependencies.authorizer, + prepared2, + current2, + material2, + s2, + ) + if err != nil { + return result, err + } + ack2, err := modelinvoker.InspectPreparedModelInvocationCommitAckV1( + ctx, + dependencies.commitGate, + ack1.Ref(), + ) + if err != nil { + return result, err + } + if ack2.PreparedRef != turn.PreparedRef || + ack2.CurrentRef != turn.CurrentRef || + ack2.ValidateCurrent(current2, s2) != nil { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_s2_ack", + "V3 S2 Commit ACK is not exact and current", + nil, + ) + } + if prepared1.Ref() != prepared2.Ref() || + current1.Ref() != current2.Ref() || + material1.RefV2() != material2.RefV2() || + ack1 != ack2 || + !sameInvocationMaterialAuthorizationClosureV3( + authorization1, + authorization2, + ) { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_s2", + "V3 exact inputs drifted between S1 and S2", + nil, + ) + } + + prepareAt := g.now() + if prepareAt.IsZero() || prepareAt.Before(s2) { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_provider_prepare_clock", + "clock regressed before reversible Provider preparation", + nil, + ) + } + preparedProvider, err := g.prepareAt(ctx, material2.Call, prepareAt) + if err != nil { + return result, err + } + defer func() { + err = retireAndJoinGovernedModelTurnV3ProviderReleaseError( + err, + preparedProvider.lease, + ) + }() + actualRouteDigest, err := + modelinvoker.DigestGovernedRouteSelectionV1(preparedProvider.resolution.Route) + if err != nil || actualRouteDigest != material2.RouteDigest || + preparedProvider.request.Model != material2.Call.Request.Model { + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_provider_prepare", + "prepared Provider route differs from exact invocation material", + err, + ) + } + return result, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorUnavailable, + "turn_v3_credential_current_contract_required", + "exact credential current proof is unavailable; V3 Provider invoke is disabled", + nil, + ) +} + +func retireAndJoinGovernedModelTurnV3ProviderReleaseError( + primary error, + lease *adapterLease, +) error { + if lease == nil { + return primary + } + releaseErr := lease.retire() + if releaseErr == nil { + return primary + } + return errors.Join( + primary, + gatewayError( + modelinvoker.ErrorProviderUnavailable, + "turn_v3_provider_release_failed", + "reversible V3 Provider adapter release failed", + releaseErr, + ), + ) +} + +func (g *Gateway) readGovernedModelTurnInputsV3( + ctx context.Context, + turn modelinvoker.GovernedModelTurnOutcomeV3, + now time.Time, +) ( + modelinvoker.PreparedModelInvocationFactV1, + modelinvoker.PreparedModelInvocationCurrentProjectionV1, + modelinvoker.InvocationMaterialV2, + error, +) { + var historical modelinvoker.PreparedModelInvocationFactV1 + var current modelinvoker.PreparedModelInvocationCurrentProjectionV1 + var material modelinvoker.InvocationMaterialV2 + if now.IsZero() { + return historical, current, material, governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorInvalid, + "turn_v3_read_inputs", + "validation clock is zero", + nil, + ) + } + dependencies := g.governedTurnActualBoundaryV3 + historical, err := dependencies.preparedHistory.InspectExactPreparedModelInvocationV1( + ctx, + turn.PreparedRef, + ) + if err != nil { + return historical, current, material, err + } + current, err = dependencies.preparedCurrent.InspectExactPreparedModelInvocationCurrentV1( + ctx, + turn.CurrentRef, + ) + if err != nil { + return historical, current, material, err + } + material, err = dependencies.materials.InspectExactInvocationMaterialV2( + ctx, + turn.MaterialRef, + ) + if err != nil { + return historical, current, material, err + } + if historical.Ref() != turn.PreparedRef || + current.Ref() != turn.CurrentRef || + material.RefV2() != turn.MaterialRef || + current.ValidateAgainstFact(historical) != nil || + current.ValidateCurrent(turn.CurrentRef, now) != nil || + material.ValidateAgainstPreparedV2(historical, current, now) != nil || + turn.AttemptRequestDigest != historical.UnifiedRequestDigest || + turn.RouteCallDigest != material.RouteCallDigest { + return modelinvoker.PreparedModelInvocationFactV1{}, + modelinvoker.PreparedModelInvocationCurrentProjectionV1{}, + modelinvoker.InvocationMaterialV2{}, + governedGatewayErrorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "turn_v3_read_inputs", + "V3 exact durable inputs drifted", + nil, + ) + } + return historical.Clone(), current.Clone(), material.CloneV2(), nil +} + +func sameInvocationMaterialAuthorizationClosureV3( + left modelinvoker.InvocationMaterialCurrentAuthorizationClosureV3, + right modelinvoker.InvocationMaterialCurrentAuthorizationClosureV3, +) bool { + leftAuthorization := left.Authorization + rightAuthorization := right.Authorization + return leftAuthorization.PreparedRef == rightAuthorization.PreparedRef && + leftAuthorization.CurrentRef == rightAuthorization.CurrentRef && + leftAuthorization.RouteCallDigest == rightAuthorization.RouteCallDigest && + reflect.DeepEqual( + leftAuthorization.SourceLineage, + rightAuthorization.SourceLineage, + ) && + leftAuthorization.ProviderInjectionRef == + rightAuthorization.ProviderInjectionRef && + leftAuthorization.RouteRef == rightAuthorization.RouteRef && + leftAuthorization.ProfileRef == rightAuthorization.ProfileRef && + leftAuthorization.ExpiresUnixNano == + rightAuthorization.ExpiresUnixNano && + reflect.DeepEqual(left.ContextPair, right.ContextPair) && + reflect.DeepEqual(left.ToolPair, right.ToolPair) +} diff --git a/ExecutionRuntime/model-invoker/routegateway/pool.go b/ExecutionRuntime/model-invoker/routegateway/pool.go index ba3123b..d280432 100644 --- a/ExecutionRuntime/model-invoker/routegateway/pool.go +++ b/ExecutionRuntime/model-invoker/routegateway/pool.go @@ -40,7 +40,8 @@ type adapterLease struct { entry *poolEntry provider modelinvoker.Provider endpoint string - once sync.Once + mu sync.Mutex + released bool err error } @@ -171,26 +172,57 @@ func (l *adapterLease) release() error { if l == nil { return nil } - l.once.Do(func() { - p, entry := l.pool, l.entry - if p == nil || entry == nil { - return + l.mu.Lock() + defer l.mu.Unlock() + l.err = errors.Join(l.err, l.transitionLocked(false)) + return l.err +} + +// retire prevents a reversibly prepared adapter from being reused, then +// releases this lease. The closer still runs exactly once when the final +// outstanding reference is released. +func (l *adapterLease) retire() error { + if l == nil { + return nil + } + l.mu.Lock() + defer l.mu.Unlock() + l.err = errors.Join(l.err, l.transitionLocked(true)) + return l.err +} + +// transitionLocked makes release and retirement commutative for one lease. +// A prior release may leave an idle reusable entry open; a later retirement +// must still mark it stale and close it exactly once. l.mu serializes the +// closer and its error so concurrent terminal calls observe the same result. +func (l *adapterLease) transitionLocked(retire bool) error { + p, entry := l.pool, l.entry + if p == nil || entry == nil { + return nil + } + var closer io.Closer + p.mu.Lock() + if retire { + entry.stale = true + if p.entries[entry.key] == entry { + delete(p.entries, entry.key) } - var closer io.Closer - p.mu.Lock() + } + if !l.released { if entry.refs > 0 { entry.refs-- } - if entry.refs == 0 && (entry.stale || p.closed) && !entry.closed { - entry.closed = true - closer = entry.closer - } - p.mu.Unlock() - if closer != nil { - l.err = closeAll([]io.Closer{closer}) - } - }) - return l.err + l.released = true + } + if entry.refs == 0 && (entry.stale || p.closed) && !entry.closed { + entry.closed = true + closer = entry.closer + } + p.mu.Unlock() + if closer == nil { + return nil + } + return closeAll([]io.Closer{closer}) } func (p *adapterPool) close() error { diff --git a/ExecutionRuntime/model-invoker/storage/sqlite/governed_model_turn_provider_boundary_v3.go b/ExecutionRuntime/model-invoker/storage/sqlite/governed_model_turn_provider_boundary_v3.go index 4a07c0b..dda9786 100644 --- a/ExecutionRuntime/model-invoker/storage/sqlite/governed_model_turn_provider_boundary_v3.go +++ b/ExecutionRuntime/model-invoker/storage/sqlite/governed_model_turn_provider_boundary_v3.go @@ -219,6 +219,45 @@ func (s *Store) InspectGovernedModelTurnProviderBoundaryAttemptV3( return fact.CloneV3(), nil } +func (s *Store) InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + ctx context.Context, + ref modelinvoker.GovernedModelTurnAttemptRefV3, +) (modelinvoker.GovernedModelTurnProviderBoundaryFactV3, error) { + if err := contextErrorV1(ctx, "inspect_provider_boundary_turn_attempt_v3"); err != nil { + return modelinvoker.GovernedModelTurnProviderBoundaryFactV3{}, err + } + if err := ref.Validate(); err != nil { + return modelinvoker.GovernedModelTurnProviderBoundaryFactV3{}, errorV1( + modelinvoker.GovernedModelInvocationErrorInvalid, + "inspect_provider_boundary_turn_attempt_v3", + "V3 Turn Attempt Ref is invalid", + err, + ) + } + row, err := loadGovernedModelTurnProviderBoundaryRowV3( + ctx, + s.db, + `WHERE turn_attempt_digest=?`, + string(ref.Digest), + ) + if err != nil { + return modelinvoker.GovernedModelTurnProviderBoundaryFactV3{}, err + } + fact, err := row.decodeV3() + if err != nil { + return modelinvoker.GovernedModelTurnProviderBoundaryFactV3{}, err + } + if fact.TurnRef.AttemptRefV3() != ref { + return modelinvoker.GovernedModelTurnProviderBoundaryFactV3{}, errorV1( + modelinvoker.GovernedModelInvocationErrorConflict, + "inspect_provider_boundary_turn_attempt_v3", + "stored provider boundary belongs to another V3 Turn Attempt", + nil, + ) + } + return fact.CloneV3(), nil +} + func (s *Store) InspectExactGovernedModelTurnProviderBoundaryV3( ctx context.Context, ref modelinvoker.GovernedModelTurnProviderBoundaryRefV3, diff --git a/ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_import_test.go b/ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_import_test.go new file mode 100644 index 0000000..1022370 --- /dev/null +++ b/ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_import_test.go @@ -0,0 +1,52 @@ +package routegateway_test + +import ( + "go/parser" + "go/token" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" +) + +func TestGovernedModelTurnV3ActualBoundaryImportClosure(t *testing.T) { + _, current, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("cannot locate V3 actual-boundary import test") + } + modelRoot := filepath.Clean(filepath.Join(filepath.Dir(current), "..", "..")) + for _, path := range []string{ + filepath.Join(modelRoot, "governed_model_turn_actual_boundary_v3.go"), + filepath.Join(modelRoot, "routegateway", "governed_v3_actual_boundary.go"), + } { + parsed, err := parser.ParseFile( + token.NewFileSet(), + path, + nil, + parser.ImportsOnly, + ) + if err != nil { + t.Fatal(err) + } + for _, spec := range parsed.Imports { + importPath, err := strconv.Unquote(spec.Path.Value) + if err != nil { + t.Fatal(err) + } + for _, forbidden := range []string{ + "/harness", + "/application", + "/context-engine", + "/tool-mcp", + "/runtime/kernel", + "/runtime/control", + "/runtime/fakes", + } { + if strings.Contains(importPath, forbidden) { + t.Fatalf("%s imports forbidden boundary %q", path, importPath) + } + } + } + } +} diff --git a/ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_test.go b/ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_test.go new file mode 100644 index 0000000..cf5188b --- /dev/null +++ b/ExecutionRuntime/model-invoker/tests/routegateway/governed_v3_actual_boundary_test.go @@ -0,0 +1,1685 @@ +package routegateway_test + +import ( + "context" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + modelinvoker "github.com/Proview-China/rax/ExecutionRuntime/model-invoker" + "github.com/Proview-China/rax/ExecutionRuntime/model-invoker/catalog" + "github.com/Proview-China/rax/ExecutionRuntime/model-invoker/routegateway" + modelsqlite "github.com/Proview-China/rax/ExecutionRuntime/model-invoker/storage/sqlite" + "github.com/Proview-China/rax/ExecutionRuntime/model-invoker/upstream" + "github.com/Proview-China/rax/ExecutionRuntime/runtime/core" + runtimeports "github.com/Proview-China/rax/ExecutionRuntime/runtime/ports" +) + +func TestGovernedModelTurnV3ActualBoundaryFailsClosedWithoutExactCredentialCurrent( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorUnavailable { + t.Fatalf("pre-invoke result=%+v err=%v", result, err) + } + if result.Turn.RefV3() != fixture.command.TurnRef || + result.Boundary.Fact.ID != "" || + result.Invoke.Response.ID != "" || + fixture.state.invoke.Load() != 0 { + t.Fatalf( + "pre-invoke result=%+v provider calls=%d want exact turn/zero boundary/0", + result, + fixture.state.invoke.Load(), + ) + } + if _, inspectErr := + fixture.store.InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + context.Background(), + result.Turn.AttemptRefV3(), + ); modelinvoker.GovernedModelInvocationErrorKindOfV1(inspectErr) != + modelinvoker.GovernedModelInvocationErrorNotFound { + t.Fatalf("pre-invoke boundary write error=%v want=not_found", inspectErr) + } +} + +func TestGovernedModelTurnV3ActualBoundaryPreservesAdapterReleaseFailure( + t *testing.T, +) { + const sentinel = "V3-RELEASE-FAILURE-MUST-NOT-LEAK" + releaseFailure := errors.New(sentinel) + var releaseFactory *actualBoundaryReleaseErrorFactoryV3 + fixture := newGovernedActualBoundaryFixtureV3WithGateway( + t, + func( + t *testing.T, + routeCatalog *catalog.Catalog, + state *callState, + dependencies routegateway.GovernedModelTurnActualBoundaryDependenciesV3, + ) *routegateway.Gateway { + t.Helper() + releaseFactory = &actualBoundaryReleaseErrorFactoryV3{ + fakeFactory: fakeFactory{id: "openai", state: state}, + closeErr: releaseFailure, + } + return actualBoundaryGatewayWithOverrideFactoryV3( + t, + routeCatalog, + releaseFactory, + state, + dependencies, + ) + }, + ) + defer fixture.close(t) + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorUnavailable || + !errors.Is(err, releaseFailure) || + strings.Contains(err.Error(), sentinel) { + t.Fatalf("release failure lost or leaked evidence: %v", err) + } + if result.Boundary.Fact.ID != "" || + result.Invoke.Response.ID != "" || + fixture.state.invoke.Load() != 0 || + releaseFactory.closeCalls.Load() != 1 { + t.Fatalf( + "release failure result=%+v invoke=%d closes=%d want zero/zero/1", + result, + fixture.state.invoke.Load(), + releaseFactory.closeCalls.Load(), + ) + } +} + +func TestGovernedModelTurnV3ActualBoundarySameCoordinateMaterialDriftStaysClosed( + t *testing.T, +) { + var resolver *sameCoordinateMaterialDriftSecretV3 + fixture := newGovernedActualBoundaryFixtureV3WithGateway( + t, + func( + t *testing.T, + routeCatalog *catalog.Catalog, + state *callState, + dependencies routegateway.GovernedModelTurnActualBoundaryDependenciesV3, + ) *routegateway.Gateway { + t.Helper() + resolver = &sameCoordinateMaterialDriftSecretV3{state: state} + return fakeGateway( + t, + routeCatalog, + countingBinding{state: state}, + resolver, + state, + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + ) + }, + ) + defer fixture.close(t) + + for attempt := 0; attempt < 2; attempt++ { + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorUnavailable || + result.Boundary.Fact.ID != "" { + t.Fatalf("material drift attempt=%d result=%+v err=%v", attempt, result, err) + } + } + if resolver.calls.Load() != 2 || fixture.state.invoke.Load() != 0 { + t.Fatalf( + "same-coordinate material generations=%d provider calls=%d want=2/0", + resolver.calls.Load(), + fixture.state.invoke.Load(), + ) + } + turn, err := fixture.store.InspectExactGovernedModelTurnV3( + context.Background(), + fixture.command.TurnRef, + ) + if err != nil { + t.Fatal(err) + } + if _, inspectErr := + fixture.store.InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + context.Background(), + turn.AttemptRefV3(), + ); modelinvoker.GovernedModelInvocationErrorKindOfV1(inspectErr) != + modelinvoker.GovernedModelInvocationErrorNotFound { + t.Fatalf("material drift boundary write error=%v want=not_found", inspectErr) + } +} + +func TestGovernedModelTurnV3ActualBoundaryConcurrentCallsWriteNothing( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + const workers = 64 + var start sync.WaitGroup + start.Add(1) + var done sync.WaitGroup + done.Add(workers) + var unavailable atomic.Int64 + for range workers { + go func() { + defer done.Done() + start.Wait() + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) == + modelinvoker.GovernedModelInvocationErrorUnavailable && + result.Boundary.Fact.ID == "" { + unavailable.Add(1) + } + }() + } + start.Done() + done.Wait() + if unavailable.Load() != workers || fixture.state.invoke.Load() != 0 { + t.Fatalf( + "fail-closed calls=%d provider calls=%d want=%d/0", + unavailable.Load(), + fixture.state.invoke.Load(), + workers, + ) + } + turn, err := fixture.store.InspectExactGovernedModelTurnV3( + context.Background(), + fixture.command.TurnRef, + ) + if err != nil { + t.Fatal(err) + } + if _, inspectErr := + fixture.store.InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + context.Background(), + turn.AttemptRefV3(), + ); modelinvoker.GovernedModelInvocationErrorKindOfV1(inspectErr) != + modelinvoker.GovernedModelInvocationErrorNotFound { + t.Fatalf("concurrent boundary write error=%v want=not_found", inspectErr) + } +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsSourceTTLDriftAcrossS1S2( + t *testing.T, +) { + for _, test := range []struct { + name string + source string + alternate time.Time + }{ + { + name: "context_non_min_shrink", + source: "context", + alternate: gatewayNow.Add(17 * time.Minute / 2), + }, + { + name: "context_non_min_extend", + source: "context", + alternate: gatewayNow.Add(19 * time.Minute / 2), + }, + { + name: "tool_non_min_shrink", + source: "tool", + alternate: gatewayNow.Add(17 * time.Minute / 2), + }, + { + name: "tool_non_min_extend", + source: "tool", + alternate: gatewayNow.Add(19 * time.Minute / 2), + }, + } { + t.Run(test.name, func(t *testing.T) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + fixture.readers.calls.Store(0) + fixture.readers.contextCalls.Store(0) + fixture.readers.toolCalls.Store(0) + fixture.readers.alternateAt = 3 + switch test.source { + case "context": + fixture.readers.contextAlternateExpires = + test.alternate.UnixNano() + case "tool": + fixture.readers.toolAlternateExpires = + test.alternate.UnixNano() + default: + t.Fatalf("unknown source %q", test.source) + } + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorConflict || + result.Boundary.Fact.ID != "" || + fixture.state.invoke.Load() != 0 { + t.Fatalf( + "TTL %s result=%+v provider=%d err=%v", + test.name, + result, + fixture.state.invoke.Load(), + err, + ) + } + for key, calls := range fixture.state.snapshot() { + if calls != 0 { + t.Fatalf("TTL %s touched %s=%d want=0", test.name, key, calls) + } + } + if fixture.readers.contextCalls.Load() != 2 || + fixture.readers.toolCalls.Load() != 2 { + t.Fatalf( + "TTL %s pair reads context/tool=%d/%d want=2/2", + test.name, + fixture.readers.contextCalls.Load(), + fixture.readers.toolCalls.Load(), + ) + } + }) + } +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsSourceCheckedDriftAcrossS1S2( + t *testing.T, +) { + for _, source := range []string{"context", "tool"} { + t.Run(source, func(t *testing.T) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + fixture.readers.calls.Store(0) + fixture.readers.contextCalls.Store(0) + fixture.readers.toolCalls.Store(0) + fixture.readers.alternateAt = 3 + switch source { + case "context": + fixture.readers.contextAlternateChecked = + gatewayNow.Add(-30 * time.Second).UnixNano() + case "tool": + fixture.readers.toolAlternateChecked = + gatewayNow.Add(-30 * time.Second).UnixNano() + } + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) + if fixture.readers.contextCalls.Load() != 2 || + fixture.readers.toolCalls.Load() != 2 { + t.Fatalf( + "checked %s pair reads context/tool=%d/%d want=2/2", + source, + fixture.readers.contextCalls.Load(), + fixture.readers.toolCalls.Load(), + ) + } + }) + } +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsPairProjectionDigestSplice( + t *testing.T, +) { + for _, source := range []string{"context", "tool"} { + t.Run(source, func(t *testing.T) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + fixture.readers.calls.Store(0) + fixture.readers.contextCalls.Store(0) + fixture.readers.toolCalls.Store(0) + switch source { + case "context": + fixture.readers.contextCorruptDigestAt = 1 + case "tool": + fixture.readers.toolCorruptDigestAt = 2 + } + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) + }) + } +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsAckExpiryEquality( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + ack := fixture.gate.ack + ack.ExpiresUnixNano = gatewayNow.UnixNano() + ack.Digest = "" + var err error + ack, err = modelinvoker.SealPreparedModelInvocationCommitAckV1(ack) + if err != nil { + t.Fatal(err) + } + fixture.gate.ack = ack + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsAckExpiryEqualityAtS2( + t *testing.T, +) { + clock := &actualBoundaryClockV3{ + values: []time.Time{ + gatewayNow, + gatewayNow.Add(time.Second), + }, + } + fixture := newGovernedActualBoundaryFixtureV3WithGateway( + t, + func( + t *testing.T, + routeCatalog *catalog.Catalog, + state *callState, + dependencies routegateway.GovernedModelTurnActualBoundaryDependenciesV3, + ) *routegateway.Gateway { + t.Helper() + return fakeGateway( + t, + routeCatalog, + countingBinding{state: state}, + countingSecret{state: state, version: "v1"}, + state, + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + routegateway.WithClock(clock.Now), + ) + }, + ) + defer fixture.close(t) + ack := fixture.gate.ack + ack.ExpiresUnixNano = gatewayNow.Add(time.Second).UnixNano() + ack.Digest = "" + var err error + ack, err = modelinvoker.SealPreparedModelInvocationCommitAckV1(ack) + if err != nil { + t.Fatal(err) + } + fixture.gate.ack = ack + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsAckBodySpliceAtS2( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + spliced := fixture.gate.ack + spliced.GateImplementationRef.ID += "-spliced" + fixture.gate.inspectOverride = &spliced + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsValidAckDriftAtS2( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + drifted := fixture.gate.ack + drifted.GateImplementationRef.ID += "-drifted" + drifted.Digest = "" + var err error + drifted, err = modelinvoker.SealPreparedModelInvocationCommitAckV1(drifted) + if err != nil { + t.Fatal(err) + } + fixture.gate.inspectOverride = &drifted + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsExactTurnBodySplice( + t *testing.T, +) { + for _, test := range []struct { + name string + splice func(*modelinvoker.GovernedModelTurnOutcomeV3) + }{ + { + name: "state", + splice: func(turn *modelinvoker.GovernedModelTurnOutcomeV3) { + turn.State = "spliced" + }, + }, + { + name: "created", + splice: func(turn *modelinvoker.GovernedModelTurnOutcomeV3) { + turn.CreatedUnixNano++ + }, + }, + { + name: "updated", + splice: func(turn *modelinvoker.GovernedModelTurnOutcomeV3) { + turn.UpdatedUnixNano++ + }, + }, + { + name: "expires", + splice: func(turn *modelinvoker.GovernedModelTurnOutcomeV3) { + turn.ExpiresUnixNano-- + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + turn, err := fixture.store.InspectExactGovernedModelTurnV3( + context.Background(), + fixture.command.TurnRef, + ) + if err != nil { + t.Fatal(err) + } + test.splice(&turn) + if turn.RefV3() != fixture.command.TurnRef { + t.Fatal("test splice unexpectedly changed exact Turn Ref") + } + reader := &actualBoundaryTurnReaderV3{ + inner: fixture.store, + override: turn, + } + dependencies, err := + routegateway.NewGovernedModelTurnActualBoundaryDependenciesV3( + fixture.store, + fixture.store, + fixture.gate, + fixture.store, + fixture.authorizer, + reader, + fixture.store, + ) + if err != nil { + t.Fatal(err) + } + gateway := fakeGateway( + t, + fixture.routeCatalog, + countingBinding{state: fixture.state}, + countingSecret{state: fixture.state, version: "v1"}, + fixture.state, + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + ) + defer gateway.Close() + + result, err := + gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + assertActualBoundaryRejectedBeforePrepareV3( + t, + fixture, + result, + err, + ) + }) + } +} + +func assertActualBoundaryRejectedBeforePrepareV3( + t *testing.T, + fixture governedActualBoundaryFixtureV3, + result routegateway.GovernedModelTurnActualBoundaryResultV3, + err error, +) { + t.Helper() + if err == nil || + result.Boundary.Fact.ID != "" || + result.Invoke.Response.ID != "" { + t.Fatalf("pre-prepare rejection result=%+v err=%v", result, err) + } + for key, calls := range fixture.state.snapshot() { + if calls != 0 { + t.Fatalf("pre-prepare rejection touched %s=%d want=0", key, calls) + } + } +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsS2ClockRegression( + t *testing.T, +) { + clock := &actualBoundaryClockV3{ + values: []time.Time{ + gatewayNow, + gatewayNow.Add(-time.Nanosecond), + }, + } + fixture := newGovernedActualBoundaryFixtureV3WithGateway( + t, + func( + t *testing.T, + routeCatalog *catalog.Catalog, + state *callState, + dependencies routegateway.GovernedModelTurnActualBoundaryDependenciesV3, + ) *routegateway.Gateway { + t.Helper() + return fakeGateway( + t, + routeCatalog, + countingBinding{state: state}, + countingSecret{state: state, version: "v1"}, + state, + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + routegateway.WithClock(clock.Now), + ) + }, + ) + defer fixture.close(t) + + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorConflict || + result.Boundary.Fact.ID != "" || + fixture.state.invoke.Load() != 0 { + t.Fatalf( + "S2 regression result=%+v provider=%d err=%v", + result, + fixture.state.invoke.Load(), + err, + ) + } + for key, calls := range fixture.state.snapshot() { + if calls != 0 { + t.Fatalf("S2 regression touched %s=%d want=0", key, calls) + } + } +} + +func TestGovernedModelTurnV3ActualBoundaryRejectsRuntimeDraftBeforeProviderPrepare( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + fixture.command.RuntimeRequest.PermitID += "-other" + + before := fixture.state.snapshot() + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorConflict || + result.Boundary.Fact.ID != "" { + t.Fatalf("invalid Runtime draft result=%+v err=%v", result, err) + } + after := fixture.state.snapshot() + for _, key := range []string{"binding", "secret", "factory", "invoke"} { + if after[key] != before[key] { + t.Fatalf( + "invalid Runtime draft touched %s: before=%d after=%d", + key, + before[key], + after[key], + ) + } + } +} + +func TestGovernedModelTurnV3ActualBoundaryExistingWinnerRequiresExactCallerBoundary( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + fact := buildGovernedActualBoundaryFactV3(t, fixture) + persisted, err := + modelinvoker.EnsureOrInspectGovernedModelTurnProviderBoundaryFactV3( + context.Background(), + fixture.store, + fact, + func() time.Time { return gatewayNow }, + ) + if err != nil || + persisted.Disposition != + modelinvoker.GovernedModelTurnProviderBoundaryPersistenceCreatedV3 { + t.Fatalf("seed boundary result=%+v err=%v", persisted, err) + } + + exact := fixture.command + exact.RuntimeRequest.ModelBoundary = persisted.Fact.RuntimeRequest.ModelBoundary + result, err := fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + exact, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorIndeterminate || + result.Boundary.Fact.RefV3() != persisted.Fact.RefV3() || + result.Boundary.Disposition != + modelinvoker.GovernedModelTurnProviderBoundaryPersistenceExistingV3 { + t.Fatalf("exact caller boundary result=%+v err=%v", result, err) + } + + mismatched := fixture.command + mismatchedBoundary := persisted.Fact.RuntimeRequest.ModelBoundary + mismatchedBoundary.ID += "-other" + mismatchedBoundary, err = + runtimeports.SealModelProviderBoundaryCurrentRefV1(mismatchedBoundary) + if err != nil { + t.Fatal(err) + } + mismatched.RuntimeRequest.ModelBoundary = mismatchedBoundary + result, err = fixture.gateway.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + mismatched, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorConflict || + result.Boundary.Fact.ID != "" || + fixture.state.invoke.Load() != 0 { + t.Fatalf( + "mismatched caller boundary result=%+v provider=%d err=%v", + result, + fixture.state.invoke.Load(), + err, + ) + } + for key, calls := range fixture.state.snapshot() { + if calls != 0 { + t.Fatalf("caller boundary replay touched %s=%d want=0", key, calls) + } + } +} + +func TestGovernedModelTurnV3ActualBoundaryConstructorRejectsSplitTypedNilStore( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + var typedNil *boundaryStoreSpyV3 + _, err := routegateway.NewGovernedModelTurnActualBoundaryDependenciesV3( + fixture.store, + fixture.store, + fixture.gate, + fixture.store, + fixture.authorizer, + fixture.store, + typedNil, + ) + if err == nil { + t.Fatal("typed-nil composite Boundary store error=nil") + } +} + +func TestGovernedModelTurnV3ActualBoundaryHistoricalWinnerUsesOneStoreBeforeProvider( + t *testing.T, +) { + fixture := newGovernedActualBoundaryFixtureV3(t) + defer fixture.close(t) + spy := &boundaryStoreSpyV3{inner: fixture.store} + fact := buildGovernedActualBoundaryFactV3(t, fixture) + persisted, err := + modelinvoker.EnsureOrInspectGovernedModelTurnProviderBoundaryFactV3( + context.Background(), + spy, + fact, + func() time.Time { return gatewayNow }, + ) + if err != nil || + persisted.Disposition != + modelinvoker.GovernedModelTurnProviderBoundaryPersistenceCreatedV3 { + t.Fatalf("seed boundary result=%+v err=%v", persisted, err) + } + dependencies, err := + routegateway.NewGovernedModelTurnActualBoundaryDependenciesV3( + fixture.store, + fixture.store, + fixture.gate, + fixture.store, + fixture.authorizer, + fixture.store, + spy, + ) + if err != nil { + t.Fatal(err) + } + + restartedState := &callState{} + restarted := fakeGateway( + t, + fixture.routeCatalog, + countingBinding{state: restartedState}, + &sameCoordinateMaterialDriftSecretV3{state: restartedState}, + restartedState, + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + ) + defer func() { + if err := restarted.Close(); err != nil { + t.Fatal(err) + } + }() + result, err := restarted.InvokeGovernedModelTurnActualBoundaryV3( + context.Background(), + fixture.command, + ) + if modelinvoker.GovernedModelInvocationErrorKindOfV1(err) != + modelinvoker.GovernedModelInvocationErrorIndeterminate || + result.Boundary.Disposition != + modelinvoker.GovernedModelTurnProviderBoundaryPersistenceExistingV3 || + result.Boundary.Fact.RefV3() != persisted.Fact.RefV3() { + t.Fatalf("historical winner result=%+v err=%v", result, err) + } + if spy.turnAttempt.Load() != 1 || spy.ensure.Load() != 1 || + spy.exact.Load() < 2 { + t.Fatalf( + "single Boundary store calls turn_attempt=%d ensure=%d exact=%d", + spy.turnAttempt.Load(), + spy.ensure.Load(), + spy.exact.Load(), + ) + } + for key, calls := range restartedState.snapshot() { + if calls != 0 { + t.Fatalf("historical winner touched %s=%d want=0", key, calls) + } + } +} + +type governedActualBoundaryFixtureV3 struct { + gateway *routegateway.Gateway + store *modelsqlite.Store + state *callState + readers *actualBoundaryReadersV3 + gate *actualBoundaryGateV3 + authorizer *modelinvoker.InvocationMaterialAuthorizerV2 + routeCatalog *catalog.Catalog + dependencies routegateway.GovernedModelTurnActualBoundaryDependenciesV3 + command routegateway.GovernedModelTurnActualBoundaryCommandV3 +} + +func buildGovernedActualBoundaryFactV3( + t *testing.T, + fixture governedActualBoundaryFixtureV3, +) modelinvoker.GovernedModelTurnProviderBoundaryFactV3 { + t.Helper() + ctx := context.Background() + turn, err := fixture.store.InspectExactGovernedModelTurnV3( + ctx, + fixture.command.TurnRef, + ) + if err != nil { + t.Fatal(err) + } + prepared, err := fixture.store.InspectExactPreparedModelInvocationV1( + ctx, + turn.PreparedRef, + ) + if err != nil { + t.Fatal(err) + } + current, err := fixture.store.InspectExactPreparedModelInvocationCurrentV1( + ctx, + turn.CurrentRef, + ) + if err != nil { + t.Fatal(err) + } + ack, err := fixture.gate.InspectExactAck(ctx, fixture.gate.ack.Ref()) + if err != nil { + t.Fatal(err) + } + checked := gatewayNow + receipt, err := modelinvoker.SealPreparedModelInvocationDispatchReceiptAgainstV1( + prepared, + current, + ack, + modelinvoker.PreparedModelInvocationDispatchValidationReceiptV1{ + PreparedRef: turn.PreparedRef, + CurrentRef: turn.CurrentRef, + AckRef: ack.Ref(), + DispatchSequence: turn.DispatchSequence, + BoundaryKind: modelinvoker.GovernedModelTurnProviderBoundaryKindV2, + ProviderAttemptOrdinal: turn.ProviderAttemptOrdinal, + AttemptRequestDigest: turn.AttemptRequestDigest, + ActualToolSurfaceDigest: prepared.ActualToolSurfaceDigest, + ActualProviderInjectionDigest: prepared.ActualProviderInjectionDigest, + CheckedUnixNano: checked.UnixNano(), + }, + checked, + ) + if err != nil { + t.Fatal(err) + } + fact, err := modelinvoker.BuildGovernedModelTurnProviderBoundaryFactV3( + ctx, + modelinvoker.GovernedModelTurnProviderBoundaryVerificationReadersV3{ + TurnHistory: fixture.store, + PreparedHistory: fixture.store, + PreparedCurrent: fixture.store, + AckHistory: fixture.gate, + }, + modelinvoker.GovernedModelTurnProviderBoundaryDraftV3{ + TurnRef: turn.RefV3(), + DispatchReceipt: receipt, + RuntimeRequest: fixture.command.RuntimeRequest, + Provider: fixture.command.RuntimeRequest.Verifier, + CheckedUnixNano: checked.UnixNano(), + }, + checked, + ) + if err != nil { + t.Fatal(err) + } + return fact +} + +func (f governedActualBoundaryFixtureV3) close(t *testing.T) { + t.Helper() + if err := f.gateway.Close(); err != nil { + t.Fatal(err) + } + if err := f.store.Close(); err != nil { + t.Fatal(err) + } +} + +func newGovernedActualBoundaryFixtureV3( + t *testing.T, +) governedActualBoundaryFixtureV3 { + return newGovernedActualBoundaryFixtureV3WithGateway(t, nil) +} + +type actualBoundaryGatewayBuilderV3 func( + *testing.T, + *catalog.Catalog, + *callState, + routegateway.GovernedModelTurnActualBoundaryDependenciesV3, +) *routegateway.Gateway + +func actualBoundaryGatewayWithOverrideFactoryV3( + t *testing.T, + routeCatalog *catalog.Catalog, + override routegateway.AdapterFactory, + state *callState, + dependencies routegateway.GovernedModelTurnActualBoundaryDependenciesV3, +) *routegateway.Gateway { + t.Helper() + builtins, err := routegateway.NewBuiltinFactoryRegistry() + if err != nil { + t.Fatal(err) + } + factories := make([]routegateway.AdapterFactory, 0, len(builtins.IDs())) + for _, id := range builtins.IDs() { + if id == override.AdapterID() { + factories = append(factories, override) + } else { + factories = append(factories, fakeFactory{id: id, state: state}) + } + } + registry, err := routegateway.NewFactoryRegistry(factories...) + if err != nil { + t.Fatal(err) + } + gateway, err := routegateway.New( + routeCatalog, + countingBinding{state: state}, + countingSecret{state: state, version: "v1"}, + registry, + routegateway.WithClock(func() time.Time { return gatewayNow }), + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + ) + if err != nil { + t.Fatal(err) + } + return gateway +} + +func newGovernedActualBoundaryFixtureV3WithGateway( + t *testing.T, + gatewayBuilder actualBoundaryGatewayBuilderV3, +) governedActualBoundaryFixtureV3 { + t.Helper() + call := governedCallV2() + call.Request.Tools[0].Name = "workspace_read" + routeCatalog := defaultCatalog(t) + tempState := &callState{} + temp := fakeGateway( + t, + routeCatalog, + countingBinding{state: tempState}, + countingSecret{state: tempState, version: "v1"}, + tempState, + ) + resolution, err := temp.Resolve(context.Background(), call) + if err != nil { + t.Fatal(err) + } + if err := temp.Close(); err != nil { + t.Fatal(err) + } + routeDigest, err := modelinvoker.DigestGovernedRouteSelectionV1(resolution.Route) + if err != nil { + t.Fatal(err) + } + requestTools, err := modelinvoker.DigestGovernedModelTurnRequestToolsV2(call) + if err != nil { + t.Fatal(err) + } + contextMapped, err := modelinvoker.DigestGovernedModelTurnContextV2(call) + if err != nil { + t.Fatal(err) + } + requestDigest := digestV2(t, "v3-unified-request", call) + prepared, err := modelinvoker.SealPreparedModelInvocationFactV1( + modelinvoker.PreparedModelInvocationFactV1{ + InvocationID: "routegateway-v3", + InvocationDigest: requestDigest, + UnifiedRequestDigest: requestDigest, + RequestToolsDigest: requestTools, + PreparedPlanDigest: digestV2(t, "v3-plan", call.Request.Input), + RouteDigest: routeDigest, + ProfileDigest: digestV2(t, "v3-profile", call.Request.Model), + ActualToolSurfaceDigest: digestV2(t, "v3-surface", call.Request.Tools), + ActualProviderInjectionDigest: digestV2(t, "v3-provider", call.RouteID), + CapabilitySnapshotRef: modelinvoker.PreparedModelInvocationCapabilitySnapshotRefV1{ + ContractVersion: "1.0.0", + ID: "v3-capability", + Revision: 1, + Digest: digestV2(t, "v3-capability", call.RouteID), + }, + RegistrySnapshotRef: runtimeports.RegistrySnapshotRefV1{ + Owner: ownerV2("registry", "v3"), + ContractVersion: "1.0.0", + ID: "v3-registry", + Revision: 1, + Digest: digestV2(t, "v3-registry", call.RouteID), + }, + CreatedUnixNano: gatewayNow.Add(-2 * time.Minute).UnixNano(), + NotAfterUnixNano: gatewayNow.Add(10 * time.Minute).UnixNano(), + }, + ) + if err != nil { + t.Fatal(err) + } + current, err := modelinvoker.SealPreparedModelInvocationCurrentV1( + modelinvoker.PreparedModelInvocationCurrentProjectionV1{ + Prepared: prepared.Ref(), + CapabilitySnapshotRef: prepared.CapabilitySnapshotRef, + RegistrySnapshotRef: prepared.RegistrySnapshotRef, + ActualToolSurfaceDigest: prepared.ActualToolSurfaceDigest, + ActualProviderInjectionDigest: prepared.ActualProviderInjectionDigest, + CheckedUnixNano: gatewayNow.Add(-time.Minute).UnixNano(), + ExpiresUnixNano: gatewayNow.Add(8 * time.Minute).UnixNano(), + NotAfterUnixNano: prepared.NotAfterUnixNano, + }, + ) + if err != nil { + t.Fatal(err) + } + contextOwner := ownerV2("praxis.context", "v3-context") + toolOwner := ownerV2("praxis.tool", "v3-tool") + lineage, err := modelinvoker.SealInvocationMaterialSourceLineageV2( + modelinvoker.InvocationMaterialSourceLineageV2{ + ContextFrame: actualBoundarySourceRefV3( + contextOwner, + modelinvoker.InvocationMaterialContextFrameKindV2, + "frame", + digestV2(t, "v3-frame", call.Request.Input), + ), + ContextMaterial: actualBoundarySourceRefV3( + contextOwner, + modelinvoker.InvocationMaterialContextMaterialKindV2, + "material", + digestV2(t, "v3-material", call.Request.Instructions), + ), + ToolInjectionMaterial: actualBoundarySourceRefV3( + toolOwner, + modelinvoker.InvocationMaterialToolInjectionMaterialKindV2, + "injection", + digestV2(t, "v3-injection", call.Request.Tools), + ), + ToolSurface: actualBoundarySourceRefV3( + toolOwner, + modelinvoker.InvocationMaterialToolSurfaceKindV2, + "surface", + digestV2(t, "v3-surface-ref", call.Request.Tools), + ), + ContextMappedInputDigest: contextMapped, + ExpectedInjectionDigest: prepared.ActualToolSurfaceDigest, + CompiledToolsDigest: digestV2(t, "v3-compiled", call.Request.Tools), + RequestToolsDigest: requestTools, + }, + ) + if err != nil { + t.Fatal(err) + } + readers := &actualBoundaryReadersV3{ + expectedInjection: lineage.ExpectedInjectionDigest, + compiledTools: lineage.CompiledToolsDigest, + checked: gatewayNow.Add(-time.Minute).UnixNano(), + expires: gatewayNow.Add(9 * time.Minute).UnixNano(), + } + closure := modelinvoker.InvocationMaterialExactClosureV2{ + SourceLineage: lineage, + ProviderInjection: actualBoundarySourceRefV3( + ownerV2("praxis.model", "v3-model"), + "model-source", + "provider", + prepared.ActualProviderInjectionDigest, + ), + Route: actualBoundarySourceRefV3( + ownerV2("praxis.model", "v3-model"), + "model-source", + "route", + prepared.RouteDigest, + ), + Profile: actualBoundarySourceRefV3( + ownerV2("praxis.model", "v3-model"), + "model-source", + "profile", + prepared.ProfileDigest, + ), + } + authorizer, err := modelinvoker.NewInvocationMaterialAuthorizerV2( + modelinvoker.InvocationMaterialAuthorizerConfigV2{ + ContextPair: readers, + ToolPair: readers, + ProviderInjection: readers, + Route: readers, + Profile: readers, + }, + ) + if err != nil { + t.Fatal(err) + } + store, err := modelsqlite.Open( + context.Background(), + modelsqlite.Config{Path: t.TempDir() + "/routegateway-v3.db"}, + ) + if err != nil { + t.Fatal(err) + } + if _, err := store.EnsurePreparedModelInvocationV1( + context.Background(), + prepared, + ); err != nil { + t.Fatal(err) + } + if _, err := store.EnsurePreparedModelInvocationCurrentV1( + context.Background(), + current, + ); err != nil { + t.Fatal(err) + } + material, err := modelinvoker.AuthorizeAndEnsureInvocationMaterialV2( + context.Background(), + authorizer, + store, + prepared, + current, + call, + closure, + func() time.Time { return gatewayNow }, + ) + if err != nil { + t.Fatal(err) + } + turn, err := modelinvoker.NewPreparedGovernedModelTurnV3( + modelinvoker.GovernedModelTurnCommandV3{ + PreparedRef: prepared.Ref(), + CurrentRef: current.Ref(), + MaterialRef: material.RefV2(), + AttemptRequestDigest: prepared.UnifiedRequestDigest, + RouteCallDigest: material.RouteCallDigest, + DispatchSequence: 1, + ProviderAttemptOrdinal: 1, + }, + gatewayNow.Add(-time.Second), + ) + if err != nil { + t.Fatal(err) + } + if _, err := store.EnsurePreparedGovernedModelTurnV3( + context.Background(), + turn, + ); err != nil { + t.Fatal(err) + } + ack, err := modelinvoker.SealPreparedModelInvocationCommitAckV1( + modelinvoker.PreparedModelInvocationCommitAckV1{ + PreparedRef: prepared.Ref(), + CurrentRef: current.Ref(), + GateImplementationRef: modelinvoker.PreparedModelInvocationGateImplementationRefV1{ + Owner: ownerV2("praxis.harness", "v3-gate"), + ContractVersion: "1.0.0", + ID: "v3-gate", + Revision: 1, + Digest: digestV2(t, "v3-gate", prepared.Ref()), + }, + SurfaceBindingRef: modelinvoker.PreparedModelInvocationSurfaceBindingRefV1{ + Owner: toolOwner, + ContractVersion: "1.0.0", + ID: "v3-surface", + Revision: 1, + Digest: prepared.ActualToolSurfaceDigest, + }, + CheckedUnixNano: gatewayNow.Add(-time.Minute).UnixNano(), + ExpiresUnixNano: gatewayNow.Add(6 * time.Minute).UnixNano(), + NotAfterUnixNano: current.NotAfterUnixNano, + }, + ) + if err != nil { + t.Fatal(err) + } + gate := &actualBoundaryGateV3{ack: ack} + provider := actualBoundaryProviderBindingV3(t) + runtimeRequest := actualBoundaryRuntimeRequestV3(t, provider) + state := &callState{} + state.governedV2.Store(true) + dependencies, err := + routegateway.NewGovernedModelTurnActualBoundaryDependenciesV3( + store, + store, + gate, + store, + authorizer, + store, + store, + ) + if err != nil { + t.Fatal(err) + } + var gateway *routegateway.Gateway + if gatewayBuilder == nil { + gateway = fakeGateway( + t, + routeCatalog, + countingBinding{state: state}, + countingSecret{state: state, version: "v1"}, + state, + routegateway.WithGovernedModelTurnActualBoundaryV3(dependencies), + ) + } else { + gateway = gatewayBuilder(t, routeCatalog, state, dependencies) + } + return governedActualBoundaryFixtureV3{ + gateway: gateway, + store: store, + state: state, + readers: readers, + gate: gate, + authorizer: authorizer, + routeCatalog: routeCatalog, + dependencies: dependencies, + command: routegateway.GovernedModelTurnActualBoundaryCommandV3{ + TurnRef: turn.RefV3(), + RuntimeRequest: runtimeRequest, + }, + } +} + +type sameCoordinateMaterialDriftSecretV3 struct { + state *callState + calls atomic.Int64 +} + +type actualBoundaryReleaseErrorFactoryV3 struct { + fakeFactory + closeErr error + closeCalls atomic.Int64 +} + +func (f *actualBoundaryReleaseErrorFactoryV3) Build( + _ context.Context, + input routegateway.FactoryInput, +) (routegateway.FactoryResult, error) { + f.state.factory.Add(1) + return routegateway.FactoryResult{ + Provider: &fakeProvider{id: f.id, state: f.state}, + Closer: actualBoundaryReleaseErrorCloserV3{ + err: f.closeErr, + calls: &f.closeCalls, + }, + Endpoint: input.Endpoint, + }, nil +} + +type actualBoundaryReleaseErrorCloserV3 struct { + err error + calls *atomic.Int64 +} + +func (c actualBoundaryReleaseErrorCloserV3) Close() error { + c.calls.Add(1) + return c.err +} + +type actualBoundaryGateV3 struct { + ack modelinvoker.PreparedModelInvocationCommitAckV1 + inspectOverride *modelinvoker.PreparedModelInvocationCommitAckV1 + commit atomic.Uint64 + inspect atomic.Uint64 +} + +type actualBoundaryTurnReaderV3 struct { + inner modelinvoker.GovernedModelTurnRepositoryV3 + override modelinvoker.GovernedModelTurnOutcomeV3 +} + +func (r *actualBoundaryTurnReaderV3) EnsurePreparedGovernedModelTurnV3( + ctx context.Context, + outcome modelinvoker.GovernedModelTurnOutcomeV3, +) (modelinvoker.GovernedModelTurnMutationV3, error) { + return r.inner.EnsurePreparedGovernedModelTurnV3(ctx, outcome) +} + +func (r *actualBoundaryTurnReaderV3) InspectGovernedModelTurnAttemptV3( + ctx context.Context, + ref modelinvoker.GovernedModelTurnAttemptRefV3, +) (modelinvoker.GovernedModelTurnOutcomeV3, error) { + return r.inner.InspectGovernedModelTurnAttemptV3(ctx, ref) +} + +func (r *actualBoundaryTurnReaderV3) InspectExactGovernedModelTurnV3( + context.Context, + modelinvoker.GovernedModelTurnRefV3, +) (modelinvoker.GovernedModelTurnOutcomeV3, error) { + return r.override, nil +} + +func (g *actualBoundaryGateV3) Commit( + _ context.Context, + prepared modelinvoker.PreparedModelInvocationRefV1, + current modelinvoker.PreparedModelInvocationCurrentRefV1, +) (modelinvoker.PreparedModelInvocationCommitAckV1, error) { + g.commit.Add(1) + if g.ack.PreparedRef != prepared || g.ack.CurrentRef != current { + return modelinvoker.PreparedModelInvocationCommitAckV1{}, + errors.New("actual boundary gate lineage drift") + } + return g.ack, nil +} + +func (g *actualBoundaryGateV3) InspectExactAck( + _ context.Context, + ref modelinvoker.PreparedModelInvocationCommitAckRefV1, +) (modelinvoker.PreparedModelInvocationCommitAckV1, error) { + g.inspect.Add(1) + if g.inspectOverride != nil { + return *g.inspectOverride, nil + } + if g.ack.Ref() != ref { + return modelinvoker.PreparedModelInvocationCommitAckV1{}, + errors.New("actual boundary ACK absent") + } + return g.ack, nil +} + +func (r *sameCoordinateMaterialDriftSecretV3) ResolveSecret( + _ context.Context, + request routegateway.SecretRequest, +) (routegateway.SecretMaterial, error) { + generation := r.calls.Add(1) + r.state.secret.Add(1) + value := "offline-api-key-generation-" + string(rune('0'+generation)) + if len(request.Profile.KeyPrefixes) > 0 { + value = request.Profile.KeyPrefixes[0] + "generation-" + + string(rune('0'+generation)) + } + return routegateway.NewSecretMaterial( + request.Profile.ID, + request.Profile.Type, + "same-version", + gatewayNow.Add(time.Hour), + map[upstream.CredentialPurpose][]byte{ + upstream.CredentialPurposeAPIKey: []byte(value), + }, + ) +} + +type boundaryStoreSpyV3 struct { + inner *modelsqlite.Store + turnAttempt atomic.Int64 + ensure atomic.Int64 + attempt atomic.Int64 + exact atomic.Int64 +} + +func (r *boundaryStoreSpyV3) InspectGovernedModelTurnProviderBoundaryTurnAttemptV3( + ctx context.Context, + ref modelinvoker.GovernedModelTurnAttemptRefV3, +) (modelinvoker.GovernedModelTurnProviderBoundaryFactV3, error) { + r.turnAttempt.Add(1) + return r.inner.InspectGovernedModelTurnProviderBoundaryTurnAttemptV3(ctx, ref) +} + +func (r *boundaryStoreSpyV3) EnsureGovernedModelTurnProviderBoundaryFactV3( + ctx context.Context, + fact modelinvoker.GovernedModelTurnProviderBoundaryFactV3, +) (modelinvoker.GovernedModelTurnProviderBoundaryMutationV3, error) { + r.ensure.Add(1) + return r.inner.EnsureGovernedModelTurnProviderBoundaryFactV3(ctx, fact) +} + +func (r *boundaryStoreSpyV3) InspectGovernedModelTurnProviderBoundaryAttemptV3( + ctx context.Context, + ref runtimeports.ModelProviderBoundaryCurrentRefV1, +) (modelinvoker.GovernedModelTurnProviderBoundaryFactV3, error) { + r.attempt.Add(1) + return r.inner.InspectGovernedModelTurnProviderBoundaryAttemptV3(ctx, ref) +} + +func (r *boundaryStoreSpyV3) InspectExactGovernedModelTurnProviderBoundaryV3( + ctx context.Context, + ref modelinvoker.GovernedModelTurnProviderBoundaryRefV3, +) (modelinvoker.GovernedModelTurnProviderBoundaryFactV3, error) { + r.exact.Add(1) + return r.inner.InspectExactGovernedModelTurnProviderBoundaryV3(ctx, ref) +} + +type actualBoundaryReadersV3 struct { + expectedInjection core.Digest + compiledTools core.Digest + checked int64 + expires int64 + contextAlternateChecked int64 + contextAlternateExpires int64 + contextCorruptDigestAt int64 + toolAlternateChecked int64 + toolAlternateExpires int64 + toolCorruptDigestAt int64 + alternateAt int64 + calls atomic.Int64 + contextCalls atomic.Int64 + toolCalls atomic.Int64 + failAt atomic.Int64 +} + +func (r *actualBoundaryReadersV3) contextExpires(call int64) int64 { + if r.alternateAt > 0 && call >= r.alternateAt && + r.contextAlternateExpires > 0 { + return r.contextAlternateExpires + } + return r.expires +} + +func (r *actualBoundaryReadersV3) contextChecked(call int64) int64 { + if r.alternateAt > 0 && call >= r.alternateAt && + r.contextAlternateChecked > 0 { + return r.contextAlternateChecked + } + return r.checked +} + +func (r *actualBoundaryReadersV3) toolExpires(call int64) int64 { + if r.alternateAt > 0 && call >= r.alternateAt && + r.toolAlternateExpires > 0 { + return r.toolAlternateExpires + } + return r.expires +} + +func (r *actualBoundaryReadersV3) toolChecked(call int64) int64 { + if r.alternateAt > 0 && call >= r.alternateAt && + r.toolAlternateChecked > 0 { + return r.toolAlternateChecked + } + return r.checked +} + +func (r *actualBoundaryReadersV3) InspectExactInvocationContextPairV2( + _ context.Context, + frame modelinvoker.InvocationMaterialExactSourceRefV1, + material modelinvoker.InvocationMaterialExactSourceRefV1, + mapped core.Digest, +) (modelinvoker.InvocationMaterialContextPairProjectionV2, error) { + call := r.calls.Add(1) + r.contextCalls.Add(1) + if r.failAt.Load() > 0 && call >= r.failAt.Load() { + return modelinvoker.InvocationMaterialContextPairProjectionV2{}, + core.NewError(core.ErrorConflict, core.ReasonBindingDrift, "context pair drifted") + } + projection, err := modelinvoker.SealInvocationMaterialContextPairProjectionV2( + modelinvoker.InvocationMaterialContextPairProjectionV2{ + ContextFrame: frame, + ContextMaterial: material, + ContextMappedInputDigest: mapped, + CheckedUnixNano: r.contextChecked(call), + ExpiresUnixNano: r.contextExpires(call), + }, + ) + if err == nil && call == r.contextCorruptDigestAt { + projection.ProjectionDigest = "" + } + return projection, err +} + +func (r *actualBoundaryReadersV3) InspectExactInvocationToolPairV2( + _ context.Context, + injection modelinvoker.InvocationMaterialExactSourceRefV1, + surface modelinvoker.InvocationMaterialExactSourceRefV1, + requestTools core.Digest, +) (modelinvoker.InvocationMaterialToolPairProjectionV2, error) { + call := r.calls.Add(1) + r.toolCalls.Add(1) + if r.failAt.Load() > 0 && call >= r.failAt.Load() { + return modelinvoker.InvocationMaterialToolPairProjectionV2{}, + core.NewError(core.ErrorConflict, core.ReasonBindingDrift, "tool pair drifted") + } + projection, err := modelinvoker.SealInvocationMaterialToolPairProjectionV2( + modelinvoker.InvocationMaterialToolPairProjectionV2{ + ToolInjectionMaterial: injection, + ToolSurface: surface, + ExpectedInjectionDigest: r.expectedInjection, + CompiledToolsDigest: r.compiledTools, + RequestToolsDigest: requestTools, + CheckedUnixNano: r.toolChecked(call), + ExpiresUnixNano: r.toolExpires(call), + }, + ) + if err == nil && call == r.toolCorruptDigestAt { + projection.ProjectionDigest = "" + } + return projection, err +} + +func (r *actualBoundaryReadersV3) projection( + ref modelinvoker.InvocationMaterialExactSourceRefV1, +) modelinvoker.InvocationMaterialExactSourceProjectionV1 { + return modelinvoker.InvocationMaterialExactSourceProjectionV1{ + Ref: ref, + CheckedUnixNano: r.checked, + ExpiresUnixNano: r.expires, + } +} + +func (r *actualBoundaryReadersV3) InspectExactInvocationProviderInjectionV1( + _ context.Context, + ref modelinvoker.InvocationMaterialExactSourceRefV1, +) (modelinvoker.InvocationMaterialExactSourceProjectionV1, error) { + return r.projection(ref), nil +} + +func (r *actualBoundaryReadersV3) InspectExactInvocationRouteV1( + _ context.Context, + ref modelinvoker.InvocationMaterialExactSourceRefV1, +) (modelinvoker.InvocationMaterialExactSourceProjectionV1, error) { + return r.projection(ref), nil +} + +func (r *actualBoundaryReadersV3) InspectExactInvocationProfileV1( + _ context.Context, + ref modelinvoker.InvocationMaterialExactSourceRefV1, +) (modelinvoker.InvocationMaterialExactSourceProjectionV1, error) { + return r.projection(ref), nil +} + +type actualBoundaryClockV3 struct { + values []time.Time + calls atomic.Int64 +} + +func (c *actualBoundaryClockV3) Now() time.Time { + index := c.calls.Add(1) - 1 + if index < int64(len(c.values)) { + return c.values[index] + } + return c.values[len(c.values)-1] +} + +func actualBoundaryRuntimeRequestV3( + t *testing.T, + provider runtimeports.ProviderBindingRefV2, +) runtimeports.InspectCurrentModelProviderActualPointRequestV1 { + t.Helper() + lease := &core.SandboxLeaseRef{ID: "v3-lease", Epoch: 1} + scope := core.ExecutionScope{ + Identity: core.AgentIdentityRef{TenantID: "tenant", ID: "agent", Epoch: 1}, + Lineage: core.LineageRef{ + ID: "v3-lineage", + PlanDigest: digestV2(t, "v3-lineage", "plan"), + }, + Instance: core.InstanceRef{ID: "v3-instance", Epoch: 1}, + SandboxLease: lease, + AuthorityEpoch: 1, + } + scopeDigest, err := runtimeports.ExecutionScopeDigestV2(scope) + if err != nil { + t.Fatal(err) + } + operation := runtimeports.OperationSubjectV3{ + Kind: runtimeports.OperationScopeRunV3, + ExecutionScope: scope, + ExecutionScopeDigest: scopeDigest, + RunID: "v3-run", + SubjectRevision: 1, + CurrentProjectionRef: "v3-run-current", + CurrentProjectionRevision: 1, + CurrentProjectionDigest: digestV2(t, "v3-run-current", "current"), + } + operationDigest, err := operation.DigestV3() + if err != nil { + t.Fatal(err) + } + attempt := runtimeports.OperationDispatchAttemptRefV3{ + OperationDigest: operationDigest, + EffectID: "v3-effect", + IntentRevision: 1, + IntentDigest: digestV2(t, "v3-intent", "intent"), + PermitID: "v3-permit", + PermitRevision: 1, + PermitDigest: digestV2(t, "v3-permit", "permit"), + AttemptID: "v3-runtime-attempt", + } + return runtimeports.InspectCurrentModelProviderActualPointRequestV1{ + Operation: operation, + EffectID: attempt.EffectID, + ExpectedEffectRevision: 3, + PermitID: attempt.PermitID, + ExpectedPermitFactRevision: 2, + PermitDigest: attempt.PermitDigest, + AdmissionDigest: digestV2(t, "v3-admission", "admission"), + ReviewAuthorization: runtimeports.OperationReviewAuthorizationRefV4{ + ID: "v3-review", + Revision: 1, + Digest: digestV2(t, "v3-review", "review"), + }, + Attempt: attempt, + Verifier: provider, + FenceDigest: digestV2(t, "v3-fence", "fence"), + RequestedNotAfterUnixNano: gatewayNow.Add(5 * time.Minute).UnixNano(), + } +} + +func actualBoundaryProviderBindingV3( + t *testing.T, +) runtimeports.ProviderBindingRefV2 { + t.Helper() + return runtimeports.ProviderBindingRefV2{ + BindingSetID: "v3-binding-set", + BindingSetRevision: 1, + ComponentID: "praxis.model/provider", + ManifestDigest: digestV2(t, "v3-manifest", "manifest"), + ArtifactDigest: digestV2(t, "v3-artifact", "artifact"), + Capability: runtimeports.ModelInvokeCapabilityV1, + } +} + +func actualBoundarySourceRefV3( + owner core.OwnerRef, + kind string, + id string, + digest core.Digest, +) modelinvoker.InvocationMaterialExactSourceRefV1 { + return modelinvoker.InvocationMaterialExactSourceRefV1{ + Owner: owner, + Kind: kind, + ID: id, + Revision: 1, + Digest: digest, + } +}