← Back to Pull requests

feat(substrate): converge egress policy on every resume #291

Merged
aramase merged 19 files (3136 lines) on Nov 23, 2026 23:13 UTC
View on GitHub
aramase aramase commented on Nov 20, 2026 09:05 UTC
Author

Closes #251.

A changed WithEgressPolicy (or -substrate-egress-policy-file) used to reach only actors created after it changed: an actor that already had a policy kept it. The backend now converges each actor's stored policy on the configured one before every resume of a suspended actor, with no opt-out.

  • The backend reads the stored policy and compares it semantically. An unchanged policy means no write; a changed one is replaced with UpdateActorEgressPolicy under the UID and version it read. A conflicting writer starts a new read, up to three attempts, then the call fails as ErrActorBusy.

  • A function that returns no policy clears a stored one to an empty rule set (deny-all) with a preconditioned Update, never a Delete.

  • It applies on Create, Restore, re-attaching a suspended actor, and the stateful fork clone.

  • Backend.SyncEgressPolicy(ctx, sessionUID) applies a changed policy to a running actor without suspending it. Substrate picks it up within its policy caches (about 10 seconds for requests and new connections, 5 seconds for DNS on v1.0.0); an open TLS passthrough connection is not cut. The daemon does not call it.

  • A Substrate router wake resumes an actor without the backend, so convergence runs the next time the backend resumes it.

  • A stored policy the adapter cannot convert is now ErrEgressPolicyInvalid, which reaches callers as FAILED_PRECONDITION / COMPUTE_CONFIG_INVALID with fixed text.

  • An error from the WithEgressPolicy function keeps its code but not its text on every path, since a non-INTERNAL code publishes the text and the function's message can name a credential reference.
  • Compatibility (changelog fragment in the Compatibility category):

  • A policy edited in Substrate by anyone else is overwritten at the next resume while the option is set.

  • A custom EgressPolicyClient used with WithEgressPolicy must implement GetActorEgressPolicy and UpdateActorEgressPolicy as well as CreateActorEgressPolicy. A ControlClient without EgressPolicyClient is refused (ErrEgressPolicyUnsupported) on every resume of an existing actor and every Sync, whatever the function returns, instead of resuming with the old policy. The daemon already refused that setup at startup.

  • A memory-tier fork whose new clone already holds a policy fails ErrActorBusy and writes nothing: the actor under the child's name may no longer be the clone, and policy calls cannot check its UID. The configured policy is authoritative only while the backend is the only policy writer in its atespace.
  • Docs updated: the EgressPolicyClient and SyncEgressPolicy docs in runtime/substrate/egress.go, docs/security.md, docs/substrate-conformance.md (with spec and conformance IDs) and spec.md.

    Tested:

  • Unit tests against a fake ControlClient cover unchanged, changed, nil-clears, create-exists and update-not-found races, precondition conflicts and retry exhaustion, error classification through Exec, Resume and Fork, fork children, and Sync. The fail-closed refusal for a client without EgressPolicyClient is pinned for Restore, Create attach and Sync.

  • go test -race ./runtime/substrate/... ./session/... and go test -race ./... in integrations/substrate.

  • gofmt, go vet, hack/changelog check, hack/check-doc-links.py and hack/doccheck pass.

  • golangci-lint was not run locally (the installed version cannot type-check Go 1.27); CI runs it. A live Substrate e2e was not run (needs a cluster).
  • Diff: 3136 lines (+2733 / -403) across 19 files Reviewer: Tatsinnit Review duration: 5167m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.72) × (1 − Review Confidence (0.72)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 3136 lines diff across 19 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.53 · 5 substantive comment(s)
    0.53
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    71%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    21 items
    Copilot Copilot commented on code on Nov 20, 2026 09:11 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,428 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    -// api.ErrComputeConfigInvalid.
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or
    +// write a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy,
    +// whatever the function returns (a nil result must clear a stored policy, which takes a read and
    +// an update), and before Create or Fork creates an actor when the function returns a policy. A
    +// function that returns nil for a new actor needs no call, since a new actor has no policy. No
    +// actor is resumed: starting compute on a policy the backend cannot converge is refused. The
    +// backend's error also wraps api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes the actor, so the actor's compute never runs without it, and never runs with a
    +// policy the function no longer returns. policy returns the policy for one session; nil, with no
    +// error, is deny-all: an actor without a policy is left without one, and one that has a policy is
    +// cleared to an empty rule set, which substrate also enforces as deny-all.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's
    +// stored policy, so that a write it bases on the result cannot undo a newer one, and a function
    +// that caches converges only as fresh as its cache. It may run several times in one backend call:
    +// once before Create creates an actor and before Fork tags the parent (so an error, or a policy
    +// with a ControlClient without EgressPolicyClient, refuses before any actor exists; that result is
    +// never written), and once for each attempt to converge, up to three. An error from any call
    +// fails the backend call without resuming the actor, and is not retried. Return rules in a stable
    +// order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. An equal policy is left as it is, so an
    +// unchanged policy costs one read and no write. A different one is replaced with
    +// UpdateActorEgressPolicy, preconditioned on the UID and version just read, and a missing one is
    +// created. An actor the backend has just created (Create, or a fork's create from tag) has no
    +// policy, so it is created without a read. A precondition that no longer holds (another writer
    +// changed the policy) starts the read, the call to policy and the write over, up to three attempts
    +// in all, then fails with ErrActorBusy, which is retryable. The backend never deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes only
    +// what differs, under the version it read. It neither resumes nor suspends the actor. Call it after
    +// changing what the function returns, to apply the change to a running actor without waiting for
    +// its next resume; a call that started before the change is not expected to reflect it. Call it on
    +// the backend that places the session: with a placement registry whose backends configure
    +// different functions, each converges the actor on its own.
    +//
    +// A call that returns nil cannot be undone by a concurrent resume or Sync: every write is
    +// preconditioned on the version its read found, and the function is asked after that read, so a
    +// converge that read before this one wrote conflicts and asks again, and one that read after asks
    +// after the change.
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none. Errors are classified as on a resume: ErrActorBusy after three
    +// conflicting writers, a policy the client refuses or a stored policy it cannot read as
    +// api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a ControlClient without
    +// EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	return b.egressFor(sessionUID).converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    +	}
    +	return policy, nil
    +}
    +
    +// errEgressUnsupported is the refusal of a policy the ControlClient cannot install.
    +func errEgressUnsupported() error {
    +	return fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    +}
    +
    +// check refuses, before any actor exists, a function that fails or a policy the ControlClient
    +// cannot install. Its result is never written: converge evaluates the function again after it has
    +// read the state its write is preconditioned on.
    +func (e *egressConverge) check(ctx context.Context) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
     	}
    -	return e.err
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return err
    +	}
    +	if _, ok := e.b.ctl.(EgressPolicyClient); policy != nil && !ok {
    +		return errEgressUnsupported()
    +	}
    +	return nil
     }
     
    -// install creates the session's policy on actor, resolving it first if needed. An actor that
    -// already has a policy keeps it. The error wraps the client's, so ErrActorNotFound and ErrActorBusy
    -// still classify it; a policy the client refuses (ErrEgressPolicyInvalid) is
    -// egressPolicyRefusedError.
    -func (e *egressInstall) install(ctx context.Context, actor ActorRef) error {
    -	if err := e.resolve(ctx); err != nil || e.policy == nil {
    +// Outcomes of a converge, logged as policy_outcome.
    +const (
    +	egressAbsent    = "absent"    // no policy wanted and none stored
    +	egressCreated   = "created"   // a policy created on an actor that had none
    +	egressUnchanged = "unchanged" // the stored policy already equals the configured one
    +	egressUpdated   = "updated"   // the stored policy replaced with the configured one
    +	egressCleared   = "cleared"   // the stored policy replaced with an empty (deny-all) rule set
    +)
    +
    +// converge makes actor's stored policy the session's configured one. fresh says the actor was just
    +// created by this backend call, so it has no policy and the first attempt creates without a read.
    +// The error wraps the client's, so ErrActorNotFound and ErrActorBusy still classify it; a policy
    +// the client refuses or cannot read (ErrEgressPolicyInvalid) is egressPolicyRefusedError. Without
    +// the option it does nothing. Without EgressPolicyClient it refuses an existing actor whatever the
    +// function returns, and a fresh one only when the function returns a policy.
    +func (e *egressConverge) converge(ctx context.Context, actor ActorRef, fresh bool) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	client, ok := e.b.ctl.(EgressPolicyClient)
    +	if !ok {
    +		if !fresh {
    +			// An existing actor can hold a policy that only a read finds and only an update
    +			// clears, so even a nil result cannot be converged: resuming would keep that policy.
    +			return errEgressUnsupported()
    +		}
    +		// A fresh actor has no policy: none wanted needs no call, any other is refused.
    +		policy, err := e.desired(ctx)
    +		if err == nil && policy != nil {
    +			err = errEgressUnsupported()
    +		}
     		return err
     	}
     	callCtx, finish := observability.BeginDebug(ctx, e.b.logger, "runtime.substrate", "install_egress_policy",
     		"actor", actor.Name,
     		"atespace", actor.Atespace,
    -		"rules", len(e.policy.Rules),
    +		"fresh", fresh,
     	)
    -	err := e.client.CreateActorEgressPolicy(callCtx, actor, *e.policy)
    +	res, err := e.attempts(callCtx, client, actor, fresh)
    +	attrs := []any{"policy_outcome", res.outcome, "rules", res.rules, "attempts", res.attempts}
     	switch {
     	case err == nil:
    -		finish(nil)
    -	case errors.Is(err, ErrEgressPolicyExists):
    -		finish(nil, "policy_exists", true)
    +		finish(nil, attrs...)
     	case errors.Is(err, ErrEgressPolicyInvalid):
    -		finish(err, "error_kind", "egress_policy_invalid")
    -		return &egressPolicyRefusedError{actor: actor, cause: err}
    +		finish(err, append(attrs, "error_kind", "egress_policy_invalid")...)
     	default:
    -		finish(err, "error_kind", "egress_policy_failed")
    -		return fmt.Errorf("%w on actor %s/%s: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +		finish(err, append(attrs, "error_kind", substrateErrorKind(err))...)
    +	}
    +	return err
    +}
    +
    +// egressResult is what a converge did: its outcome, the configured policy's rule count (-1 before
    +// the function answered) and the attempts it made. It carries no policy contents.
    +type egressResult struct {
    +	outcome  string
    +	rules    int
    +	attempts int
    +}
    +
    +// attempts runs up to egressConvergeAttempts attempts, each of which reads (unless fresh), asks the
    +// function and writes, and starts over only on a conflict.
    +func (e *egressConverge) attempts(ctx context.Context, client EgressPolicyClient, actor ActorRef, fresh bool) (egressResult, error) {
    +	res := egressResult{rules: -1}
    +	var conflict error
    +	for res.attempts = 1; ; res.attempts++ {
    +		var err error
    +		if fresh && res.attempts == 1 {
    +			conflict, err = e.createFresh(ctx, client, actor, &res)
    +		} else {
    +			conflict, err = e.convergeExisting(ctx, client, actor, &res)
    +		}
    +		if err != nil || conflict == nil {
    +			return res, err
    +		}
    +		if res.attempts == egressConvergeAttempts {
    +			break
    +		}
    +		if err := ctx.Err(); err != nil {
    +			return res, fmt.Errorf("%w on actor %s/%s: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +		}
    +	}
    +	res.outcome = ""
    +	// The conflict's text can carry substrate's own message, so it stays in the chain only.
    +	return res, &hiddenCause{
    +		err: fmt.Errorf("%w on actor %s/%s: its policy changed during each of %d attempts to converge it: %w",
    +			errEgressPolicyInstall, actor.Atespace, actor.Name, egressConvergeAttempts, ErrActorBusy),
    +		cause: conflict,
    +	}
    +}
    +
    +// createFresh is the first attempt on an actor this call just created. The function is asked only
    +// now, after the actor exists, so what it returns reflects any change made before the actor did; a
    +// policy created in between (ErrEgressPolicyExists) is a conflict, and the next attempt reads it.
    +func (e *egressConverge) createFresh(ctx context.Context, client EgressPolicyClient, actor ActorRef, res *egressResult) (conflict, err error) {
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return nil, err
    +	}
    +	if policy == nil {
    +		res.rules, res.outcome = 0, egressAbsent
    +		return nil, nil
    +	}

    If another writer installs an allow policy after actor creation and the callback then returns nil, this early return lets Create/Fork resume with that policy instead of deny-all. For a nil result, use the existing read/compare/update path rather than assuming the fresh actor is still policy-free. Add a regression for this interleaving and update the callback-count documentation and call-sequence tests for the extra read-then-evaluate step.

    Copilot Copilot commented on code on Nov 20, 2026 09:11 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,428 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    -// api.ErrComputeConfigInvalid.
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or
    +// write a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy,
    +// whatever the function returns (a nil result must clear a stored policy, which takes a read and
    +// an update), and before Create or Fork creates an actor when the function returns a policy. A
    +// function that returns nil for a new actor needs no call, since a new actor has no policy. No
    +// actor is resumed: starting compute on a policy the backend cannot converge is refused. The
    +// backend's error also wraps api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes the actor, so the actor's compute never runs without it, and never runs with a
    +// policy the function no longer returns. policy returns the policy for one session; nil, with no
    +// error, is deny-all: an actor without a policy is left without one, and one that has a policy is
    +// cleared to an empty rule set, which substrate also enforces as deny-all.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's
    +// stored policy, so that a write it bases on the result cannot undo a newer one, and a function
    +// that caches converges only as fresh as its cache. It may run several times in one backend call:
    +// once before Create creates an actor and before Fork tags the parent (so an error, or a policy
    +// with a ControlClient without EgressPolicyClient, refuses before any actor exists; that result is
    +// never written), and once for each attempt to converge, up to three. An error from any call
    +// fails the backend call without resuming the actor, and is not retried. Return rules in a stable
    +// order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. An equal policy is left as it is, so an
    +// unchanged policy costs one read and no write. A different one is replaced with
    +// UpdateActorEgressPolicy, preconditioned on the UID and version just read, and a missing one is
    +// created. An actor the backend has just created (Create, or a fork's create from tag) has no
    +// policy, so it is created without a read. A precondition that no longer holds (another writer
    +// changed the policy) starts the read, the call to policy and the write over, up to three attempts
    +// in all, then fails with ErrActorBusy, which is retryable. The backend never deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes only
    +// what differs, under the version it read. It neither resumes nor suspends the actor. Call it after
    +// changing what the function returns, to apply the change to a running actor without waiting for
    +// its next resume; a call that started before the change is not expected to reflect it. Call it on
    +// the backend that places the session: with a placement registry whose backends configure
    +// different functions, each converges the actor on its own.
    +//
    +// A call that returns nil cannot be undone by a concurrent resume or Sync: every write is
    +// preconditioned on the version its read found, and the function is asked after that read, so a
    +// converge that read before this one wrote conflicts and asks again, and one that read after asks
    +// after the change.
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none. Errors are classified as on a resume: ErrActorBusy after three
    +// conflicting writers, a policy the client refuses or a stored policy it cannot read as
    +// api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a ControlClient without
    +// EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	return b.egressFor(sessionUID).converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    +	}
    +	return policy, nil
    +}
    +
    +// errEgressUnsupported is the refusal of a policy the ControlClient cannot install.
    +func errEgressUnsupported() error {
    +	return fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    +}
    +
    +// check refuses, before any actor exists, a function that fails or a policy the ControlClient
    +// cannot install. Its result is never written: converge evaluates the function again after it has
    +// read the state its write is preconditioned on.
    +func (e *egressConverge) check(ctx context.Context) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
     	}
    -	return e.err
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return err
    +	}
    +	if _, ok := e.b.ctl.(EgressPolicyClient); policy != nil && !ok {
    +		return errEgressUnsupported()
    +	}
    +	return nil
     }
     
    -// install creates the session's policy on actor, resolving it first if needed. An actor that
    -// already has a policy keeps it. The error wraps the client's, so ErrActorNotFound and ErrActorBusy
    -// still classify it; a policy the client refuses (ErrEgressPolicyInvalid) is
    -// egressPolicyRefusedError.
    -func (e *egressInstall) install(ctx context.Context, actor ActorRef) error {
    -	if err := e.resolve(ctx); err != nil || e.policy == nil {
    +// Outcomes of a converge, logged as policy_outcome.
    +const (
    +	egressAbsent    = "absent"    // no policy wanted and none stored
    +	egressCreated   = "created"   // a policy created on an actor that had none
    +	egressUnchanged = "unchanged" // the stored policy already equals the configured one
    +	egressUpdated   = "updated"   // the stored policy replaced with the configured one
    +	egressCleared   = "cleared"   // the stored policy replaced with an empty (deny-all) rule set
    +)
    +
    +// converge makes actor's stored policy the session's configured one. fresh says the actor was just
    +// created by this backend call, so it has no policy and the first attempt creates without a read.
    +// The error wraps the client's, so ErrActorNotFound and ErrActorBusy still classify it; a policy
    +// the client refuses or cannot read (ErrEgressPolicyInvalid) is egressPolicyRefusedError. Without
    +// the option it does nothing. Without EgressPolicyClient it refuses an existing actor whatever the
    +// function returns, and a fresh one only when the function returns a policy.
    +func (e *egressConverge) converge(ctx context.Context, actor ActorRef, fresh bool) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	client, ok := e.b.ctl.(EgressPolicyClient)
    +	if !ok {
    +		if !fresh {
    +			// An existing actor can hold a policy that only a read finds and only an update
    +			// clears, so even a nil result cannot be converged: resuming would keep that policy.
    +			return errEgressUnsupported()
    +		}
    +		// A fresh actor has no policy: none wanted needs no call, any other is refused.
    +		policy, err := e.desired(ctx)
    +		if err == nil && policy != nil {
    +			err = errEgressUnsupported()
    +		}
     		return err
     	}
     	callCtx, finish := observability.BeginDebug(ctx, e.b.logger, "runtime.substrate", "install_egress_policy",
     		"actor", actor.Name,
     		"atespace", actor.Atespace,
    -		"rules", len(e.policy.Rules),
    +		"fresh", fresh,
     	)
    -	err := e.client.CreateActorEgressPolicy(callCtx, actor, *e.policy)
    +	res, err := e.attempts(callCtx, client, actor, fresh)
    +	attrs := []any{"policy_outcome", res.outcome, "rules", res.rules, "attempts", res.attempts}
     	switch {
     	case err == nil:
    -		finish(nil)
    -	case errors.Is(err, ErrEgressPolicyExists):
    -		finish(nil, "policy_exists", true)
    +		finish(nil, attrs...)
     	case errors.Is(err, ErrEgressPolicyInvalid):
    -		finish(err, "error_kind", "egress_policy_invalid")
    -		return &egressPolicyRefusedError{actor: actor, cause: err}
    +		finish(err, append(attrs, "error_kind", "egress_policy_invalid")...)
     	default:
    -		finish(err, "error_kind", "egress_policy_failed")
    -		return fmt.Errorf("%w on actor %s/%s: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +		finish(err, append(attrs, "error_kind", substrateErrorKind(err))...)
    +	}
    +	return err
    +}
    +
    +// egressResult is what a converge did: its outcome, the configured policy's rule count (-1 before
    +// the function answered) and the attempts it made. It carries no policy contents.
    +type egressResult struct {
    +	outcome  string
    +	rules    int
    +	attempts int
    +}
    +
    +// attempts runs up to egressConvergeAttempts attempts, each of which reads (unless fresh), asks the
    +// function and writes, and starts over only on a conflict.
    +func (e *egressConverge) attempts(ctx context.Context, client EgressPolicyClient, actor ActorRef, fresh bool) (egressResult, error) {
    +	res := egressResult{rules: -1}
    +	var conflict error
    +	for res.attempts = 1; ; res.attempts++ {
    +		var err error
    +		if fresh && res.attempts == 1 {
    +			conflict, err = e.createFresh(ctx, client, actor, &res)
    +		} else {
    +			conflict, err = e.convergeExisting(ctx, client, actor, &res)
    +		}
    +		if err != nil || conflict == nil {
    +			return res, err
    +		}
    +		if res.attempts == egressConvergeAttempts {
    +			break
    +		}
    +		if err := ctx.Err(); err != nil {
    +			return res, fmt.Errorf("%w on actor %s/%s: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +		}
    +	}
    +	res.outcome = ""
    +	// The conflict's text can carry substrate's own message, so it stays in the chain only.
    +	return res, &hiddenCause{
    +		err: fmt.Errorf("%w on actor %s/%s: its policy changed during each of %d attempts to converge it: %w",
    +			errEgressPolicyInstall, actor.Atespace, actor.Name, egressConvergeAttempts, ErrActorBusy),
    +		cause: conflict,
    +	}
    +}
    +
    +// createFresh is the first attempt on an actor this call just created. The function is asked only
    +// now, after the actor exists, so what it returns reflects any change made before the actor did; a
    +// policy created in between (ErrEgressPolicyExists) is a conflict, and the next attempt reads it.
    +func (e *egressConverge) createFresh(ctx context.Context, client EgressPolicyClient, actor ActorRef, res *egressResult) (conflict, err error) {
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return nil, err
    +	}
    +	if policy == nil {
    +		res.rules, res.outcome = 0, egressAbsent
    +		return nil, nil
    +	}
    +	res.rules = len(policy.Rules)
    +	return e.create(ctx, client, actor, *policy, res)
    +}
    +
    +// convergeExisting is one attempt on an actor that may already have a policy: read it, ask the
    +// function, and write only what differs, preconditioned on what was read.
    +func (e *egressConverge) convergeExisting(ctx context.Context, client EgressPolicyClient, actor ActorRef, res *egressResult) (conflict, err error) {
    +	stored, err := client.GetActorEgressPolicy(ctx, actor)
    +	found := err == nil
    +	switch {
    +	case errors.Is(err, ErrEgressPolicyNotFound):
    +	case errors.Is(err, ErrEgressPolicyInvalid):
    +		return nil, &egressPolicyRefusedError{actor: actor, cause: err, stored: true}
    +	case err != nil:
    +		return nil, fmt.Errorf("%w on actor %s/%s: read the stored policy: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +	}
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return nil, err
    +	}
    +	res.rules = 0
    +	if policy != nil {
    +		res.rules = len(policy.Rules)
    +	}
    +	want, outcome := EgressPolicy{}, egressCleared
    +	switch {
    +	case !found && policy == nil:
    +		res.outcome = egressAbsent
    +		return nil, nil

    A no-op Sync does not fence an older convergence: a resume can read no policy and evaluate an allow policy, pause, then successfully create it after configuration changes to nil and Sync returns success. The equal-policy branches at lines 436–441 have the same problem because they leave the version unchanged, allowing a delayed update to restore revoked permissions. Fence stale evaluations across backend instances, or require callers to quiesce convergence during configuration changes and narrow the documented guarantee; add regressions for both no-write cases.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 20, 2026 09:11 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Critical races allow stale convergence to restore revoked permissions and let Create/Fork retain an allow policy when the callback returns nil instead of enforcing deny-all.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Nil policy callback can preserve a concurrently installed allow policy · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> No-op Sync leaves stale convergence unfenced · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    This PR extends the Substrate backend’s egress-policy management so configuration changes reach existing actors before backend-driven resumes, supporting the session isolation work in #251.

    Changes:

  • Adds semantic policy comparison, version-preconditioned updates, bounded conflict retries, and deny-all clearing.

  • Introduces SyncEgressPolicy for running actors and classifies unreadable stored policies as configuration errors.

  • Expands lifecycle and error-handling tests, with documentation covering compatibility changes and enforcement limits.
  • | File | Description |
    | ---- | ----------- |
    | spec.md | Records policy convergence before later resumes. |
    | session/​egress_policy_error_test.go | Tests API error classification and safe error text. |
    | runtime/​substrate/​substrate.go | Integrates convergence into create, restore, attach, and fork. |
    | runtime/​substrate/​egress.go | Implements comparison, convergence, retries, and explicit sync. |
    | runtime/​substrate/​egress_test.go | Tests policy changes, clearing, conflicts, and sync behavior. |
    | integrations/​substrate/​egress.go | Classifies stored-policy conversion failures. |
    | integrations/​substrate/​egress_test.go | Tests conversion-error classification and privacy. |
    | integrations/​substrate/​e2e/​egress_test.go | Adds stored-policy checks across resume and running-actor sync. |
    | integrations/​substrate/​cmd/​agentsessionsd/​substrate.go | Updates policy-file flag help for convergence behavior. |
    | integrations/​substrate/​cmd/​agentsessionsd/​egress_test.go | Tests changed policy files reaching existing actors. |
    | docs/​substrate-conformance.md | Documents convergence, sync, cache limits, and coverage. |
    | docs/​security.md | Explains policy authority, revocation, and enforcement limits. |
    | changelog/​unreleased/​egress-policy-sync.md | Announces the explicit sync API. |
    | changelog/​unreleased/​egress-policy-stored-invalid.md | Records stored-policy error classification changes. |
    | changelog/​unreleased/​egress-policy-converge-compat.md | Documents changed behavior and client requirements. |
    </details>

    <sub>Review effort: Balanced</sub>

    Copilot Copilot commented on code on Nov 21, 2026 02:25 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,467 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or write
    +// a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy, whatever
    +// the function returns (a nil result must clear a stored policy, which takes a read and an update),
    +// and before Create or Fork creates an actor when the function returns a policy. Without the
    +// client, a function that returns nil for a new actor is not refused: a new actor has no policy,
    +// which is deny-all, and there is nothing to write with. No actor is resumed: starting compute on a
    +// policy the backend cannot converge is refused. The backend's error also wraps
     // api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes the actor, so the actor's compute never runs without it, and never runs with a
    +// policy the function no longer returns. policy returns the policy for one session; nil, with no
    +// error, is deny-all, stored as an empty rule set: an actor the backend creates gets an empty
    +// policy, an existing actor without a policy is left without one, and one that has rules is cleared
    +// to an empty rule set. Substrate v1.0.0 enforces an empty rule set as it does no policy (its
    +// egress gateway denies both, cmd/atenet/internal/router/egress/egress.go, and its DNS answers no
    +// name for either, internal/atunnel/dns/evaluator.go), and deletes the policy with the actor.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's stored
    +// policy, so that a write it bases on the result cannot undo a newer one, and a function that
    +// caches converges only as fresh as its cache. It may run several times in one backend call: once
    +// before Create creates an actor and before Fork tags the parent (so an error, or a policy with a
    +// ControlClient without EgressPolicyClient, refuses before any actor exists; that result is never
    +// written), and once for each attempt to converge, up to three, whatever it returns. An error from
    +// any call fails the backend call without resuming the actor, and is not retried. Return rules in a
    +// stable order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. On a resume an equal policy is left as it is, so
    +// an unchanged policy costs one read and no write (SyncEgressPolicy writes it again, which costs a
    +// write, not a call). A different one is replaced with UpdateActorEgressPolicy, preconditioned on
    +// the UID and version just read, and a missing one is created. An actor the backend has just
    +// created (Create, or a fork's create from tag) has no policy, so it gets the configured policy,
    +// or an empty one for nil, without a read. A precondition that no longer holds (another writer
    +// changed the policy, or created one first) starts the read, the call to policy and the write over,
    +// up to three attempts in all, then fails with ErrActorBusy, which is retryable. The backend never
    +// deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes the
    +// result under the version it read. Unlike a resume it writes even when nothing differs: an equal
    +// policy is written again, and with none stored and none returned it creates an empty one. It
    +// neither resumes nor suspends the actor. Call it after changing what the function returns, to
    +// apply the change to a running actor without waiting for its next resume; a call that started
    +// before the change is not expected to reflect it. Call it on the backend that places the session:
    +// with a placement registry whose backends configure different functions, each converges the actor
    +// on its own.
    +//
    +// The protocol is: change the function, then call SyncEgressPolicy. A call that returns nil cannot
    +// be undone by a converge (a resume, Create, Fork or another Sync) that read the stored policy, or
    +// asked the function, before this call wrote: every write is preconditioned, an update on the
    +// version its read found and a create on there being no policy, and every Sync writes, so such a
    +// converge conflicts, reads again and asks again, after the change. A resume that writes nothing
    +// fences nothing, so a change applied only by resumes carries no such guarantee. On an actor that
    +// does not exist yet the call writes nothing; the backend's create of that actor asks the function
    +// afterwards and stores its policy, or an empty one, and that create is what a stale writer
    +// conflicts with. This relies on Substrate moving the version on every update, an unchanged policy
    +// included, as Substrate v1.0.0 does (cmd/ateapi/internal/store/atepg/egress_policy.go).
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none, also when the actor is deleted during the call. Errors are classified
    +// as on a resume: ErrActorBusy after three conflicting writers, a policy the client refuses or a
    +// stored policy it cannot read as api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a
    +// ControlClient without EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	e := b.egressFor(sessionUID)
    +	e.fence = true
    +	return e.converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
    +	// fence makes every attempt write, even when the stored policy already matches
    +	// (SyncEgressPolicy): the write moves the version, so a converge that read before it conflicts
    +	// and asks again.
    +	fence bool
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
     	}
    -	return e.err
    +	return policy, nil
    +}
    +
    +// errEgressUnsupported is the refusal of a policy the ControlClient cannot install.
    +func errEgressUnsupported() error {
    +	return fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
     }
     
    -// install creates the session's policy on actor, resolving it first if needed. An actor that
    -// already has a policy keeps it. The error wraps the client's, so ErrActorNotFound and ErrActorBusy
    -// still classify it; a policy the client refuses (ErrEgressPolicyInvalid) is
    -// egressPolicyRefusedError.
    -func (e *egressInstall) install(ctx context.Context, actor ActorRef) error {
    -	if err := e.resolve(ctx); err != nil || e.policy == nil {
    +// check refuses, before any actor exists, a function that fails or a policy the ControlClient
    +// cannot install. Its result is never written: converge evaluates the function again after it has
    +// read the state its write is preconditioned on.
    +func (e *egressConverge) check(ctx context.Context) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return err
    +	}
    +	if _, ok := e.b.ctl.(EgressPolicyClient); policy != nil && !ok {
    +		return errEgressUnsupported()
    +	}
    +	return nil
    +}
    +
    +// Outcomes of a converge, logged as policy_outcome.
    +const (
    +	egressAbsent    = "absent"    // no policy wanted and none stored
    +	egressCreated   = "created"   // a policy created on an actor that had none
    +	egressUnchanged = "unchanged" // the stored policy already equals the configured one
    +	egressUpdated   = "updated"   // the stored policy replaced with the configured one
    +	egressCleared   = "cleared"   // the stored policy replaced with an empty (deny-all) rule set
    +	egressFenced    = "fenced"    // an equal stored policy written again to move its version (Sync)
    +)
    +
    +// converge makes actor's stored policy the session's configured one. fresh says the actor was just
    +// created by this backend call, so it has no policy and the first attempt creates the configured
    +// one, or an empty one for none, without a read. The error wraps the client's, so ErrActorNotFound
    +// and ErrActorBusy still classify it; a policy the client refuses or cannot read
    +// (ErrEgressPolicyInvalid) is egressPolicyRefusedError. Without the option it does nothing. Without
    +// EgressPolicyClient it refuses an existing actor whatever the function returns, and a fresh one
    +// only when the function returns a policy.
    +func (e *egressConverge) converge(ctx context.Context, actor ActorRef, fresh bool) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	client, ok := e.b.ctl.(EgressPolicyClient)
    +	if !ok {
    +		if !fresh {
    +			// An existing actor can hold a policy that only a read finds and only an update
    +			// clears, so even a nil result cannot be converged: resuming would keep that policy.
    +			return errEgressUnsupported()
    +		}
    +		// A fresh actor has no policy: none wanted needs no call, any other is refused.
    +		policy, err := e.desired(ctx)
    +		if err == nil && policy != nil {
    +			err = errEgressUnsupported()
    +		}
     		return err
     	}
     	callCtx, finish := observability.BeginDebug(ctx, e.b.logger, "runtime.substrate", "install_egress_policy",
     		"actor", actor.Name,
     		"atespace", actor.Atespace,
    -		"rules", len(e.policy.Rules),
    +		"fresh", fresh,
     	)
    -	err := e.client.CreateActorEgressPolicy(callCtx, actor, *e.policy)
    +	res, err := e.attempts(callCtx, client, actor, fresh)
    +	attrs := []any{"policy_outcome", res.outcome, "rules", res.rules, "attempts", res.attempts}
     	switch {
     	case err == nil:
    -		finish(nil)
    -	case errors.Is(err, ErrEgressPolicyExists):
    -		finish(nil, "policy_exists", true)
    +		finish(nil, attrs...)
     	case errors.Is(err, ErrEgressPolicyInvalid):
    -		finish(err, "error_kind", "egress_policy_invalid")
    -		return &egressPolicyRefusedError{actor: actor, cause: err}
    +		finish(err, append(attrs, "error_kind", "egress_policy_invalid")...)
     	default:
    -		finish(err, "error_kind", "egress_policy_failed")
    -		return fmt.Errorf("%w on actor %s/%s: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +		finish(err, append(attrs, "error_kind", substrateErrorKind(err))...)
    +	}
    +	return err
    +}
    +
    +// egressResult is what a converge did: its outcome, the configured policy's rule count (-1 before
    +// the function answered) and the attempts it made. It carries no policy contents.
    +type egressResult struct {
    +	outcome  string
    +	rules    int
    +	attempts int
    +}
    +
    +// attempts runs up to egressConvergeAttempts attempts, each of which reads (unless fresh), asks the
    +// function and writes, and starts over only on a conflict.
    +func (e *egressConverge) attempts(ctx context.Context, client EgressPolicyClient, actor ActorRef, fresh bool) (egressResult, error) {
    +	res := egressResult{rules: -1}
    +	var conflict error
    +	for res.attempts = 1; ; res.attempts++ {
    +		var err error
    +		if fresh && res.attempts == 1 {
    +			conflict, err = e.createFresh(ctx, client, actor, &res)
    +		} else {
    +			conflict, err = e.convergeExisting(ctx, client, actor, &res)
    +		}
    +		if err != nil || conflict == nil {
    +			return res, err
    +		}
    +		if res.attempts == egressConvergeAttempts {
    +			break
    +		}
    +		if err := ctx.Err(); err != nil {
    +			return res, fmt.Errorf("%w on actor %s/%s: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)
    +		}
    +	}
    +	res.outcome = ""
    +	// The conflict's text can carry substrate's own message, so it stays in the chain only.
    +	return res, &hiddenCause{
    +		err: fmt.Errorf("%w on actor %s/%s: its policy changed during each of %d attempts to converge it: %w",
    +			errEgressPolicyInstall, actor.Atespace, actor.Name, egressConvergeAttempts, ErrActorBusy),
    +		cause: conflict,
    +	}
    +}
    +
    +// createFresh is the first attempt on an actor this call just created. The function is asked only
    +// now, after the actor exists, so what it returns reflects any change made before the actor did.
    +// No policy is created as an empty one, which substrate enforces as none: a policy another writer
    +// created on the actor, before this create or after it, then conflicts (ErrEgressPolicyExists),
    +// and that writer's next attempt, or this one's, reads it.
    +func (e *egressConverge) createFresh(ctx context.Context, client EgressPolicyClient, actor ActorRef, res *egressResult) (conflict, err error) {
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return nil, err
    +	}
    +	want := EgressPolicy{}
    +	if policy != nil {
    +		want = *policy
    +	}
    +	res.rules = len(want.Rules)
    +	return e.create(ctx, client, actor, want, res)
    +}
    +
    +// convergeExisting is one attempt on an actor that may already have a policy: read it, ask the
    +// function, and write only what differs, preconditioned on what was read. With fence it also writes
    +// what does not differ: an empty policy when none is stored and none is wanted, and the stored one
    +// again when it is equal.
    +func (e *egressConverge) convergeExisting(ctx context.Context, client EgressPolicyClient, actor ActorRef, res *egressResult) (conflict, err error) {
    +	stored, err := client.GetActorEgressPolicy(ctx, actor)
    +	found := err == nil
    +	switch {
    +	case errors.Is(err, ErrEgressPolicyNotFound):
    +	case errors.Is(err, ErrEgressPolicyInvalid):
    +		return nil, &egressPolicyRefusedError{actor: actor, cause: err, stored: true}
    +	case err != nil:
    +		return nil, fmt.Errorf("%w on actor %s/%s: read the stored policy: %w", errEgressPolicyInstall, actor.Atespace, actor.Name, err)

    If GetActorEgressPolicy returns a wrapped ErrActorBusy, this includes the client's diagnostic in the error that Exec/Resume expose as ABORTED, even with authorization enabled. A diagnostic containing a private hostname or credential reference therefore reaches the caller. Use busyRefusal for busy read failures, retain the cause in the error chain, and add a regression test with a wrapped ErrActorBusy.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 21, 2026 02:25 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    A wrapped ErrActorBusy can leak private client diagnostics through Exec/Resume ABORTED errors even with authorization enabled, requiring sanitization via busyRefusal and a regression test.

    <details open>
    <summary><strong>1 open issue</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Redact diagnostics from wrapped actor-busy errors · New

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> No-op Sync leaves stale convergence unfenced

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Nil policy callback can preserve a concurrently installed allow policy

  • </details>

    <sub>Review effort: Balanced</sub>

    Copilot Copilot commented on code on Nov 21, 2026 06:49 UTC
    Code Review
    docs/security.md:1
    @@ -248,25 +248,47 @@ spec §17.
     
     The egress policy is runtime configuration: which hosts and ports the harness's compute may reach,
     and which credential the egress injects on a matching request. The journal does not record it. On
    -substrate, `substrate.WithEgressPolicy` or the daemon's `-substrate-egress-policy-file` installs a
    -Substrate `EgressPolicy` on each session's actor before the backend resumes it, so no turn runs on
    -compute without the policy. The policy holds credential references (`ate-secret://...`) or an actor
    -JWT audience, never a credential value. The backend's install log records the rule count and an
    -`error_kind`, not the rules. A policy Substrate refuses as invalid reaches callers as fixed text
    -(`FAILED_PRECONDITION`, `COMPUTE_CONFIG_INVALID`), without Substrate's message, which can name a
    -rejected hostname or credential reference. Other install failures keep the backend error's text,
    -which reaches callers when authorization is off. A daemon startup error for a policy file that
    -does not parse can quote the offending JSON token; it goes only to the operator.
    +substrate, `substrate.WithEgressPolicy` or the daemon's `-substrate-egress-policy-file` sets the
    +Substrate `EgressPolicy` of each session's actor before every backend resume of a suspended actor,
    +so compute the backend resumes never runs a turn without the policy, or with one the configuration
    +no longer holds. An actor already running when the backend reaches it, or woken by the Substrate
    +router, keeps its stored policy until it is suspended and the backend resumes it, or until
    +`substrate.Backend.SyncEgressPolicy` applies the change. The policy holds credential references
    +(`ate-secret://...`) or an actor JWT audience, never a credential value. The backend's install log
    +records the rule count, the outcome and an `error_kind`, not the rules. A policy Substrate
    +refuses as invalid reaches callers as fixed text (`FAILED_PRECONDITION`,
    +`COMPUTE_CONFIG_INVALID`), without Substrate's message, which can name a rejected hostname or
    +credential reference. A policy call Substrate refuses because another operation holds the actor,
    +and an `Exec` refused because the actor was replaced while its policy was converged or it was
    +resumed, are `ABORTED` with `COMPUTE_BUSY` and leave Substrate's message out as well. Other install
    +failures keep the backend error's text, which reaches callers when authorization is off. A daemon
    +startup error for a policy file that does not parse can quote the offending JSON token; it goes only
    +to the operator.
     
     - **Fail closed.** A configured policy that the control client cannot install, or that Substrate
    -  refuses, fails the call and leaves the actor suspended. An actor without a policy is deny-all.
    -- **Existing actors keep their policy.** A policy changed in the option or the file reaches only
    -  actors created afterwards. Tightening it does not reach existing sessions until their actors are
    -  recreated or their policy is updated in Substrate.
    -- **Running compute is not changed.** An actor already running when the backend reaches it keeps
    -  whatever policy it has, or stays deny-all without one.
    -
    -See [Actor egress policy](substrate-conformance.md#actor-egress-policy) for the install points.
    +  refuses, fails the call and leaves the actor suspended. A control client that cannot read and
    +  update policies fails every resume of an existing actor and every Sync, even when no policy is
    +  configured, since only a read finds a stored policy and only an update clears it. An actor
    +  without a policy is deny-all.

    This refusal requires WithEgressPolicy to be set: when the option is unset, converge returns without an egress call and an existing actor can resume with its stored policy. Please distinguish an unset option from a configured function returning nil, so removing configuration is not described as fail-closed.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 21, 2026 06:49 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    The security documentation should distinguish an unset WithEgressPolicy option, which allows an existing actor to resume with its stored policy, from a configured function returning nil, rather than describing removed configuration as fail-closed.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Redact diagnostics from wrapped actor-busy errors

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Unset egress policy allows actors to resume with stored policy · New

  • </details>

    <sub>Review effort: Balanced</sub>

    Copilot Copilot commented on code on Nov 21, 2026 08:15 UTC
    Code Review
    docs/security.md:1
    @@ -248,25 +248,55 @@ spec §17.
     
     The egress policy is runtime configuration: which hosts and ports the harness's compute may reach,
     and which credential the egress injects on a matching request. The journal does not record it. On
    -substrate, `substrate.WithEgressPolicy` or the daemon's `-substrate-egress-policy-file` installs a
    -Substrate `EgressPolicy` on each session's actor before the backend resumes it, so no turn runs on
    -compute without the policy. The policy holds credential references (`ate-secret://...`) or an actor
    -JWT audience, never a credential value. The backend's install log records the rule count and an
    -`error_kind`, not the rules. A policy Substrate refuses as invalid reaches callers as fixed text
    -(`FAILED_PRECONDITION`, `COMPUTE_CONFIG_INVALID`), without Substrate's message, which can name a
    -rejected hostname or credential reference. Other install failures keep the backend error's text,
    -which reaches callers when authorization is off. A daemon startup error for a policy file that
    -does not parse can quote the offending JSON token; it goes only to the operator.
    +substrate, `substrate.WithEgressPolicy` or the daemon's `-substrate-egress-policy-file` sets the
    +Substrate `EgressPolicy` of each session's actor before every backend resume of a suspended actor,
    +so while the option is set, compute the backend resumes never runs a turn without the policy, or
    +with one the configuration no longer holds. Without the option, or with the flag empty, the backend

    A quick suspend, policy tightening and resume can still allow traffic under the cached old policy, despite the stored policy being updated. Qualify this as a stored-policy guarantee and apply the Sync cache caveat to resumes too; upstream's default-branch cache documents a 10-second default (the integration pins v1.0.0). Apply the same qualification in runtime/substrate/egress.go:165–168.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 21, 2026 08:15 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    The documentation needs to qualify its stored-policy guarantee because a quick suspend, policy tightening, and resume can still permit traffic under the cached old policy.

    <details open>
    <summary><strong>1 open issue</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Clarify that resumes may use a cached pre-tightening policy · New

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Redact diagnostics from wrapped actor-busy errors

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Unset egress policy allows actors to resume with stored policy

  • </details>

    <sub>Review effort: Balanced</sub>

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 21, 2026 17:44 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🔵 Needs a closer look

    Maintainer validation is needed because security-sensitive policy convergence depends on Substrate versioning and gateway-cache behavior, while tests verify stored policies rather than live traffic enforcement or credential injection.

    No open issues 🎉

    <details>
    <summary><strong>1 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Clarify that resumes may use a cached pre-tightening policy

  • </details>

    <sub>Review effort: Balanced</sub>

    Tatsinnit Tatsinnit commented on code on Nov 23, 2026 00:50 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,480 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or write
    +// a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy, whatever
    +// the function returns (a nil result must clear a stored policy, which takes a read and an update),
    +// and before Create or Fork creates an actor when the function returns a policy. Without the
    +// client, a function that returns nil for a new actor is not refused: a new actor has no policy,
    +// which is deny-all, and there is nothing to write with. No actor is resumed: starting compute on a
    +// policy the backend cannot converge is refused. The backend's error also wraps
     // api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes a SUSPENDED actor (one it created or found suspended), so the backend resumes
    +// an actor only once its stored policy is the one the function returns, or deny-all for nil.
    +// Substrate enforces a stored policy through its caches (see Backend.SyncEgressPolicy), so requests
    +// a resumed actor makes soon after a change can still be judged by the policy cached before its
    +// suspend. An actor already RUNNING when the backend reaches it, or one the substrate router wakes,
    +// keeps its stored policy until it is suspended and the backend resumes it, or until
    +// Backend.SyncEgressPolicy applies the change. policy returns the policy for one session; nil, with
    +// no error, is deny-all, stored as an empty rule set: an actor the backend creates gets an empty
    +// policy, an existing actor without a policy is left without one, and one that has rules is cleared
    +// to an empty rule set. Substrate v1.0.0 enforces an empty rule set as it does no policy (its
    +// egress gateway denies both, cmd/atenet/internal/router/egress/egress.go, and its DNS answers no
    +// name for either, internal/atunnel/dns/evaluator.go), and deletes the policy with the actor.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's stored
    +// policy, so that a write it bases on the result cannot undo a newer one, and a function that
    +// caches converges only as fresh as its cache. It may run several times in one backend call: once
    +// before Create creates an actor and before Fork tags the parent (so an error, or a policy with a
    +// ControlClient without EgressPolicyClient, refuses before any actor exists; that result is never
    +// written), and once for each attempt to converge, up to three, whatever it returns. An error from
    +// any call fails the backend call without resuming the actor, and is not retried. Return rules in a
    +// stable order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. On a resume an equal policy is left as it is, so
    +// an unchanged policy costs one read and no write (SyncEgressPolicy writes it again, which costs a
    +// write, not a call). A different one is replaced with UpdateActorEgressPolicy, preconditioned on
    +// the UID and version just read, and a missing one is created. An actor the backend has just
    +// created (Create, or a fork's create from tag) has no policy, so it gets the configured policy,
    +// or an empty one for nil, without a read. A precondition that no longer holds (another writer
    +// changed the policy, or created one first) starts the read, the call to policy and the write over,
    +// up to three attempts in all, then fails with ErrActorBusy, which is retryable. The backend never
    +// deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes the
    +// result under the version it read. Unlike a resume it writes even when nothing differs: an equal
    +// policy is written again, and with none stored and none returned it creates an empty one. It
    +// neither resumes nor suspends the actor. Call it after changing what the function returns, to
    +// apply the change to a running actor without waiting for its next resume; a call that started
    +// before the change is not expected to reflect it. Call it on the backend that places the session:
    +// with a placement registry whose backends configure different functions, each converges the actor
    +// on its own.
    +//
    +// The protocol is: change the function, then call SyncEgressPolicy. A call that returns nil cannot
    +// be undone by a converge (a resume, Create, Fork or another Sync) that read the stored policy, or
    +// asked the function, before this call wrote: every write is preconditioned, an update on the
    +// version its read found and a create on there being no policy, and every Sync writes, so such a
    +// converge conflicts, reads again and asks again, after the change. A resume that writes nothing
    +// fences nothing, so a change applied only by resumes carries no such guarantee. On an actor that
    +// does not exist yet the call writes nothing; the backend's create of that actor asks the function
    +// afterwards and stores its policy, or an empty one, and that create is what a stale writer
    +// conflicts with. This relies on Substrate moving the version on every update, an unchanged policy
    +// included, as Substrate v1.0.0 does (cmd/ateapi/internal/store/atepg/egress_policy.go).
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none, also when the actor is deleted during the call. Errors are classified
    +// as on a resume: ErrActorBusy after three conflicting writers, a policy the client refuses or a
    +// stored policy it cannot read as api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a
    +// ControlClient without EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	e := b.egressFor(sessionUID)
    +	e.fence = true
    +	return e.converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
    +	// fence makes every attempt write, even when the stored policy already matches
    +	// (SyncEgressPolicy): the write moves the version, so a converge that read before it conflicts
    +	// and asks again.
    +	fence bool
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)

    Thank you for consistently retaining causes while removing control-client diagnostics from caller-visible busy/configuration refusals. One adjacent observation: callback errors retain their full text here. A temporary authorized Exec with the callback returning fmt.Errorf("%w: policy lookup for ate-secret://provider/private-key failed", api.ErrComputeBusy) produced ABORTED and returned that credential reference to the caller; authorization sanitizes only INTERNAL. The Fork path already hides a busy callback error at runtime/substrate/substrate.go:1434-1437, but Create/Resume do not.

    Would it be worth applying the same fixed-text/cause-in-chain treatment when a callback error carries a caller-visible runtime sentinel such as ErrComputeBusy or ErrComputeConfigInvalid, with an authorized Exec/Resume regression? I am treating this as an observation about the public error boundary rather than assuming callbacks normally include sensitive text.

    Tatsinnit Tatsinnit commented on code on Nov 23, 2026 00:50 UTC
    Code Review
    runtime/substrate/substrate.go:1
    @@ -1424,11 +1428,12 @@ func (b *Backend) Fork(ctx context.Context, ref api.SnapshotRef, opts api.ForkOp
     	// The child holds the tag's snapshot, so resuming it restores the cloned RAM. The clone is
     	// SUSPENDED until then, so it can be deleted and another actor created under its name, and
     	// ResumeActor resolves the name, not the UID: compare the UID it reports with the clone's. It
    -	// gets the child's egress policy first; a failed install is torn down as a failed resume is.
    +	// gets the child's egress policy first; a failed converge is torn down as a failed resume is.
     	childRef := b.ref(child)
    -	if err := egress.install(ctx, childRef); err != nil {
    +	if err := egress.converge(ctx, childRef, true); err != nil {

    Thank you for the careful UID check after the clone resumes. One observation specific to changing this step from install-only to convergence: the policy operation is still by actor name before that UID check. In a temporary test, I replaced the clone after CreateActorFromTag and gave the replacement its own policy. The fresh create saw AlreadyExists, retried through read/update, and replaced that actor's policy with the child's credential-bearing policy. ResumeActor then returned the replacement UID, so Fork correctly failed ErrActorBusy, but the replacement was intentionally left running with its policy changed.

    Before this PR, the create-only install treated AlreadyExists as already installed and did not update it, so the overwrite appears to be introduced by convergence. Would it make sense for fresh convergence to treat ErrEgressPolicyExists as busy unless it can bind the policy operation to created.UID? I could not find an actor-UID precondition in the v1 policy API/store (the policy CAS protects policy UID/version, not actor UID), but please correct me if an upstream lease or transaction closes this window.

    Tatsinnit Tatsinnit commented on code on Nov 23, 2026 00:50 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,480 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or write
    +// a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy, whatever
    +// the function returns (a nil result must clear a stored policy, which takes a read and an update),
    +// and before Create or Fork creates an actor when the function returns a policy. Without the
    +// client, a function that returns nil for a new actor is not refused: a new actor has no policy,
    +// which is deny-all, and there is nothing to write with. No actor is resumed: starting compute on a
    +// policy the backend cannot converge is refused. The backend's error also wraps
     // api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes a SUSPENDED actor (one it created or found suspended), so the backend resumes
    +// an actor only once its stored policy is the one the function returns, or deny-all for nil.
    +// Substrate enforces a stored policy through its caches (see Backend.SyncEgressPolicy), so requests
    +// a resumed actor makes soon after a change can still be judged by the policy cached before its
    +// suspend. An actor already RUNNING when the backend reaches it, or one the substrate router wakes,
    +// keeps its stored policy until it is suspended and the backend resumes it, or until
    +// Backend.SyncEgressPolicy applies the change. policy returns the policy for one session; nil, with
    +// no error, is deny-all, stored as an empty rule set: an actor the backend creates gets an empty
    +// policy, an existing actor without a policy is left without one, and one that has rules is cleared
    +// to an empty rule set. Substrate v1.0.0 enforces an empty rule set as it does no policy (its
    +// egress gateway denies both, cmd/atenet/internal/router/egress/egress.go, and its DNS answers no
    +// name for either, internal/atunnel/dns/evaluator.go), and deletes the policy with the actor.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's stored
    +// policy, so that a write it bases on the result cannot undo a newer one, and a function that
    +// caches converges only as fresh as its cache. It may run several times in one backend call: once
    +// before Create creates an actor and before Fork tags the parent (so an error, or a policy with a
    +// ControlClient without EgressPolicyClient, refuses before any actor exists; that result is never
    +// written), and once for each attempt to converge, up to three, whatever it returns. An error from
    +// any call fails the backend call without resuming the actor, and is not retried. Return rules in a
    +// stable order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. On a resume an equal policy is left as it is, so
    +// an unchanged policy costs one read and no write (SyncEgressPolicy writes it again, which costs a
    +// write, not a call). A different one is replaced with UpdateActorEgressPolicy, preconditioned on
    +// the UID and version just read, and a missing one is created. An actor the backend has just
    +// created (Create, or a fork's create from tag) has no policy, so it gets the configured policy,
    +// or an empty one for nil, without a read. A precondition that no longer holds (another writer
    +// changed the policy, or created one first) starts the read, the call to policy and the write over,
    +// up to three attempts in all, then fails with ErrActorBusy, which is retryable. The backend never
    +// deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes the
    +// result under the version it read. Unlike a resume it writes even when nothing differs: an equal
    +// policy is written again, and with none stored and none returned it creates an empty one. It
    +// neither resumes nor suspends the actor. Call it after changing what the function returns, to
    +// apply the change to a running actor without waiting for its next resume; a call that started
    +// before the change is not expected to reflect it. Call it on the backend that places the session:
    +// with a placement registry whose backends configure different functions, each converges the actor
    +// on its own.
    +//
    +// The protocol is: change the function, then call SyncEgressPolicy. A call that returns nil cannot
    +// be undone by a converge (a resume, Create, Fork or another Sync) that read the stored policy, or
    +// asked the function, before this call wrote: every write is preconditioned, an update on the
    +// version its read found and a create on there being no policy, and every Sync writes, so such a
    +// converge conflicts, reads again and asks again, after the change. A resume that writes nothing
    +// fences nothing, so a change applied only by resumes carries no such guarantee. On an actor that
    +// does not exist yet the call writes nothing; the backend's create of that actor asks the function
    +// afterwards and stores its policy, or an empty one, and that create is what a stale writer
    +// conflicts with. This relies on Substrate moving the version on every update, an unchanged policy
    +// included, as Substrate v1.0.0 does (cmd/ateapi/internal/store/atepg/egress_policy.go).
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none, also when the actor is deleted during the call. Errors are classified
    +// as on a resume: ErrActorBusy after three conflicting writers, a policy the client refuses or a
    +// stored policy it cannot read as api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a
    +// ControlClient without EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	e := b.egressFor(sessionUID)
    +	e.fence = true
    +	return e.converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
    +	// fence makes every attempt write, even when the stored policy already matches
    +	// (SyncEgressPolicy): the write moves the version, so a converge that read before it conflicts
    +	// and asks again.
    +	fence bool
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
     	}
    -	return e.err
    +	return policy, nil
    +}
    +
    +// errEgressUnsupported is the refusal of a policy the ControlClient cannot install.
    +func errEgressUnsupported() error {
    +	return fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
     }
     
    -// install creates the session's policy on actor, resolving it first if needed. An actor that
    -// already has a policy keeps it. The error wraps the client's, so ErrActorNotFound and ErrActorBusy
    -// still classify it; a policy the client refuses (ErrEgressPolicyInvalid) is
    -// egressPolicyRefusedError.
    -func (e *egressInstall) install(ctx context.Context, actor ActorRef) error {
    -	if err := e.resolve(ctx); err != nil || e.policy == nil {
    +// check refuses, before any actor exists, a function that fails or a policy the ControlClient
    +// cannot install. Its result is never written: converge evaluates the function again after it has
    +// read the state its write is preconditioned on.
    +func (e *egressConverge) check(ctx context.Context) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return err
    +	}
    +	if _, ok := e.b.ctl.(EgressPolicyClient); policy != nil && !ok {
    +		return errEgressUnsupported()
    +	}
    +	return nil
    +}
    +
    +// Outcomes of a converge, logged as policy_outcome.
    +const (
    +	egressAbsent    = "absent"    // no policy wanted and none stored
    +	egressCreated   = "created"   // a policy created on an actor that had none
    +	egressUnchanged = "unchanged" // the stored policy already equals the configured one
    +	egressUpdated   = "updated"   // the stored policy replaced with the configured one
    +	egressCleared   = "cleared"   // the stored policy replaced with an empty (deny-all) rule set
    +	egressFenced    = "fenced"    // an equal stored policy written again to move its version (Sync)
    +)
    +
    +// converge makes actor's stored policy the session's configured one. fresh says the actor was just
    +// created by this backend call, so it has no policy and the first attempt creates the configured
    +// one, or an empty one for none, without a read. The error wraps the client's, so ErrActorNotFound
    +// and ErrActorBusy still classify it; a busy refusal (api.ErrComputeBusy) keeps the client's error
    +// in its chain but not in its text (busyRefusal); a policy the client refuses or cannot read
    +// (ErrEgressPolicyInvalid) is egressPolicyRefusedError. Without the option it does nothing. Without
    +// EgressPolicyClient it refuses an existing actor whatever the function returns, and a fresh one
    +// only when the function returns a policy.
    +func (e *egressConverge) converge(ctx context.Context, actor ActorRef, fresh bool) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	client, ok := e.b.ctl.(EgressPolicyClient)
    +	if !ok {
    +		if !fresh {
    +			// An existing actor can hold a policy that only a read finds and only an update
    +			// clears, so even a nil result cannot be converged: resuming would keep that policy.
    +			return errEgressUnsupported()
    +		}
    +		// A fresh actor has no policy: none wanted needs no call, any other is refused.

    Thank you for preserving compatibility with custom ControlClient implementations. One observation from exercising this branch: when WithEgressPolicy returns nil and the client does not implement EgressPolicyClient, the fresh-actor path assumes the actor remains policy-free until ResumeActor. I added a temporary interleaving that installed a credential-bearing allow policy immediately after CreateActor; the call still completed with get -> create -> resume, because this branch could neither read nor clear that policy.

    My reading is that this leaves a narrow gap in the documented nil = deny-all behavior for custom embedders (the shipped adapter/daemon are not affected). Would it be safer to require EgressPolicyClient whenever WithEgressPolicy is configured, including a fresh actor with a nil result, unless the resume can atomically assert policy absence? I may be overlooking a Substrate guarantee around who can write during this interval, so please do correct me if the actor lifecycle already excludes it.

    Tatsinnit Tatsinnit requested changes on Nov 23, 2026 00:51 UTC
    Changes Requested Reviewer

    Thank you for the thoughtful and thorough work here. The convergence protocol, bounded CAS retries, Sync fencing, fixed-text client refusals, cache caveats, and extensive tests show a great deal of care, and I appreciate how each earlier review observation was worked through.

    While exercising a few less common interleavings locally, I noticed three edge cases and left the reproductions inline. I am sharing them as observations rather than assumptions about the intended Substrate behavior, especially since you know this control plane and integration much better than I do. Please do correct me if an upstream lease, authorization rule, or actor-policy invariant already closes any of these windows.

    For context, the root runtime/substrate and session race suites, the full integrations/substrate race suite, vet, doccheck, diff checks, all GitHub checks, and a synthetic merge with current main passed on my side. Thank you again for the careful work and for making the security boundary much clearer.

    Tatsinnit Tatsinnit approved these changes on Nov 23, 2026 00:51 UTC
    Approved Reviewer

    Approved these changes.

    gambtho gambtho approved these changes on Nov 23, 2026 13:52 UTC
    Approved Reviewer

    Approved these changes.

    aramase aramase commented on code on Nov 23, 2026 20:11 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,480 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or write
    +// a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy, whatever
    +// the function returns (a nil result must clear a stored policy, which takes a read and an update),
    +// and before Create or Fork creates an actor when the function returns a policy. Without the
    +// client, a function that returns nil for a new actor is not refused: a new actor has no policy,
    +// which is deny-all, and there is nothing to write with. No actor is resumed: starting compute on a
    +// policy the backend cannot converge is refused. The backend's error also wraps
     // api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes a SUSPENDED actor (one it created or found suspended), so the backend resumes
    +// an actor only once its stored policy is the one the function returns, or deny-all for nil.
    +// Substrate enforces a stored policy through its caches (see Backend.SyncEgressPolicy), so requests
    +// a resumed actor makes soon after a change can still be judged by the policy cached before its
    +// suspend. An actor already RUNNING when the backend reaches it, or one the substrate router wakes,
    +// keeps its stored policy until it is suspended and the backend resumes it, or until
    +// Backend.SyncEgressPolicy applies the change. policy returns the policy for one session; nil, with
    +// no error, is deny-all, stored as an empty rule set: an actor the backend creates gets an empty
    +// policy, an existing actor without a policy is left without one, and one that has rules is cleared
    +// to an empty rule set. Substrate v1.0.0 enforces an empty rule set as it does no policy (its
    +// egress gateway denies both, cmd/atenet/internal/router/egress/egress.go, and its DNS answers no
    +// name for either, internal/atunnel/dns/evaluator.go), and deletes the policy with the actor.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's stored
    +// policy, so that a write it bases on the result cannot undo a newer one, and a function that
    +// caches converges only as fresh as its cache. It may run several times in one backend call: once
    +// before Create creates an actor and before Fork tags the parent (so an error, or a policy with a
    +// ControlClient without EgressPolicyClient, refuses before any actor exists; that result is never
    +// written), and once for each attempt to converge, up to three, whatever it returns. An error from
    +// any call fails the backend call without resuming the actor, and is not retried. Return rules in a
    +// stable order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. On a resume an equal policy is left as it is, so
    +// an unchanged policy costs one read and no write (SyncEgressPolicy writes it again, which costs a
    +// write, not a call). A different one is replaced with UpdateActorEgressPolicy, preconditioned on
    +// the UID and version just read, and a missing one is created. An actor the backend has just
    +// created (Create, or a fork's create from tag) has no policy, so it gets the configured policy,
    +// or an empty one for nil, without a read. A precondition that no longer holds (another writer
    +// changed the policy, or created one first) starts the read, the call to policy and the write over,
    +// up to three attempts in all, then fails with ErrActorBusy, which is retryable. The backend never
    +// deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes the
    +// result under the version it read. Unlike a resume it writes even when nothing differs: an equal
    +// policy is written again, and with none stored and none returned it creates an empty one. It
    +// neither resumes nor suspends the actor. Call it after changing what the function returns, to
    +// apply the change to a running actor without waiting for its next resume; a call that started
    +// before the change is not expected to reflect it. Call it on the backend that places the session:
    +// with a placement registry whose backends configure different functions, each converges the actor
    +// on its own.
    +//
    +// The protocol is: change the function, then call SyncEgressPolicy. A call that returns nil cannot
    +// be undone by a converge (a resume, Create, Fork or another Sync) that read the stored policy, or
    +// asked the function, before this call wrote: every write is preconditioned, an update on the
    +// version its read found and a create on there being no policy, and every Sync writes, so such a
    +// converge conflicts, reads again and asks again, after the change. A resume that writes nothing
    +// fences nothing, so a change applied only by resumes carries no such guarantee. On an actor that
    +// does not exist yet the call writes nothing; the backend's create of that actor asks the function
    +// afterwards and stores its policy, or an empty one, and that create is what a stale writer
    +// conflicts with. This relies on Substrate moving the version on every update, an unchanged policy
    +// included, as Substrate v1.0.0 does (cmd/ateapi/internal/store/atepg/egress_policy.go).
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none, also when the actor is deleted during the call. Errors are classified
    +// as on a resume: ErrActorBusy after three conflicting writers, a policy the client refuses or a
    +// stored policy it cannot read as api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a
    +// ControlClient without EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	e := b.egressFor(sessionUID)
    +	e.fence = true
    +	return e.converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
    +	// fence makes every attempt write, even when the stored policy already matches
    +	// (SyncEgressPolicy): the write moves the version, so a converge that read before it conflicts
    +	// and asks again.
    +	fence bool
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)

    Fixed, a bit more broadly than suggested: any error from the policy function now has fixed text naming the session, with the original error kept in the chain, whatever sentinel it wraps. Hiding only busy and config-invalid would still leak through the other non-INTERNAL mappings, like SESSION_BUSY.

    aramase aramase commented on code on Nov 23, 2026 20:12 UTC
    Code Review
    runtime/substrate/substrate.go:1
    @@ -1424,11 +1428,12 @@ func (b *Backend) Fork(ctx context.Context, ref api.SnapshotRef, opts api.ForkOp
     	// The child holds the tag's snapshot, so resuming it restores the cloned RAM. The clone is
     	// SUSPENDED until then, so it can be deleted and another actor created under its name, and
     	// ResumeActor resolves the name, not the UID: compare the UID it reports with the clone's. It
    -	// gets the child's egress policy first; a failed install is torn down as a failed resume is.
    +	// gets the child's egress policy first; a failed converge is torn down as a failed resume is.
     	childRef := b.ref(child)
    -	if err := egress.install(ctx, childRef); err != nil {
    +	if err := egress.converge(ctx, childRef, true); err != nil {

    Good catch. The convergence change turned an Exists on a fork's fresh clone into read+update, so a replacement that already had a policy got it overwritten and resumed. A fork now refuses (busy) when its new clone already has a policy, writes nothing, and goes through discardClone, so a replacement is left untouched and not resumed. One window remains, and it predates this PR: if the clone is replaced by an actor with no policy, the create succeeds on the replacement before the UID check after ResumeActor. Closing that needs a UID precondition on the policy or resume call, which Substrate v1 doesn't have. I've documented the gap.

    aramase aramase commented on code on Nov 23, 2026 20:12 UTC
    Code Review
    runtime/substrate/egress.go:1
    @@ -126,139 +135,480 @@ var ErrEgressPolicyNotFound = errors.New("substrate: actor egress policy not fou
     
     // ErrEgressPolicyInvalid is what an EgressPolicyClient must return (or wrap) from
     // CreateActorEgressPolicy and UpdateActorEgressPolicy when the policy itself is refused:
    -// substrate's INVALID_ARGUMENT, or a rule the client cannot express. The backend reports a refused
    -// install as api.ErrComputeConfigInvalid, since it repeats until the configured policy changes,
    -// and leaves the client's message out of the error text, since it can name a rejected hostname or
    -// credential reference. Go callers reach the client's error through Unwrap; logs record only the
    -// error_kind egress_policy_invalid, as for every runtime error.
    +// substrate's INVALID_ARGUMENT, or a rule the client cannot express; and from
    +// GetActorEgressPolicy when the stored policy cannot be converted. The backend reports either as
    +// api.ErrComputeConfigInvalid, since it repeats until the configured policy (or the client)
    +// changes, and leaves the client's message out of the error text, since it can name a rejected
    +// hostname or credential reference. A stored policy that cannot be read is never overwritten:
    +// without it the backend has nothing to compare with and no precondition to write under. Go
    +// callers reach the client's error through Unwrap; logs record only the error_kind
    +// egress_policy_invalid, as for every runtime error.
     var ErrEgressPolicyInvalid = errors.New("substrate: actor egress policy is invalid")
     
    -// ErrEgressPolicyUnsupported is returned when WithEgressPolicy yields a policy but the backend's
    -// ControlClient does not implement EgressPolicyClient. No actor is resumed: starting compute
    -// without the policy it was configured with is refused. The backend's error also wraps
    +// ErrEgressPolicyUnsupported is returned when WithEgressPolicy is set but the backend's
    +// ControlClient does not implement EgressPolicyClient, and the backend would have to read or write
    +// a policy: before it resumes an existing SUSPENDED actor and on every SyncEgressPolicy, whatever
    +// the function returns (a nil result must clear a stored policy, which takes a read and an update),
    +// and before Create or Fork creates an actor when the function returns a policy. Without the
    +// client, a function that returns nil for a new actor is not refused: a new actor has no policy,
    +// which is deny-all, and there is nothing to write with. No actor is resumed: starting compute on a
    +// policy the backend cannot converge is refused. The backend's error also wraps
     // api.ErrComputeConfigInvalid.
     var ErrEgressPolicyUnsupported = errors.New("substrate: egress policy configured but the control client does not implement EgressPolicyClient")
     
     // errEgressPolicyFunc marks an error returned by the WithEgressPolicy function.
     var errEgressPolicyFunc = errors.New("substrate: egress policy function")
     
    -// errEgressPolicyInstall marks a failed CreateActorEgressPolicy.
    +// errEgressPolicyInstall marks a failed egress policy read or write.
     var errEgressPolicyInstall = errors.New("substrate: install egress policy")
     
    -// WithEgressPolicy installs an egress policy on each actor before the backend first resumes it, so
    -// the actor's compute never runs without it. policy returns the policy for one session; nil, with
    -// no error, installs none, and the actor stays deny-all as substrate leaves an actor without a
    -// policy.
    +// WithEgressPolicy converges each actor's egress policy on the one policy returns before the
    +// backend resumes a SUSPENDED actor (one it created or found suspended), so the backend resumes
    +// an actor only once its stored policy is the one the function returns, or deny-all for nil.
    +// Substrate enforces a stored policy through its caches (see Backend.SyncEgressPolicy), so requests
    +// a resumed actor makes soon after a change can still be judged by the policy cached before its
    +// suspend. An actor already RUNNING when the backend reaches it, or one the substrate router wakes,
    +// keeps its stored policy until it is suspended and the backend resumes it, or until
    +// Backend.SyncEgressPolicy applies the change. policy returns the policy for one session; nil, with
    +// no error, is deny-all, stored as an empty rule set: an actor the backend creates gets an empty
    +// policy, an existing actor without a policy is left without one, and one that has rules is cleared
    +// to an empty rule set. Substrate v1.0.0 enforces an empty rule set as it does no policy (its
    +// egress gateway denies both, cmd/atenet/internal/router/egress/egress.go, and its DNS answers no
    +// name for either, internal/atunnel/dns/evaluator.go), and deletes the policy with the actor.
     //
     // policy receives a spec whose SessionUID is set (the child's on Fork). No other field is set
     // today, on any path; later releases may set more, so key per-session policies on SessionUID and do
    -// not rely on other fields being zero. It runs at most once per backend call, and only when the
    -// call is about to start an actor's compute: Create before it creates an actor (so an error, or a
    -// ControlClient without EgressPolicyClient, refuses before any actor exists) or before it resumes a
    -// SUSPENDED one, Restore before it resumes, and Fork before it tags the parent.
    +// not rely on other fields being zero. It must return the current policy each time it is called,
    +// read after any change made before the call: the backend calls it after reading the actor's stored
    +// policy, so that a write it bases on the result cannot undo a newer one, and a function that
    +// caches converges only as fresh as its cache. It may run several times in one backend call: once
    +// before Create creates an actor and before Fork tags the parent (so an error, or a policy with a
    +// ControlClient without EgressPolicyClient, refuses before any actor exists; that result is never
    +// written), and once for each attempt to converge, up to three, whatever it returns. An error from
    +// any call fails the backend call without resuming the actor, and is not retried. Return rules in a
    +// stable order: rule order is compared, so a reordered policy is written again.
    +//
    +// Converging reads the stored policy (GetActorEgressPolicy) and compares it with the configured
    +// one by meaning: a rule that leaves its ports unset equals one with substrate's default port
    +// stored, and hostnames and ports compare as sets. On a resume an equal policy is left as it is, so
    +// an unchanged policy costs one read and no write (SyncEgressPolicy writes it again, which costs a
    +// write, not a call). A different one is replaced with UpdateActorEgressPolicy, preconditioned on
    +// the UID and version just read, and a missing one is created. An actor the backend has just
    +// created (Create, or a fork's create from tag) has no policy, so it gets the configured policy,
    +// or an empty one for nil, without a read. A precondition that no longer holds (another writer
    +// changed the policy, or created one first) starts the read, the call to policy and the write over,
    +// up to three attempts in all, then fails with ErrActorBusy, which is retryable. The backend never
    +// deletes a policy.
     //
    -// The policy is installed with CreateActorEgressPolicy between the backend's CreateActor (or a
    -// fork's create from tag) and its ResumeActor, and again before every later ResumeActor the
    -// backend issues. An actor that already has a policy keeps it, so a changed policy reaches only
    -// actors created after the change; nothing converges existing actors. A failed install fails the
    -// call without resuming the actor, which stays SUSPENDED (a fork's clone is torn down).
    +// The converge runs between the backend's CreateActor (or a fork's create from tag) and its
    +// ResumeActor, and before every later ResumeActor the backend issues on a SUSPENDED actor: Create
    +// attaching to one, and Restore. A failed converge fails the call without resuming the actor, which
    +// stays SUSPENDED (a fork's clone is torn down). While the option is set, a policy edited in
    +// substrate by anyone else is overwritten at the actor's next backend resume. Without it, the
    +// backend makes no egress call, and policies already stored are kept.
     //
     // Refusals that repeat until the configuration changes wrap api.ErrComputeConfigInvalid
    -// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient, and a
    -// policy the client refuses as invalid (ErrEgressPolicyInvalid), whose message the error text
    -// leaves out. An error from policy itself, and any other install failure, is not classified.
    +// (FAILED_PRECONDITION at the Sessions API): a ControlClient without EgressPolicyClient
    +// (ErrEgressPolicyUnsupported, which refuses every resume of an existing actor whatever the
    +// function returns), a policy the client refuses as invalid (ErrEgressPolicyInvalid), whose
    +// message the error text leaves out, and a stored policy the client cannot read. An error from
    +// policy itself, and any other egress call failure, is not classified.
     //
     // The backend issues no egress call for an actor it finds RUNNING (Create attaching to it, or
    -// Restore of it): it does not change the policy of running compute. Such an actor without a policy,
    -// one running before the option was set or woken by a routed request after a failed install, stays
    -// deny-all until it is suspended and the backend resumes it.
    +// Restore of it): a turn does not pay for a policy read. Call Backend.SyncEgressPolicy after a
    +// change to apply it to running compute; without that, a running actor keeps the policy it has
    +// until it is suspended and the backend resumes it.
     func WithEgressPolicy(policy func(ctx context.Context, s *api.SessionSpec) (*EgressPolicy, error)) Option {
     	return func(b *Backend) { b.egressPolicy = policy }
     }
     
    -// egressInstall resolves and installs the egress policy for one session within one backend call.
    -// It evaluates the WithEgressPolicy function at most once, on first use.
    -type egressInstall struct {
    +// Errors of SyncEgressPolicy called without what it needs.
    +var (
    +	errEgressPolicyNotConfigured = errors.New("substrate: SyncEgressPolicy needs WithEgressPolicy")
    +	errSyncRequiresSessionUID    = errors.New("substrate: SyncEgressPolicy requires a session uid")
    +)
    +
    +// SyncEgressPolicy converges the egress policy of sessionUID's actor on the one the
    +// WithEgressPolicy function returns now, as the backend does before it resumes a SUSPENDED actor,
    +// whatever state the actor is in: it reads the stored policy, asks the function, and writes the
    +// result under the version it read. Unlike a resume it writes even when nothing differs: an equal
    +// policy is written again, and with none stored and none returned it creates an empty one. It
    +// neither resumes nor suspends the actor. Call it after changing what the function returns, to
    +// apply the change to a running actor without waiting for its next resume; a call that started
    +// before the change is not expected to reflect it. Call it on the backend that places the session:
    +// with a placement registry whose backends configure different functions, each converges the actor
    +// on its own.
    +//
    +// The protocol is: change the function, then call SyncEgressPolicy. A call that returns nil cannot
    +// be undone by a converge (a resume, Create, Fork or another Sync) that read the stored policy, or
    +// asked the function, before this call wrote: every write is preconditioned, an update on the
    +// version its read found and a create on there being no policy, and every Sync writes, so such a
    +// converge conflicts, reads again and asks again, after the change. A resume that writes nothing
    +// fences nothing, so a change applied only by resumes carries no such guarantee. On an actor that
    +// does not exist yet the call writes nothing; the backend's create of that actor asks the function
    +// afterwards and stores its policy, or an empty one, and that create is what a stale writer
    +// conflicts with. This relies on Substrate moving the version on every update, an unchanged policy
    +// included, as Substrate v1.0.0 does (cmd/ateapi/internal/store/atepg/egress_policy.go).
    +//
    +// It returns an error, and makes no call, without WithEgressPolicy. An actor that does not exist is
    +// ErrActorNotFound when the function returns a policy (the next Create installs it), and is no
    +// error when it returns none, also when the actor is deleted during the call. Errors are classified
    +// as on a resume: ErrActorBusy after three conflicting writers, a policy the client refuses or a
    +// stored policy it cannot read as api.ErrComputeConfigInvalid, and ErrEgressPolicyUnsupported for a
    +// ControlClient without EgressPolicyClient, whatever the function returns and without calling it.
    +//
    +// On Substrate v1.0.0, "applies" is bounded by Substrate's caches: the egress gateway acts on a
    +// fetched policy for up to 10 seconds by default (its --egress-policy-cache-ttl,
    +// cmd/atenet/internal/router/egress/policycache.go) for each new HTTP request, intercepted HTTPS
    +// request and new connection, and the actor's DNS answers follow within 5 seconds, keeping the
    +// last policy while a fetch fails (internal/atunnel/egresspolicy.go). A TLS passthrough connection
    +// is allowed once, on its SNI, so one already open stays open until it closes.
    +func (b *Backend) SyncEgressPolicy(ctx context.Context, sessionUID string) error {
    +	if b.egressPolicy == nil {
    +		return errEgressPolicyNotConfigured
    +	}
    +	if sessionUID == "" {
    +		return errSyncRequiresSessionUID
    +	}
    +	e := b.egressFor(sessionUID)
    +	e.fence = true
    +	return e.converge(ctx, b.ref(sessionUID), false)
    +}
    +
    +// egressConvergeAttempts bounds the read, evaluate and write attempts of one converge. Each
    +// precondition another writer moved starts a new attempt.
    +const egressConvergeAttempts = 3
    +
    +// egressConverge converges one session's egress policy on its actor within one backend call.
    +type egressConverge struct {
     	b          *Backend
     	sessionUID string
    -	resolved   bool
    -	policy     *EgressPolicy
    -	client     EgressPolicyClient
    -	err        error
    +	// fence makes every attempt write, even when the stored policy already matches
    +	// (SyncEgressPolicy): the write moves the version, so a converge that read before it conflicts
    +	// and asks again.
    +	fence bool
     }
     
    -// egressFor returns the egress install of one session for one backend call.
    -func (b *Backend) egressFor(sessionUID string) *egressInstall {
    -	return &egressInstall{b: b, sessionUID: sessionUID}
    +// egressFor returns the egress converge of one session for one backend call.
    +func (b *Backend) egressFor(sessionUID string) *egressConverge {
    +	return &egressConverge{b: b, sessionUID: sessionUID}
     }
     
    -// resolve evaluates the WithEgressPolicy function and checks that the ControlClient can install
    -// what it returns. Without the option, or with a nil policy, there is nothing to install.
    -func (e *egressInstall) resolve(ctx context.Context) error {
    -	if e.resolved || e.b.egressPolicy == nil {
    -		return e.err
    -	}
    -	e.resolved = true
    +// desired evaluates the WithEgressPolicy function for the session.
    +func (e *egressConverge) desired(ctx context.Context) (*EgressPolicy, error) {
     	policy, err := e.b.egressPolicy(ctx, &api.SessionSpec{SessionUID: e.sessionUID})
    -	switch {
    -	case err != nil:
    -		e.err = fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
    -	case policy == nil:
    -	default:
    -		client, ok := e.b.ctl.(EgressPolicyClient)
    -		if !ok {
    -			e.err = fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
    -			break
    -		}
    -		e.policy, e.client = policy, client
    +	if err != nil {
    +		return nil, fmt.Errorf("%w for session %q: %w", errEgressPolicyFunc, e.sessionUID, err)
     	}
    -	return e.err
    +	return policy, nil
    +}
    +
    +// errEgressUnsupported is the refusal of a policy the ControlClient cannot install.
    +func errEgressUnsupported() error {
    +	return fmt.Errorf("%w: %w", api.ErrComputeConfigInvalid, ErrEgressPolicyUnsupported)
     }
     
    -// install creates the session's policy on actor, resolving it first if needed. An actor that
    -// already has a policy keeps it. The error wraps the client's, so ErrActorNotFound and ErrActorBusy
    -// still classify it; a policy the client refuses (ErrEgressPolicyInvalid) is
    -// egressPolicyRefusedError.
    -func (e *egressInstall) install(ctx context.Context, actor ActorRef) error {
    -	if err := e.resolve(ctx); err != nil || e.policy == nil {
    +// check refuses, before any actor exists, a function that fails or a policy the ControlClient
    +// cannot install. Its result is never written: converge evaluates the function again after it has
    +// read the state its write is preconditioned on.
    +func (e *egressConverge) check(ctx context.Context) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	policy, err := e.desired(ctx)
    +	if err != nil {
    +		return err
    +	}
    +	if _, ok := e.b.ctl.(EgressPolicyClient); policy != nil && !ok {
    +		return errEgressUnsupported()
    +	}
    +	return nil
    +}
    +
    +// Outcomes of a converge, logged as policy_outcome.
    +const (
    +	egressAbsent    = "absent"    // no policy wanted and none stored
    +	egressCreated   = "created"   // a policy created on an actor that had none
    +	egressUnchanged = "unchanged" // the stored policy already equals the configured one
    +	egressUpdated   = "updated"   // the stored policy replaced with the configured one
    +	egressCleared   = "cleared"   // the stored policy replaced with an empty (deny-all) rule set
    +	egressFenced    = "fenced"    // an equal stored policy written again to move its version (Sync)
    +)
    +
    +// converge makes actor's stored policy the session's configured one. fresh says the actor was just
    +// created by this backend call, so it has no policy and the first attempt creates the configured
    +// one, or an empty one for none, without a read. The error wraps the client's, so ErrActorNotFound
    +// and ErrActorBusy still classify it; a busy refusal (api.ErrComputeBusy) keeps the client's error
    +// in its chain but not in its text (busyRefusal); a policy the client refuses or cannot read
    +// (ErrEgressPolicyInvalid) is egressPolicyRefusedError. Without the option it does nothing. Without
    +// EgressPolicyClient it refuses an existing actor whatever the function returns, and a fresh one
    +// only when the function returns a policy.
    +func (e *egressConverge) converge(ctx context.Context, actor ActorRef, fresh bool) error {
    +	if e.b.egressPolicy == nil {
    +		return nil
    +	}
    +	client, ok := e.b.ctl.(EgressPolicyClient)
    +	if !ok {
    +		if !fresh {
    +			// An existing actor can hold a policy that only a read finds and only an update
    +			// clears, so even a nil result cannot be converged: resuming would keep that policy.
    +			return errEgressUnsupported()
    +		}
    +		// A fresh actor has no policy: none wanted needs no call, any other is refused.

    I checked this one. With the client, an outside write before the backend's create is caught: the create returns Exists and the converge clears it. It doesn't close the window between that create and ResumeActor, or on a running actor, so the guarantee assumes the backend is the only policy writer in the atespace either way. I've made that explicit in docs/security.md and the WithEgressPolicy doc rather than refusing a config this wouldn't make safe.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 23, 2026 20:14 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🔵 Needs a closer look

    The security-sensitive policy replacement depends on Substrate v1.0.0 precondition/version semantics and gateway cache behavior, but current tests establish storage ordering rather than traffic enforcement, leaving live gateway validation outstanding.

    No open issues 🎉

    <sub>Review effort: Balanced</sub>

    Reviewers
    Assignees
    aramase aramase
    Labels
    risk: low confidence: 71.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 71.9% · Lower = rushed or shallow review
    71.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.1% · Safe to merge
    20.1%