Compare commits

..

2 Commits

Author SHA1 Message Date
mix 98c820e3bd perf: cap the History list and fold column widths incrementally
History was appended to on every recorded run and never trimmed, and every
event re-sorted the whole slice and re-measured the Job, Detail and Log
columns across every row. The per-run cost therefore grew with the number of
rows, in exactly the mode the app is designed for: left in the tray for days.

The session History now keeps the newest maxHistoryRows (1000) records, the
way maxJobLogs caps a job's own activity list, and drops the oldest from the
front, zeroing the tail so a dropped record's full captured output is not
kept alive by the backing array. Column widths move into a historyLog value
that folds each new record into the current maxima instead of rescanning.
Widths only grow within a theme, so a column never narrows when a record ages
out; a theme change is the one case that still rescans, because every stored
width was measured at the old text size.

Measured with a throwaway benchmark over 5000 accumulated records: one
refresh went from 15.8 ms to 0.9 ms. At the new cap the full width rescan
alone costs 1.5 ms, so both halves of the fix carry weight.

Plan item 6 of docs/PROJECT_REVIEW_PLAN.md (finding 3.1).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 17:16:02 +03:00
mix 263717874c fix: remove no-op SaveJobs calls, fix PendingRuns lifecycle and cap
Implements items 4-5 of the whole-project review's suggested order
(docs/PROJECT_REVIEW_PLAN.md):

- Drop the three SaveJobs calls in the run lifecycle (startRunLocked,
  executeRun, SetGlobalPause): none of them change a durable Job field,
  everything they touch lives on JobRuntime, which is never persisted.
  Retire TestStartRunLockedRollbackOnSaveFailure with the rollback it
  guarded, since a run can no longer fail to start this way.
- Clear PendingRuns (the "queue" overlap policy's backlog) when a job is
  disabled or the scheduler is globally paused, so resuming or
  re-enabling a job no longer replays a deferred run left over from
  before the pause/disable. Cap it at maxPendingRuns (10) so a job whose
  runs take longer than its own interval stops accumulating an unbounded
  backlog. Surface the queued count in the details pane via DisplayStats.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 17:06:55 +03:00
12 changed files with 378 additions and 112 deletions
+14
View File
@@ -32,6 +32,20 @@ the app icon (experimental).**
loss mid-write can no longer leave a truncated or empty file. `Service.Stop()`
is now called when the app quits, which also makes the run context
cancellation reach in-flight runs on shutdown.
- Fixed the "queue" overlap policy's backlog (`PendingRuns`): it no longer
survives a global pause or a job being disabled, so resuming or re-enabling a
job can no longer replay a deferred run left over from before the pause/
disable. It is also capped at 10 queued occurrences, so a job whose runs take
longer than its own interval no longer accumulates an unbounded backlog that
then runs back-to-back indefinitely. The job details pane now shows the
queued-run count (", N queued") whenever it is non-zero.
- The History tab no longer grows without bound: it keeps the newest 1000
records and drops the oldest, the way a job's own activity list is capped.
Column widths are also folded in one record at a time instead of being
re-measured across every row on every event, so recording a run no longer
gets slower the longer the app has been running. Measured on 5000 accumulated
records, one History redraw went from **15.8 ms to 0.9 ms**; at the new cap
the width rescan alone accounted for 1.5 ms of every redraw.
**Jobs:**
+17
View File
@@ -65,6 +65,14 @@ change to their shape has to stay compatible on its own.
- **History tab is session-only.** `JobRuntime.Logs` exists only in memory for the
current process. Log files on disk feed aggregate statistics via `SeedStats`
only. See [ARCHITECTURE.md](ARCHITECTURE.md).
- **History is capped and its columns only widen.** The tab keeps the newest
`maxHistoryRows` records and drops the oldest, the way `maxJobLogs` caps a
job's own activity list — an app left in the tray records thousands of runs a
day, each carrying the run's full captured output. Column widths are folded in
one record at a time instead of rescanned from every row, so a column never
narrows when a record ages out: the rows on screen were laid out against the
wider value. A theme change is the one case that rescans, because every stored
width was measured at the old text size.
- Several tests share a coverage profile with another test on purpose, and a few
functions sit at 0% on purpose. Both lists live in
[TESTS.md](TESTS.md) — check them before reporting a test as redundant or a
@@ -79,6 +87,15 @@ change to their shape has to stay compatible on its own.
mid-session (see [ROADMAP.md](ROADMAP.md)).
- **`--start-in-tray` defers to config.** A stale autostart shortcut that still
passes the flag does not hide the window when `KeepRunningInTray` is off.
- **`JobRuntime.PendingRuns` (the "queue" overlap policy's backlog) is capped at
`maxPendingRuns` (10) and cleared on pause or disable.** A job whose runs take
longer than its interval stops accumulating backlog once the cap is hit —
further overlaps are dropped like the "skip" policy until the backlog drains
below the cap. `SetGlobalPause(true)` and `SetEnabled(id, false)` both zero
the counter, so resuming or re-enabling a job never replays a deferred run for
an occurrence that fired before the pause/disable. The details pane appends
", N queued" to the statistics line via `DisplayStats` whenever the count is
non-zero.
## Out of scope
+7 -2
View File
@@ -136,6 +136,7 @@ Tests all mutating operations on the Service, scheduler integration, and setting
| `TestDeleteJobNotFound` | Verifies that `DeleteJob` returns an error for an unknown job ID. |
| `TestSetEnabledNotFound` | Verifies that `SetEnabled` returns an error for an unknown job ID. |
| `TestSetEnabledToggles` | Verifies that `SetEnabled` flips the enabled flag and persists the change. |
| `TestSetEnabledClearsPendingRuns` | Verifies that disabling a job zeroes a `PendingRuns` backlog it was carrying, so re-enabling it later does not replay a stale deferred run. |
#### Global pause / run-now / run-due
@@ -187,11 +188,11 @@ and scheduler edge cases using injected `runJob` and `primeDue`.
| `TestRunDueSkipDropsOverlap` | Global skip: no second concurrent run, `PendingRuns` stays 0. |
| `TestRunDueQueueRerunsAfterFinish` | Queue: one deferred run after an in-flight finish; also covers an empty per-job policy inheriting the global default. |
| `TestRunDueQueueDrainsMultipleOverlaps` | Queue: multiple missed ticks drain as separate runs. |
| `TestRunDueQueueCapsPendingRuns` | Regression: `PendingRuns` stops growing at `maxPendingRuns` instead of accumulating without bound for a job that never keeps up with its schedule. |
| `TestRunDuePerJobQueueOverridesGlobalSkip` | Per-job `queue` beats global `skip`. |
| `TestRunDuePerJobSkipOverridesGlobalQueue` | Per-job `skip` beats global `queue`. |
| `TestRunNowSequentialGuard` | Manual run refused while another job runs in sequential mode. |
| `TestStartRunLockedRollbackOnSaveFailure` | Regression: run does not start when `SaveJobs` fails. |
| `TestRunDueQueueDrainSkippedWhenPaused` | Queued overlaps are not drained while the scheduler is paused. |
| `TestRunDueQueueDrainSkippedWhenPaused` | Queued overlaps are not drained while the scheduler is paused, and pausing clears the backlog rather than leaving it to fire a stale deferred run on resume. |
| `TestEffectiveTimeout` | Verifies the three-state resolution: `nil` inherits the global default, a positive value overrides it, and an explicit `0` means no timeout without inheriting. |
---
@@ -493,6 +494,10 @@ column-width behaviour of the assembled table.
| `TestHistoryCellTemplateIsPlainText` | Verifies the cell template already carries the zero `TextStyle`, since the per-cell assignment that used to reset it is gone. |
| `TestTextColumnWidthClamps` | Covers the three shapes of `textColumnWidth`: below the minimum, in range, and capped at the maximum. |
| `TestHistoryColumnsFitTheirContent` | Verifies every column is at least as wide as its widest known or present value, at the default text size and at a scaled theme. |
| `TestHistoryLogCapsRecords` | Regression guard for the unbounded History list: the log keeps the newest `maxHistoryRows` records, drops the oldest from the front, and trims a list handed in already over the cap. |
| `TestHistoryLogWidthsMatchAFullScan` | Verifies the incremental column widths equal a full rescan while every measured record is still present — the cheaper path must not clip what the old one showed. |
| `TestHistoryLogWidthsDoNotShrinkWhenRecordsAgeOut` | Verifies a column keeps its width after the record that set it is dropped by the cap, since the rows on screen were laid out against it. |
| `TestHistoryLogRescansOnThemeChange` | Verifies a theme change falls back to a full rescan, the one case the incremental fold cannot handle because every stored width was measured at the old text size. |
---
+18 -3
View File
@@ -82,14 +82,29 @@ func DisplayInvocation(job domain.Job) string {
return job.Command + " " + strings.ReplaceAll(strings.TrimSpace(job.Arguments), "\n", " ")
}
// DisplayStats returns a one-line execution-time summary for a job runtime.
// Returns "No runs recorded" when no runs have been counted yet.
// DisplayStats returns a one-line execution-time summary for a job runtime,
// with the queued-run depth appended whenever the "queue" overlap policy has
// deferred runs waiting (see maxPendingRuns). Returns "No runs recorded" when
// no runs have been counted yet, still showing the queue depth if one exists.
func DisplayStats(rt *domain.JobRuntime) string {
if rt == nil || rt.RunCount == 0 {
if rt != nil && rt.PendingRuns > 0 {
return "No runs recorded" + pendingRunsSuffix(rt.PendingRuns)
}
return "No runs recorded"
}
return fmt.Sprintf("%d runs, %d failed, last %d ms, avg %d ms, max %d ms",
rt.RunCount, rt.FailCount, rt.LastDurationMS, rt.AvgDurationMS, rt.MaxDurationMS)
rt.RunCount, rt.FailCount, rt.LastDurationMS, rt.AvgDurationMS, rt.MaxDurationMS) +
pendingRunsSuffix(rt.PendingRuns)
}
// pendingRunsSuffix formats the queued-run depth for DisplayStats, empty when
// nothing is queued.
func pendingRunsSuffix(pending int) string {
if pending <= 0 {
return ""
}
return fmt.Sprintf(", %d queued", pending)
}
// DisplayOverlapPolicy formats a job's effective overlap policy for the details
+11
View File
@@ -126,6 +126,17 @@ func TestDisplayStats(t *testing.T) {
if got := DisplayStats(rtNoFail); got != wantNoFail {
t.Errorf("DisplayStats no-fail = %q, want %q", got, wantNoFail)
}
// A "queue" overlap backlog is appended to whichever form applies, so it stays
// visible even before the first run has completed.
if got, want := DisplayStats(&domain.JobRuntime{PendingRuns: 2}), "No runs recorded, 2 queued"; got != want {
t.Errorf("DisplayStats pending, no runs = %q, want %q", got, want)
}
rtPending := &domain.JobRuntime{RunCount: 5, FailCount: 2, LastDurationMS: 450, AvgDurationMS: 380, MaxDurationMS: 520, PendingRuns: 3}
wantPending := "5 runs, 2 failed, last 450 ms, avg 380 ms, max 520 ms, 3 queued"
if got := DisplayStats(rtPending); got != wantPending {
t.Errorf("DisplayStats pending = %q, want %q", got, wantPending)
}
}
func TestEventLine(t *testing.T) {
+11 -3
View File
@@ -148,6 +148,10 @@ func (s *Service) SetEnabled(id int, enabled bool) error {
runtime.LastState = "Paused"
runtime.NextRun = "Paused"
runtime.NextDue = time.Time{}
// A disabled job's own occurrences stop firing, so a "queue" backlog it was
// carrying no longer corresponds to anything: clear it rather than replaying
// stale deferred runs if the job is re-enabled later.
runtime.PendingRuns = 0
record = uiRecord(id, job.Name, "Paused", "Job was disabled")
}
prependLog(runtime, record)
@@ -175,12 +179,16 @@ func (s *Service) SetGlobalPause(paused bool) error {
for index := range s.jobs {
job := &s.jobs[index]
runtime := s.runtimeForLocked(job)
if paused {
// A "queue" backlog counts occurrences missed *while paused is off*; once
// paused, none of those correspond to anything the user would expect
// replayed on resume, so drop it rather than letting a stale counter fire
// a deferred run for an occurrence from before the pause.
runtime.PendingRuns = 0
}
s.refreshNextRunFromLocked(job, runtime, now)
}
err := s.store.SaveConfig()
if err == nil {
err = s.store.SaveJobs(s.jobs)
}
s.mu.Unlock()
if err != nil {
+17
View File
@@ -217,6 +217,23 @@ func TestSetEnabledToggles(t *testing.T) {
}
}
// TestSetEnabledClearsPendingRuns verifies that disabling a job drops any
// "queue" overlap backlog it was carrying, so re-enabling it later does not
// replay a deferred run for an occurrence that fired before the disable.
func TestSetEnabledClearsPendingRuns(t *testing.T) {
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
svc.mu.Lock()
svc.runtimes[1].PendingRuns = 2
svc.mu.Unlock()
if err := svc.SetEnabled(1, false); err != nil {
t.Fatalf("SetEnabled false: %v", err)
}
if rt := svc.Runtime(1); rt.PendingRuns != 0 {
t.Errorf("PendingRuns after disable = %d, want 0", rt.PendingRuns)
}
}
func TestSetGlobalPauseUpdatesRuntimesAndEmits(t *testing.T) {
svc := newTempService(t, []domain.Job{
{ID: 1, Name: "On", Schedule: "@every 1m", Command: "echo", Enabled: true},
+22 -39
View File
@@ -11,6 +11,13 @@ import (
"gitea.mixdep.ru/mix/gosentry/src/runner"
)
// maxPendingRuns bounds how many missed occurrences the "queue" overlap policy
// will defer for one job. Without a ceiling a job whose runs take longer than
// its interval would queue one more occurrence on every tick forever, so once
// the cap is reached further overlaps are dropped exactly as the "skip" policy
// would drop them, until the backlog drains below the cap again.
const maxPendingRuns = 10
// RunNow starts a manual run of a job. Global pause stops only the scheduler's
// automatic runs (see RunDue), so a manual "Run now" is allowed even while
// paused — it is the user's explicit, one-off action. It will not start a job
@@ -36,14 +43,12 @@ func (s *Service) RunNow(id int) error {
s.mu.Unlock()
return errors.New("another job is already running (sequential mode)")
}
err := s.startRunLocked(job, runtime, "Manual", time.Now())
s.startRunLocked(job, runtime, "Manual", time.Now())
s.mu.Unlock()
if err == nil {
// Reflect the "Running" transition; the run's completion emits again later.
s.emit(JobChanged{JobID: id})
}
return err
return nil
}
// RunDue is the scheduler's per-tick entry point: it starts whatever is due at
@@ -63,7 +68,6 @@ func (s *Service) RunNow(id int) error {
func (s *Service) RunDue(now time.Time) {
s.mu.Lock()
var started []int
var startErr error
if !s.paused {
sequential := s.store.Config.ExecutionMode == domain.ExecutionModeSequential
running := s.anyRunningLocked()
@@ -77,7 +81,7 @@ func (s *Service) RunDue(now time.Time) {
// The job came due again while its own run is still in flight.
// Apply the effective overlap policy and step past this
// occurrence.
if s.effectiveOverlapPolicy(job) == domain.OverlapPolicyQueue {
if s.effectiveOverlapPolicy(job) == domain.OverlapPolicyQueue && runtime.PendingRuns < maxPendingRuns {
runtime.PendingRuns++
}
s.advanceNextDueLocked(job, runtime, now)
@@ -88,19 +92,13 @@ func (s *Service) RunDue(now time.Time) {
// tick once the in-flight run has finished.
continue
}
if err := s.startRunLocked(job, runtime, "Schedule", now); err != nil {
startErr = err
continue
}
s.startRunLocked(job, runtime, "Schedule", now)
started = append(started, job.ID)
running = true
}
}
s.mu.Unlock()
if startErr != nil {
s.emit(ErrorOccurred{Err: fmt.Errorf("save jobs before scheduled run: %w", startErr)})
}
for _, id := range started {
s.emit(JobChanged{JobID: id})
}
@@ -116,29 +114,19 @@ type runEnv struct {
}
// startRunLocked transitions a job to "Running", advances its NextDue to the next
// scheduled occurrence, persists that, and launches the run on a background
// goroutine. Advancing (rather than zeroing) NextDue keeps the schedule marching
// while the run is in flight, which is what lets RunDue notice a fresh occurrence
// firing during a long run and apply the overlap policy. The caller must hold mu.
// now is the reference time for next-due advancement and the running placeholder.
func (s *Service) startRunLocked(job *domain.Job, runtime *domain.JobRuntime, trigger string, now time.Time) error {
// scheduled occurrence, and launches the run on a background goroutine. Neither
// step touches a durable field — both live on JobRuntime, which is never
// persisted — so there is nothing to save here. Advancing (rather than zeroing)
// NextDue keeps the schedule marching while the run is in flight, which is what
// lets RunDue notice a fresh occurrence firing during a long run and apply the
// overlap policy. The caller must hold mu. now is the reference time for
// next-due advancement and the running placeholder.
func (s *Service) startRunLocked(job *domain.Job, runtime *domain.JobRuntime, trigger string, now time.Time) {
jobCopy := *job
prevState := runtime.LastState
prevNextRun := runtime.NextRun
prevOutput := runtime.Output
prevNextDue := runtime.NextDue
runtime.LastState = "Running"
runtime.NextRun = "Running"
runtime.Output = runningOutput(jobCopy, trigger, now)
s.advanceNextDueLocked(job, runtime, now)
if err := s.store.SaveJobs(s.jobs); err != nil {
runtime.LastState = prevState
runtime.NextRun = prevNextRun
runtime.Output = prevOutput
runtime.NextDue = prevNextDue
return err
}
env := runEnv{
logsDir: s.store.Paths.LogsDir,
maxFiles: s.store.Config.MaxLogFiles,
@@ -148,7 +136,6 @@ func (s *Service) startRunLocked(job *domain.Job, runtime *domain.JobRuntime, tr
// Capture ctx under the lock so a concurrent Start/Stop cannot swap it out
// from under the goroutine after we release mu.
go s.executeRun(s.ctx, jobCopy, trigger, env)
return nil
}
// executeRun runs the job off the lock, then records the result back through the
@@ -160,7 +147,7 @@ func (s *Service) executeRun(ctx context.Context, jobCopy domain.Job, trigger st
record, logErr := s.runJob(ctx, &jobCopy, trigger, env.logsDir, env.timeout)
s.mu.Lock()
var cleanupErr, saveErr error
var cleanupErr error
var rerunStarted bool
if current := s.findByIDLocked(jobCopy.ID); current != nil {
runtime := s.runtimeForLocked(current)
@@ -174,11 +161,10 @@ func (s *Service) executeRun(ctx context.Context, jobCopy domain.Job, trigger st
runtime.PendingRuns--
// A scheduled occurrence fired while this run was active under the
// "queue" policy; start one deferred run now.
saveErr = s.startRunLocked(current, runtime, "Schedule", time.Now())
rerunStarted = saveErr == nil
s.startRunLocked(current, runtime, "Schedule", time.Now())
rerunStarted = true
} else {
s.refreshNextRunLocked(current, runtime)
saveErr = s.store.SaveJobs(s.jobs)
}
cleanupErr = runner.CleanupLogs(env.logsDir, env.maxFiles, env.maxAge)
}
@@ -190,9 +176,6 @@ func (s *Service) executeRun(ctx context.Context, jobCopy domain.Job, trigger st
if cleanupErr != nil {
s.emit(ErrorOccurred{Err: fmt.Errorf("log cleanup after run %q: %w", jobCopy.Name, cleanupErr)})
}
if saveErr != nil {
s.emit(ErrorOccurred{Err: fmt.Errorf("save jobs after run %q: %w", jobCopy.Name, saveErr)})
}
s.emit(RunRecorded{Record: record})
if !rerunStarted {
s.emit(JobChanged{JobID: jobCopy.ID})
+47 -33
View File
@@ -2,7 +2,6 @@ package app
import (
"context"
"os"
"sync/atomic"
"testing"
"time"
@@ -359,6 +358,42 @@ func TestRunDueQueueDrainsMultipleOverlaps(t *testing.T) {
}
}
// TestRunDueQueueCapsPendingRuns verifies that a job whose runs never keep up
// with its schedule stops accumulating PendingRuns at maxPendingRuns instead of
// growing without bound.
func TestRunDueQueueCapsPendingRuns(t *testing.T) {
svc := newQueueService(t, domain.ExecutionModeParallel, domain.OverlapPolicyQueue, []domain.Job{
{ID: 1, Name: "A", Schedule: "@every 1h", Command: "echo", Enabled: true},
})
release := make(chan struct{})
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
<-release
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
}
done := completions(svc)
t.Cleanup(func() {
close(release)
waitRecord(t, done)
})
primeDue(t, svc, 1)
svc.RunDue(time.Now())
// Far more due ticks than the cap while the first run stays in flight.
for range maxPendingRuns + 5 {
primeDue(t, svc, 1)
svc.RunDue(time.Now())
}
svc.mu.Lock()
pending := svc.runtimes[1].PendingRuns
svc.mu.Unlock()
if pending != maxPendingRuns {
t.Fatalf("PendingRuns = %d, want capped at %d", pending, maxPendingRuns)
}
}
// TestRunDuePerJobQueueOverridesGlobalSkip verifies that a job carrying its own
// "queue" policy queues a re-run even though the global default is "skip": the
// effective policy is resolved per job, so the job-level value wins.
@@ -493,37 +528,9 @@ func TestRunNowSequentialGuard(t *testing.T) {
waitRecord(t, done)
}
// TestStartRunLockedRollbackOnSaveFailure is a regression test for CODE_REVIEW
// finding #2: a run must not start when persisting the Running state fails.
func TestStartRunLockedRollbackOnSaveFailure(t *testing.T) {
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1h", Command: "echo", Enabled: true}})
if err := svc.store.SaveJobs(svc.jobs); err != nil {
t.Fatalf("seed jobs.json: %v", err)
}
if err := os.Chmod(svc.store.Paths.JobsPath, 0o444); err != nil {
t.Fatalf("chmod jobs.json: %v", err)
}
t.Cleanup(func() { _ = os.Chmod(svc.store.Paths.JobsPath, 0o644) })
var started int32
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
atomic.AddInt32(&started, 1)
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "OK"}, nil
}
if err := svc.RunNow(1); err == nil {
t.Fatal("expected RunNow to fail when jobs.json is not writable")
}
if atomic.LoadInt32(&started) != 0 {
t.Error("run goroutine must not start when SaveJobs fails")
}
if rt := svc.Runtime(1); rt == nil || rt.LastState == "Running" {
t.Errorf("runtime should roll back from Running, got %+v", rt)
}
}
// TestRunDueQueueDrainSkippedWhenPaused verifies that queued overlap runs are not
// drained while the scheduler is globally paused.
// drained while the scheduler is globally paused, and that pausing clears the
// backlog rather than leaving it to fire a stale deferred run on resume.
func TestRunDueQueueDrainSkippedWhenPaused(t *testing.T) {
svc := newQueueService(t, domain.ExecutionModeParallel, domain.OverlapPolicyQueue, []domain.Job{
{ID: 1, Name: "A", Schedule: "@every 1h", Command: "echo", Enabled: true},
@@ -561,6 +568,13 @@ func TestRunDueQueueDrainSkippedWhenPaused(t *testing.T) {
t.Fatalf("SetGlobalPause: %v", err)
}
svc.mu.Lock()
pending = svc.runtimes[1].PendingRuns
svc.mu.Unlock()
if pending != 0 {
t.Errorf("pausing must clear a queued backlog, PendingRuns = %d, want 0", pending)
}
close(release)
waitRecord(t, done)
expectNoEntry(t, entered)
@@ -568,8 +582,8 @@ func TestRunDueQueueDrainSkippedWhenPaused(t *testing.T) {
svc.mu.Lock()
pending = svc.runtimes[1].PendingRuns
svc.mu.Unlock()
if pending != 1 {
t.Errorf("paused scheduler must not drain queue, PendingRuns = %d, want 1", pending)
if pending != 0 {
t.Errorf("paused scheduler must not drain queue, PendingRuns = %d, want 0", pending)
}
if got := atomic.LoadInt32(&calls); got != 1 {
t.Errorf("runner called %d time(s), want 1", got)
+111 -20
View File
@@ -102,23 +102,113 @@ const historyTimeSample = "2026-01-02 15:04:05"
// Detail and Log are free text, so their width tracks the values actually
// present, bounded the same way the Log column always was.
func historyColumnWidths(rows []event) [6]float32 {
jobNames := make([]string, 0, len(rows))
details := make([]string, 0, len(rows))
logNames := make([]string, 0, len(rows))
var content [3][]string
for i := range content {
content[i] = make([]string, 0, len(rows))
}
for _, current := range rows {
jobNames = append(jobNames, current.JobName)
details = append(details, current.Detail)
logNames = append(logNames, logFileName(current.LogFile))
for i, value := range historyContentValues(current) {
content[i] = append(content[i], value)
}
}
min, max := textColumnMinWidth(), textColumnMaxWidth()
return [6]float32{
textWidth(historyTimeSample) + cellPadding(),
textColumnWidth(historyTriggerSamples, min, max),
textColumnWidth(jobNames, min, max),
textColumnWidth(historyStateSamples, min, max),
textColumnWidth(details, min, max),
textColumnWidth(logNames, min, max),
widths := [6]float32{
0: textWidth(historyTimeSample) + cellPadding(),
1: textColumnWidth(historyTriggerSamples, min, max),
3: textColumnWidth(historyStateSamples, min, max),
}
for i, col := range historyContentCols {
widths[col] = textColumnWidth(content[i], min, max)
}
return widths
}
// maxHistoryRows caps the session History list, the way app.maxJobLogs caps a
// job's own activity list. History is never persisted and every record carries
// the run's full captured output, so an app left running in the tray — the mode
// GoSentry is designed for — would otherwise hold every record of every run
// forever, and pay a full resort plus a full column-width rescan on each new
// one. One job on @every 10s produces ~8 600 records a day.
const maxHistoryRows = 1000
// historyLog is the session History: the capped record list plus the column
// widths measured from it. It exists so the widths can be folded in one record
// at a time instead of being recomputed from every row on every event, which
// is what made the per-event cost grow with the number of rows.
type historyLog struct {
records []event
widths [6]float32
// textSize and padding are the theme metrics widths were last measured at.
// A theme change invalidates every measurement, so it forces a full rescan
// rather than folding new records into stale numbers.
textSize float32
padding float32
}
func newHistoryLog(records []event) *historyLog {
h := &historyLog{records: trimHistory(records)}
h.rescan()
return h
}
// trimHistory drops the oldest records past the cap. The tail of the backing
// array is zeroed because a dropped record holds the run's whole output, which
// would otherwise stay reachable until the slice happens to be reallocated.
func trimHistory(records []event) []event {
if len(records) <= maxHistoryRows {
return records
}
kept := copy(records, records[len(records)-maxHistoryRows:])
for i := kept; i < len(records); i++ {
records[i] = event{}
}
return records[:kept]
}
// add appends one record and widens any content-measured column the record
// does not fit. Widths only ever grow within a theme: a column is never
// narrowed when a record ages out, because the rows still on screen were laid
// out against the wider value.
func (h *historyLog) add(record event) {
h.records = trimHistory(append(h.records, record))
if h.stale() {
h.rescan()
return
}
min, max := textColumnMinWidth(), textColumnMaxWidth()
for i, value := range historyContentValues(record) {
if width := textColumnWidth([]string{value}, min, max); width > h.widths[historyContentCols[i]] {
h.widths[historyContentCols[i]] = width
}
}
}
// columnWidths returns the widths to apply to the table, rescanning every
// record only when the theme's text metrics have changed since the last scan.
func (h *historyLog) columnWidths() [6]float32 {
if h.stale() {
h.rescan()
}
return h.widths
}
func (h *historyLog) stale() bool {
return theme.TextSize() != h.textSize || cellPadding() != h.padding
}
func (h *historyLog) rescan() {
h.textSize, h.padding = theme.TextSize(), cellPadding()
h.widths = historyColumnWidths(h.records)
}
// historyContentCols are the columns whose width follows the values actually
// present, in the order historyContentValues returns them. Both the
// incremental fold in add and the full scan in historyColumnWidths go through
// this pair, so they cannot disagree about which columns follow content.
var historyContentCols = [3]int{2, 4, 5}
func historyContentValues(record event) [3]string {
return [3]string{record.JobName, record.Detail, logFileName(record.LogFile)}
}
// historyHeader is a bold tappable label used in the History table header row.
@@ -156,7 +246,7 @@ func (h *historyHeader) SetText(text string) {
// Time caption is built per update because it carries the sort direction arrow.
var historyHeaders = [...]string{"Time", "Trigger", "Job", "State", "Detail", "Log"}
func newHistoryView(events *[]event) (*fyne.Container, func()) {
func newHistoryView(log *historyLog) (*fyne.Container, func()) {
descending := false
headerText := func(id widget.TableCellID) string {
if id.Row < 0 && id.Col == 0 {
@@ -179,7 +269,7 @@ func newHistoryView(events *[]event) (*fyne.Container, func()) {
// per redraw: at build time, on a sort toggle, and from refresh().
var rows []event
resort := func() {
rows = append(rows[:0], (*events)...)
rows = append(rows[:0], log.records...)
sort.SliceStable(rows, func(left int, right int) bool {
if descending {
return rows[left].Time > rows[right].Time
@@ -224,16 +314,17 @@ func newHistoryView(events *[]event) (*fyne.Container, func()) {
table.Unselect(id)
}
setColumnWidths := func() {
for col, width := range historyColumnWidths(rows) {
for col, width := range log.columnWidths() {
table.SetColumnWidth(col, width)
}
}
setColumnWidths()
// refresh re-reads the event list into the sorted snapshot and recomputes
// every content-fit column width before redrawing, so newly recorded events
// appear in the current sort order and longer values widen their column
// instead of being truncated.
// refresh re-reads the event list into the sorted snapshot and re-applies
// the column widths before redrawing, so newly recorded events appear in
// the current sort order and longer values widen their column instead of
// being truncated. The widths come from historyLog, which folded each new
// record in as it arrived — this does not rescan every row.
refresh := func() {
resort()
setColumnWidths()
+95 -4
View File
@@ -1,6 +1,7 @@
package ui
import (
"strconv"
"strings"
"testing"
"time"
@@ -144,7 +145,8 @@ func TestHistorySortToggleKeepsRowsInSync(t *testing.T) {
{Time: "2026-06-01 11:00:00", JobName: "B"},
{Time: "2026-06-01 12:00:00", JobName: "C"},
}
content, refresh := newHistoryView(&events)
log := newHistoryLog(events)
content, refresh := newHistoryView(log)
table, ok := content.Objects[0].(*widget.Table)
if !ok {
t.Fatal("history view does not wrap a table")
@@ -192,7 +194,7 @@ func TestHistorySortToggleKeepsRowsInSync(t *testing.T) {
// A new run arrives while the table is sorted newest-first: it must be
// counted and placed in the order currently on screen, not the build-time one.
events = append(events, event{Time: "2026-06-01 13:00:00", JobName: "D"})
log.add(event{Time: "2026-06-01 13:00:00", JobName: "D"})
refresh()
assertOrder("descending after refresh", "D", "C", "B", "A")
@@ -207,8 +209,7 @@ func TestHistoryCellTemplateIsPlainText(t *testing.T) {
testApp := test.NewApp()
defer testApp.Quit()
var events []event
content, _ := newHistoryView(&events)
content, _ := newHistoryView(newHistoryLog(nil))
table := content.Objects[0].(*widget.Table)
label, ok := table.CreateCell().(*widget.Label)
if !ok {
@@ -292,6 +293,96 @@ func TestHistoryColumnsFitTheirContent(t *testing.T) {
check("scaled theme")
}
// TestHistoryLogCapsRecords is the regression guard for the unbounded History
// list: an app left in the tray records thousands of runs a day, each carrying
// the run's whole captured output, so the list must drop the oldest instead of
// growing forever.
func TestHistoryLogCapsRecords(t *testing.T) {
testApp := test.NewApp()
defer testApp.Quit()
log := newHistoryLog(nil)
for i := 0; i < maxHistoryRows+25; i++ {
log.add(event{Time: "t", JobName: "Job " + strconv.Itoa(i)})
}
if len(log.records) != maxHistoryRows {
t.Fatalf("record count = %d, want capped at %d", len(log.records), maxHistoryRows)
}
if got, want := log.records[0].JobName, "Job 25"; got != want {
t.Errorf("oldest kept record = %q, want %q — the cap must drop from the front", got, want)
}
last := log.records[len(log.records)-1].JobName
if want := "Job " + strconv.Itoa(maxHistoryRows+24); last != want {
t.Errorf("newest record = %q, want %q", last, want)
}
// A list handed in above the cap is trimmed too, not only one grown into it.
oversized := make([]event, maxHistoryRows+10)
if got := len(newHistoryLog(oversized).records); got != maxHistoryRows {
t.Errorf("pre-filled log length = %d, want %d", got, maxHistoryRows)
}
}
// TestHistoryLogWidthsMatchAFullScan pins the incremental column widths: while
// every measured record is still in the list, folding each one in as it
// arrives must give exactly what rescanning every row would, or the cheaper
// path would clip values the old one showed.
func TestHistoryLogWidthsMatchAFullScan(t *testing.T) {
testApp := test.NewApp()
defer testApp.Quit()
log := newHistoryLog(nil)
for _, record := range []event{
{Time: "1", JobName: "A", Detail: "short", LogFile: `/logs/a.log`},
{Time: "2", JobName: "A moderately long job name", Detail: "a longer detail message", LogFile: `/logs/20260601-120000_SomeJobName.log`},
{Time: "3", JobName: "B", Detail: "s", LogFile: `/logs/b.log`},
} {
log.add(record)
}
if got, want := log.columnWidths(), historyColumnWidths(log.records); got != want {
t.Errorf("incremental widths = %v, want the full-scan widths %v", got, want)
}
}
// TestHistoryLogWidthsDoNotShrinkWhenRecordsAgeOut covers the other half of the
// rule: widths only grow. Dropping the record that set a column's width must
// not narrow the column, because the rows on screen were laid out against it.
func TestHistoryLogWidthsDoNotShrinkWhenRecordsAgeOut(t *testing.T) {
testApp := test.NewApp()
defer testApp.Quit()
log := newHistoryLog(nil)
log.add(event{Time: "1", JobName: "A job name long enough to widen its column"})
widest := log.columnWidths()[2]
for i := 0; i < maxHistoryRows; i++ {
log.add(event{Time: "t", JobName: "x"})
}
if got := log.columnWidths()[2]; got != widest {
t.Errorf("Job column width = %v after the wide record aged out, want it held at %v", got, widest)
}
}
// TestHistoryLogRescansOnThemeChange guards the one case the incremental fold
// cannot handle: every stored width was measured at the old text size, so a
// theme change has to fall back to a full rescan.
func TestHistoryLogRescansOnThemeChange(t *testing.T) {
testApp := test.NewApp()
defer testApp.Quit()
log := newHistoryLog([]event{
{Time: "1", JobName: "A moderately long job name", Detail: "a longer detail message"},
})
before := log.columnWidths()
testApp.Settings().SetTheme(test.NewTheme())
after := log.columnWidths()
if after == before {
t.Fatal("widths unchanged after a theme change; the fixture theme must alter text metrics")
}
if want := historyColumnWidths(log.records); after != want {
t.Errorf("widths after theme change = %v, want the rescanned %v", after, want)
}
}
func TestNewEventUsesConsistentTimestampShape(t *testing.T) {
ev := newEvent(1, "Job", "OK", "detail")
if _, err := time.Parse("2006-01-02 15:04:05", ev.Time); err != nil {
+6 -6
View File
@@ -34,11 +34,11 @@ func newMainView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func(time.
initialRuntimes[j.ID] = rt
}
}
events := collectActivity(initialJobs, initialRuntimes)
events := newHistoryLog(collectActivity(initialJobs, initialRuntimes))
jobsPanel, refreshJobsView := newJobsView(w, svc)
history, refreshHistory := newHistoryView(&events)
history, refreshHistory := newHistoryView(events)
recordStartup := func(duration time.Duration, windowShown bool) {
// Startup is recorded as an in-memory History event instead of being
// persisted into jobs.json. It is session diagnostics, not durable job
@@ -48,7 +48,7 @@ func newMainView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func(time.
if !windowShown {
detail = "Started in tray in " + duration.Round(time.Millisecond).String()
}
events = append(events, newEvent(0, "Application", "Started", detail))
events.add(newEvent(0, "Application", "Started", detail))
refreshHistory()
}
@@ -70,7 +70,7 @@ func newMainView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func(time.
jobsLoaded, isJobsLoaded := ev.(app.JobsLoaded)
fyne.Do(func() {
if isRecorded {
events = append(events, recorded.Record)
events.add(recorded.Record)
r := recorded.Record
if r.State == "Failed" &&
(r.Trigger == "Manual" || r.Trigger == "Schedule") &&
@@ -96,13 +96,13 @@ func newMainView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func(time.
}
}
if isError {
events = append(events, newEvent(0, "Service", "Error", errOccurred.Err.Error()))
events.add(newEvent(0, "Service", "Error", errOccurred.Err.Error()))
}
if isJobsLoaded {
// Selecting an existing jobs file replaces the job list without a
// prompt, so History carries the receipt: how many jobs, from where.
detail := strconv.Itoa(jobsLoaded.Count) + " jobs from " + jobsLoaded.Path
events = append(events, newEvent(0, "Service", "Jobs loaded", detail))
events.add(newEvent(0, "Service", "Jobs loaded", detail))
}
refresh()
})