fix(sync): studio lyric corrections not refreshing in the app

Reported by Wynell

Also the corrections I have been making in the past few days are not refreshing in the app. Is there a scheduled time when that happens? I want to be sure what I’m putting in Studio translates over to the App.

Details

  • Observed Behavior: Lyric corrections entered in Studio over the past several days are not appearing/refreshing in the client app.
  • Investigation / Follow-up:
    • Verify the sync pipeline between Studio (CMS/database) and the client app (e.g., PowerSync / SQLite bundle / background sync triggers).
    • Clarify whether updates propagate automatically in real time, on a scheduled job, or require a published database/sync update.

Triage & Root Cause Analysis

1. Answer to Question: Is there a scheduled time when Studio changes sync to the App?

Yes — there are currently two separate background cron jobs in packages/hfw_server/main.go (L136-L151), plus an unscheduled startup-only cache in the Web App:

  1. Hourly (@hourly) — hymn_jobs_checker (packages/hfw_server/main.go:148-151):
    • When a lyric stanza (hymn_portions) is created or edited in Studio (hymnsforworship.studio), InitHymnPortionHooks (packages/hfw_server/hooks/hymn_portion.go:10-33) calls addHymnJob(pb, hymnId) (packages/hfw_server/hooks/hymn_jobs.go:21-53), which queues a pending job in PocketBase SQLite (hymn_jobs).
    • On the top of every hour (@hourly), tasks.CheckHymnJobs (packages/hfw_server/tasks/convert_v3.go:258-304) processes pending hymn_jobs, rebuilds the hymn’s .fb FlatBuffer (hymn.fb) and hymn.zip archive (packages/hfw_server/tasks/flatbuffer.go:27-214), and uploads them to Cloudflare R2 (packages/hfw_server/tasks/sync_r2.go:47-82).
  2. Daily at Midnight (@midnight UTC) — sync-library-data (packages/hfw_server/main.go:143-147):
    • Studio saves changes to PocketBase’s local SQLite database (/app/pb_data/data.db), whereas the App syncs via PowerSync, which replicates from PostgreSQL (hfw-postgres).
    • There is no real-time hook pushing hymn_portions edits from PocketBase SQLite to PostgreSQL when saved in Studio. Instead, scripts.SyncLibraryData (packages/hfw_server/scripts/sync_pb_to_pg.go:93-143) only runs once per day at @midnight (or on server restart at main.go:155).

However, even after the hourly and midnight jobs run, multiple bugs prevent lyric corrections from refreshing in both the Web App and Native App.


2. Root Causes Preventing Lyric Corrections from Refreshing

Root Cause A: Web App (hymnsforworship.app / packages/hfw_jaspr) Caches the Catalog in Memory at Startup and Never Refreshes

  • In packages/hfw_jaspr/lib/services/catalog_service.dart:68-114, CatalogService.instance is an in-memory singleton on the Jaspr SSR server:
    bool get isLoaded => _isLoaded && hymns.isNotEmpty;
    
    Future<void> ensureLoaded() async {
      if (isLoaded) return;
      await populateCatalog(this);
      _isLoaded = hymns.isNotEmpty;
    }
    
  • During server startup (packages/hfw_jaspr/lib/main.server.dart:566-574), CatalogService.instance.ensureLoaded() runs once via populateCatalogPlatform (packages/hfw_jaspr/lib/services/catalog_loader_io.dart:286-380).
  • Once _isLoaded is set to true, ensureLoaded() is a no-op for the entire lifetime of the hfw-jaspr container, and there is no periodic refresh, webhook, or cache invalidation mechanism.
  • Additionally:
    • In packages/hfw_jaspr/lib/services/catalog_loader_io.dart:287-353, if .hfw/hfw_cli.db exists on disk, populateCatalogPlatform loads lyrics exclusively from that static SQLite file and returns early at line 349 without querying PocketBase (https://hymnsforworship.studio).
    • Even when falling back to build/jaspr/catalog_snapshot.json (baked into the Docker image at packages/hfw_jaspr/Dockerfile:14) and refreshing from PocketBase once at startup (catalog_loader_io.dart:356-378), it never fetches from PocketBase again until the container is redeployed or restarted.
    • SSR responses for /hymns/:id also set Cache-Control: private, max-age=0, s-maxage=3600, stale-while-revalidate=86400 (packages/hfw_jaspr/lib/main.server.dart:549-552).

Root Cause B: PocketBase → PostgreSQL Midnight Sync (SyncLibraryData) Does Not Trigger on Studio Edits & Misses Portion Updates/Deletions

  • No real-time sync on Studio save: InitHymnPortionHooks (packages/hfw_server/hooks/hymn_portion.go:10-33) only queues a hymn_jobs record for R2 FlatBuffer conversion; it does not sync the updated hymn_portions row (or touch the parent hymns.updated timestamp) in PostgreSQL (powersyncDb).
  • Pre-save hook binding: InitHymnPortionHooks binds to OnRecordCreateRequest and OnRecordUpdateRequest (hooks/hymn_portion.go:11, 20) and runs PostHymnPortionUpdateHook before e.Next() commits the record, instead of OnRecordAfterCreateSuccess / OnRecordAfterUpdateSuccess (and does not hook OnRecordAfterDeleteSuccess at all).
  • Timestamp format mismatch in syncTableIncremental (packages/hfw_server/scripts/sync_pb_to_pg.go:242-255):
    • syncTableIncremental queries PostgreSQL for SELECT max(updated) FROM public."hymn_portions" (where updated is timestamptz in packages/hfw_server/pg_migrations/01-init-schema.sql:38) and passes the scanned string directly into SQLite: SELECT * FROM "hymn_portions" WHERE updated > ?.
    • lib/pq formats timestamptz into sql.NullString using RFC3339 (YYYY-MM-DDTHH:MM:SS.sssZ with a 'T' separator), whereas PocketBase stores updated in SQLite as 'YYYY-MM-DD HH:MM:SS.sssZ' (with a space ' ' separator).
    • Because SQLite compares text strings lexicographically and ASCII 'T' (0x54) > ' ' (0x20), any edit made on the same UTC date as max(updated) has '2026-MM-DD ...' < '2026-MM-DDT...' and is silently skipped by WHERE updated > ?!
  • Deleted portions are never removed from PostgreSQL: syncTableIncremental only performs INSERT ... ON CONFLICT DO UPDATE, so any hymn_portions deleted in Studio remain in PostgreSQL and PowerSync indefinitely.

Root Cause C: Native/Client App (packages/hfw_flutter) Does Not Watch hymn_portions Changes or Invalidate Cached .hymn Bundles

  • Unassigned active hymn stream: In packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart:845, StreamSubscription<dynamic>? _activeHymnSub; is declared (and cancelled in closeHymn() at hfw_headless_coordinator_hymns.dart:31), but it is never subscribed when opening a hymn. Instead, _refreshActiveHymnDetail (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator_hymns.dart:376-423) performs a one-time _database.db.getHymnDetails(hymnId) query.
  • Database stream listener ignores hymn_portions: _setupDatabaseStreams() (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart:1311-1342) only watches watchHymnals() and watchHymns('') (which watches the hymns table, not hymn_portions). Because editing a lyric portion in Studio does not update hymns.updated, watchHymns('') never fires when lyrics change.
  • Downloaded .hymn bundles are skipped on sync: HymnDownloadService.enqueue (packages/hfw_flutter/lib/services/downloads/hymns.dart:341-357) defaults to skipDownloaded: true, so once a device has downloaded <hymnId>.hymn locally, background sync skips re-downloading it even after R2 regenerates hymn.fb / hymn.zip.

3. Recommended Fix Plan

  1. Immediate Real-Time Sync from PocketBase (hfw_server) to PostgreSQL (hfw-postgres):
    • Update packages/hfw_server/hooks/hymn_portion.go to use OnRecordAfterCreateSuccess, OnRecordAfterUpdateSuccess, and OnRecordAfterDeleteSuccess.
    • When a hymn_portions (or hymns) record is created, updated, or deleted in Studio:
      • Immediately upsert/delete the row in PostgreSQL so PowerSync streams lyric corrections to connected apps within seconds instead of waiting until @midnight.
      • Touch the parent hymns record’s updated timestamp so catalog watchers and cache validators detect the change.
  2. Fix syncTableIncremental Timestamp Comparison in packages/hfw_server/scripts/sync_pb_to_pg.go:
    • Normalize lastUpdated from PostgreSQL (strings.Replace(lastUpdated.String, "T", " ", 1) or format explicitly via to_char(max(updated) AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.MS"Z"')) before querying SQLite WHERE updated > ?.
    • Reconcile deleted hymn_portions rows between SQLite and PostgreSQL.
  3. Add Periodic / On-Demand Catalog Refresh in Web App (packages/hfw_jaspr):
    • Update CatalogService (packages/hfw_jaspr/lib/services/catalog_service.dart and catalog_loader_io.dart) to periodically refresh changed hymns and hymn_portions from PocketBase/PostgreSQL (e.g. every 5–15 minutes or via an invalidation endpoint triggered by hfw_server), rather than freezing _isLoaded = true forever after boot.
  4. Reactively Watch hymn_portions in packages/hfw_flutter:
    • Wire up _activeHymnSub in openHymn (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator_hymns.dart) to _database.db.watchHymnDetails(hymnId) (packages/hfw_core/lib/src/services/powersync/queries.dart:132-167), which already uses watchWithTrigger on ['hymns', 'hymnal_hymns', 'hymn_portions', ...].

Fix Implemented

  1. Incremental Sync Timestamp & Deleted Row Reconciliation (packages/hfw_server/scripts/sync_pb_to_pg.go):
    • Formatted PostgreSQL max(updated) in UTC (YYYY-MM-DD HH24:MI:SS.MS"Z") and normalized 'T' → ' ' before comparing against PocketBase SQLite updated > ?, fixing the bug where same-day lyric edits were skipped.
    • Added mutex synchronization (syncMu) and reconcileDeletedRows so deleted hymn_portions / library records are also removed from PostgreSQL.
  2. Real-Time Studio Hook Trigger (packages/hfw_server/hooks/hymn_portion.go, packages/hfw_server/hooks/hymn.go):
    • Bound post-commit hooks (OnRecordAfterCreateSuccess, OnRecordAfterUpdateSuccess, OnRecordAfterDeleteSuccess) on hymn_portions and triggered go scripts.SyncLibraryData() immediately upon Studio edits so changes replicate to PostgreSQL → PowerSync within seconds rather than waiting until midnight UTC.
  3. Reactive Active Hymn Detail Stream (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator_hymns.dart):
    • Subscribed _activeHymnSub in openHymn() to _database.db.watchHymnDetails(cleanId, userId: _effectiveUserId) so open hymns automatically refresh their stanzas as soon as PowerSync receives lyric updates.
  4. Web App TTL Refresh (packages/hfw_jaspr/lib/services/catalog_service.dart, packages/hfw_jaspr/lib/services/catalog_loader_io.dart):
    • Added a 5-minute TTL check to CatalogService.ensureLoaded() so the web server refreshes its in-memory catalog from PocketBase in the background without requiring a container restart.