package device import ( "context" "fmt" "sync/atomic" "time" "google.golang.org/protobuf/types/known/timestamppb" "hth/internal/backend" "hth/internal/config" hthv1 "hth/internal/gen/hth/api/v1" "hth/internal/grpcserver" "hth/internal/protocol" ) type jobKind int const ( jobOpen jobKind = iota jobGetTemp jobGetMotor jobSetAllApply jobSetAllHB jobSetAllSafe ) const originEpochBaseline = "epoch_safe_baseline" const originShutdown = "shutdown" type serialJob struct { id uint64 portGen uint64 epoch uint64 kind jobKind origin string commandID string peerUID int32 peerGID int32 peerPID int32 startedAt time.Time deadline time.Time timeout time.Duration frame protocol.SetAll } // ActionExecutionContext is the Actor-owned identity of one physical SET_ALL. // Call sites must not invent command IDs, epochs, or peer credentials ad hoc. type ActionExecutionContext struct { CommandID string Origin string Mode hthv1.ActionMode DeviceEpoch uint64 PortGeneration uint64 JobID uint64 LeaseID string LeaseEpoch uint64 PeerUID int32 PeerGID int32 PeerPID int32 RequestedAt time.Time QueuedAt time.Time DispatchStartedAt time.Time ValidUntil time.Time Frame protocol.SetAll Requested *hthv1.ActionBatch Normalized protocol.SetAll Accepted protocol.SetAll EffectiveTarget protocol.SetAll } func (d *Device) newActionContext(commandID, origin string, mode hthv1.ActionMode, frame protocol.SetAll, rpcCtx context.Context) ActionExecutionContext { now := d.clk.Now() if commandID == "" { commandID = d.nextInternalCommandID(origin) } ax := ActionExecutionContext{ CommandID: commandID, Origin: origin, Mode: mode, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, Frame: frame, RequestedAt: now, QueuedAt: now, EffectiveTarget: frame, } if rpcCtx != nil { if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok { ax.PeerUID, ax.PeerGID, ax.PeerPID = cred.UID, cred.GID, cred.PID } } return ax } func (d *Device) serialJobFromAction(kind jobKind, timeout time.Duration, ax ActionExecutionContext) serialJob { return serialJob{ kind: kind, timeout: timeout, frame: ax.Frame, origin: ax.Origin, commandID: ax.CommandID, peerUID: ax.PeerUID, peerGID: ax.PeerGID, peerPID: ax.PeerPID, } } func bindActionRecord(rec *hthv1.ActionRecord, ax ActionExecutionContext, dispatch hthv1.ActionDispatchState) *hthv1.ActionRecord { if rec == nil { return nil } if rec.CommandId == "" { rec.CommandId = ax.CommandID } rec.Origin = ax.Origin rec.ActionMode = ax.Mode rec.ActionEpoch = ax.DeviceEpoch rec.PortGeneration = ax.PortGeneration rec.PeerUid = ax.PeerUID rec.PeerGid = ax.PeerGID rec.PeerPid = ax.PeerPID rec.DispatchState = dispatch return rec } type serialResult struct { id uint64 portGen uint64 epoch uint64 kind jobKind origin string commandID string peerUID int32 peerGID int32 peerPID int32 started time.Time wr backend.WriteResult err error temp *backend.TempReport motor *backend.MotorReport frame protocol.SetAll } type inflightIdent struct { id uint64 portGen uint64 epoch uint64 kind jobKind origin string startedAt time.Time } type pendingResumeState struct { req req prepared *hthv1.ActionResult target protocol.SetAll credit map[string]float64 commandID string leaseID string leaseEp uint64 devEpoch uint64 validUntil time.Time acceptedAt time.Time } type pendingSafeState struct { commandID string reason string origin string peerUID int32 peerGID int32 peerPID int32 enqueued time.Time deadline time.Time epoch uint64 requestedAt time.Time attempts int maxAttempts int nextRetry time.Time } const safeNotStartedRetry = 50 * time.Millisecond const safeNotStartedMaxAttempts = 8 func (d *Device) newPendingSafe(cmd, reason, origin string, rpcCtx context.Context) *pendingSafeState { now := d.clk.Now() st := &pendingSafeState{ commandID: cmd, reason: reason, origin: origin, enqueued: now, deadline: now.Add(d.cfg.SetAllTimeout()), epoch: d.store.Epoch(), requestedAt: now, maxAttempts: safeNotStartedMaxAttempts, } if rpcCtx != nil { if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok { st.peerUID, st.peerGID, st.peerPID = cred.UID, cred.GID, cred.PID } } return st } func (d *Device) markProgress() { atomic.StoreInt64(&d.progressUnix, time.Now().UnixNano()) } func (d *Device) ActorProgress() time.Time { n := atomic.LoadInt64(&d.progressUnix) if n == 0 { return time.Time{} } return time.Unix(0, n) } func (d *Device) serialInflight() bool { return atomic.LoadInt64(&d.inflightSinceNano) != 0 } func (d *Device) beginInflight(j serialJob) { atomic.StoreInt64(&d.inflightSinceNano, time.Now().UnixNano()) d.inflightMu.Lock() d.currentInflight = inflightIdent{ id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind, origin: j.origin, startedAt: j.startedAt, } d.inflightMu.Unlock() } func (d *Device) endInflight() { atomic.StoreInt64(&d.inflightSinceNano, 0) d.inflightTimeout = 0 d.inflightKind = 0 d.inflightMu.Lock() d.currentInflight = inflightIdent{} d.inflightMu.Unlock() } func (d *Device) inflightSnapshot() inflightIdent { d.inflightMu.Lock() defer d.inflightMu.Unlock() return d.currentInflight } func (d *Device) resultMatchesInflight(res serialResult) bool { inf := d.inflightSnapshot() if inf.id == 0 { return false } return res.id == inf.id && res.portGen == inf.portGen && res.epoch == inf.epoch && res.kind == inf.kind } func (d *Device) SerialBusy() time.Duration { n := atomic.LoadInt64(&d.inflightSinceNano) if n == 0 { return 0 } return time.Since(time.Unix(0, n)) } func (d *Device) schedulerMargin() time.Duration { if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.SchedulerMarginMs > 0 { return time.Duration(d.caps.Timing.SchedulerMarginMs) * time.Millisecond } return 50 * time.Millisecond } func (d *Device) remainingInflight() time.Duration { if !d.serialInflight() { return 0 } to := d.inflightTimeout if to <= 0 { to = d.worstCaseJob(d.inflightKind) } elapsed := d.SerialBusy() rem := to - elapsed if rem < 0 { rem = 0 } return rem + d.schedulerMargin() } func (d *Device) worstCaseJob(k jobKind) time.Duration { switch k { case jobGetTemp: return d.cfg.GetTempTimeout(d.prof) case jobGetMotor: return d.cfg.GetMotorTimeout() case jobOpen: return d.cfg.OpenTimeout() default: return d.cfg.SetAllTimeout() } } func (d *Device) minControlPeriod() time.Duration { if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.MinimumControlPeriodMs > 0 { return time.Duration(d.caps.Timing.MinimumControlPeriodMs) * time.Millisecond } return 50 * time.Millisecond } func (d *Device) leaseActive(now time.Time) bool { if d.lease == nil { return false } l := d.lease.Current() return l != nil && l.Active(now) } func (d *Device) controlWindowOpen(now time.Time) bool { return d.leaseActive(now) && !d.controlWindowUntil.IsZero() && now.Before(d.controlWindowUntil) } func (d *Device) deadlineUnmeetable(batch *hthv1.ActionBatch) string { if batch == nil || batch.ValidUntil == nil { return "" } now := d.clk.Now() until := batch.ValidUntil.AsTime() if !until.After(now) { return "valid_until expired before first hardware write" } need := d.remainingInflight() if need <= 0 { return "" } if !until.After(now.Add(need)) { return fmt.Sprintf("valid_until cannot wait for in-flight serial (%s remaining); rejected before enqueue", need.Round(time.Millisecond)) } return "" } func (d *Device) nextJobID() uint64 { d.jobSeq++ return d.jobSeq } func (d *Device) nextInternalCommandID(origin string) string { d.cmdSeq++ return fmt.Sprintf("%s:%d:%d:%s", d.daemon, d.store.Epoch(), d.cmdSeq, origin) } func (d *Device) enqueueSerial(j serialJob) bool { if d.serialInflight() { return false } if j.kind != jobOpen && !d.connected { return false } now := d.clk.Now() j.id = d.nextJobID() j.portGen = d.portGen j.epoch = d.store.Epoch() j.startedAt = now if j.timeout > 0 { j.deadline = now.Add(j.timeout) } d.inflightTimeout = j.timeout d.inflightKind = j.kind d.beginInflight(j) select { case d.jobs <- j: return true default: d.endInflight() return false } } func (d *Device) serialWorker(ctx context.Context) { for { select { case <-ctx.Done(): return case j := <-d.jobs: res := d.execSerial(ctx, j) select { case d.results <- res: case <-ctx.Done(): return } } } } func (d *Device) execSerial(parent context.Context, j serialJob) serialResult { to := j.timeout if to <= 0 { to = 2 * time.Second } ctx, cancel := context.WithTimeout(parent, to) defer cancel() out := serialResult{ id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind, origin: j.origin, commandID: j.commandID, peerUID: j.peerUID, peerGID: j.peerGID, peerPID: j.peerPID, started: j.startedAt, frame: j.frame, } switch j.kind { case jobOpen: out.err = d.backend.Open(ctx) if out.err != nil { _ = d.backend.Close() } case jobGetTemp: out.temp, out.err = d.backend.GetTemperature(ctx) case jobGetMotor: out.motor, out.err = d.backend.GetMotorStatus(ctx) case jobSetAllApply, jobSetAllHB, jobSetAllSafe: out.wr, out.err = d.backend.WriteSetAll(ctx, j.frame) } return out } func (d *Device) applySerialResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) { if !d.resultMatchesInflight(res) { inf := d.inflightSnapshot() d.log.Warn("discarding stale serial result", "job_id", res.id, "job_epoch", res.epoch, "job_port_gen", res.portGen, "inflight_id", inf.id, "inflight_epoch", inf.epoch, "inflight_port_gen", inf.portGen, "kind", int(res.kind)) return } d.endInflight() d.markProgress() if res.kind == jobOpen { d.onOpenResult(ctx, res, backoff, next) return } if res.err != nil && res.kind != jobSetAllApply && res.kind != jobSetAllHB && res.kind != jobSetAllSafe { d.log.Warn("serial transaction failed", "kind", int(res.kind), "origin", res.origin, "err", res.err) d.handleIOErr(ctx, res.err, backoff, next) d.kickPendingSerial(ctx) return } switch res.kind { case jobGetTemp: if res.temp != nil { d.lastTemp = d.clk.Now() d.applyTempMeas(res.temp) d.publishNow() } if d.leaseActive(d.clk.Now()) { d.controlWindowUntil = d.clk.Now().Add(d.minControlPeriod()) } case jobGetMotor: if res.motor != nil { d.applyMotorReport(res.motor) } case jobSetAllApply: d.finishApplyWrite(ctx, res) case jobSetAllHB: d.finishHeartbeat(ctx, res) case jobSetAllSafe: d.finishSafeWrite(ctx, res) } d.kickPendingSerial(ctx) } func (d *Device) onOpenResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) { if res.err != nil { kind := backend.ClassifyOpen(res.err) t := hthv1.FaultType_FAULT_TYPE_SERIAL_DEVICE_NOT_FOUND if kind == "permission" { t = hthv1.FaultType_FAULT_TYPE_SERIAL_PERMISSION_DENIED } if d.cfg.Backend == config.BackendSerial { d.book.Raise(d.clk.Now(), t, d.id, "", res.err.Error(), "", map[string]string{"class": kind}) d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", "reconnect backoff", "", nil) } *backoff = serialBackoff(*backoff) *next = d.clk.Now().Add(*backoff) d.connected = false d.log.Warn("serial open failed", "class", kind, "err", res.err) d.publishNow() return } *backoff = 0 d.connected = true d.inflightMu.Lock() d.portGen++ d.inflightMu.Unlock() d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING) d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", d.clk.Now()) d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", d.clk.Now()) d.publishNow() frame := d.safeFrame() ax := d.newActionContext("", originEpochBaseline, hthv1.ActionMode_ACTION_MODE_SAFE, frame, nil) if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) { d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED) } } func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) { job := d.applyJob d.applyJob = nil if job == nil || job.result == nil { if backend.WriteNeedsReconnect(sr.wr, sr.err) { d.onDrop(ctx, fmt.Errorf("orphaned apply write %s: %v", sr.wr.Outcome, sr.err)) } return } now := d.clk.Now() out := job.result if sr.wr.Outcome == backend.WriteNotStarted { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED out.Message = "serial write not started" if job.resume { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_not_started") } d.recordAction(out) d.publishActionResult(out) replyNonblock(job.reply, res{action: out}) return } conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED if backend.WriteNeedsReconnect(sr.wr, sr.err) { conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, job.batch.GetCommandId(), fmt.Sprintf("write outcome unknown: %v", sr.err), "", nil) out.Confirmation = conf out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN out.Message = "OUTCOME_UNKNOWN; transport closed, epoch bumped, lease invalidated; action not auto-replayed" out.DeviceEpoch = d.store.Epoch() if job.resume { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_unknown") } d.lease.Cache().Store(job.batch.CommandId, job.payload, out) d.recordAction(out) d.publishActionResult(out) replyNonblock(job.reply, res{action: out}) d.onDrop(ctx, fmt.Errorf("ambiguous serial write outcome=%v err=%v", sr.wr.Outcome, sr.err)) return } d.lastCont = job.target d.haveCont = true d.haveDispatch = true d.lastDispatchAt = now if job.credit != nil { d.slewCredit = job.credit } if job.resume { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL, "resume_dispatched") d.safeMode = false if d.startupDone { d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY) } d.publishEvent(hthv1.EventKind_EVENT_KIND_RESUME_FROM_SAFE, job.batch.GetCommandId()) } d.store.BumpControlRevision() out.Confirmation = conf out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED out.ControlRevision = d.store.ControlRevision() out.DeviceEpoch = d.store.Epoch() out.Dispatched = actionRecord(job.batch, now, conf, job.target) if out.Dispatched != nil { out.Dispatched.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED } out.AcceptedAction = actionRecord(job.batch, now, conf, job.target) d.lease.Cache().Store(job.batch.CommandId, job.payload, out) d.recordAction(out) d.publishActionResult(out) d.publishNow() replyNonblock(job.reply, res{action: out}) } func (d *Device) finishHeartbeat(ctx context.Context, res serialResult) { now := d.clk.Now() origin := res.origin if origin == "" { origin = "watchdog_heartbeat_repeat_continuous" } cmd := res.commandID if cmd == "" { cmd = fmt.Sprintf("%s:heartbeat-job:%d", d.daemon, res.id) } if res.wr.Outcome == backend.WriteFullyWritten && res.err == nil { d.lastHWHeartbeat = now d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED d.hub.PublishEvent(&hthv1.Event{ EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_WATCHDOG_HEARTBEAT, WallTime: timestamppb.New(now), DeviceId: d.id, Message: origin, PortGeneration: d.portGen, }) rec := d.makeInternalRecord(cmd, origin, hthv1.ActionMode_ACTION_MODE_NORMAL, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, res.frame) d.publishActionResult(&hthv1.ActionResult{ CommandId: cmd, Accepted: true, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin, Dispatched: rec, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED, Message: "hardware heartbeat dispatched UNCONFIRMED; control_revision unchanged", ControlRevision: d.store.ControlRevision(), }) d.publishNow() return } if res.wr.Outcome == backend.WriteNotStarted { d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, origin, fmt.Sprintf("heartbeat NOT_STARTED n=%d err=%v", res.wr.N, res.err), "", nil) d.publishActionResult(&hthv1.ActionResult{ CommandId: cmd, Accepted: false, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED, Message: "hardware heartbeat not started; not counted as success", DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin, ControlRevision: d.store.ControlRevision(), }) d.publishNow() if d.watchdogMargin() < d.cfg.Heartbeat()*2 { d.pendingHB = true } return } d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, origin, fmt.Sprintf("heartbeat %s: %v", res.wr.Outcome, res.err), "", nil) d.publishActionResult(&hthv1.ActionResult{ CommandId: cmd, Accepted: false, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN, Message: "hardware heartbeat outcome unknown; transport dropped", DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin, ControlRevision: d.store.ControlRevision(), }) d.onDrop(ctx, fmt.Errorf("heartbeat write %s: %v", res.wr.Outcome, res.err)) } func (d *Device) watchdogTimeout() time.Duration { if d.prof != nil && d.prof.Watchdog.TimeoutSeconds > 0 { return time.Duration(d.prof.Watchdog.TimeoutSeconds) * time.Second } return 30 * time.Second } func (d *Device) watchdogMargin() time.Duration { to := d.watchdogTimeout() if d.lastHWHeartbeat.IsZero() { return 0 } elapsed := d.clk.Now().Sub(d.lastHWHeartbeat) if elapsed >= to { return 0 } return to - elapsed } func (d *Device) kickPendingSerial(ctx context.Context) { if !d.connected || d.serialInflight() { return } if d.draining { return } d.expirePendingResume(ctx) if d.pendingSafeJob != nil { job := d.pendingSafeJob now := d.clk.Now() origin := "queued_safe" if job.origin != "" { origin = job.origin } if !job.deadline.IsZero() && now.After(job.deadline) { d.pendingSafeJob = nil d.publishActionResult(&hthv1.ActionResult{ CommandId: job.commandID, Accepted: false, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin, ControlRevision: d.store.ControlRevision(), Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED, Message: "SAFE_NOT_DELIVERED: WriteNotStarted retry budget/deadline exhausted", }) if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_retry_deadline") } d.publishNow() return } if !job.nextRetry.IsZero() && now.Before(job.nextRetry) { return } frame := d.safeFrame() if !d.enqueueSerial(serialJob{ kind: jobSetAllSafe, timeout: d.cfg.SetAllTimeout(), frame: frame, origin: origin, commandID: job.commandID, peerUID: job.peerUID, peerGID: job.peerGID, peerPID: job.peerPID, }) { return } return } if d.pendingResume != nil { d.dispatchPendingResume(ctx) return } if len(d.pendingApply) > 0 { r := d.pendingApply[0] d.pendingApply = d.pendingApply[1:] if r.rpcCtx != nil && r.rpcCtx.Err() != nil { replyNonblock(r.reply, res{action: cancelledResult(r.batch, r.rpcCtx.Err()), err: r.rpcCtx.Err()}) d.kickPendingSerial(ctx) return } d.beginApply(ctx, r) return } if d.pendingTemp && d.startupDone { if d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) { return } d.pendingTemp = false d.enqueueSerial(serialJob{kind: jobGetTemp, timeout: d.cfg.GetTempTimeout(d.prof)}) return } if d.pendingHB { d.pendingHB = false d.heartbeat(ctx) return } } func replyNonblock(ch chan res, r res) { if ch == nil { return } select { case ch <- r: default: } }