| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "log" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "sort" |
| 13 | "time" |
| 14 | |
| 15 | "reasonix/internal/fileutil" |
| 16 | filelock "reasonix/internal/identitylock" |
| 17 | ) |
| 18 | |
| 19 | func (e *HeartbeatEngine) readConfigSnapshot() (heartbeatConfigSnapshot, error) { |
| 20 | path := e.configPath() |
| 21 | b, err := readFileUTF8(path) |
| 22 | if err != nil { |
| 23 | if os.IsNotExist(err) { |
| 24 | return heartbeatConfigSnapshot{}, nil |
| 25 | } |
| 26 | return heartbeatConfigSnapshot{}, err |
| 27 | } |
| 28 | var cfg heartbeatConfig |
| 29 | if err := json.Unmarshal(b, &cfg); err != nil { |
| 30 | return heartbeatConfigSnapshot{}, fmt.Errorf("invalid config: %w", err) |
| 31 | } |
| 32 | // Reject future schemas on read as well as write: the scheduler must not |
| 33 | // execute tasks with scheduling or approval semantics this binary does not |
| 34 | // understand. |
| 35 | if cfg.SchemaVersion > heartbeatSchemaVersion { |
| 36 | return heartbeatConfigSnapshot{}, fmt.Errorf("heartbeat config schemaVersion %d is newer than this binary supports (%d); upgrade Reasonix", cfg.SchemaVersion, heartbeatSchemaVersion) |
| 37 | } |
| 38 | // Merge the run-history sidecar (execution journal kept outside the main |
| 39 | // config so an older binary cannot drop it on a full-table save). Union by |
| 40 | // execution timestamp and keep the newest maxRunHistory entries. |
| 41 | runs, err := e.readRunHistorySidecar(cfg) |
| 42 | if err != nil { |
| 43 | return heartbeatConfigSnapshot{}, err |
| 44 | } |
| 45 | if len(runs) > 0 { |
| 46 | for i := range cfg.Tasks { |
| 47 | if hist, ok := runs[cfg.Tasks[i].ID]; ok && len(hist) > 0 { |
| 48 | cfg.Tasks[i].RunHistory = mergeRunHistory(cfg.Tasks[i].RunHistory, hist) |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | snapshot := heartbeatConfigSnapshot{ |
| 53 | cfg: cfg, |
| 54 | digest: sha256.Sum256(b), |
| 55 | exists: true, |
| 56 | } |
| 57 | return snapshot, nil |
| 58 | } |
| 59 | |
| 60 | func (e *HeartbeatEngine) recordConfigSnapshotLocked(snapshot heartbeatConfigSnapshot) { |
| 61 | e.cfgRevision = snapshot.cfg.Revision |
| 62 | e.cfgDigest = snapshot.digest |
| 63 | e.cfgKnown = snapshot.exists |
| 64 | e.cfgInitialized = true |
| 65 | if snapshot.exists { |
| 66 | e.cfgDeleted = false |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // adoptExternalEditsLocked compares the exact content digest so edits are |
| 71 | // detected even on filesystems with coarse mtimes. |
| 72 | func (e *HeartbeatEngine) adoptExternalEditsLocked() { |
| 73 | snapshot, err := e.readConfigSnapshot() |
| 74 | if err != nil { |
| 75 | log.Printf("[heartbeat] invalid external config: %v", err) |
| 76 | return |
| 77 | } |
| 78 | if !snapshot.exists { |
| 79 | // Treat deletion of a previously observed config as authoritative. |
| 80 | // Retaining the old tasks would execute them on the next tick and recreate |
| 81 | // the file from stale state. |
| 82 | if e.cfgInitialized && e.cfgKnown { |
| 83 | e.tasks = nil |
| 84 | e.pendingTopics = make(map[string]heartbeatPendingTopic) |
| 85 | e.cfgDeleted = true |
| 86 | e.recordConfigSnapshotLocked(snapshot) |
| 87 | } |
| 88 | return |
| 89 | } |
| 90 | if e.cfgKnown && snapshot.digest == e.cfgDigest { |
| 91 | return |
| 92 | } |
| 93 | e.recordConfigSnapshotLocked(snapshot) |
| 94 | e.tasks = snapshot.cfg.Tasks |
| 95 | e.prunePendingTopicsLocked(e.tasks) |
| 96 | } |
| 97 | |
| 98 | func (e *HeartbeatEngine) writeTasks(tasks []HeartbeatTask, expected heartbeatConfigSnapshot, compare bool) error { |
| 99 | if tasks == nil { |
| 100 | tasks = []HeartbeatTask{} |
| 101 | } |
| 102 | path := e.configPath() |
| 103 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 104 | return err |
| 105 | } |
| 106 | lockCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 107 | defer cancel() |
| 108 | release, err := filelock.Acquire(lockCtx, path+".lock") |
| 109 | if err != nil { |
| 110 | return err |
| 111 | } |
| 112 | defer release() |
| 113 | |
| 114 | current, err := e.readConfigSnapshot() |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | // Forward protection: a config written by a future binary carries a |
| 119 | // schemaVersion this binary does not understand. Refuse to overwrite it |
| 120 | // with a full-table save instead of silently downgrading the schema. |
| 121 | if current.exists && current.cfg.SchemaVersion > heartbeatSchemaVersion { |
| 122 | return fmt.Errorf("heartbeat config schemaVersion %d is newer than this binary supports (%d); upgrade Reasonix before editing", current.cfg.SchemaVersion, heartbeatSchemaVersion) |
| 123 | } |
| 124 | if compare && (current.exists != expected.exists || current.digest != expected.digest || current.cfg.Revision != expected.cfg.Revision) { |
| 125 | return ErrHeartbeatConfigConflict |
| 126 | } |
| 127 | revision := current.cfg.Revision + 1 |
| 128 | if !current.exists { |
| 129 | revision = 1 |
| 130 | } |
| 131 | // Keep run history only in the sidecar so older full-table writers cannot |
| 132 | // drop it from heartbeat-tasks.json. The engine writes that owned state back |
| 133 | // through writeRunHistorySidecar. |
| 134 | sidecar := make(map[string][]HeartbeatRun, len(tasks)) |
| 135 | mainTasks := make([]HeartbeatTask, len(tasks)) |
| 136 | for i, t := range tasks { |
| 137 | mainTasks[i] = t |
| 138 | mainTasks[i].RunHistory = nil |
| 139 | if len(t.RunHistory) > 0 { |
| 140 | sidecar[t.ID] = t.RunHistory |
| 141 | } |
| 142 | } |
| 143 | cfg := heartbeatConfig{SchemaVersion: heartbeatSchemaVersion, Revision: revision, Tasks: mainTasks} |
| 144 | b, err := json.MarshalIndent(cfg, "", " ") |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | // Publish the sidecar first; the main config is the two-file commit marker. |
| 149 | // If the config write fails, restore the previous sidecar while the config |
| 150 | // lock remains held. |
| 151 | previousSidecar, sidecarReadErr := os.ReadFile(e.runHistoryPath()) |
| 152 | previousSidecarExists := sidecarReadErr == nil |
| 153 | if sidecarReadErr != nil && !os.IsNotExist(sidecarReadErr) { |
| 154 | return sidecarReadErr |
| 155 | } |
| 156 | if previousSidecarExists { |
| 157 | var persistedSidecar heartbeatRunHistorySidecar |
| 158 | if err := json.Unmarshal(previousSidecar, &persistedSidecar); err == nil && persistedSidecar.SchemaVersion > heartbeatRunHistorySchemaVersion { |
| 159 | return fmt.Errorf("heartbeat run-history sidecar schemaVersion %d is newer than this binary supports (%d); upgrade Reasonix before editing", persistedSidecar.SchemaVersion, heartbeatRunHistorySchemaVersion) |
| 160 | } |
| 161 | } |
| 162 | var previousGeneration *heartbeatRunHistoryGeneration |
| 163 | if current.exists { |
| 164 | previousGeneration = &heartbeatRunHistoryGeneration{ |
| 165 | Revision: current.cfg.Revision, |
| 166 | Runs: heartbeatRunHistoryByTask(current.cfg.Tasks), |
| 167 | } |
| 168 | } |
| 169 | if err := e.writeRunHistorySidecar(revision, sidecar, previousGeneration); err != nil { |
| 170 | return err |
| 171 | } |
| 172 | if err := fileutil.AtomicWriteFile(path, b, 0o644); err != nil { |
| 173 | var rollbackErr error |
| 174 | if previousSidecarExists { |
| 175 | rollbackErr = fileutil.AtomicWriteFile(e.runHistoryPath(), previousSidecar, 0o644) |
| 176 | } else if removeErr := os.Remove(e.runHistoryPath()); removeErr != nil && !os.IsNotExist(removeErr) { |
| 177 | rollbackErr = removeErr |
| 178 | } |
| 179 | if rollbackErr != nil { |
| 180 | return fmt.Errorf("write heartbeat config: %w (restore run-history sidecar: %w)", err, rollbackErr) |
| 181 | } |
| 182 | return err |
| 183 | } |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | func (e *HeartbeatEngine) mergeRunUpdatesLocked(updates map[string]HeartbeatTask) { |
| 188 | if len(updates) == 0 { |
| 189 | return |
| 190 | } |
| 191 | // Rebase onto the human/AI-editable disk list before saving. The engine owns |
| 192 | // only run-state fields; task definitions added, edited, or deleted outside |
| 193 | // this process remain authoritative. |
| 194 | for range 3 { |
| 195 | expected, err := e.readConfigSnapshot() |
| 196 | if err != nil { |
| 197 | log.Printf("[heartbeat] cannot read config before run-state merge: %v", err) |
| 198 | return |
| 199 | } |
| 200 | tasks := expected.cfg.Tasks |
| 201 | if !expected.exists { |
| 202 | switch { |
| 203 | case e.cfgDeleted || (e.cfgInitialized && e.cfgKnown): |
| 204 | // Observe deletion in this CAS loop too. A run can finish before the |
| 205 | // next scheduler tick adopts external edits; relying only on tick |
| 206 | // would let that completion recreate a file the user just removed. |
| 207 | e.tasks = nil |
| 208 | e.pendingTopics = make(map[string]heartbeatPendingTopic) |
| 209 | e.cfgDeleted = true |
| 210 | e.recordConfigSnapshotLocked(expected) |
| 211 | return |
| 212 | case !e.cfgInitialized: |
| 213 | // Only an engine that has never observed disk may bootstrap from an |
| 214 | // in-memory list. Once a config existed, deletion is authoritative. |
| 215 | tasks = append([]HeartbeatTask(nil), e.tasks...) |
| 216 | } |
| 217 | } |
| 218 | mergeHeartbeatRunUpdates(tasks, updates) |
| 219 | if err := e.writeTasks(tasks, expected, true); err != nil { |
| 220 | if errors.Is(err, ErrHeartbeatConfigConflict) { |
| 221 | continue |
| 222 | } |
| 223 | log.Printf("[heartbeat] run-state merge failed: %v", err) |
| 224 | return |
| 225 | } |
| 226 | latest, err := e.readConfigSnapshot() |
| 227 | if err != nil { |
| 228 | log.Printf("[heartbeat] reload after run-state merge: %v", err) |
| 229 | return |
| 230 | } |
| 231 | e.recordConfigSnapshotLocked(latest) |
| 232 | e.tasks = tasks |
| 233 | e.prunePendingTopicsLocked(tasks) |
| 234 | return |
| 235 | } |
| 236 | log.Printf("[heartbeat] run-state merge lost repeated config races; next tick will retry") |
| 237 | } |
| 238 | |
| 239 | func mergeHeartbeatRunUpdates(tasks []HeartbeatTask, updates map[string]HeartbeatTask) { |
| 240 | for i := range tasks { |
| 241 | update, ok := updates[tasks[i].ID] |
| 242 | if !ok { |
| 243 | continue |
| 244 | } |
| 245 | // Run state is monotonic. A runtime that lost the cross-process lease may |
| 246 | // merge a stale snapshot later, but must not roll back the owner's timestamp |
| 247 | // or fresh-conversation topic. |
| 248 | newerRun := update.LastRunAt > tasks[i].LastRunAt |
| 249 | if update.TopicID != "" && (tasks[i].TopicID == "" || newerRun) { |
| 250 | tasks[i].TopicID = update.TopicID |
| 251 | } |
| 252 | if newerRun { |
| 253 | tasks[i].LastRunAt = update.LastRunAt |
| 254 | } |
| 255 | if tasks[i].CreatedAt == 0 && update.CreatedAt != 0 { |
| 256 | tasks[i].CreatedAt = update.CreatedAt |
| 257 | } |
| 258 | // Merge run history: the on-disk list may be a stale snapshot (external |
| 259 | // edits or a tick that raced), so union by execution timestamp and keep |
| 260 | // the most recent maxRunHistory entries. |
| 261 | if len(update.RunHistory) > 0 { |
| 262 | tasks[i].RunHistory = mergeRunHistory(tasks[i].RunHistory, update.RunHistory) |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // mergeRunHistory unions two run-history lists by execution timestamp (At), |
| 268 | // dedupes, sorts oldest-first and keeps the newest maxRunHistory entries. Used |
| 269 | // by both the update-merge and the disk-protection paths below. |
| 270 | func mergeRunHistory(base, extra []HeartbeatRun) []HeartbeatRun { |
| 271 | merged := append([]HeartbeatRun(nil), base...) |
| 272 | seen := make(map[int64]bool, len(merged)) |
| 273 | for _, r := range merged { |
| 274 | seen[r.At] = true |
| 275 | } |
| 276 | for _, r := range extra { |
| 277 | if !seen[r.At] { |
| 278 | merged = append(merged, r) |
| 279 | } |
| 280 | } |
| 281 | sort.Slice(merged, func(a, b int) bool { return merged[a].At < merged[b].At }) |
| 282 | if len(merged) > maxRunHistory { |
| 283 | merged = merged[len(merged)-maxRunHistory:] |
| 284 | } |
| 285 | return merged |
| 286 | } |
| 287 | |
| 288 | // mergeHeartbeatDiskRunHistory protects engine-owned execution state during a |
| 289 | // frontend full-list save. A stale snapshot must not roll back TopicID or |
| 290 | // LastRunAt, and run history is unioned by timestamp so both snapshots survive. |
| 291 | func mergeHeartbeatDiskRunHistory(submitted, disk []HeartbeatTask) []HeartbeatTask { |
| 292 | if len(disk) == 0 { |
| 293 | return submitted |
| 294 | } |
| 295 | diskByID := make(map[string]HeartbeatTask, len(disk)) |
| 296 | for _, d := range disk { |
| 297 | diskByID[d.ID] = d |
| 298 | } |
| 299 | out := make([]HeartbeatTask, len(submitted)) |
| 300 | copy(out, submitted) |
| 301 | for i := range out { |
| 302 | diskTask, ok := diskByID[out[i].ID] |
| 303 | if !ok { |
| 304 | continue |
| 305 | } |
| 306 | out[i].TopicID = diskTask.TopicID |
| 307 | out[i].LastRunAt = diskTask.LastRunAt |
| 308 | // Always union by At: once history reaches maxRunHistory, a new disk run |
| 309 | // replaces the oldest entry without changing length, so length comparison |
| 310 | // would incorrectly drop the engine's new run. |
| 311 | out[i].RunHistory = mergeRunHistory(out[i].RunHistory, diskTask.RunHistory) |
| 312 | } |
| 313 | return out |
| 314 | } |
| 315 |