mirror of
https://github.com/agent-substrate/substrate.git
synced 2026-11-10 10:13:50 +08:00
Closes #1802. ## What this does Deletes the `ate.scheduler.eligible_workers` histogram. Nothing replaces it in this PR. ## Why **It is expensive on the resume path.** `Schedule` built a second slice of the matching workers that scheduling never read, walked it again, and repeated `HasRoom` for each entry. `HasRoom` parses resource quantity strings up to three times for each worker. The metric roughly doubled the per-worker arithmetic of a placement. The filter loop is now one pass over the fleet and builds one slice. **A metric cannot answer the question it was built for.** #564 wanted to tell a full fleet apart from an empty intersection of the constraints, such as a cordoned node behind a node requirement. That needs the selectors, the node requirement and the actor. `docs/metrics/substrate.yaml` bars all three from a metric label and sends them to logs and spans, so no shape of this instrument reaches the answer. A log record at the rejection is the replacement the issue names, and it is not in this PR. ## Also removed `ate.scheduling.constraint` goes with the instrument. No other signal used the attribute. ## Scope of the change - `cmd/ateapi/internal/scheduling/metrics.go` deleted, along with the `WithMeter` option and the second filter pass in `Schedule`. - The instrument and the attribute removed from `docs/metrics/registry/metrics.yaml`. The `pool-keys-paired` exception in `docs/metrics/substrate.yaml` dropped, because the empty pool pair was this instrument's alone. - `docs/observability.md`: the table row and the two label notes removed. - The e2e collector check and the label assertions for the instrument removed. - `TestSchedule_EligibleWorkersMetric` removed. The behaviors it covered (draining workers, a sandbox class mismatch, busy workers) are already in the `TestSchedule` table. ## Testing `go test ./cmd/... ./internal/...` passes. `make verify` passes except `hack/verify/metrics.sh`, which needs Weaver or Docker. Neither is available on this machine, so CI is what checks the registry.
222 lines
10 KiB
Go
222 lines
10 KiB
Go
// Copyright 2026 Google LLC
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package controlapi
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/agent-substrate/substrate/cmd/ateapi/internal/scheduling"
|
|
"github.com/agent-substrate/substrate/cmd/ateapi/internal/store"
|
|
"github.com/agent-substrate/substrate/cmd/ateapi/internal/workercache"
|
|
"github.com/agent-substrate/substrate/internal/actorevent"
|
|
"github.com/agent-substrate/substrate/internal/ateattr"
|
|
"github.com/agent-substrate/substrate/internal/objectstore"
|
|
"github.com/agent-substrate/substrate/internal/resources"
|
|
listersv1alpha1 "github.com/agent-substrate/substrate/pkg/client/listers/api/v1alpha1"
|
|
"github.com/agent-substrate/substrate/pkg/proto/ateapipb"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/trace"
|
|
grpcCodes "google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
storagev1listers "k8s.io/client-go/listers/storage/v1"
|
|
)
|
|
|
|
// stepSpan opens the per-step trace span ("step.<name>" on the controlapi
|
|
// tracer) and returns the step context plus a finish func the step defers:
|
|
// it records a non-nil error on the span and wraps it with the step name.
|
|
//
|
|
// Workflow steps follow the ensure pattern: each step derives whether its
|
|
// work is already done from persisted state alone (calling markSkipped when
|
|
// so), validates the state-machine edge it is about to take, and persists
|
|
// what it changed before returning — so a re-entered workflow fast-forwards
|
|
// to wherever the previous attempt stopped.
|
|
func stepSpan(ctx context.Context, name string) (context.Context, func(error) error) {
|
|
ctx, span := otel.Tracer("controlapi").Start(ctx, "step."+name)
|
|
return ctx, func(err error) error {
|
|
defer span.End()
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
span.RecordError(err)
|
|
span.SetStatus(codes.Error, err.Error())
|
|
return fmt.Errorf("workflow failed at step %s: %w", name, err)
|
|
}
|
|
}
|
|
|
|
// markSkipped annotates the current step's span when its postcondition
|
|
// already holds, so a re-entered workflow's trace shows which steps
|
|
// fast-forwarded and where real work restarted.
|
|
func markSkipped(ctx context.Context, reason string) {
|
|
trace.SpanFromContext(ctx).SetAttributes(
|
|
attribute.Bool("step.skipped", true),
|
|
attribute.String("step.skip_reason", reason),
|
|
)
|
|
}
|
|
|
|
// logActorStateChanged records an actor state change. The last record for an
|
|
// actor's uid is the state it is in now.
|
|
//
|
|
// The state is read off the committed record, never passed in, so a record
|
|
// cannot claim a state the store did not hold. Pass the actor the store returned
|
|
// and call it after UpdateActor returns, not inside the mutate closure, which
|
|
// can be retried. Every state commit carries a version precondition, so a call
|
|
// that returns is the one that made the change.
|
|
//
|
|
// Crashes go through logActorCrashed instead, so read the state off
|
|
// ate.actor.state rather than off the message.
|
|
func logActorStateChanged(ctx context.Context, actor *ateapipb.Actor, opName string) {
|
|
logActorState(ctx, actor, opName, ateattr.ActorStateValue(actor.GetStatus().GetState()))
|
|
}
|
|
|
|
// logActorDeleted records the terminal transition. The row is gone, so there is
|
|
// no committed state left to read and this is the one state named by hand.
|
|
func logActorDeleted(ctx context.Context, actor *ateapipb.Actor, opName string) {
|
|
logActorState(ctx, actor, opName, ateattr.ActorStateDeleted)
|
|
}
|
|
|
|
func logActorState(ctx context.Context, actor *ateapipb.Actor, opName, state string) {
|
|
attrs := ateattr.ActorLogAttrs(resources.ActorAttributionFromActor(actor))
|
|
attrs = append(attrs,
|
|
slog.String(string(ateattr.ActorOperationNameKey), ateattr.NormalizeOperationName(opName)),
|
|
slog.String(string(ateattr.ActorStateKey), state))
|
|
actorevent.Log(ctx, actorevent.StateChanged, attrs)
|
|
}
|
|
|
|
// ActorWorkflow handles the workflows for actor's resume / suspend operations.
|
|
type ActorWorkflow struct {
|
|
store actorWorkflowStore
|
|
workerCache *workercache.Cache
|
|
scheduler scheduling.Scheduler
|
|
dialer *AteletDialer
|
|
sandboxConfigLister listersv1alpha1.SandboxConfigLister
|
|
storageClassLister storagev1listers.StorageClassLister
|
|
instruments *Instruments
|
|
egressGatewayAddress string
|
|
pluginRegistry VolumePluginRegistry
|
|
objectStore objectstore.Store
|
|
}
|
|
|
|
// NewActorWorkflow creates a new ActorWorkflow. instruments may be nil.
|
|
//
|
|
// objectStore may be nil, which leaves external snapshots in place instead of
|
|
// copying and releasing them. Only tests that never reach those steps pass nil;
|
|
// ate-api always builds one.
|
|
func NewActorWorkflow(
|
|
store actorWorkflowStore,
|
|
workerCache *workercache.Cache,
|
|
dialer *AteletDialer,
|
|
sandboxConfigLister listersv1alpha1.SandboxConfigLister,
|
|
storageClassLister storagev1listers.StorageClassLister,
|
|
instruments *Instruments,
|
|
egressGatewayAddress string,
|
|
pluginRegistry VolumePluginRegistry,
|
|
objectStore objectstore.Store,
|
|
) *ActorWorkflow {
|
|
return &ActorWorkflow{
|
|
store: store,
|
|
workerCache: workerCache,
|
|
scheduler: scheduling.New(workerCache),
|
|
dialer: dialer,
|
|
sandboxConfigLister: sandboxConfigLister,
|
|
storageClassLister: storageClassLister,
|
|
instruments: instruments,
|
|
egressGatewayAddress: egressGatewayAddress,
|
|
pluginRegistry: pluginRegistry,
|
|
objectStore: objectStore,
|
|
}
|
|
}
|
|
|
|
// actorWorkflowStore enumerates the exact storage methods needed by
|
|
// ActorWorkflow and nothing more.
|
|
type actorWorkflowStore interface {
|
|
GetActor(ctx context.Context, actorRef resources.ActorRef) (*ateapipb.Actor, error)
|
|
UpdateActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(toUpdate *ateapipb.Actor) error) (*ateapipb.Actor, error)
|
|
DeleteActor(ctx context.Context, actorRef resources.ActorRef) (*ateapipb.Actor, error)
|
|
GetWorker(ctx context.Context, name string) (*ateapipb.Worker, error)
|
|
UpdateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapipb.Worker) error) (*ateapipb.Worker, error)
|
|
BindActorToWorker(ctx context.Context, workerName string, assignment *ateapipb.ActorAssignment, admit func(*ateapipb.Worker) error) error
|
|
ReleaseActorFromWorker(ctx context.Context, workerName string, actorUID string) (*ateapipb.Worker, error)
|
|
GetWorkerAssignment(ctx context.Context, workerName, actorUID string) (*ateapipb.ActorAssignment, error)
|
|
FindWorkerHostingActor(ctx context.Context, actorUID string) (string, error)
|
|
// Read from the records rather than the Worker's status: only the service
|
|
// layer attaches assignments on read, and this workflow holds the store.
|
|
ListWorkerAssignments(ctx context.Context, workerName string, opts store.ListOptions) (store.ListResponse[*ateapipb.ActorAssignment], error)
|
|
CreateTag(ctx context.Context, tag *ateapipb.Tag) (*ateapipb.Tag, error)
|
|
GetTag(ctx context.Context, tagRef resources.TagRef) (*ateapipb.Tag, error)
|
|
UpdateTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(toUpdate *ateapipb.Tag) error) (*ateapipb.Tag, error)
|
|
DeleteTag(ctx context.Context, tagRef resources.TagRef) (*ateapipb.Tag, error)
|
|
GetActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef) (*ateapipb.ActorTemplate, error)
|
|
AcquireLease(ctx context.Context, key string) (*store.Lease, error)
|
|
}
|
|
|
|
// WorkerWorkflow handles the multi-step operations on a Worker.
|
|
//
|
|
// Its steps reach across the Actor↔Worker binding, which an ActorWorkflow step
|
|
// does from the other side: releasing the Actor bound to a Worker stays
|
|
// in-process because there is no bind/release RPC.
|
|
type WorkerWorkflow struct {
|
|
store workerWorkflowStore
|
|
}
|
|
|
|
// NewWorkerWorkflow creates a new WorkerWorkflow.
|
|
func NewWorkerWorkflow(store workerWorkflowStore) *WorkerWorkflow {
|
|
return &WorkerWorkflow{store: store}
|
|
}
|
|
|
|
// workerWorkflowStore enumerates the exact storage methods needed by
|
|
// WorkerWorkflow and nothing more.
|
|
type workerWorkflowStore interface {
|
|
GetWorker(ctx context.Context, name string) (*ateapipb.Worker, error)
|
|
UpdateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapipb.Worker) error) (*ateapipb.Worker, error)
|
|
DeleteWorker(ctx context.Context, name string, pre store.DeletePreconditions) (*ateapipb.Worker, error)
|
|
ListWorkerAssignments(ctx context.Context, workerName string, opts store.ListOptions) (store.ListResponse[*ateapipb.ActorAssignment], error)
|
|
GetActor(ctx context.Context, actorRef resources.ActorRef) (*ateapipb.Actor, error)
|
|
UpdateActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(toUpdate *ateapipb.Actor) error) (*ateapipb.Actor, error)
|
|
}
|
|
|
|
// leaseHolder takes the distributed leases that serialize the operations on one
|
|
// resource.
|
|
type leaseHolder interface {
|
|
AcquireLease(ctx context.Context, key string) (*store.Lease, error)
|
|
}
|
|
|
|
// acquireLease takes the lease named by key and returns the context to run
|
|
// under: it is cancelled if the lease is lost. subject names what the lease
|
|
// covers, for the message a caller that loses the race gets.
|
|
func acquireLease(ctx context.Context, holder leaseHolder, key, subject string) (context.Context, *store.Lease, error) {
|
|
lease, err := holder.AcquireLease(ctx, key)
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrLeaseConflict) {
|
|
return nil, nil, status.Errorf(grpcCodes.Aborted, "another operation is in progress for this %s", subject)
|
|
}
|
|
return nil, nil, fmt.Errorf("while acquiring lease: %w", err)
|
|
}
|
|
|
|
return lease.Context(), lease, nil
|
|
}
|
|
|
|
func (w *ActorWorkflow) acquireActorLease(ctx context.Context, actorRef resources.ActorRef) (context.Context, *store.Lease, error) {
|
|
return acquireLease(ctx, w.store, "lease:actor:"+actorRef.Atespace+":"+actorRef.Name, "actor")
|
|
}
|
|
|
|
func acquireTagLease(ctx context.Context, holder leaseHolder, tagRef resources.TagRef) (context.Context, *store.Lease, error) {
|
|
return acquireLease(ctx, holder, "lease:tag:"+tagRef.Atespace+":"+tagRef.Name, "Tag")
|
|
}
|