Skip to content

refactor: remove layered fallbacks that hide failures - #563

Merged
stefan-ernst merged 2 commits into
mainfrom
fix/layered-fallback-simplifications
Nov 24, 2026
Merged

stefan-ernst merged 2 commits into
mainfrom
fix/layered-fallback-simplifications

Conversation

@stefan-ernst

Copy link
Copy Markdown
Contributor

Implements the simplifications from docs/layered-fallback-audit-2026-11-24.md.

Data integrity

  • Worklog booking has one success boundary. New TimeWorklogRepository.CreateDetail inserts the row and reads the joined display row in one transaction. TimeWorklogService.Create uses it, so a failed post-insert read rolls the insert back instead of leaving committed time that a caller retry can double-book. The id-returning Create stays for callers that only need the id (internal/aitools).
  • Priority saves are atomic and preparation is read-only. PriorityRepository.Create/Update write the priority, transfer default status, and replace configuration-set memberships in one transaction. preparePriority no longer clears other defaults, and duplicate membership ids are treated as a set, so the repeated-id case can no longer trip the membership unique index and surface as catalog name already exists.
  • Preference retries are account-scoped. collectionPreferences keeps the actual unsaved patch for the session that produced it and discards it on reset, instead of re-marking dirty scope names that a later flush reconstructs into {saved_filters: {scope: null}} from the current snapshot.

Conflicting decisions

  • Draft replay has one comparison. BookDraft returns the recorded Booking; the service resolves replay vs. conflict through bookingWorklog. Every transaction outcome uses the same (user, key, draft) check, so reusing a key never reports another draft's worklog as this draft's success while the caller's draft still exists.
  • Failed lookups propagate instead of falling back to an unrestricted result:
    • IsPriorityAllowedInWorkspace checks the query error before treating a nil assignment as unrestricted.
    • CoverageSummary/CoverageRequirements check the error before treating empty type ids as an empty summary.
    • AssetRepository.GetDefaultStatus checks the error before treating an invalid id as "no default".

Delete duplicate ownership

  • timeLogStore picker promise represents only an in-flight load; a failed directory stays retryable and last-good data stays on screen.
  • Delete the unused item-detail time-modal picker loader (loadTimeModalData and its controller/promise/loaded flag/reset plumbing). Item detail already uses the global store.
  • moduleSettings.ensureLoaded has a real early return and one shared in-flight request. A failed fetch stays retryable, and the authenticated-page call sites no longer issue a second GET after shell hydration. reload() remains the explicit forced refresh.

Consistency

  • Item updates select one emitter at construction. The fallback emitter field, the fallback-only setters, and the second action-payload builder are gone. The legacy emitter and the coordinator share buildItemUpdatedActionEvent, which uses the actual changed fields.
  • PriorityPicker loads the target workspace's priorities through the workspace-priorities API (GET /workspaces/{id}/priorities) and renders the result; collectionEditorOptions no longer reimplements assignment → scoped → global resolution, and the picker no longer double-loads on mount plus effect.

Rule decision for the workspace-priority row

The audit asked to settle the rule for unassigned workspace + curated default set first. Listing (ListForWorkspace) and write validation (IsPriorityAllowedInWorkspace) already agree on the explicit-assignment rule, and the existing tests assert it, so this change makes the UI agree with them rather than changing the backend rule. The ResolveEffective inheritance difference is left for a follow-up once the product rule is decided.

Not included

Transition/approval atomicity is intentionally left for its own design review, per the audit.

Verification

  • go test ./internal/services ./internal/repository ./internal/validation ./internal/handlers via the core-tests overlay (only the pre-existing TestAddMilestoneWithContextStoresAutomationMetadata and TestCompactCatalogContainsExactlyRetainedMigrations failures remain, both failing on main too).
  • New Go regressions: TestCreateDetailRollsBackWhenJoinedReadFails, TestBookDraftConflictingKeyDoesNotReplayAnotherDraft, TestCreatePriorityDeduplicatesConfigurationSetMemberships, TestIsPriorityAllowedInWorkspacePropagatesLookupError.
  • Frontend unit tests via the core-tests overlay: full suite 4133 passed; the only new-vs-main delta is the pre-existing in-flight saveField fix that lives uncommitted in the main worktree.
  • New frontend regressions for the session-scoped preference retry, retryable picker load, and moduleSettings.ensureLoaded.
  • golangci-lint, svelte-check, and biome check clean.

Implement the simplifications from docs/layered-fallback-audit-2026-11-24.md.

Data integrity:
- Add TimeWorklogRepository.CreateDetail, which inserts the worklog and reads
  the joined display row in one transaction. TimeWorklogService.Create uses it,
  so a failed post-insert read rolls back instead of leaving committed time a
  caller retry can double-book. The id-returning Create stays for callers that
  only need the id.
- PriorityRepository.Create/Update now write the priority, transfer default
  status, and replace configuration-set memberships in one transaction.
  preparePriority no longer writes, and duplicate membership ids are treated as
  a set so they cannot surface as a misleading name conflict.
- collectionPreferences keeps the actual unsaved patch per authenticated
  session and discards it on reset, instead of re-marking dirty scope names
  that a later flush reconstructs into a delete from the current snapshot.

Conflicting decisions:
- BookDraft now returns the recorded Booking and resolves replay/conflict
  through one comparison. Every transaction outcome uses the same
  (user, key, draft) check, so a reused key never reports another draft's
  worklog as this draft's success.
- Failed lookups propagate instead of falling back to an unrestricted result:
  workspace priority assignment, test coverage summaries/requirements, and the
  asset default-status query.

Delete duplicate ownership:
- timeLogStore's picker promise represents only an in-flight load; a failed
  directory stays retryable and last-good data stays displayed.
- Delete the unused item-detail time-modal picker loader.
- moduleSettings exposes ensureLoaded with a real early return and a shared
  in-flight request; a failed fetch stays retryable, and the authenticated-page
  call sites no longer issue a second GET after shell hydration.

Consistency:
- Item updates select one emitter at construction. The legacy emitter and the
  coordinator share one changed-fields action payload builder, and the
  fallback-only setters and second payload builder are removed.
- PriorityPicker loads the target workspace's priorities through the
  workspace-priorities API; collectionEditorOptions no longer reimplements
  assignment/scoped/global resolution.

Transition/approval atomicity is intentionally left for its own design review.
@github-actions

Copy link
Copy Markdown

Size Change: 0 B 🆕

Total Size: 0 B

compressed-size-action

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

I’d request changes on bf67d927. The blocking issue is that an idempotent draft replay can still double-book time. I reproduced that and three other findings with isolated tests against this head.

  1. P1 — Two requests for one 30-minute draft can book 60 minutes. In BookDraft, the worklog is inserted before the conditional draft delete. If another transaction wins, the loser sees zero deleted rows, finds the winner’s booking, and returns nil from the transaction callback. That commits the loser’s insert as well. On PostgreSQL, both calls returned worklog ID 1, but the database held 2 worklogs totaling 60 minutes. Claim the draft with the conditional delete before inserting the worklog; a replay then has nothing to roll back, and a later insert failure still restores the draft. The regression should assert persisted minutes and row count, not just matching return IDs.

  2. P2 — Concurrent priority saves can leave two defaults. Create and transferDefaultStatus make each save atomic, but don’t enforce uniqueness across transactions. Starting with no default, I paused save A just before commit and let save B create a different default. Both succeeded on PostgreSQL; two rows had is_default = true. Item creation then uses LIMIT 1 with no tie-breaker. Enforce at most one default in the database and clear the old default before setting the new one in the same transaction. A uniqueness conflict here is a default-selection conflict, not a duplicate name.

  3. P2 — A failed workspace directory still doesn’t retry when the time picker reopens. The picker loader handles rejected promises, but workspacesStore.load() catches an HTTP 500, marks [] as loaded, and resolves. With the real workspace store and a successful response queued for the next request, opening the picker twice made one workspace GET. Fix the cache where it’s owned: preserve the last good workspace list on failure and leave a failed load retryable.

  4. P2 — An older settings GET can undo a forced reload. reload() drops the inFlight reference, but the old request can still call set() and clear inFlight. In a deferred-response test, the reload set workspace_managed_agents to false; the older GET finished last and changed it back to true. Let only the current request publish or clear itself, and have shell hydration supersede any pending GET the same way.

The four new companion Go regressions passed on both SQLite and PostgreSQL, and all 90 tests in the six affected frontend suites passed. The failures above came from additional tests for overlapping transactions, out-of-order responses, and the real workspace-store integration.

1. BookDraft claims the draft with the conditional delete before inserting
   the worklog. A losing transaction previously inserted a worklog and then
   returned the winner's booking without rolling back, so two requests could
   book 60 minutes for one 30-minute draft. The claim now precedes the insert,
   so a replay has nothing to roll back. The regression asserts persisted row
   count and minutes, not just matching return IDs.

2. Enforce at most one default priority in the database with a partial unique
   index, and clear the old default before writing the new one in the same
   transaction. Two concurrent saves can no longer both become default. The
   index violation maps to ErrDefaultConflict ("another priority is already
   the default") instead of a duplicate-name conflict. The migration collapses
   any pre-existing duplicate defaults before creating the index.

3. workspacesStore.load no longer caches a failure as an empty, loaded
   directory: it preserves the last good list and leaves a failed load
   retryable, so the time picker's next open issues a fresh workspace GET.

4. moduleSettings tags each load with a generation. Only the current request
   may publish or clear itself, and reload()/hydrate() supersede a pending
   GET, so a slow response cannot overwrite a forced reload or shell snapshot.
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Addressed all four findings in e4e113f9 (companion tests in Windshiftapp/core-tests-internal#71, commit bcd7d3db).

  1. P1 — double-book on draft replay. BookDraft now claims the draft with the conditional DELETE ... AND version = ? before inserting the worklog. A transaction that loses the race has no worklog to roll back and returns the winner's booking from the rollback path. The regression now asserts persisted COUNT(*) and SUM(duration_minutes), not just matching return IDs.

  2. P2 — two defaults. Added a partial unique index uq_priorities_single_default ON priorities(is_default) WHERE is_default = true (migration 20261203_priorities_single_default, plus the base schemas). Create/Update clear the old default before writing the new one in the same transaction, and the index violation maps to a new ErrDefaultConflict → 409 "another priority is already the default" instead of the duplicate-name message. The migration collapses any pre-existing duplicates first.

  3. P2 — failed workspace directory. Fixed the cache where it is owned: workspacesStore.load no longer writes []/total=0/loaded=true on failure. It preserves the last good list and leaves loaded false, so the next open issues a fresh GET. Tests cover both the first-load failure retry and a failed force reload preserving the previous directory.

  4. P2 — older GET undoing a reload. moduleSettings now tags every load with a generation. Only the request that still owns the generation may set() or clear inFlight, and both reload() and hydrate() bump the generation, so a slow GET cannot overwrite a forced reload or a shell snapshot. Tests cover the out-of-order reload and hydration-supersede cases.

Verification on the clean origin/main core-tests overlay: ./internal/database, ./internal/services, and the full frontend suite (4138 passed; only the pre-existing AssetManager failure remains, which also fails on main).

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

I’d merge e4e113f9 once CI is green. I rechecked all four previous findings against this head and companion tests at 76996bdb.

  • Draft booking: I reran the PostgreSQL race that previously booked 60 minutes. I paused one transaction after it missed the idempotency key, let the other book the same draft, then resumed the first. Both returned worklog ID 1; the database held one row totaling 30 minutes.
  • Default priority: Two overlapping PostgreSQL saves now leave exactly one default; the losing save returns ErrDefaultConflict, not a duplicate-name error. I also tested upgrading a catalog containing multiple defaults on both SQLite and PostgreSQL: both retained the lowest-ID default and completed the migration.
  • Frontend: The real workspace picker issued a second GET and recovered after a failed first load. An older settings GET no longer overwrites a forced reload or shell hydration. All 66 tests in the four focused frontend suites passed.

One non-blocking test improvement: keep the overlapping same-draft, same-key case in the companion suite. The committed row-count assertion is useful, but it runs two different drafts sequentially and would also pass with the old insert-before-delete ordering. The overlapping case directly guards the double-booking fix.

@stefan-ernst
stefan-ernst merged commit c4e20a3 into main Nov 24, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant