fix: harden Landwelle cron jobs, job snapshots and build guard v1.5.74

* fix(ai): atomically claim cron tasks and isolate job status snapshots

* test(ai): verify independent job snapshots, retention and atomic cron claim

* fix(build): detect obsolete untracked Go files before compilation

* chore(release): mark Landwelle v1.5.74

* chore(release): mark Landwelle v1.5.74

* docs: document v1.5.74 fixes and deferred architecture

* docs: add operational release notes for v1.5.74

* ci: prove stale local Go files are rejected before ARM build

* fix(build): restore script and correct untracked-source guard

* fix(build): use correctly escaped Go-source pattern
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-21 15:42:36 +02:00
1 parent 1831e499c8
commit a6eb693c32
8 files changed
+171 -5

No files matched your search

+10
View File
@@ -91,3 +91,13 @@ jobs:
find scripts -name '*.sh' -print0 | while IFS= read -r -d '' file; do
bash -n "$file"
done
- name: Refuse unexpected local Go files
run: |
trap 'rm -f destination_one_ci_sentinel.go' EXIT
printf 'package main\n' > destination_one_ci_sentinel.go
if ./scripts/build-pi.sh > /tmp/landwelle-build-guard.log 2>&1; then
echo "Build unexpectedly accepted an untracked Go source" >&2
exit 1
fi
grep -q destination_one_ci_sentinel.go /tmp/landwelle-build-guard.log
+7
View File
@@ -1,3 +1,10 @@
## v1.5.74
- Automatische KI-Nachrichtenaufträge werden atomar in PostgreSQL beansprucht; parallele Cron-Aufrufe können denselben Tages-/Minutenauftrag nicht mehr doppelt starten.
- Live-Jobstatus liefert eigenständige Snapshots statt gemeinsam veränderbarer Step-Arrays; abgeschlossene Jobs werden nach sechs Stunden und verwaiste laufende Jobs nach 24 Stunden beim nächsten Auftrag bereinigt.
- Der ARM64-Build erkennt nicht versionierte Go-Dateien im Quellverzeichnis frühzeitig und nennt sie mit einer verständlichen Fehlermeldung.
- Regressionstests für Cron-Claim, Jobstatus-Snapshots und Aufräumlogik ergänzt.
- Keine Datenbankmigration; pgxpool-Migration, persistente KI-Jobqueue, öffentliche CSP-Härtung und Browser-Staging-Tests bleiben separate Arbeiten.
## v1.5.73
- Einheitliche proxybewusste Client-IP-Erkennung, Rate-Limit-Bereinigung und sichere Readiness-Ausgabe.
- Atomare Template-Ausgabe und größere HTTP-Timeouts für synchrone KI-Verarbeitung.
+46 -3
View File
@@ -35,6 +35,28 @@ type aiJobStore struct {
}
func newAIJobStore() *aiJobStore { return &aiJobStore{jobs: map[string]AIJob{}} }
// A job returned to HTTP handlers must not share its mutable Steps backing array
// with the store, otherwise concurrent status updates can race with JSON encoding.
func cloneAIJob(job AIJob) AIJob {
job.Steps = append([]AIJobStep(nil), job.Steps...)
return job
}
// Finished jobs need only remain available for their progress display. Remove
// old snapshots when the next job is created instead of retaining them forever.
func (s *aiJobStore) pruneLocked(now time.Time) {
for id, job := range s.jobs {
retention := 6 * time.Hour
if job.Status == "running" {
retention = 24 * time.Hour
}
if now.Sub(job.UpdatedAt) > retention {
delete(s.jobs, id)
}
}
}
func (s *aiJobStore) New(channel string) AIJob {
labels := []string{"Quellen laden", "Texte mit OpenAI erzeugen"}
count := 3
@@ -56,9 +78,10 @@ func (s *aiJobStore) NewWithSteps(channel string, labels []string) AIJob {
}
j := AIJob{ID: id, Channel: channel, Status: "running", CreatedAt: now, UpdatedAt: now, Steps: steps}
s.mu.Lock()
s.pruneLocked(now)
s.jobs[id] = j
s.mu.Unlock()
return j
return cloneAIJob(j)
}
func (s *aiJobStore) Update(id string, idx int, status, msg string) {
s.mu.Lock()
@@ -95,7 +118,7 @@ func (s *aiJobStore) Get(id string) (AIJob, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
j, ok := s.jobs[id]
return j, ok
return cloneAIJob(j), ok
}
func (a *adminHandler) streamAIJobHTML(w http.ResponseWriter, r *http.Request, jobID string) {
@@ -314,6 +337,21 @@ func sameAutoTaskMinute(last *time.Time, now time.Time) bool {
return last.In(location).Format("2006-01-02 15:04") == now.In(location).Format("2006-01-02 15:04")
}
// Claim an automatic task atomically in PostgreSQL. A read followed by an
// unconditional UPDATE can start the same task twice when cron requests overlap.
// Comparing Berlin wall-clock minutes also preserves one run during the autumn
// daylight-saving-time clock change.
func autoTaskClaimSQL(id int64) string {
return `UPDATE landwelle.ai_auto_tasks
SET last_run_at=now(), last_status='queued', last_error='', updated_at=now()
WHERE id=` + strconv.FormatInt(id, 10) + `
AND active
AND (last_run_at IS NULL OR
date_trunc('minute', last_run_at AT TIME ZONE 'Europe/Berlin')
IS DISTINCT FROM date_trunc('minute', now() AT TIME ZONE 'Europe/Berlin'))
RETURNING id;`
}
func cronRequestAuthorized(r *http.Request) bool {
token := strings.TrimSpace(os.Getenv("LANDWELLE_CRON_TOKEN"))
if token == "" || r == nil {
@@ -342,12 +380,17 @@ func (a *adminHandler) runDueAutoTasks(ctx context.Context) (int, int, error) {
}
due++
if a.database != nil && a.database.Enabled() {
if _, err := a.database.exec(ctx, `UPDATE landwelle.ai_auto_tasks SET last_run_at=now(),last_status='queued',last_error='',updated_at=now() WHERE id=`+strconv.FormatInt(task.ID, 10)); err != nil {
claimed, err := a.database.exec(ctx, autoTaskClaimSQL(task.ID))
if err != nil {
if a.logger != nil {
a.logger.Printf("auto task %d could not be claimed: %v", task.ID, err)
}
continue
}
// RETURNING yields no rows if another request already claimed the task.
if strings.TrimSpace(string(claimed)) != strconv.FormatInt(task.ID, 10) {
continue
}
}
started++
go a.executeAutoTask(task)
+70
View File
@@ -0,0 +1,70 @@
package main
import (
"strings"
"testing"
"time"
)
func TestAIJobStoreSnapshotsAreIndependent(t *testing.T) {
store := newAIJobStore()
job := store.NewWithSteps("news", []string{"Quellen", "Audio"})
job.Steps[0].Label = "externer Eingriff"
stored, ok := store.Get(job.ID)
if !ok || stored.Steps[0].Label != "Quellen" {
t.Fatalf("returned NewWithSteps job mutated stored steps: %+v", stored)
}
stored.Steps[1].Status = "done"
stored.Steps[0].Label = "anderer Eingriff"
store.Update(job.ID, 1, "running", "Lädt")
next, ok := store.Get(job.ID)
if !ok || next.Steps[0].Label != "Quellen" || next.Steps[1].Status != "running" {
t.Fatalf("returned Get snapshot mutated stored steps: %+v", next)
}
}
func TestAIJobStorePrunesExpiredJobs(t *testing.T) {
store := newAIJobStore()
expired := store.NewWithSteps("weather", nil)
recent := store.NewWithSteps("sport", nil)
running := store.NewWithSteps("news", nil)
store.Finish(expired.ID, nil)
store.Finish(recent.ID, nil)
store.mu.Lock()
oldFinished := store.jobs[expired.ID]
oldFinished.UpdatedAt = time.Now().Add(-7 * time.Hour)
store.jobs[expired.ID] = oldFinished
oldRunning := store.jobs[running.ID]
oldRunning.UpdatedAt = time.Now().Add(-25 * time.Hour)
store.jobs[running.ID] = oldRunning
store.mu.Unlock()
store.NewWithSteps("new", []string{"start"})
if _, ok := store.Get(expired.ID); ok {
t.Fatal("expired completed job was retained")
}
if _, ok := store.Get(running.ID); ok {
t.Fatal("stale running job was retained")
}
if _, ok := store.Get(recent.ID); !ok {
t.Fatal("recent completed job was removed")
}
}
func TestAutoTaskClaimSQLPreventsDuplicateStarts(t *testing.T) {
query := autoTaskClaimSQL(123)
for _, clause := range []string{
"WHERE id=123",
"AND active",
"last_run_at IS NULL",
"IS DISTINCT FROM",
"AT TIME ZONE 'Europe/Berlin'",
"RETURNING id;",
} {
if !strings.Contains(query, clause) {
t.Errorf("claim query missing %q: %s", clause, query)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
# Landwelle v1.5.74 – KI-Aufträge und Build absichern
## Enthalten
- Doppelte Cron-Anfragen beanspruchen einen fälligen KI-Automatikauftrag jetzt per einzelner PostgreSQL-UPDATE-Anweisung mit RETURNING und Minutenvergleich in der Zeitzone Europe/Berlin. Nur der erfolgreiche Claim startet die Produktion.
- Die Jobstatus-API liefert Kopien der Statusschritte. Gleichzeitige Fortschrittsupdates und JSON-Ausgaben teilen sich keine veränderbaren Step-Slices mehr.
- Beendete Statusaufträge werden nach sechs Stunden und hängen gebliebene laufende Statusaufträge nach 24 Stunden beim nächsten neuen Job aus dem RAM entfernt. Die Produktionsdateien bzw. der Datenbankverlauf bleiben davon unberührt.
- Das Skript scripts/build-pi.sh weist auf nicht versionierte .go-Dateien direkt im Projektverzeichnis hin, bevor es zu schwer verständlichen Compilerfehlern kommt.
- Automatisierte Regressionstests für Job-Snapshots, Retention und SQL-Claim, plus Build-Guard-Test in der CI.
## Betrieb
Keine neue Datenbankmigration. Nach dem Merge die geänderten Quellen auf den Build-Server übernehmen und dort:
```bash
cd /opt/landwelle
./scripts/build-pi.sh
```
Bei der Meldung über nicht versionierte .go-Dateien diese erst prüfen und außerhalb des Projektordners sichern. Sie werden nicht automatisch gelöscht.
## Noch nicht Teil dieses Releases
Die vollständige Migration der zahlreichen psql-Aufrufe auf pgxpool mit parameterisierten Queries und Transaktionen, eine persistente KI-Jobqueue mit Wiederaufnahme nach Neustart, eine restriktivere öffentliche CSP sowie reale Browser-/Staging-Tests benötigen eigene, separat testbare Änderungen.
+1 -1
View File
@@ -37,7 +37,7 @@ const (
apiVersion = "v1"
apiContractVersion = "1.0.0"
applicationName = "Landwelle Radio"
applicationVersion = "1.5.73"
applicationVersion = "1.5.74"
)
var publicTemplateFiles = []string{
+1 -1
View File
@@ -181,7 +181,7 @@ func TestWeatherHelpers(t *testing.T) {
}
func TestApplicationVersion(t *testing.T) {
if applicationVersion != "1.5.73" {
if applicationVersion != "1.5.74" {
t.Fatalf("unexpected application version %q", applicationVersion)
}
}
+12
View File
@@ -4,6 +4,18 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
mkdir -p "$ROOT_DIR/dist"
cd "$ROOT_DIR"
# Go compiles all .go files in the package directory, including untracked files.
# A stale local source (e.g. destination_one.go) can break an otherwise green CI.
# Refuse to build instead of silently deleting potentially valuable local work.
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
EXTRA_GO="$(git ls-files --others --exclude-standard -- '*.go' | grep -E '^[^/]+\.go$' || true)"
if [[ -n "$EXTRA_GO" ]]; then
printf 'Build abgebrochen: nicht versionierte Go-Dateien im Projektverzeichnis:\n%s\n' "$EXTRA_GO" >&2
echo "Bitte Dateien sichern und aus dem Projektverzeichnis verschieben, bevor du neu baust." >&2
exit 1
fi
fi
# Startkritische ServeMux-Routen vor dem Build statisch prüfen.
# contentPages() registriert seine Slugs später dynamisch als "/"+slug. Deshalb
# reicht ein grep nach wörtlichen HandleFunc-Aufrufen nicht aus: Ein Slug darf