host: time each startup step up to the end of the first full pass
A fleet box's first reconcile lands about 17 s after its agent starts and the journal says nothing about where the time goes. Every step from agent start to the end of the first full pass now logs one line with its duration, its offset from agent start and, where it reads the deployment store, the store op counts and summed latency: agent: startup: <step> took <d> at +<since start> (store: get N/<t>, ...) Covered: runDuties' wait for the activator startup and each duty before fastConvergeLoop starts; each arming step in fastConvergeLoop; the first tick's wait and parts; each stage of the first passLegs run; and reconcile's own stages through a new ReconcileConfig.Trace hook, set on the first pass only. Later passes keep today's logSlow behaviour. The store is counted through a wrapper that keeps the wrapped store's optional interfaces exactly (plain, fleet door and DirStore shapes); any other store is left unwrapped and its steps are timed only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+850
−13
internal/host/agent.go+84 −6internal/host/changeindex.go+27 −7internal/host/startuptiming.go+430 −0internal/host/startuptiming_test.go+289 −0internal/provision/reconcile.go+20 −0
Intent
Attributed to this commit: 17.0 g CO₂e (1,967,322 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-first-reconcile-speed, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 7d4920c78..dd83106ec 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -243,6 +243,8 @@ func dataDirFrom(getenv func(string) string) string { |
| // account or region IMDS did not answer within 2 seconds is asked for |
| // again every minute. |
| func RunAgent(args []string) { |
| + // The instant every startup timing line is measured from (startuptiming.go). |
| + markAgentStart(time.Now()) |
| groupBoot, err := loadGroupConfiguration(os.Getenv) |
| if err != nil { |
| log.Fatal(err) |
| @@ -996,6 +998,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| dutiesDone := make(chan struct{}) |
| runDuties := func() { |
| defer close(dutiesDone) |
| + // Startup timing: each duty below runs in turn before the fast |
| + // converge loop starts, so each is timed. |
| + duties := newStartupLog().steps("duties: ", nil) |
| select { |
| case <-started: |
| case <-startupCtx.Done(): |
| @@ -1004,6 +1009,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| if startupCtx.Err() != nil { |
| return |
| } |
| + duties.done("wait for the activator startup") |
| // Fleet box binding publish, startup half (customer-fleets plan, Task 6): |
| // a one-shot pass over every route already resident in this box's local |
| @@ -1021,6 +1027,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| } |
| go publishResidentFleetBindings(fleetStore, identity.Fleet, identity.Label, reg) |
| } |
| + duties.done("fleet bindings") |
| // Scheduled work (schedule spec §6.2/§6.3), built ONCE here and shared by |
| // all three legs below: the seed and the fast leg in fastConvergeLoop, the |
| @@ -1059,6 +1066,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| if sd != nil { |
| sd.runner.Start(context.Background()) // runs until the process ends, like every loop below |
| } |
| + duties.done("schedule") |
| serialClaims := make(chan struct{}, 1) |
| regionalReport := func(err error) { log.Printf("agent: regional claims: %v", err) } |
| if hostwrite.Enabled(claimEntryEnv(claimCtx)) && moves.Enabled(os.Getenv) { |
| @@ -1067,13 +1075,16 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| if err := claims.startRegional(agentCtx, serialClaims, regionalReport); err != nil { |
| log.Fatalf("agent: regional claims: %v", err) |
| } |
| + duties.done("regional claims") |
| // The relocation pass (stage B Task 10): it says itself what it started. |
| startRelocationPass(agentCtx, claimCtx, claims, reg, svc) |
| + duties.done("relocation pass") |
| // The change index (S3 change-index design §4): armed before the |
| // loops that read through it, with its backstop running from here. |
| // Without an index the backstop loop handles early full-pass requests. |
| v := armChangeIndex(agentCtx, os.Getenv, openDeployStore) |
| + duties.done("change index") |
| // Requested here, not in the backstop loop: that loop starts only |
| // once the HA ingress startup pass returns, tens of seconds later. |
| requestBootFullPass(v, &backstopFullDue) |
| @@ -1088,6 +1099,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // box), before any loop that reconciles. |
| admission.armRoles(agentCtx, os.Getenv, metricsBoxLabel(os.Getenv, readMachineID())) |
| armPolicyCache() |
| + duties.done("box roles and policy cache") |
| startDemoWorker(agentCtx, reg, demoData, cfg.Prefix, traffic, stopDemoTraffic, func(w *demoWorker) { |
| w.claimActivator = svc |
| w.wireDemoClaimSnapshot(instancectl.NewClient(controlsock.Path), dd) |
| @@ -1099,6 +1111,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| } |
| servingWorker.Store(w) |
| }) |
| + duties.done("demo worker") |
| go adoptLoop(reg, svc, sd, claims.Writes) |
| go fastConvergeLoop(reg, svc, sd, claims.Writes, serialClaims, bs, boxJudge, claims.Providers.Provision) |
| if logSink != nil { |
| @@ -1337,6 +1350,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| serveHADrainSocket(healthCtx, haDrainSocketPath, driver) |
| }() |
| } |
| + newStartupLog().at("edge ready, tunnel loop starting") |
| go tunnelLoop(e, tunnelDrain) |
| // The home side of a linked deployment (linked deployments spec |
| // §6.2): a second, registry-driven loop that dials the link's hub |
| @@ -2261,8 +2275,15 @@ func reconcileSerializedWith(ctx context.Context, s release.Store, reg *registry |
| // been seen. The report is fresh per pass (ReconcileReport is overwritten). |
| // Sidecar records decide no host's catch: sidecars are never published. |
| func reconcileSerializedAuth(ctx context.Context, s release.Store, reg *registry.Registry, cfg provision.ReconcileConfig, w *movesWorker, auth *assetAuthority) error { |
| + // The first pass's stage timing (passLegs.startup); nil otherwise. |
| + trace := func(stage string) { |
| + if cfg.Trace != nil { |
| + cfg.Trace(stage) |
| + } |
| + } |
| reconcileMu.Lock() |
| defer reconcileMu.Unlock() |
| + trace("lock wait") |
| if cfg.WithdrawPool == nil { |
| cfg.WithdrawPool = preparePoolWithdrawal |
| cfg.PoolWithdrawn = finishPoolWithdrawal |
| @@ -2287,6 +2308,7 @@ func reconcileSerializedAuth(ctx context.Context, s release.Store, reg *registry |
| // read from s afterwards. Disarmed, or when the view cannot vouch, rs is |
| // s and the pass walks the bucket as before. |
| rs, epoch, cached := viewStore(ctx, s) |
| + trace("record view") |
| source, complete := provision.DepartureSource(rs) |
| walkStarted := time.Now() |
| if !cached { |
| @@ -2338,6 +2360,7 @@ func reconcileSerializedAuth(ctx context.Context, s release.Store, reg *registry |
| // Sessions ride them too (rootfs apps Plan 6 Task 12): the worker notes |
| // every in-scope record with a session marker. |
| cfg = withInteractiveHook(cfg) |
| + trace("pass setup") |
| var rep provision.ReconcileReport |
| instances := cfg |
| instances.Report = &rep |
| @@ -2347,6 +2370,7 @@ func reconcileSerializedAuth(ctx context.Context, s release.Store, reg *registry |
| err := provision.Reconcile(ctx, rs, reg, instances) |
| auth.recordsPass(start, rep) |
| err = errors.Join(err, provision.ReconcileSidecars(ctx, rs, reg, cfg)) |
| + trace("sidecars") |
| if err == nil && cfg.PolicyScope == nil && boxDepartureInventory.Snapshot().Complete { |
| armedFixedAdmission.Load().observe(groupadmission.Facts{Reconciled: true}) |
| } |
| @@ -2906,6 +2930,11 @@ type fastDeps struct { |
| // the agent armed (restartGainSeed), so the first restart request after |
| // a fresh box comes up is acted on. nil = not armed. |
| restartGain func(ctx context.Context, now time.Time) |
| + |
| + // startup times the parts of the first tick after the agent starts |
| + // (startuptiming.go); nil on every other tick, where its calls do |
| + // nothing. |
| + startup *startupSteps |
| } |
| // canaryRead is one canary group's last good pointer read: the head it |
| @@ -3357,13 +3386,17 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| if d.coordinator != nil { |
| d.coordinator.SignalTick() |
| } |
| + d.startup.done("replica workers") |
| // The index is observed BEFORE any pass this tick runs, so a pass covers |
| // at least what was observed and indexActed can take it afterwards. |
| obs, indexOK := d.observeIndex(ctx) |
| + d.startup.done("change index") |
| if err := d.movedReader.pass(ctx, d.store, d.reg, d.pub, now); err != nil { |
| log.Printf("agent: demo moved: %v", err) |
| } |
| + d.startup.done("moved reader") |
| armedBoxRoleReader.Load().pass(ctx, now) |
| + d.startup.done("box role reader") |
| // Before the serial read, on every tick: an app this box gained since the |
| // agent armed gets its restart baseline now, while nobody has asked for |
| // anything, rather than on the serial move that carries the first request |
| @@ -3372,8 +3405,10 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| if d.restartGain != nil { |
| d.restartGain(ctx, now) |
| } |
| + d.startup.done("restart gain") |
| fullRan := false |
| doc, _, err := release.ReadSerial(ctx, d.store) |
| + d.startup.done("serial read") |
| switch { |
| case err != nil: |
| if !d.serialBroken { |
| @@ -3406,6 +3441,7 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| } |
| d.runFull(ctx) |
| fullRan = true |
| + d.startup.done("full pass") |
| if d.restartLeg != nil { |
| d.restartLeg(ctx) |
| } |
| @@ -3455,6 +3491,7 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| } |
| d.lastSerial = doc.Serial |
| d.lastFull = now |
| + d.startup.done("serial move legs") |
| } |
| } |
| @@ -3464,9 +3501,11 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| d.runFull(ctx) |
| fullRan = true |
| d.lastFull = now |
| + d.startup.done("full pass") |
| } |
| // An index-only change runs the scoped pass (spec §4.5). |
| d.indexTick(ctx, now, obs, indexOK, fullRan) |
| + d.startup.done("index tick") |
| // The self-update tick, outside the serial switch and before the sweep's |
| // early return: it is what runs a spread deadline down and re-touches an |
| @@ -3482,11 +3521,13 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| if d.mintLeg != nil { |
| d.mintLeg(ctx) |
| } |
| + d.startup.done("system tick and mint asker") |
| members := d.fastMembers(now) |
| if len(members) == 0 { |
| return // zero store reads: no PassFilter, no bake-clock write |
| } |
| + defer d.startup.done(fmt.Sprintf("sweep of %d routes", len(members))) |
| defer logSlow("fast sweep", time.Now(), fmt.Sprintf("%d routes", len(members))) |
| member := map[string]bool{} |
| for _, h := range members { |
| @@ -3672,6 +3713,13 @@ func (d *fastDeps) indexTick(ctx context.Context, now time.Time, obs map[string] |
| // Thin and untested by convention, like adoptLoop/statusLoop — the tick's |
| // whole decision lives in fastTick/fastMembers, which are tested. |
| func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *scheduleDeps, writes hostwrite.Config, serialNotify chan<- struct{}, bs *buildStates, judge *provision.LifetimeJudge, configure ...func(*provision.ReconcileConfig)) { |
| + // Startup timing (startuptiming.go): every step before the loop arms, |
| + // the first tick and the first full pass each get a line. The seeds |
| + // read through a counting wrapper (seedStore); what is kept for the |
| + // loop's life holds the plain store. |
| + startup := newStartupLog() |
| + startup.at("fast converge loop entered") |
| + arming := startup.steps("arming: ", nil) |
| // Every pass this loop runs carries the box's judge (newBoxJudge). |
| ctx := provision.WithLifetimes(context.Background(), judge) |
| store, err := openDeployStore(ctx) |
| @@ -3679,6 +3727,9 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| declinedHoldsStay("no deploy store") |
| return // adoptLoop already logged this |
| } |
| + seedStore, seedOps := countStore(store) |
| + arming.done("deploy store") |
| + arming.count(seedOps) |
| pub, err := release.ParsePublicKey(os.Getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY") |
| if err != nil { |
| declinedHoldsStay("no release key") |
| @@ -3731,6 +3782,7 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| // (spec §11). |
| restartMem.pub = pub |
| restartMem.retryHost = rolloutRetryHost() |
| + arming.done("pass options") |
| // The declined box's pointer pass (Task 10, ruling 194): `carlos promote |
| // --retry` clears a record, a signed rollback a marker, read through |
| // the same verified pointer read the armed scheduler uses, at most |
| @@ -3740,7 +3792,9 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| return release.Channel(ctx, store, pub, acct, app, channel) |
| }) |
| } |
| - restartSeed(ctx, reg, store, dd, restartMem) |
| + arming.done("held holds") |
| + restartSeed(ctx, reg, seedStore, dd, restartMem) |
| + arming.done("restart seed") |
| // The seed alone is not enough on a fresh box: its agent arms before |
| // reconcile has minted a route, so the seed sees no apps, and the leg |
| // runs only on a serial move. The gain hook baselines each app as its |
| @@ -3748,24 +3802,29 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| // after a replacement box comes up is acted on, not taken as the |
| // baseline. |
| restartGain, restartLeg := armRestartLegs(reg, store, dd, restartMem, bounceFn(svc), wakeFn(svc)) |
| + arming.done("restart legs") |
| // The sidecar wake leg's own memory, seeded the same way and for the |
| // same reason: one silent read per served sidecar at arming so the |
| // FIRST wake request after a boot is acted on rather than swallowed as |
| // the baseline (sidecarWakeSeed's own doc comment). |
| sidecarWakeMem := newSidecarWakeMemory(writes.Enabled) |
| - sidecarWakeSeed(ctx, reg, store, sidecarWakeMem) |
| + sidecarWakeSeed(ctx, reg, seedStore, sidecarWakeMem) |
| sidecarWake := wakeFn(svc) |
| + arming.done("sidecar wake seed") |
| // The moves hold view, built before the converge below: that converge |
| // runs before the first moves pass, and an unbuilt view freezes every |
| // host (moves spec §9.4). Nothing with the Phase 1 switch off. |
| - refreshMovesHolds(ctx, store) |
| + refreshMovesHolds(ctx, seedStore) |
| + arming.done("moves holds") |
| // The offline keep view, likewise before any reconcile pass: once it is |
| // read, keep answers false for every host with no offline move, so the |
| // first pass removes what it always has (movesoffline.go). |
| - refreshOfflineView(ctx, store, armedOfflineView()) |
| + refreshOfflineView(ctx, seedStore, armedOfflineView()) |
| + arming.done("offline view") |
| // carlos run's boot pass (run spec §5.2, index item 2): reconcile's |
| // first pass is a minute away and the CLI expires a run at 60 s. |
| runRunsBootPass(ctx) |
| + arming.done("runs boot pass") |
| // The schedule converge's own seed, on restartSeed's precedent and for the |
| // same shape of reason: the leg below runs only on a serial MOVE, so |
| // without one pass here a box that booted after the bump would carry no |
| @@ -3776,6 +3835,7 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| if err := sd.converge(ctx); err != nil { |
| log.Printf("agent: schedule converge (start): %v", err) |
| } |
| + arming.done("schedule converge") |
| d.restart = restart |
| d.passOpts = opts |
| // The scheduler's pass with CARLOS_SWAP=overlap armed, nothing while |
| @@ -3791,7 +3851,7 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| // making it — and it is what lets a recovery promote through the console |
| // converge immediately even mid-hold. |
| legs := &passLegs{store: store, reg: reg, pub: pub, optDir: optDir, restart: restart, opts: opts, |
| - priv: priv, dd: dd, svc: svc, writes: writes, bs: bs, |
| + priv: priv, dd: dd, svc: svc, writes: writes, bs: bs, startup: startup, |
| cfg: func() provision.ReconcileConfig { |
| return BoxProvisionConfig(reg, os.Getenv, judge, configure) |
| }} |
| @@ -3840,6 +3900,7 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| // ever fetches into /data and writes a request. It lives here rather than |
| // in a loop of its own because the spread deadline needs a seconds |
| // cadence to run down on, and this is the loop that already has one. |
| + arming.done("loop wiring") |
| d.systemLeg = newSystemLeg(store, pub, os.Getenv, dd, optDir) |
| if d.systemLeg != nil { |
| d.systemLeg.readers = cachedGroupReaders |
| @@ -3848,13 +3909,30 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| // (re)starts under an already-promoted pointer would otherwise sit on the |
| // old build for up to an hour with nobody to bump the serial. observe |
| // handles "no pointer" itself, which is every deployment before its first |
| - // `carlos system update`. |
| + // `carlos system update`. Read through the counting wrapper for |
| + // this one observe only. |
| + d.systemLeg.store = seedStore |
| d.systemLeg.observe(ctx) |
| + d.systemLeg.store = store |
| } |
| + arming.done("system pointer") |
| + arming.total("total") |
| log.Printf("agent: fast converge loop armed (2s + jitter: serial poll + canary/* + unstaged routes + system pointer)") |
| + first := true |
| for { |
| time.Sleep(fastTickEvery + rand.N(time.Second)) |
| + if !first { |
| + fastTick(ctx, d, time.Now()) |
| + continue |
| + } |
| + // The first tick, timed part by part, its own reads counted. |
| + first = false |
| + arming.done("first tick wait") |
| + tickStore, tickOps := countStore(store) |
| + d.store, d.startup = tickStore, startup.steps("first tick: ", tickOps) |
| fastTick(ctx, d, time.Now()) |
| + d.startup.total("total") |
| + d.store, d.startup = store, nil |
| } |
| } |
diff --git a/internal/host/changeindex.go b/internal/host/changeindex.go| index 5cce83ff3..558fbea6c 100644 |
| --- a/internal/host/changeindex.go |
| +++ b/internal/host/changeindex.go |
| @@ -376,6 +376,12 @@ type passLegs struct { |
| writes hostwrite.Config |
| bs *buildStates |
| cfg func() provision.ReconcileConfig // read per pass, as provisionTickConfig always was |
| + |
| + // startup, when set, times the first run's stages and reconcile's own |
| + // stages, one line each with the store ops each made |
| + // (startuptiming.go). Later runs log only when slow, as before. |
| + startup *startupLog |
| + firstRan atomic.Bool |
| } |
| // passAfterReconcileHook, when set, runs in every pass right after its |
| @@ -411,15 +417,29 @@ func (l *passLegs) run(ctx context.Context, what string, keep func(registry.Rout |
| // journal says WHICH stage held a promote back. |
| var took []string |
| t := time.Now() |
| + // The first run after start reads through a counting wrapper and logs |
| + // every stage; store is l.store on every other run. |
| + store := l.store |
| + var stages *startupSteps |
| + if l.startup != nil && l.firstRan.CompareAndSwap(false, true) { |
| + var ops *storeCounter |
| + store, ops = countStore(l.store) |
| + stages = l.startup.steps("first pass: ", ops) |
| + defer stages.total("total") |
| + } |
| mark := func(name string) { |
| took = append(took, fmt.Sprintf("%s %s", name, time.Since(t).Round(100*time.Millisecond))) |
| t = time.Now() |
| + stages.done(name) |
| } |
| defer func(start time.Time) { logSlow(what, start, strings.Join(took, ", ")) }(time.Now()) |
| cfg := l.cfg() |
| cfg.PolicyScope = policyScope |
| - if err := reconcileSerialized(ctx, l.store, l.reg, cfg); err != nil { |
| + if stages != nil { |
| + cfg.Trace = stages.nested("reconcile: ").done |
| + } |
| + if err := reconcileSerialized(ctx, store, l.reg, cfg); err != nil { |
| log.Printf("agent: fast converge reconcile: %v", err) |
| } |
| mark("reconcile") |
| @@ -434,19 +454,19 @@ func (l *passLegs) run(ctx context.Context, what string, keep func(registry.Rout |
| l.bs.refreshKept(ctx, keep) |
| mark("build states") |
| } |
| - telemetryPass(ctx, l.store, l.reg) |
| + telemetryPass(ctx, store, l.reg) |
| mark("telemetry") |
| // The plans pass is box-wide (the marker, then every served account's |
| // limits record, published as one whole snapshot), so a scoped pass |
| // leaves it out: the full pass, the instances floor and the backstop's |
| // full pass run it. |
| if keep == nil { |
| - plansPass(ctx, l.store, l.reg, os.Getenv) |
| + plansPass(ctx, store, l.reg, os.Getenv) |
| mark("plans") |
| } |
| // The moves pass takes its own snapshot inside w.pass (spec §4.3): it |
| // is handed the plain store, never this pass's reconcile snapshot. |
| - runMovesPass(ctx, l.store) |
| + runMovesPass(ctx, store) |
| mark("moves") |
| runRunsPass(ctx) |
| mark("runs") |
| @@ -471,17 +491,17 @@ func (l *passLegs) run(ctx context.Context, what string, keep func(registry.Rout |
| // the domain claims, not the record families, so they read the |
| // bucket. The pass's report feeds the box's domain confirmed time |
| // (edge asset cache design §4.2). |
| - if err := aliasPassReporting(ctx, l.store, l.reg, &aliasClaimCache, boxAssetAuthority, cfg.Region); err != nil { |
| + if err := aliasPassReporting(ctx, store, l.reg, &aliasClaimCache, boxAssetAuthority, cfg.Region); err != nil { |
| log.Printf("agent: fast converge alias pass: %v", err) |
| } |
| mark("aliases") |
| } |
| - if err := release.PassFilter(ctx, l.reg, l.store, l.pub, l.optDir, l.restart, keep, l.opts...); err != nil { |
| + if err := release.PassFilter(ctx, l.reg, store, l.pub, l.optDir, l.restart, keep, l.opts...); err != nil { |
| log.Printf("agent: fast converge adopt pass: %v", err) |
| } |
| mark("adopt") |
| if l.priv != nil { |
| - if err := syncExecSerializedFiltered(ctx, keep, l.reg, l.store, l.priv, l.dd, l.svc, l.writes); err != nil { |
| + if err := syncExecSerializedFiltered(ctx, keep, l.reg, store, l.priv, l.dd, l.svc, l.writes); err != nil { |
| log.Printf("agent: fast converge config sync: %v", err) |
| } |
| mark("config") |
diff --git a/internal/host/startuptiming.go b/internal/host/startuptiming.go| new file mode 100644 |
| index 000000000..88bb34a50 |
| --- /dev/null |
| +++ b/internal/host/startuptiming.go |
| @@ -0,0 +1,430 @@ |
| +package host |
| + |
| +// Startup timing (fleet first reconcile, Task 1). A fleet box's first |
| +// reconcile landed about 17 s after its agent started, and nothing in the |
| +// journal said where the time went. These helpers print one line per step |
| +// from agent start to the end of the first full pass: |
| +// |
| +// agent: startup: <step> took <d> at +<since start> (store: get N/<t>, list N/<t>, dirs N/<t>) |
| +// |
| +// "at" is the step's END, as an offset from agent start, so the lines read |
| +// as a timeline in journal order. The store part counts only the deployment |
| +// store operations made through an opCountingStore during that step, and is |
| +// left off when there were none or the store could not be counted. |
| +// |
| +// Steady state prints nothing new: every caller below builds its lines for |
| +// the first pass after start only. |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "log" |
| + "strings" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// processStart is when this package was initialised, the fallback agent |
| +// start for a process that never ran RunAgent (tests, the CLI). |
| +var processStart = time.Now() |
| + |
| +// agentStartAt is the agent's start instant, set once at the top of |
| +// RunAgent. A pointer to a time.Time so the monotonic reading survives. |
| +var agentStartAt atomic.Pointer[time.Time] |
| + |
| +// markAgentStart records t as the agent's start. |
| +func markAgentStart(t time.Time) { agentStartAt.Store(&t) } |
| + |
| +// agentStart is the agent's start instant, or the process's when RunAgent |
| +// has not marked one. |
| +func agentStart() time.Time { |
| + if t := agentStartAt.Load(); t != nil { |
| + return *t |
| + } |
| + return processStart |
| +} |
| + |
| +// ---- store op counts -------------------------------------------------------- |
| + |
| +type storeOp int |
| + |
| +const ( |
| + opGet storeOp = iota |
| + opList |
| + opDirs |
| + opPut |
| + opDelete |
| + numStoreOps |
| +) |
| + |
| +var storeOpNames = [numStoreOps]string{"get", "list", "dirs", "put", "delete"} |
| + |
| +// storeOps is a snapshot of a storeCounter: per op, how many calls and their |
| +// summed wall time. |
| +type storeOps struct { |
| + n [numStoreOps]int64 |
| + t [numStoreOps]time.Duration |
| +} |
| + |
| +// minus is o less an earlier snapshot p: the ops made between the two. |
| +func (o storeOps) minus(p storeOps) storeOps { |
| + var d storeOps |
| + for i := range d.n { |
| + d.n[i] = o.n[i] - p.n[i] |
| + d.t[i] = o.t[i] - p.t[i] |
| + } |
| + return d |
| +} |
| + |
| +// String is "get N/<t>, list N/<t>, ..." over the ops with any calls, or "" |
| +// when there were none. |
| +func (o storeOps) String() string { |
| + var parts []string |
| + for i, name := range storeOpNames { |
| + if o.n[i] > 0 { |
| + parts = append(parts, fmt.Sprintf("%s %d/%s", name, o.n[i], o.t[i].Round(time.Millisecond))) |
| + } |
| + } |
| + return strings.Join(parts, ", ") |
| +} |
| + |
| +// storeCounter is the live counts an opCountingStore adds to. Safe for |
| +// concurrent use; a nil counter counts nothing and snapshots as zero. |
| +type storeCounter struct { |
| + n [numStoreOps]atomic.Int64 |
| + t [numStoreOps]atomic.Int64 // nanoseconds |
| +} |
| + |
| +func (c *storeCounter) record(op storeOp, start time.Time) { |
| + c.n[op].Add(1) |
| + c.t[op].Add(int64(time.Since(start))) |
| +} |
| + |
| +func (c *storeCounter) snapshot() storeOps { |
| + var o storeOps |
| + if c == nil { |
| + return o |
| + } |
| + for i := range o.n { |
| + o.n[i] = c.n[i].Load() |
| + o.t[i] = time.Duration(c.t[i].Load()) |
| + } |
| + return o |
| +} |
| + |
| +// ---- the counting wrapper --------------------------------------------------- |
| + |
| +// opCountingStore is a release.Store that counts and times every call it |
| +// passes to the store it wraps. Only the five Store methods: it is the |
| +// wrapper for a store with none of release's optional interfaces. |
| +// countStore picks the shape that matches the wrapped store exactly. |
| +type opCountingStore struct { |
| + inner release.Store |
| + c *storeCounter |
| +} |
| + |
| +func (s *opCountingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + defer s.c.record(opGet, time.Now()) |
| + return s.inner.Get(ctx, key) |
| +} |
| + |
| +func (s *opCountingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + defer s.c.record(opPut, time.Now()) |
| + return s.inner.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (s *opCountingStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + defer s.c.record(opList, time.Now()) |
| + return s.inner.List(ctx, prefix) |
| +} |
| + |
| +func (s *opCountingStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + defer s.c.record(opDirs, time.Now()) |
| + return s.inner.ListDirs(ctx, prefix) |
| +} |
| + |
| +func (s *opCountingStore) Delete(ctx context.Context, key string) error { |
| + defer s.c.record(opDelete, time.Now()) |
| + return s.inner.Delete(ctx, key) |
| +} |
| + |
| +// open counts an Open as a get. The time is to the reader's return, not |
| +// to the end of the body. |
| +func (s *opCountingStore) open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + defer s.c.record(opGet, time.Now()) |
| + return s.inner.(release.Opener).Open(ctx, key) |
| +} |
| + |
| +func (s *opCountingStore) listETags(ctx context.Context, prefix string) ([]release.KeyETag, error) { |
| + defer s.c.record(opList, time.Now()) |
| + return s.inner.(release.ETagLister).ListETags(ctx, prefix) |
| +} |
| + |
| +// doorCountingStore is the shape of the fleet store door (fleetapi): Store, |
| +// Opener and ETagLister. |
| +type doorCountingStore struct{ *opCountingStore } |
| + |
| +func (s doorCountingStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + return s.open(ctx, key) |
| +} |
| + |
| +func (s doorCountingStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) { |
| + return s.listETags(ctx, prefix) |
| +} |
| + |
| +// dirCountingStore is the shape of release.DirStore, the single-box and test |
| +// store: every optional interface DirStore implements, forwarded. |
| +type dirCountingStore struct{ *opCountingStore } |
| + |
| +func (s dirCountingStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + return s.open(ctx, key) |
| +} |
| + |
| +func (s dirCountingStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) { |
| + return s.listETags(ctx, prefix) |
| +} |
| + |
| +func (s dirCountingStore) PutFrom(ctx context.Context, key string, body io.ReadSeeker, size int64, ifMatch string) (string, error) { |
| + defer s.c.record(opPut, time.Now()) |
| + return s.inner.(release.PutStreamer).PutFrom(ctx, key, body, size, ifMatch) |
| +} |
| + |
| +func (s dirCountingStore) ListPage(ctx context.Context, prefix, startAfter string, limit int) ([]string, error) { |
| + defer s.c.record(opList, time.Now()) |
| + return s.inner.(release.PageLister).ListPage(ctx, prefix, startAfter, limit) |
| +} |
| + |
| +func (s dirCountingStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + defer s.c.record(opList, time.Now()) |
| + return s.inner.(release.ModLister).ListMod(ctx, prefix) |
| +} |
| + |
| +func (s dirCountingStore) ListSizes(ctx context.Context, prefix string) ([]release.KeySize, error) { |
| + defer s.c.record(opList, time.Now()) |
| + return s.inner.(release.SizeLister).ListSizes(ctx, prefix) |
| +} |
| + |
| +func (s dirCountingStore) GetIfChanged(ctx context.Context, key, etag string) ([]byte, string, bool, error) { |
| + defer s.c.record(opGet, time.Now()) |
| + return s.inner.(release.ConditionalGetter).GetIfChanged(ctx, key, etag) |
| +} |
| + |
| +func (s dirCountingStore) DeleteIfMatch(ctx context.Context, key, etag string) error { |
| + defer s.c.record(opDelete, time.Now()) |
| + return s.inner.(release.ConditionalDeleter).DeleteIfMatch(ctx, key, etag) |
| +} |
| + |
| +func (s dirCountingStore) DeleteRevision(ctx context.Context, key, etag string) error { |
| + defer s.c.record(opDelete, time.Now()) |
| + return s.inner.(release.IndexedDeleter).DeleteRevision(ctx, key, etag) |
| +} |
| + |
| +// IndexDeletion bumps the change index: a read and a write, counted as a put. |
| +func (s dirCountingStore) IndexDeletion(ctx context.Context, key string) error { |
| + defer s.c.record(opPut, time.Now()) |
| + return s.inner.(release.IndexedDeleter).IndexDeletion(ctx, key) |
| +} |
| + |
| +func (s dirCountingStore) DeleteKeys(ctx context.Context, keys []string) error { |
| + defer s.c.record(opDelete, time.Now()) |
| + return s.inner.(release.BatchDeleter).DeleteKeys(ctx, keys) |
| +} |
| + |
| +// The optional interfaces callers type-assert a Store on. A wrapper must |
| +// answer each assertion as the wrapped store would: a wrapper that has an |
| +// extension the store lacks, or lacks one it has, changes what its caller |
| +// does. So countStore wraps only a store whose set is exactly one of the |
| +// shapes above, and returns any other store as it is, uncounted. |
| +const ( |
| + extOpener storeExt = 1 << iota |
| + extPutStreamer |
| + extPageLister |
| + extModLister |
| + extSizeLister |
| + extConditionalGetter |
| + extETagLister |
| + extConditionalDeleter |
| + extIndexedDeleter |
| + extBatchDeleter |
| + extStampedGetter |
| + extCountedDirLister |
| + extVersionPager |
| + extVersionDeleter |
| + extVersionDirLister |
| + extBucketListDirs |
| + extAppMutationRunner |
| +) |
| + |
| +type storeExt uint32 |
| + |
| +const ( |
| + plainShape = storeExt(0) |
| + doorShape = extOpener | extETagLister |
| + dirShape = extOpener | extPutStreamer | extPageLister | extModLister | extSizeLister | |
| + extConditionalGetter | extETagLister | extConditionalDeleter | extIndexedDeleter | extBatchDeleter |
| +) |
| + |
| +func storeExts(s release.Store) storeExt { |
| + var e storeExt |
| + has := func(bit storeExt, ok bool) { |
| + if ok { |
| + e |= bit |
| + } |
| + } |
| + _, ok := s.(release.Opener) |
| + has(extOpener, ok) |
| + _, ok = s.(release.PutStreamer) |
| + has(extPutStreamer, ok) |
| + _, ok = s.(release.PageLister) |
| + has(extPageLister, ok) |
| + _, ok = s.(release.ModLister) |
| + has(extModLister, ok) |
| + _, ok = s.(release.SizeLister) |
| + has(extSizeLister, ok) |
| + _, ok = s.(release.ConditionalGetter) |
| + has(extConditionalGetter, ok) |
| + _, ok = s.(release.ETagLister) |
| + has(extETagLister, ok) |
| + _, ok = s.(release.ConditionalDeleter) |
| + has(extConditionalDeleter, ok) |
| + _, ok = s.(release.IndexedDeleter) |
| + has(extIndexedDeleter, ok) |
| + _, ok = s.(release.BatchDeleter) |
| + has(extBatchDeleter, ok) |
| + _, ok = s.(release.StampedGetter) |
| + has(extStampedGetter, ok) |
| + _, ok = s.(release.CountedDirLister) |
| + has(extCountedDirLister, ok) |
| + _, ok = s.(release.VersionPager) |
| + has(extVersionPager, ok) |
| + _, ok = s.(release.VersionDeleter) |
| + has(extVersionDeleter, ok) |
| + _, ok = s.(release.VersionDirLister) |
| + has(extVersionDirLister, ok) |
| + _, ok = s.(release.BucketListDirs) |
| + has(extBucketListDirs, ok) |
| + _, ok = s.(release.AppMutationRunner) |
| + has(extAppMutationRunner, ok) |
| + return e |
| +} |
| + |
| +// countStore wraps s so its operations are counted, returning the wrapper |
| +// and its counter. A store whose optional interfaces match no wrapper shape |
| +// (the S3 store, a prefix store) comes back unwrapped with a nil counter: |
| +// its steps are timed but not counted. A nil s is returned as it is. |
| +func countStore(s release.Store) (release.Store, *storeCounter) { |
| + if s == nil { |
| + return nil, nil |
| + } |
| + c := &storeCounter{} |
| + base := &opCountingStore{inner: s, c: c} |
| + switch storeExts(s) { |
| + case plainShape: |
| + return base, c |
| + case doorShape: |
| + return doorCountingStore{base}, c |
| + case dirShape: |
| + return dirCountingStore{base}, c |
| + } |
| + return s, nil |
| +} |
| + |
| +// ---- the step logger -------------------------------------------------------- |
| + |
| +// startupLog writes the startup timing lines, as offsets from start. |
| +type startupLog struct { |
| + start time.Time |
| + now func() time.Time |
| + logf func(format string, args ...any) |
| +} |
| + |
| +// newStartupLog is the agent's startup log: offsets from agent start, to |
| +// the journal. |
| +func newStartupLog() *startupLog { |
| + return &startupLog{start: agentStart(), now: time.Now, logf: log.Printf} |
| +} |
| + |
| +func (l *startupLog) offset(t time.Time) time.Duration { return t.Sub(l.start).Round(time.Millisecond) } |
| + |
| +// at logs that what happened now. Nil-safe. |
| +func (l *startupLog) at(what string) { |
| + if l == nil { |
| + return |
| + } |
| + l.logf("agent: startup: %s at +%s", what, l.offset(l.now())) |
| +} |
| + |
| +// steps starts a sequence of steps, each timed from the end of the one |
| +// before (the first from now), every name given prefix. ops is the counter |
| +// of the store the steps read through, or nil. Nil-safe: a nil log gives a |
| +// nil sequence, whose methods do nothing. |
| +func (l *startupLog) steps(prefix string, ops *storeCounter) *startupSteps { |
| + if l == nil { |
| + return nil |
| + } |
| + now := l.now() |
| + o := ops.snapshot() |
| + return &startupSteps{log: l, prefix: prefix, ops: ops, first: now, firstOps: o, last: now, lastOps: o} |
| +} |
| + |
| +// startupSteps is one sequence of timed steps. Not safe for concurrent use: |
| +// each sequence belongs to one goroutine. |
| +type startupSteps struct { |
| + log *startupLog |
| + prefix string |
| + ops *storeCounter |
| + first, last time.Time |
| + firstOps storeOps |
| + lastOps storeOps |
| +} |
| + |
| +// count switches the sequence to counting ops from now on. |
| +func (s *startupSteps) count(ops *storeCounter) { |
| + if s == nil { |
| + return |
| + } |
| + s.ops = ops |
| + s.lastOps = ops.snapshot() |
| + s.firstOps = s.lastOps |
| +} |
| + |
| +// done logs the step that just ended: its time since the previous step |
| +// ended and the store ops made in between. |
| +func (s *startupSteps) done(step string) { |
| + if s == nil { |
| + return |
| + } |
| + now := s.log.now() |
| + o := s.ops.snapshot() |
| + s.line(step, now.Sub(s.last), now, o.minus(s.lastOps)) |
| + s.last, s.lastOps = now, o |
| +} |
| + |
| +// total logs the whole sequence so far as one step. |
| +func (s *startupSteps) total(step string) { |
| + if s == nil { |
| + return |
| + } |
| + now := s.log.now() |
| + s.line(step, now.Sub(s.first), now, s.ops.snapshot().minus(s.firstOps)) |
| +} |
| + |
| +// nested starts a sub-sequence from now, on the same counter, its names |
| +// under this one's prefix. |
| +func (s *startupSteps) nested(prefix string) *startupSteps { |
| + if s == nil { |
| + return nil |
| + } |
| + return s.log.steps(s.prefix+prefix, s.ops) |
| +} |
| + |
| +func (s *startupSteps) line(step string, took time.Duration, now time.Time, ops storeOps) { |
| + msg := fmt.Sprintf("agent: startup: %s%s took %s at +%s", s.prefix, step, took.Round(time.Millisecond), s.log.offset(now)) |
| + if o := ops.String(); o != "" { |
| + msg += " (store: " + o + ")" |
| + } |
| + s.log.logf("%s", msg) |
| +} |
diff --git a/internal/host/startuptiming_test.go b/internal/host/startuptiming_test.go| new file mode 100644 |
| index 000000000..37f7f1ce5 |
| --- /dev/null |
| +++ b/internal/host/startuptiming_test.go |
| @@ -0,0 +1,289 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/fleetapi" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// plainShapedStore is a Store with none of release's optional interfaces. |
| +type plainShapedStore struct{ release.Store } |
| + |
| +// doorShapedStore has the fleet door's shape: Store, Opener and ETagLister. |
| +type doorShapedStore struct{ inner *release.DirStore } |
| + |
| +func (s doorShapedStore) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + return s.inner.Get(ctx, k) |
| +} |
| +func (s doorShapedStore) Put(ctx context.Context, k string, b []byte, m string) (string, error) { |
| + return s.inner.Put(ctx, k, b, m) |
| +} |
| +func (s doorShapedStore) List(ctx context.Context, p string) ([]string, error) { |
| + return s.inner.List(ctx, p) |
| +} |
| +func (s doorShapedStore) ListDirs(ctx context.Context, p string) ([]string, error) { |
| + return s.inner.ListDirs(ctx, p) |
| +} |
| +func (s doorShapedStore) Delete(ctx context.Context, k string) error { return s.inner.Delete(ctx, k) } |
| +func (s doorShapedStore) Open(ctx context.Context, k string) (io.ReadCloser, string, error) { |
| + return s.inner.Open(ctx, k) |
| +} |
| +func (s doorShapedStore) ListETags(ctx context.Context, p string) ([]release.KeyETag, error) { |
| + return s.inner.ListETags(ctx, p) |
| +} |
| + |
| +// modShapedStore has an extension set no wrapper shape matches. |
| +type modShapedStore struct { |
| + release.Store |
| + ml release.ModLister |
| +} |
| + |
| +func (s modShapedStore) ListMod(ctx context.Context, p string) ([]release.KeyMod, error) { |
| + return s.ml.ListMod(ctx, p) |
| +} |
| + |
| +func TestCountingStoreCountsAndDiffs(t *testing.T) { |
| + t.Parallel() |
| + ctx := context.Background() |
| + s, c := countStore(plainShapedStore{release.NewDirStore(t.TempDir())}) |
| + if c == nil { |
| + t.Fatal("a plain store was not wrapped") |
| + } |
| + if _, err := s.Put(ctx, "apps/a/one.json", []byte("{}"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := c.snapshot() |
| + for i := 0; i < 3; i++ { |
| + if _, _, err := s.Get(ctx, "apps/a/one.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, _, err := s.Get(ctx, "apps/a/missing.json"); err == nil { |
| + t.Fatal("fixture: a missing key read") |
| + } |
| + if _, err := s.List(ctx, "apps/"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.ListDirs(ctx, "apps/"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.ListDirs(ctx, "apps/a/"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.Delete(ctx, "apps/a/one.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + all := c.snapshot() |
| + if got := all.n; got != [numStoreOps]int64{opGet: 4, opList: 1, opDirs: 2, opPut: 1, opDelete: 1} { |
| + t.Fatalf("totals %v", got) |
| + } |
| + d := all.minus(before) |
| + if got := d.n; got != [numStoreOps]int64{opGet: 4, opList: 1, opDirs: 2, opPut: 0, opDelete: 1} { |
| + t.Fatalf("diff %v: the put before the snapshot was counted", got) |
| + } |
| + if d.t[opPut] != 0 || d.t[opGet] < 0 { |
| + t.Fatalf("diff times %v", d.t) |
| + } |
| + if re := regexp.MustCompile(`^get 4/[0-9.]+[µnm]?s, list 1/[0-9.]+[µnm]?s, dirs 2/[0-9.]+[µnm]?s, delete 1/[0-9.]+[µnm]?s$`); !re.MatchString(d.String()) { |
| + t.Fatalf("diff renders %q", d.String()) |
| + } |
| + if got := all.minus(all).String(); got != "" { |
| + t.Fatalf("an empty diff renders %q", got) |
| + } |
| + var none *storeCounter |
| + if got := none.snapshot(); got != (storeOps{}) { |
| + t.Fatalf("a nil counter snapshots %v", got) |
| + } |
| +} |
| + |
| +// A wrapper answers every optional-interface assertion as the store it |
| +// wraps does, and a store no shape matches is left alone. |
| +func TestCountingStoreKeepsTheStoreShape(t *testing.T) { |
| + t.Parallel() |
| + door, err := fleetapi.New("https://door.example.com", "fleet/box-1", "token") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := release.NewDirStore(t.TempDir()) |
| + for name, tc := range map[string]struct { |
| + s release.Store |
| + counted bool |
| + }{ |
| + "plain": {plainShapedStore{dir}, true}, |
| + "door": {doorShapedStore{dir}, true}, |
| + "fleet door": {door, true}, |
| + "dir": {dir, true}, |
| + "ci store": {newCICountingStore(t), true}, |
| + "mod only": {modShapedStore{plainShapedStore{dir}, dir}, false}, |
| + "prefix door": {release.NewPrefixStore(door, "fleets/f/"), false}, |
| + } { |
| + got, c := countStore(tc.s) |
| + if (c != nil) != tc.counted { |
| + t.Errorf("%s: counted %v, want %v", name, c != nil, tc.counted) |
| + } |
| + if !tc.counted && got != tc.s { |
| + t.Errorf("%s: an uncounted store was wrapped", name) |
| + } |
| + if storeExts(got) != storeExts(tc.s) { |
| + t.Errorf("%s: wrapper extensions %b, store's %b", name, storeExts(got), storeExts(tc.s)) |
| + } |
| + } |
| + if s, c := countStore(nil); s != nil || c != nil { |
| + t.Fatal("a nil store was wrapped") |
| + } |
| +} |
| + |
| +// The extensions a wrapper forwards are counted under their op. |
| +func TestCountingStoreCountsExtensions(t *testing.T) { |
| + t.Parallel() |
| + ctx := context.Background() |
| + s, c := countStore(release.NewDirStore(t.TempDir())) |
| + if _, err := s.Put(ctx, "apps/a/one.json", []byte("{}"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + rc, _, err := release.OpenObject(ctx, s, "apps/a/one.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rc.Close() |
| + if _, _, _, err := s.(release.ConditionalGetter).GetIfChanged(ctx, "apps/a/one.json", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.(release.ETagLister).ListETags(ctx, "apps/"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.(release.ModLister).ListMod(ctx, "apps/"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := c.snapshot().n; got != [numStoreOps]int64{opGet: 2, opList: 2, opPut: 1} { |
| + t.Fatalf("counts %v", got) |
| + } |
| +} |
| + |
| +// startupCapture is a startupLog on a fake clock that keeps its lines. |
| +type startupCapture struct { |
| + mu sync.Mutex |
| + lines []string |
| + now time.Time |
| +} |
| + |
| +func (c *startupCapture) log(start time.Time) *startupLog { |
| + return &startupLog{start: start, now: func() time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.now |
| + }, logf: func(format string, args ...any) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.lines = append(c.lines, fmt.Sprintf(format, args...)) |
| + }} |
| +} |
| + |
| +func (c *startupCapture) advance(d time.Duration) { c.mu.Lock(); c.now = c.now.Add(d); c.mu.Unlock() } |
| + |
| +func (c *startupCapture) got() []string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return append([]string(nil), c.lines...) |
| +} |
| + |
| +func TestStartupStepsLines(t *testing.T) { |
| + t.Parallel() |
| + start := time.Date(2026, 11, 15, 20, 0, 0, 0, time.UTC) |
| + cl := &startupCapture{now: start.Add(200 * time.Millisecond)} |
| + l := cl.log(start) |
| + ctx := context.Background() |
| + s, c := countStore(plainShapedStore{release.NewDirStore(t.TempDir())}) |
| + |
| + l.at("fast converge loop entered") |
| + steps := l.steps("arming: ", nil) |
| + cl.advance(1500 * time.Millisecond) |
| + steps.done("deploy store") // no counter yet: time only |
| + steps.count(c) |
| + if _, _, err := s.Get(ctx, "control/serial.json"); err == nil { |
| + t.Fatal("fixture: the serial exists") |
| + } |
| + cl.advance(2 * time.Second) |
| + steps.done("restart seed") |
| + sub := steps.nested("reconcile: ") |
| + cl.advance(250 * time.Millisecond) |
| + sub.done("record scan") |
| + steps.total("total") |
| + var nilSteps *startupSteps |
| + nilSteps.done("nothing") // nil-safe |
| + var nilLog *startupLog |
| + nilLog.at("nothing") |
| + if nilLog.steps("x", c) != nil { |
| + t.Fatal("a nil log gave a sequence") |
| + } |
| + |
| + got := cl.got() |
| + want := []*regexp.Regexp{ |
| + regexp.MustCompile(`^agent: startup: fast converge loop entered at \+200ms$`), |
| + regexp.MustCompile(`^agent: startup: arming: deploy store took 1\.5s at \+1\.7s$`), |
| + regexp.MustCompile(`^agent: startup: arming: restart seed took 2s at \+3\.7s \(store: get 1/[0-9.]+[µnm]?s\)$`), |
| + regexp.MustCompile(`^agent: startup: arming: reconcile: record scan took 250ms at \+3\.95s$`), |
| + regexp.MustCompile(`^agent: startup: arming: total took 3\.75s at \+3\.95s \(store: get 1/[0-9.]+[µnm]?s\)$`), |
| + } |
| + if len(got) != len(want) { |
| + t.Fatalf("lines:\n%s", strings.Join(got, "\n")) |
| + } |
| + for i, re := range want { |
| + if !re.MatchString(got[i]) { |
| + t.Errorf("line %d: %q does not match %s", i, got[i], re) |
| + } |
| + } |
| +} |
| + |
| +// The first run of the pass set logs every stage, reconcile's own stages |
| +// among them, with its store ops; a later fast run logs nothing. |
| +func TestFirstPassOnlyLogsStages(t *testing.T) { |
| + w := newCIWorld(t) |
| + disarmView(t) |
| + t.Cleanup(func() { disarmView(t) }) |
| + reg := restartTestRegistry(t) |
| + rcfg := ciReconcileConfig(t) |
| + cl := &startupCapture{now: time.Now()} |
| + legs := &passLegs{store: w.live, reg: reg, optDir: t.TempDir(), dd: t.TempDir(), |
| + startup: cl.log(cl.now), |
| + cfg: func() provision.ReconcileConfig { return rcfg }} |
| + |
| + legs.full(context.Background()) |
| + first := cl.got() |
| + joined := strings.Join(first, "\n") |
| + for _, want := range []string{ |
| + "agent: startup: first pass: reconcile: lock wait took ", |
| + "agent: startup: first pass: reconcile: record scan took ", |
| + "agent: startup: first pass: reconcile: mint took ", |
| + "agent: startup: first pass: reconcile: removal took ", |
| + "agent: startup: first pass: reconcile: sidecars took ", |
| + "agent: startup: first pass: reconcile took ", |
| + "agent: startup: first pass: moves took ", |
| + "agent: startup: first pass: adopt took ", |
| + "agent: startup: first pass: total took ", |
| + } { |
| + if !strings.Contains(joined, want) { |
| + t.Errorf("first run: no line starting %q in:\n%s", want, joined) |
| + } |
| + } |
| + if !regexp.MustCompile(`first pass: reconcile: record scan took \S+ at \+\S+ \(store: [^)]*list \d+/`).MatchString(joined) { |
| + t.Errorf("first run: the record scan carries no store listing:\n%s", joined) |
| + } |
| + if routes, err := reg.List(); err != nil || len(routes) == 0 { |
| + t.Fatalf("fixture: the first pass minted nothing (%v)", err) |
| + } |
| + |
| + legs.full(context.Background()) |
| + if again := cl.got(); len(again) != len(first) { |
| + t.Fatalf("a second run logged:\n%s", strings.Join(again[len(first):], "\n")) |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index 780da7732..c0da6d3c6 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -43,6 +43,11 @@ type ReconcileConfig struct { |
| // HAIngress receives the complete pre-pool record scan; errors revoke its evidence. |
| HAIngress func([]Record, error) |
| + // Trace, when set, is called as each of Reconcile's coarse stages ends, |
| + // with the stage's name. The agent sets it on its first pass after start |
| + // to time the stages; nil everywhere else. |
| + Trace func(stage string) |
| + |
| Departures *DeparturePass |
| ClaimEnabled bool |
| ClaimInstall func(context.Context, ClaimRecord, func(registry.ClaimOwnership) error) error |
| @@ -1459,6 +1464,7 @@ func scanInstanceRecords(ctx context.Context, st release.Store, cfg ReconcileCon |
| // proceeds regardless. |
| func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig) error { |
| cfg.withdrawPools(ctx, s, reg, false) |
| + cfg.trace("pool withdrawal") |
| cfg = withDemoClaimHolds(cfg) |
| if cfg.Now == nil { |
| cfg.Now = time.Now |
| @@ -1480,6 +1486,7 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| } |
| cfg.Departures.family("instance", sc.departureRecords, err == nil && !sc.departureInvalid && !sc.readFailed && !sc.partial && len(sc.unread) == 0 && len(sc.protect) == 0) |
| + cfg.trace("record scan") |
| if err != nil { |
| return err |
| } |
| @@ -1585,6 +1592,7 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| tombs[k] = tombRead{tomb, terr} |
| prefetchMu.Unlock() |
| }) |
| + cfg.trace("manifests and trash markers") |
| // The apps' signed operator policies (#328, #329), for the apps this |
| // pass mints or keeps rows for: those with an in-scope record and a |
| // trash marker read and absent. Read through the cache, so a pass reads |
| @@ -1609,6 +1617,7 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| } |
| policyNow := cfg.Now() |
| policies := newPolicyPass(policyCache.read(ctx, freshStore(s), cfg.ReleasePub, policyApps, policyNow, policyScope), policyNow) |
| + cfg.trace("policies") |
| seedCache := map[acctApp]string{} |
| seedKnown := map[acctApp]bool{} |
| @@ -1829,6 +1838,7 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| } |
| } |
| fp.run() |
| + cfg.trace("forward phase") |
| // --- mint / converge / conflict ------------------------------------------- |
| routes, err := reg.List() |
| @@ -1848,6 +1858,7 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| // A colliding host's journal waits too (given neither): its row is the |
| // instance pass's to leave exactly as it is, the import's included. |
| journalHandled, journaled, journalOK := journalPass(ctx, s, reg, cfg, recs, readFailed, protect, collide) |
| + cfg.trace("import journal") |
| if !journalOK { |
| readFailed = true |
| pr.whole = true // an unread journal could be holding any host's import gate |
| @@ -2387,6 +2398,8 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| } |
| } |
| policies.publish() |
| + cfg.trace("mint") |
| + defer cfg.trace("removal") |
| // --- removal, only when nothing failed to read this pass ------------------ |
| // Three conditions, each load-bearing: Provisioned (the flag — not the |
| @@ -3610,3 +3623,10 @@ func seedJSON(m *Manifest) string { |
| } |
| return string(b) |
| } |
| + |
| +// trace reports that a Reconcile stage ended (ReconcileConfig.Trace). |
| +func (c ReconcileConfig) trace(stage string) { |
| + if c.Trace != nil { |
| + c.Trace(stage) |
| + } |
| +} |