carlos / platform Public

console: End follows the last output; one end row per session; ends in flight stay owned; a daily orphan grant scan (rootfs plan 6 task 11 fix round 1)

The splice waits for both leg writers to finish every accepted frame
before it returns, so the CLI's End never overtakes its last output. An
end whose writes are in flight is held as ending, never pruned and
skipped by the marker phase. Every interactive-end row is written once,
checked in the audit table under one lock: the end step, the sweep
(cleared or replaced markers) and an admission that replaces a dead
marker, which now writes the replaced session's lost row. The orphan
grant scan runs once a day per app in either record-view mode.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6bf1161d086544801f4dd6d8c7971b80fca09a86 parent 419ba4f
10 files changed, +486 −96
  • internal/console/apiinteractive.go +49 −5
  • internal/console/apiinteractive_test.go +65 −8
  • internal/console/apiinteractivebox_test.go +42 −3
  • internal/console/interactivehub.go +59 −9
  • internal/console/jobs_test.go +1 −1
  • internal/console/runsweep.go +72 −32
  • internal/console/runsweep_test.go +171 −35
  • internal/console/server.go +3 −0
  • internal/console/store.go +15 −0
  • internal/provision/rootfs_apps_6_census_test.go +9 −3

Intent

Human

<task-notification> <task-id>bopvn3hhi</task-id> <tool-use-id>toolu_013GtQpFoAMW2zA35J7Yy14r</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bopvn3hhi.output</output-file> <status>completed</status> <summary>Background command "Run Astra review of Plan 6 Task 11" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 19.0 g CO₂e (2,397,463 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-6-interactive, 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/console/apiinteractive.go b/internal/console/apiinteractive.go
index cc24bf631..8a34616a9 100644
--- a/internal/console/apiinteractive.go
+++ b/internal/console/apiinteractive.go
@@ -335,9 +335,22 @@ func (s *Server) admitSession(ctx context.Context, sess *hubSession, token strin
s.cleanupGrant(ctx, sess) // the write may have landed
return failed
}
- _, err = provision.SetRecordInteractive(ctx, s.cfg.Releases, sess.acct, sess.app, sess.host,
- provision.InteractiveAdmit(provision.InteractiveAdmission{ID: sess.id, By: sess.by, Console: s.bootID, PickupBy: sess.pickupBy,
- Live: func(st provision.InteractiveState) bool { return h.live(st, s.bootID) }}))
+ admit := provision.InteractiveAdmit(provision.InteractiveAdmission{ID: sess.id, By: sess.by, Console: s.bootID, PickupBy: sess.pickupBy,
+ Live: func(st provision.InteractiveState) bool { return h.live(st, s.bootID) }})
+ // replaced is the dead marker the landing write replaced, if any: the
+ // marker on the read the write was made from. A retry that finds this
+ // admission's own marker (a lost response) keeps the first read's.
+ var replaced *provision.InteractiveState
+ _, err = provision.SetRecordInteractive(ctx, s.cfg.Releases, sess.acct, sess.app, sess.host, func(rec *provision.Record) error {
+ switch m := rec.Interactive; {
+ case m == nil:
+ replaced = nil
+ case m.ID != sess.id:
+ old := *m
+ replaced = &old
+ }
+ return admit(rec)
+ })
// updateRecord's retry after a lost response finds this admission's own
// marker, live because the id is reserved: that is the admission.
var open *provision.InteractiveOpenError
@@ -358,6 +371,14 @@ func (s *Server) admitSession(ctx context.Context, sess *hubSession, token strin
// Unreachable: only this goroutine releases or ends its id.
log.Printf("console: api interactive %s/%s/%s: %s was not reserved at activation", sess.acct, sess.app, sess.host, sess.id)
}
+ if m := replaced; m != nil && !h.owns(m.ID) {
+ // The replaced session's end row (fix round 1, P2 3): lost, unless
+ // it has one. A session this hub still owns writes its own.
+ if err := s.auditInteractiveEnd(sess.account, sess.app, sess.host, m.By, m.ID,
+ interactive.End{Reason: interactive.EndLost, Ended: time.Now().UTC()}); err != nil {
+ log.Printf("console: api interactive %s/%s/%s: the replaced session %s: %v", sess.acct, sess.app, sess.host, m.ID, err)
+ }
+ }
s.auditActivity(sess.account, sess.app, sess.by, Activity{Action: "interactive-start", TargetType: "instance", Target: sess.host,
Detail: interactiveStartDetail(sess)})
return nil
@@ -452,12 +473,17 @@ func (s *Server) endSession(ws *websocket.Conn, sess *hubSession, e interactive.
err := s.lifetimesStep(context.Background(), true, func(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, interactiveEndTimeout)
defer cancel()
+ if h.beforeEndWrites != nil {
+ h.beforeEndWrites(sess.id)
+ }
return s.endWrites(ctx, sess, e)
})
if err != nil {
log.Printf("console: api interactive %s/%s/%s: end %s (%s) waits for the sweep: %v", sess.acct, sess.app, sess.host, sess.id, e.Reason, err)
h.pend(sess, e)
+ return
}
+ h.endDone(sess)
}
// endWrites are an end's writes: the marker cleared (InteractiveClear: a
@@ -474,8 +500,26 @@ func (s *Server) endWrites(ctx context.Context, sess *hubSession, e interactive.
if err := s.deleteGrant(ctx, sess); err != nil {
return err
}
- s.auditActivity(sess.account, sess.app, sess.by, Activity{Action: "interactive-end", TargetType: "instance", Target: sess.host,
- Detail: interactiveEndDetail(sess.id, e)})
+ return s.auditInteractiveEnd(sess.account, sess.app, sess.host, sess.by, sess.id, e)
+}
+
+// auditInteractiveEnd writes session id's interactive-end row unless one
+// exists already: one terminal row per session, whoever ends it (fix round
+// 1, P2 3). The check reads the audit table itself, not the hub, and the
+// check and the insert run under the hub's endRows lock, so the end step,
+// the sweep and an admission replacing a dead marker never both write.
+func (s *Server) auditInteractiveEnd(acct *Account, app, host, by, id string, e interactive.End) error {
+ h := s.interactive
+ h.endRows.Lock()
+ defer h.endRows.Unlock()
+ done, err := s.store.InteractiveEndRecorded(acct.ID, app, id)
+ if err != nil {
+ return fmt.Errorf("check the end row of %s: %w", id, err)
+ }
+ if !done {
+ s.auditActivity(acct, app, by, Activity{Action: "interactive-end", TargetType: "instance", Target: host,
+ Detail: interactiveEndDetail(id, e)})
+ }
return nil
}
diff --git a/internal/console/apiinteractive_test.go b/internal/console/apiinteractive_test.go
index 025e62c76..08a332fc8 100644
--- a/internal/console/apiinteractive_test.go
+++ b/internal/console/apiinteractive_test.go
@@ -231,7 +231,7 @@ func ixEndRow(t *testing.T, e Event) ixEndDetail {
}
// hubState is what the hub holds for id: "" (nothing), "reserved",
-// "active", "ended" or "pending".
+// "active", "ending" (its end's writes in flight), "pending" or "ended".
func hubState(h *interactiveHub, id string) string {
h.mu.Lock()
defer h.mu.Unlock()
@@ -241,6 +241,9 @@ func hubState(h *interactiveHub, id string) string {
}
return "reserved"
}
+ if _, ok := h.ending[id]; ok {
+ return "ending"
+ }
if _, ok := h.endPending[id]; ok {
return "pending"
}
@@ -657,9 +660,7 @@ func TestPickupWindowExpiresTheSession(t *testing.T) {
if g := ixGrants(t, fx); len(g) != 0 {
t.Fatalf("grants %v left after expiry", g)
}
- if st := hubState(fx.srv.interactive, id); st != "ended" {
- t.Fatalf("hub: %q, want ended", st)
- }
+ ixWaitHub(t, fx.srv.interactive, id, "ended")
fx.srv.interactive.pickupWindow = 0
ws = ixStart(t, fx, fx.alice, ixOpenArgv())
ws.Close()
@@ -682,9 +683,7 @@ func TestCancelledBeforePickup(t *testing.T) {
if g := ixGrants(t, fx); len(g) != 0 {
t.Fatalf("grants %v left after the cancel", g)
}
- if st := hubState(fx.srv.interactive, id); st != "ended" {
- t.Fatalf("hub: %q, want ended", st)
- }
+ ixWaitHub(t, fx.srv.interactive, id, "ended")
}
func TestAdmissionReplacesAMarkerFromAnotherConsoleBoot(t *testing.T) {
@@ -697,8 +696,66 @@ func TestAdmissionReplacesAMarkerFromAnotherConsoleBoot(t *testing.T) {
if rec.Interactive == nil || rec.Interactive.ID == old || rec.Interactive.Console != fx.srv.bootID || rec.Interactive.By != "alice@keymail.dev" {
t.Fatalf("marker %+v, want this boot's session replacing %s", rec.Interactive, old)
}
+ // Fix round 1, P2 3: the replaced session's end row, lost, as bob's.
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || evs[0].Address != "bob@keymail.dev" || evs[0].Target != ixHost {
+ t.Fatalf("end rows %+v, want one for bob's replaced session", evs)
+ }
+ if d := ixEndRow(t, evs[0]); d.ID != old || d.Reason != interactive.EndLost || d.Ended.IsZero() {
+ t.Fatalf("end row %+v, want %s lost", d, old)
+ }
ws.Close()
- ixWaitEvents(t, fx, "interactive-end", 1)
+ ixWaitEvents(t, fx, "interactive-end", 2)
+
+ // A replaced session whose end row exists already gets no second one.
+ const ended = "tty_dddddddddddddddddddddddddd"
+ ixWaitHub(t, fx.srv.interactive, rec.Interactive.ID, "ended")
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk",
+ Interactive: &provision.InteractiveState{ID: ended, By: "bob@keymail.dev", Console: "old", PickupBy: time.Now().Add(time.Minute)}})
+ if err := fx.st.RecordActivity(fx.acctID, "shop", "bob@keymail.dev", Activity{Action: "interactive-end", TargetType: "instance", Target: ixHost,
+ Detail: interactiveEndDetail(ended, interactive.End{Reason: interactive.EndExited, Ended: time.Now().UTC()})}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ ws = ixStart(t, fx, fx.alice, ixOpenArgv())
+ n := 0
+ for _, e := range ixEvents(t, fx, "interactive-end") {
+ if ixEndRow(t, e).ID == ended {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatalf("%d end rows for %s, want its one", n, ended)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 4)
+}
+
+// A pending end's marker is not live, so an admission replaces it; the
+// replaced session's row is its own end step's, written once by the sweep
+// with its own reason, never lost.
+func TestAdmissionLeavesAPendingEndsRowToItsOwner(t *testing.T) {
+ fx := newIxFx(t, "code-ix-pendrow")
+ h := fx.srv.interactive
+ const id = "tty_ffffffffffffffffffffffffff"
+ m := &provision.InteractiveState{ID: id, By: "bob@keymail.dev", Console: fx.srv.bootID, PickupBy: time.Now().Add(time.Minute)}
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Interactive: m})
+ acct, err := fx.st.AccountBySqid(fx.acct)
+ if err != nil || acct == nil {
+ t.Fatal(acct, err)
+ }
+ h.pend(&hubSession{id: id, acct: fx.acct, app: "shop", host: ixHost, by: "bob@keymail.dev", account: acct, pickupBy: m.PickupBy},
+ interactive.End{Reason: interactive.EndExited, Ended: time.Now().UTC()})
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("the admission wrote %+v for a pending end", evs)
+ }
+ ixSweepAt(fx, time.Now())
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || ixEndRow(t, evs[0]).ID != id || ixEndRow(t, evs[0]).Reason != interactive.EndExited {
+ t.Fatalf("end rows %+v, want %s's own exited", evs, id)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 2)
}
// ixAttempt is one client's go at a session, run on its own goroutine.
diff --git a/internal/console/apiinteractivebox_test.go b/internal/console/apiinteractivebox_test.go
index 50ee0348d..6b1b24be0 100644
--- a/internal/console/apiinteractivebox_test.go
+++ b/internal/console/apiinteractivebox_test.go
@@ -593,9 +593,7 @@ func TestSpliceCarriesBothWays(t *testing.T) {
if gs := ixGrants(t, fx); len(gs) != 0 {
t.Fatalf("grants %v left", gs)
}
- if st := hubState(fx.srv.interactive, id); st != "ended" {
- t.Fatalf("hub: %q, want ended", st)
- }
+ ixWaitHub(t, fx.srv.interactive, id, "ended")
// carlos console: the box gets the Open as the CLI sent it, Process
// console and no argv, never the resolved command.
@@ -612,6 +610,47 @@ func TestSpliceCarriesBothWays(t *testing.T) {
ixFinish(t, fx, cli, box, 2)
}
+// End follows every output frame the console accepted (fix round 1, P1):
+// the box sends its last output and its End back to back, and the CLI reads
+// every byte before the End, every time.
+func TestSpliceEndFollowsEveryOutputFrame(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-order")
+ chunk := bytes.Repeat([]byte("y"), interactive.MaxFrame-1)
+ const frames = 8
+ for round := 1; round <= 4; round++ {
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ go func() {
+ for i := 0; i < frames; i++ {
+ if interactive.Send(box, interactive.KindData, chunk) != nil {
+ return
+ }
+ }
+ _ = interactive.SendJSON(box, interactive.KindEnd, interactive.End{Reason: interactive.EndExited})
+ }()
+ got := 0
+ for {
+ k, p, err := ixFrameOf(cli)
+ if err != nil {
+ t.Fatalf("round %d: CLI after %d bytes: %v", round, got, err)
+ }
+ if k == interactive.KindData {
+ got += len(p)
+ continue
+ }
+ if k != interactive.KindEnd {
+ t.Fatalf("round %d: CLI frame %q", round, k)
+ }
+ if want := frames * len(chunk); got != want {
+ t.Fatalf("round %d: the End came after %d bytes of %d", round, got, want)
+ }
+ break
+ }
+ ixWaitEvents(t, fx, "interactive-end", round)
+ }
+}
+
func TestSpliceAppliesBackpressure(t *testing.T) {
fx := newIxFx(t, "code-ixb-pressure")
cli := ixStart(t, fx, fx.alice, ixOpenArgv())
diff --git a/internal/console/interactivehub.go b/internal/console/interactivehub.go
index d0c83e345..0ed22177d 100644
--- a/internal/console/interactivehub.go
+++ b/internal/console/interactivehub.go
@@ -28,9 +28,10 @@ import (
// reserve -> (record CAS) -> activate -> end
// \-> release (the admission failed: no session started)
//
-// end moves an id to ended, or to endPending when its end step did not
-// finish (the gate refused it while draining, or a write failed): the sweep
-// finishes it, then it is ended. An admission whose grant cleanup did not
+// end moves an id to ending while its end step's writes are in flight;
+// they land (ended) or did not finish (the gate refused the step while
+// draining, or a write failed: endPending, which the sweep finishes, then
+// it is ended). Pruning touches only ended ids. An admission whose grant cleanup did not
// finish within OpenWait is pending too, for the grant alone. An id is
// live, for another admission's CAS, while it is reserved or active; never
// once ended or pending.
@@ -46,6 +47,8 @@ type interactiveHub struct {
byHost map[string]string // host -> its active session's id
// ended is each ended id and when it may be pruned: its PickupBy.
ended map[string]time.Time
+ // ending is every ended id whose end step's writes are in flight.
+ ending map[string]bool
// endPending is every ended session whose end step did not finish: the
// sweep makes its writes with this End, then ends it.
endPending map[string]interactive.End
@@ -84,6 +87,12 @@ type interactiveHub struct {
hangupWait time.Duration
boxRegistry func() (consoleRegistry, error)
beforeHandoff func(id string)
+ // beforeEndWrites runs in a session's end step, before its writes.
+ beforeEndWrites func(id string)
+
+ // endRows serializes every interactive-end row's check and insert, so
+ // a session gets one terminal row (auditInteractiveEnd).
+ endRows sync.Mutex
}
// hubSession is one session this console admitted.
@@ -130,6 +139,7 @@ func newInteractiveHub() *interactiveHub {
byID: map[string]*hubSession{},
byHost: map[string]string{},
ended: map[string]time.Time{},
+ ending: map[string]bool{},
endPending: map[string]interactive.End{},
pendingSess: map[string]*hubSession{},
grantOnly: map[string]bool{},
@@ -253,7 +263,9 @@ func (h *interactiveHub) registry(path string) (consoleRegistry, error) {
return openRegistry(path)
}
-// end takes id out of the live set and marks it ended until its PickupBy.
+// end takes id out of the live set. A session's id is ending until its end
+// step's writes land (endDone) or wait for the sweep (pend); any other id is
+// marked ended until now.
// Called as a session ends, before its end step's writes: from then on no
// admission finds it live and the box door finds nothing to attach to.
func (h *interactiveHub) end(id string) {
@@ -267,20 +279,33 @@ func (h *interactiveHub) end(id string) {
delete(h.byHost, sess.host)
}
delete(h.byID, id)
- until = sess.pickupBy
if sess.over != nil {
close(sess.over)
}
+ // Its end step's writes are in flight: owned until they land
+ // (endDone) or wait for the sweep (pend). Never pruned meanwhile.
+ h.ending[id] = true
+ return
}
h.ended[id] = until
}
+// endDone records that an ending session's writes landed: it is ended
+// until its PickupBy.
+func (h *interactiveHub) endDone(sess *hubSession) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ delete(h.ending, sess.id)
+ h.ended[sess.id] = sess.pickupBy
+}
+
// pend records that sess's end step did not finish: the sweep finishes it
// with e.
func (h *interactiveHub) pend(sess *hubSession, e interactive.End) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.ended, sess.id)
+ delete(h.ending, sess.id)
h.endPending[sess.id] = e
h.pendingSess[sess.id] = sess
}
@@ -332,8 +357,9 @@ func (h *interactiveHub) finished(id string) {
const (
hubUnknown = iota // never held here, released, or pruned
hubHeld // reserved or active
+ hubEnding // ended, its end step's writes in flight
hubPending // ended, its end's writes waiting in endPending
- hubEnded // ended, its writes done or under way
+ hubEnded // ended, its writes done
)
// stateOf is what the hub holds of id.
@@ -343,6 +369,9 @@ func (h *interactiveHub) stateOf(id string) int {
if _, ok := h.byID[id]; ok {
return hubHeld
}
+ if h.ending[id] {
+ return hubEnding
+ }
if _, ok := h.endPending[id]; ok {
return hubPending
}
@@ -352,6 +381,17 @@ func (h *interactiveHub) stateOf(id string) int {
return hubUnknown
}
+// owns reports whether this hub owns id's end row: the session is held, or
+// its end's writes are in flight or pending. Only its own end step writes
+// that row; nobody else may write one for it.
+func (h *interactiveHub) owns(id string) bool {
+ switch h.stateOf(id) {
+ case hubHeld, hubEnding, hubPending:
+ return true
+ }
+ return false
+}
+
// prune forgets every ended id whose pickup window has passed by now.
func (h *interactiveHub) prune(now time.Time) {
h.mu.Lock()
@@ -399,11 +439,15 @@ type legWriter struct {
gone chan struct{}
shutOnce sync.Once
stop <-chan struct{}
+ // exited is closed when the writer's goroutine has returned: every
+ // frame it accepted is written (or its leg failed) by then.
+ exited chan struct{}
}
func startLegWriter(ws *websocket.Conn, wait time.Duration, stop <-chan struct{}) *legWriter {
- w := &legWriter{in: make(chan ixFrame), dead: make(chan struct{}), gone: make(chan struct{}), stop: stop}
+ w := &legWriter{in: make(chan ixFrame), dead: make(chan struct{}), gone: make(chan struct{}), stop: stop, exited: make(chan struct{})}
go func() {
+ defer close(w.exited)
for {
select {
case f := <-w.in:
@@ -517,8 +561,14 @@ func (h *interactiveHub) hangupWaitFor() time.Duration {
func (h *interactiveHub) splice(ctx context.Context, sess *hubSession, box *boxConn) interactive.End {
every, lost := h.aliveEvery(), h.aliveLost()
stop := make(chan struct{})
+ var toCLI, toBox *legWriter
defer func() {
close(stop)
+ // End follows every accepted output frame (fix round 1, P1): both
+ // writers finish what they accepted and return before the caller
+ // writes the End, so one goroutine at a time writes each socket.
+ <-toCLI.exited
+ <-toBox.exited
box.ws.Close()
close(box.done)
}()
@@ -531,8 +581,8 @@ func (h *interactiveHub) splice(ctx context.Context, sess *hubSession, box *boxC
}
return e
}
- toCLI := startLegWriter(sess.cli, lost, stop)
- toBox := startLegWriter(box.ws, lost, stop)
+ toCLI = startLegWriter(sess.cli, lost, stop)
+ toBox = startLegWriter(box.ws, lost, stop)
open, _ := json.Marshal(sess.open)
if !toBox.sendWait(interactive.KindOpen, open) {
return stamp(interactive.End{Reason: interactive.EndLost})
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index 2b3c70fef..b4577dd3c 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -52,7 +52,7 @@ var jobPassFuncs = map[string][]string{
"PublishPlansMarker": {"publishPlansMarkerOnce"},
"StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns",
"orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd",
- "finishPendingInteractiveEnds", "interactiveSweep", "clearDeadMarker", "sweepOrphanGrants"},
+ "finishPendingInteractiveEnds", "interactiveSweep", "clearDeadMarker", "sweepEndRow", "scanOrphanGrants", "sweepOrphanGrants"},
"StartSeedsPass": {"seedsPass", "abandonSeed"},
"StartLifetimesCutoverWatch": {"lifetimesWatchOnce", "lifetimesFloorWatch", "materializeAppsOnce", "materializeAppsJudged",
"MaterializeApps"},
diff --git a/internal/console/runsweep.go b/internal/console/runsweep.go
index ebb2a5179..33ad8705a 100644
--- a/internal/console/runsweep.go
+++ b/internal/console/runsweep.go
@@ -82,8 +82,8 @@ func (s *Server) runSweep(ctx context.Context, now time.Time) { s.runSweepPass(c
// Interactive sessions (rootfs apps Plan 6, Task 11) ride the same pass:
// first the ends the draining gate refused (finishPendingInteractiveEnds),
// then every pass the markers of dead sessions (interactiveSweep), and with
-// housekeeping the grants no record names (sweepOrphanGrants), on the same
-// complete read and the same app narrowing as the run orphan phase.
+// housekeeping, on a complete read as the run orphan phase, once a day per
+// app, the grants no record names (scanOrphanGrants).
func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping bool) {
if s.cfg.Releases == nil {
return
@@ -143,8 +143,7 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
if !housekeeping || !complete {
return
}
- candidates, full := s.orphanCandidates(ctx, apps, now, "run-start")
- grantApps, _ := s.orphanCandidates(ctx, apps, now, "interactive-start")
+ candidates, full := s.orphanCandidates(ctx, apps, now)
for app := range candidates {
if ctx.Err() != nil {
log.Printf("console: run sweep: pass cut short: %v", ctx.Err())
@@ -152,36 +151,61 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
}
s.sweepOrphanRuns(ctx, app[0], app[1], named, now, viewed)
}
- for app := range grantApps {
+ if full && s.recordView != nil {
+ s.lastOrphanFull = now
+ }
+ s.scanOrphanGrants(ctx, apps, grants, now)
+}
+
+// orphanGrantScanEvery is how often each app's interactive/ is scanned for
+// orphan grants, whatever the record view's mode (fix round 1, P2 4).
+const orphanGrantScanEvery = 24 * time.Hour
+
+// scanOrphanGrants runs sweepOrphanGrants for each app in apps whose last
+// scan is a day old (or that this process has not scanned), and forgets the
+// apps that no longer have records. A scan that did not list (an error, or
+// a store without modification times) is not counted, so the next
+// housekeeping pass tries again.
+func (s *Server) scanOrphanGrants(ctx context.Context, apps map[[2]string]bool, grants map[string]bool, now time.Time) {
+ if s.lastGrantScan == nil {
+ s.lastGrantScan = map[[2]string]time.Time{}
+ }
+ for app := range s.lastGrantScan {
+ if !apps[app] {
+ delete(s.lastGrantScan, app)
+ }
+ }
+ for app := range apps {
+ if last, ok := s.lastGrantScan[app]; ok && now.Sub(last) < orphanGrantScanEvery {
+ continue
+ }
if ctx.Err() != nil {
log.Printf("console: run sweep: pass cut short: %v", ctx.Err())
return
}
- s.sweepOrphanGrants(ctx, app[0], app[1], grants, now)
- }
- if full && s.recordView != nil {
- s.lastOrphanFull = now
+ if s.sweepOrphanGrants(ctx, app[0], app[1], grants, now) {
+ s.lastGrantScan[app] = now
+ }
}
}
-// orphanCandidates is the apps whose runs/ (action "run-start") or
-// interactive/ ("interactive-start") an orphan phase lists, out of apps,
-// every app with records, and whether that is all of them. Disarmed it is
-// all of them, as before the index. Armed (S3 change-index design §4.6,
-// codex R2-1) it is only those with an action row in the last
+// orphanCandidates is the apps whose runs/ the orphan phase lists, out of
+// apps, every app with records, and whether that is all of them. Disarmed it
+// is all of them, as before the index. Armed (S3 change-index design §4.6,
+// codex R2-1) it is only those with a run-start row in the last
// orphanCandidateWindow, except on the first housekeeping after start and
// then once every orphanFullSweepEvery, which take every app, as does a
// failed read of the rows. Orphans are still found by age, not by index
-// movement. The narrowed set is always a subset of apps, so it never lists
-// an app the full sweep would not.
-func (s *Server) orphanCandidates(ctx context.Context, apps map[[2]string]bool, now time.Time, action string) (map[[2]string]bool, bool) {
+// movement: runs/ is outside every scope. The narrowed set is always a
+// subset of apps, so it never lists an app the full sweep would not.
+func (s *Server) orphanCandidates(ctx context.Context, apps map[[2]string]bool, now time.Time) (map[[2]string]bool, bool) {
if s.recordView == nil || s.lastOrphanFull.IsZero() || now.Sub(s.lastOrphanFull) >= orphanFullSweepEvery {
return apps, true
}
- recent, err := s.store.AppsWithActionSince(action, now.Add(-orphanCandidateWindow))
+ recent, err := s.store.AppsWithActionSince("run-start", now.Add(-orphanCandidateWindow))
if err != nil {
- log.Printf("console: run sweep: recent %s rows: %v (every app is swept this pass)", action, err)
- jobFailed(ctx, fmt.Errorf("run sweep: recent %s rows: %w (every app is swept this pass)", action, err))
+ log.Printf("console: run sweep: recent runs: %v (every app's runs are swept this pass)", err)
+ jobFailed(ctx, fmt.Errorf("run sweep: recent runs: %w (every app's runs are swept this pass)", err))
return apps, true
}
out := map[[2]string]bool{}
@@ -457,9 +481,10 @@ func (s *Server) strayIsOld(ctx context.Context, dir string, now time.Time) bool
// with it), or when its PickupBy has passed and this console's hub does not
// hold its id. An id the hub holds in endPending is left to
// finishPendingInteractiveEnds, which ran first in this pass with the
-// session's own End. An interactive-end row with reason lost is written for
-// each marker it clears, unless the hub has the id as ended (its own end
-// step writes that row).
+// session's own End, and an id whose end step's writes are in flight
+// (ending) to that step: the hub owns their rows. An interactive-end row
+// with reason lost is written for each other marker it clears, or finds
+// replaced, unless the session has an end row already.
func (s *Server) interactiveSweep(ctx context.Context, recs []provision.Record, now time.Time) {
h := s.interactive
if h == nil {
@@ -475,7 +500,7 @@ func (s *Server) interactiveSweep(ctx context.Context, recs []provision.Record,
return
}
state := h.stateOf(m.ID)
- if state == hubPending {
+ if state == hubPending || state == hubEnding {
continue
}
if m.Console == s.bootID && (state == hubHeld || !now.After(m.PickupBy)) {
@@ -489,8 +514,9 @@ func (s *Server) interactiveSweep(ctx context.Context, recs []provision.Record,
// deletes its grant, then writes its lost row unless ended. A marker that
// changed since the read (another session replaced it, or it was cleared,
// or the record went) is not this phase's to clear: the old grant is still
-// deleted, and no row is written, since who ended it is unknown. A grant
-// delete that fails after the clear landed leaves the rest to
+// deleted, and its lost row is written unless the session has an end row
+// (fix round 1, P2 3), checked in the audit table (auditInteractiveEnd). A
+// grant delete that fails after the clear landed leaves the rest to
// finishPendingInteractiveEnds (endPending), so the row is written once,
// after the delete.
func (s *Server) clearDeadMarker(ctx context.Context, rec provision.Record, m provision.InteractiveState, now time.Time, ended bool) {
@@ -513,6 +539,9 @@ func (s *Server) clearDeadMarker(ctx context.Context, rec provision.Record, m pr
log.Printf("console: run sweep: %s/%s/%s: interactive %s grant: %v", rec.Account, rec.App, rec.Host, m.ID, err)
jobFailed(ctx, fmt.Errorf("run sweep: %s/%s/%s: interactive %s grant: %w", rec.Account, rec.App, rec.Host, m.ID, err))
}
+ if !ended {
+ s.sweepEndRow(ctx, acct, rec, m, now)
+ }
return
case err != nil:
log.Printf("console: run sweep: %s/%s/%s: clear interactive %s: %v", rec.Account, rec.App, rec.Host, m.ID, err)
@@ -533,8 +562,16 @@ func (s *Server) clearDeadMarker(ctx context.Context, rec provision.Record, m pr
if ended {
return
}
- s.auditActivity(acct, rec.App, m.By, Activity{Action: "interactive-end", TargetType: "instance", Target: rec.Host,
- Detail: interactiveEndDetail(m.ID, e)})
+ s.sweepEndRow(ctx, acct, rec, m, now)
+}
+
+// sweepEndRow writes a dead session's lost row, unless it has an end row.
+func (s *Server) sweepEndRow(ctx context.Context, acct *Account, rec provision.Record, m provision.InteractiveState, now time.Time) {
+ err := s.auditInteractiveEnd(acct, rec.App, rec.Host, m.By, m.ID, interactive.End{Reason: interactive.EndLost, Ended: now.UTC()})
+ if err != nil {
+ log.Printf("console: run sweep: %s/%s/%s: interactive %s end row: %v", rec.Account, rec.App, rec.Host, m.ID, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: %s/%s/%s: interactive %s end row: %w", rec.Account, rec.App, rec.Host, m.ID, err))
+ }
}
// sweepOrphanGrants deletes the session grants under acct/app's interactive/
@@ -547,18 +584,20 @@ func (s *Server) clearDeadMarker(ctx context.Context, rec provision.Record, m pr
// lasts at most its pickup window and MaxDuration and a minute, so a
// day-old grant is never a live one, whatever a stale record view says,
// and an endPending grant it deletes first is one the pending pass then
-// finds already gone.
-func (s *Server) sweepOrphanGrants(ctx context.Context, acct, app string, named map[string]bool, now time.Time) {
+// finds already gone. It reports whether it listed. Its requests: the
+// listing's pages (ListMod pages at 1000 keys) and, per orphan, a DELETE
+// and its change-index GET and PUT.
+func (s *Server) sweepOrphanGrants(ctx context.Context, acct, app string, named map[string]bool, now time.Time) bool {
ml, ok := s.cfg.Releases.(release.ModLister)
if !ok {
- return
+ return false
}
prefix := interactive.Prefix(acct, app)
objs, err := ml.ListMod(ctx, prefix)
if err != nil {
log.Printf("console: run sweep: %s/%s: list interactive grants: %v", acct, app, err)
jobFailed(ctx, fmt.Errorf("run sweep: %s/%s: list interactive grants: %w", acct, app, err))
- return
+ return false
}
for _, o := range objs {
id, ok := strings.CutSuffix(strings.TrimPrefix(o.Key, prefix), ".json")
@@ -570,4 +609,5 @@ func (s *Server) sweepOrphanGrants(ctx context.Context, acct, app string, named
jobFailed(ctx, fmt.Errorf("run sweep: %s/%s: delete orphan grant %s: %w", acct, app, id, err))
}
}
+ return true
}
diff --git a/internal/console/runsweep_test.go b/internal/console/runsweep_test.go
index 025d82a0e..d75c62b2a 100644
--- a/internal/console/runsweep_test.go
+++ b/internal/console/runsweep_test.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
+ "net/http"
"os"
"path/filepath"
"reflect"
@@ -995,32 +996,103 @@ func TestSweepLeavesAPendingEndToItsOwnPass(t *testing.T) {
}
// A marker the phase read that has changed since (a later admission
-// replaced it, from a stale read) is not cleared: the new marker stays, the
-// old grant goes, and no row is written, since who ended the old session
-// is unknown.
-func TestSweepLeavesAReplacedMarkerAlone(t *testing.T) {
+// replaced it, from a stale read) is not cleared: the new marker stays and
+// the old grant goes. The old session's end row is written, lost, unless a
+// row for that id exists already (fix round 1, P2 3).
+func TestSweepWritesAReplacedMarkersEndOnce(t *testing.T) {
fx := newIxFx(t, "code-ixs-replaced")
- const old = "tty_jjjjjjjjjjjjjjjjjjjjjjjjjj"
- oldGrant := ixPutGrant(t, fx, old)
- stale, _ := ixRecord(t, fx, ixHost)
- stale.Interactive = &provision.InteractiveState{ID: old, By: "bob@keymail.dev", Console: "old", PickupBy: time.Now().Add(-time.Minute)}
+ const old, done = "tty_jjjjjjjjjjjjjjjjjjjjjjjjjj", "tty_kkkkkkkkkkkkkkkkkkkkkkkkkk"
+ oldGrant, doneGrant := ixPutGrant(t, fx, old), ixPutGrant(t, fx, done)
+ if err := fx.st.RecordActivity(fx.acctID, "shop", "bob@keymail.dev", Activity{Action: "interactive-end", TargetType: "instance", Target: ixHost,
+ Detail: interactiveEndDetail(done, interactive.End{Reason: interactive.EndExited, Ended: time.Now().UTC()})}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ stale := func(id string) provision.Record {
+ rec, _ := ixRecord(t, fx, ixHost)
+ rec.Interactive = &provision.InteractiveState{ID: id, By: "bob@keymail.dev", Console: "old", PickupBy: time.Now().Add(-time.Minute)}
+ return rec
+ }
cli := ixStart(t, fx, fx.alice, ixOpenArgv())
liveID, _ := ixSessionGrant(t, fx, ixHost)
- fx.srv.interactiveSweep(context.Background(), []provision.Record{stale}, time.Now())
+ for pass := 0; pass < 2; pass++ {
+ fx.srv.interactiveSweep(context.Background(), []provision.Record{stale(old), stale(done)}, time.Now())
+ }
if m := ixMarker(t, fx, ixHost); m == nil || m.ID != liveID {
t.Fatalf("marker %+v, want the new session %s kept", m, liveID)
}
- if ixHasObject(t, fx, oldGrant) {
- t.Fatal("the replaced session's grant survived")
+ if ixHasObject(t, fx, oldGrant) || ixHasObject(t, fx, doneGrant) {
+ t.Fatal("a replaced session's grant survived")
}
if !ixHasObject(t, fx, interactive.GrantKey(fx.acct, "shop", liveID)) {
t.Fatal("the new session's grant was deleted")
}
- if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
- t.Fatalf("rows %+v, want none", evs)
+ rows := map[string][]string{}
+ for _, e := range ixEvents(t, fx, "interactive-end") {
+ d := ixEndRow(t, e)
+ rows[d.ID] = append(rows[d.ID], d.Reason)
+ }
+ if got := rows[old]; len(got) != 1 || got[0] != interactive.EndLost {
+ t.Fatalf("rows for %s: %v, want one lost (two passes)", old, got)
+ }
+ if got := rows[done]; len(got) != 1 || got[0] != interactive.EndExited {
+ t.Fatalf("rows for %s: %v, want its own exited only", done, got)
+ }
+ if len(rows) != 2 {
+ t.Fatalf("rows %v", rows)
}
cli.Close()
- ixWaitEvents(t, fx, "interactive-end", 1)
+ ixWaitEvents(t, fx, "interactive-end", 3)
+}
+
+// An end whose writes are in flight stays owned (fix round 1, P2 2): a
+// prune and a sweep pass while its end step is held neither forget it nor
+// write a lost row; the end step then writes the one row, its own.
+func TestAnEndInFlightIsNotSweptAsLost(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-inflight")
+ h := fx.srv.interactive
+ entered, release := make(chan string, 1), make(chan struct{})
+ var once sync.Once
+ let := func() { once.Do(func() { close(release) }) }
+ h.beforeEndWrites = func(id string) {
+ entered <- id
+ <-release
+ }
+ t.Cleanup(let) // runs before the fixture's wait for every end
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, _ := ixSessionGrant(t, fx, ixHost)
+ cli.Close()
+ select {
+ case got := <-entered:
+ if got != id {
+ t.Fatalf("end step for %s, want %s", got, id)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the end step never ran")
+ }
+ if st := hubState(h, id); st != "ending" {
+ t.Fatalf("hub: %q while the end's writes are held, want ending", st)
+ }
+ // Past the session's PickupBy: a prune and the marker phase.
+ fx.srv.runSweepPass(context.Background(), time.Now().Add(interactive.PickupWindow+time.Minute), false)
+ if st := hubState(h, id); st != "ending" {
+ t.Fatalf("hub: %q after a prune, want ending", st)
+ }
+ if m := ixMarker(t, fx, ixHost); m == nil || m.ID != id {
+ t.Fatalf("marker %+v, want %s left to its end step", m, id)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("the sweep wrote %+v for an end in flight", evs)
+ }
+ let()
+ evs := ixWaitEvents(t, fx, "interactive-end", 1)
+ if d := ixEndRow(t, evs[0]); d.ID != id || d.Reason != interactive.EndCancelled {
+ t.Fatalf("end row %+v, want its own cancelled", d)
+ }
+ ixWaitHub(t, h, id, "ended")
+ fx.srv.runSweepPass(context.Background(), time.Now().Add(interactive.PickupWindow+time.Minute), false)
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 1 {
+ t.Fatalf("rows %+v after a later pass, want one", evs)
+ }
}
// ixAge sets key's modification time d in the past.
@@ -1112,31 +1184,95 @@ func interactiveListings(lists []string) []string {
return out
}
-// Armed, between daily full sweeps, orphan grant housekeeping lists
-// interactive/ only for apps with an interactive-start row in the last 48
-// hours, as the run orphan phase does with run-start rows.
-func TestOrphanGrantHousekeepingListsOnlyRecentSessionApps(t *testing.T) {
- fx := newIxFx(t, "code-ixs-recent")
- cs := indexedDeployment(t, fx.consoleFixture)
- rec := provision.Record{Schema: 1, Host: "cafe.example.com", Slug: "cafe", App: "cafe", Account: fx.acct, Channel: "stable", CreatedAt: time.Now().UTC()}
- if err := provision.CreateRecord(context.Background(), cs, rec); err != nil {
- t.Fatal(err)
+// The orphan grant scan runs once a day per app, armed or not (fix round
+// 1, P2 4): the first housekeeping lists every app with records, the next
+// ones nothing, and a day later every app again.
+func TestOrphanGrantScanRunsOncePerAppPerDay(t *testing.T) {
+ for _, armed := range []bool{false, true} {
+ fx := newIxFx(t, "code-ixs-daily")
+ cs := indexedDeployment(t, fx.consoleFixture)
+ rec := provision.Record{Schema: 1, Host: "cafe.example.com", Slug: "cafe", App: "cafe", Account: fx.acct, Channel: "stable", CreatedAt: time.Now().UTC()}
+ if err := provision.CreateRecord(context.Background(), cs, rec); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.RecordActivity(fx.acctID, "shop", "alice@keymail.dev", Activity{Action: "interactive-start"}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if armed {
+ armRecordView(t, fx.srv, cs)
+ }
+ all := []string{"ListMod " + interactive.Prefix(fx.acct, "cafe"), "ListMod " + interactive.Prefix(fx.acct, "shop")}
+ now := time.Now()
+ cs.taken()
+ fx.srv.runSweepPass(context.Background(), now, true)
+ if got := interactiveListings(cs.taken()); !reflect.DeepEqual(got, all) {
+ t.Fatalf("armed %v: first housekeeping listed %q, want %q", armed, got, all)
+ }
+ for k := 1; k < 144; k++ {
+ fx.srv.runSweepPass(context.Background(), now.Add(time.Duration(k)*10*time.Minute), true)
+ }
+ if got := interactiveListings(cs.taken()); len(got) != 0 {
+ t.Fatalf("armed %v: housekeeping within the day listed %q", armed, got)
+ }
+ fx.srv.runSweepPass(context.Background(), now.Add(24*time.Hour), true)
+ if got := interactiveListings(cs.taken()); !reflect.DeepEqual(got, all) {
+ t.Fatalf("armed %v: a day later housekeeping listed %q, want %q", armed, got, all)
+ }
}
+}
+
+// A day's housekeeping passes for an app with no sessions, counted at the
+// production deployment store's wire (an s3fake behind
+// NewDeploymentS3Store): exactly one LIST page of its interactive/ prefix.
+func TestOrphanGrantScanRequestsForADay(t *testing.T) {
+ lat := &perfLatency{}
+ fx := newInteractiveFxWith(t, 7, "code-ixs-wire", consoleFixtureOptions{WithKey: true, S3: lat})
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk"})
+ prefix := interactive.Prefix(fx.acct, "shop")
+ var mu sync.Mutex
+ var lists, other []string
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ mu.Lock()
+ defer mu.Unlock()
+ q := r.URL.Query()
+ switch {
+ case q.Get("list-type") == "2" && q.Get("prefix") == prefix:
+ lists = append(lists, r.URL.RawQuery)
+ case strings.Contains(r.URL.Path, "/interactive/") || strings.Contains(q.Get("prefix"), "/interactive/"):
+ other = append(other, r.Method+" "+r.URL.String())
+ }
+ return 0, nil
+ })
+ defer lat.Fake().OnRequest(nil)
now := time.Now()
- if err := fx.st.RecordActivity(fx.acctID, "shop", "alice@keymail.dev", Activity{Action: "interactive-start"}, now.Add(-time.Hour)); err != nil {
- t.Fatal(err)
+ for k := 0; k < 144; k++ {
+ fx.srv.runSweepPass(context.Background(), now.Add(time.Duration(k)*10*time.Minute), true)
}
- armRecordView(t, fx.srv, cs)
- all := []string{"ListMod " + interactive.Prefix(fx.acct, "cafe"), "ListMod " + interactive.Prefix(fx.acct, "shop")}
+ mu.Lock()
+ defer mu.Unlock()
+ if len(lists) != 1 || len(other) != 0 {
+ t.Fatalf("a day of housekeeping made %d LIST pages of %s (%q) and %q, want one page and nothing else", len(lists), prefix, lists, other)
+ }
+}
- cs.taken()
- fx.srv.runSweepPass(context.Background(), now, true)
- if got := interactiveListings(cs.taken()); !reflect.DeepEqual(got, all) {
- t.Fatalf("first housekeeping listed %q, want every app with records %q", got, all)
+// One terminal row per session, whoever writes first (fix round 1, P2 3):
+// a session whose end row is already in the audit table (here written
+// ahead of it) gets no second row from its own end step.
+func TestAnEndStepWritesNoSecondRow(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-onerow")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, _ := ixSessionGrant(t, fx, ixHost)
+ if err := fx.st.RecordActivity(fx.acctID, "shop", "alice@keymail.dev", Activity{Action: "interactive-end", TargetType: "instance", Target: ixHost,
+ Detail: interactiveEndDetail(id, interactive.End{Reason: interactive.EndLost, Ended: time.Now().UTC()})}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ cli.Close()
+ ixWaitHub(t, fx.srv.interactive, id, "ended")
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || ixEndRow(t, evs[0]).Reason != interactive.EndLost {
+ t.Fatalf("end rows %+v, want the one already there", evs)
}
- fx.srv.runSweepPass(context.Background(), now.Add(10*time.Minute), true)
- want := []string{"ListMod " + interactive.Prefix(fx.acct, "shop")}
- if got := interactiveListings(cs.taken()); !reflect.DeepEqual(got, want) {
- t.Fatalf("narrowed housekeeping listed %q, want %q", got, want)
+ if m := ixMarker(t, fx, ixHost); m != nil || len(ixGrants(t, fx)) != 0 {
+ t.Fatalf("marker %+v, grants %v: the end's other writes did not land", m, ixGrants(t, fx))
}
}
diff --git a/internal/console/server.go b/internal/console/server.go
index b6721038e..e4af3b215 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1446,6 +1446,9 @@ type Server struct {
// every app with records (runsweep.go); zero until the first, which is
// therefore full. Only the run sweep's one goroutine touches it.
lastOrphanFull time.Time
+ // lastGrantScan is when the run sweep last scanned each app's
+ // interactive/ for orphan grants (scanOrphanGrants): once a day each.
+ lastGrantScan map[[2]string]time.Time
// seen is when each person's current last-seen hour was reserved
// (lastseen.go), keyed by address and only for addresses that passed a
// gate; seenMu guards it. lastSeenWrites counts last_seen write
diff --git a/internal/console/store.go b/internal/console/store.go
index 3764cc2d7..c45099707 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -2918,6 +2918,21 @@ FROM audit WHERE account_id = ? AND app = ? ORDER BY id DESC LIMIT ?`, accountID
return out, rows.Err()
}
+// InteractiveEndRecorded reports whether the account's app has an
+// interactive-end row for session id (rootfs apps Plan 6): its detail is
+// interactiveEndDetail's JSON, which starts with the id. A session id is
+// [a-z2-7_] only, so the needle needs no escaping.
+func (s *Store) InteractiveEndRecorded(accountID int64, app, id string) (bool, error) {
+ var one int
+ err := s.db.QueryRow(`SELECT 1 FROM audit
+WHERE account_id = ? AND app = ? AND action = 'interactive-end' AND instr(detail, ?) > 0 LIMIT 1`,
+ accountID, app, `{"id":"`+id+`"`).Scan(&one)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return err == nil, err
+}
+
// AppRef names one app by its account's sqid, as the bucket keys it.
type AppRef struct{ Sqid, App string }
diff --git a/internal/provision/rootfs_apps_6_census_test.go b/internal/provision/rootfs_apps_6_census_test.go
index 0f76f169e..d26c91244 100644
--- a/internal/provision/rootfs_apps_6_census_test.go
+++ b/internal/provision/rootfs_apps_6_census_test.go
@@ -53,6 +53,12 @@ package provision
// transitions. NewServer registers GET /api/box/interactive/{id} (the
// box door reads the hub, the token and the registry, and touches no
// record); re-pinned, the same lit:instances.
+// - Task 11 fix round 1: admitSession wraps InteractiveAdmit to learn the
+// dead marker its write replaced and writes that session's lost row
+// once; endWrites writes its row through auditInteractiveEnd (one row
+// per session, checked in the audit table); clearDeadMarker writes a
+// replaced marker's lost row the same way. Each still has its one
+// SetRecordInteractive, same class; re-pinned.
func rootfsApps6WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), fleetPublicRoutesWriteCensusInventory()...)
replacements := []censusEntry{
@@ -79,11 +85,11 @@ func rootfsApps6WriteCensusInventory() []censusEntry {
added := []censusEntry{
{"internal/provision/interactive.go", "SetRecordInteractive", "record-writer", "key:SetRecordInteractive,key:updateRecord", "f2f8c0ad8647cc048a0be0fa3edc051ddd8e3157eba038123f9e5bab79f4530e"},
{"internal/appconfig/interactive.go", "claimRawSetInteractive", "nonrecord", "sel:Put", "d4c768601d1b9bdb44c0fd0c2c6f058c18c1434856e357f00628d2f600ce039b"},
- {"internal/console/apiinteractive.go", "Server.admitSession", "record-writer", "key:SetRecordInteractive", "480a81596e1a07fab59673711a889f20e1ea30d96b870767f20488cdd20acd98"},
- {"internal/console/apiinteractive.go", "Server.endWrites", "record-writer", "key:SetRecordInteractive", "6a183621b60073e45f698e046a177adca2f536b47a365bdb66de5548257b9fea"},
+ {"internal/console/apiinteractive.go", "Server.admitSession", "record-writer", "key:SetRecordInteractive", "ca082ecf21d2f2a654abc941518f1938d462148ac71693125f02907bac3a91d2"},
+ {"internal/console/apiinteractive.go", "Server.endWrites", "record-writer", "key:SetRecordInteractive", "8fb7e6e57049398f1221b4dbb6eb338d6ac414345cd197bcb39188617f0e27e7"},
{"internal/console/apiinteractive.go", "Server.putGrant", "nonrecord", "sel:Put", "22a18ef45051da8cfb8a6a62ad8891afd28e3bf71cc26a541639cd2a1dc0a1ff"},
{"internal/console/server.go", "consolePerfSkip", "key-site", "lit:instances", "d4b65473d3702b49d79a799d46f078e4491b6e86a59a101dd4c1ce4d50f698e7"},
- {"internal/console/runsweep.go", "Server.clearDeadMarker", "record-writer", "key:SetRecordInteractive", "d0e66bf2e33b4086f435ded4d44750a9eacf8a1b6d1e661c09481be1b54580ee"},
+ {"internal/console/runsweep.go", "Server.clearDeadMarker", "record-writer", "key:SetRecordInteractive", "3e26dfe2a13a9e3b6525fb3c4f4a54da79a464c061f95eaa9fadbaf1ee041f9a"},
}
for _, a := range added {
for _, e := range entries {