Altinity / Altinity/altinity-sql-browser

Cross-tab workspace conflict detection and stale-write protection

Abierto
#409 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

inbox
Lenguaje dominante
TypeScript
Estrellas
8
Forks
2
Merge medio
1 h 34 min
PR fusionados (30 d)
6

Descripción

Goal

Prevent silent lost updates when the same workspace is open for editing in multiple browser tabs.

This is a follow-up to:

  • #406 — multi-workspace persistence;
  • #407 — unified Workbench/Dashboard routing;
  • #408 — workspace selector and management UI.

Those issues may initially retain documented last-write-wins behavior, but this issue defines the required safer end state.

Problem

Workspace commits replace the complete workspace aggregate. If two tabs load revision N, then make independent changes, the later successful write can silently erase the earlier tab's committed changes.

Examples:

  • Workbench tab edits/saves a query while another tab reorders Dashboard tiles.
  • Two Workbench tabs edit different saved queries in the same workspace.
  • One tab deletes or renames a workspace while another continues editing it.

The atomic whole-record write prevents partial corruption, but it does not prevent stale overwrites.

Product decisions

  • One browser tab may safely view a workspace while another edits it.
  • Multiple editable tabs are allowed, but stale commits must not overwrite newer state silently.
  • The application should notify open tabs promptly when another tab commits or deletes the same workspace.
  • Conflict handling must preserve the user's local draft for review/retry.
  • Automatic field-level merging is not required initially.

Revision/generation contract

Add a workspace-level persistence generation suitable for optimistic concurrency.

Equivalent model:

interface StoredWorkspace {
  storageVersion: 2;
  id: string;
  key: string;
  name: string;
  generation: number;
  queries: SavedQueryV2[];
  dashboard: DashboardDocumentV1 | null;
}

Rules:

  • New workspace starts at generation 1.
  • Every successful workspace mutation increments generation exactly once.
  • Validation, reads, previews, exports, and failed writes do not increment it.
  • The repository commit accepts the generation the caller loaded.
  • A commit succeeds only if the stored generation still matches the caller's expected generation.
  • On success, persist and return the next generation atomically.
  • On mismatch, return a typed stale/conflict result and do not write.

The exact storage implementation may use an IndexedDB readwrite transaction containing get/check/put.

Repository API

Equivalent contract:

type WorkspaceCommitResult =
  | { ok: true; workspace: StoredWorkspace }
  | { ok: false; kind: 'stale'; current: StoredWorkspace }
  | { ok: false; kind: 'not-found' }
  | { ok: false; kind: 'invalid' | 'persistence'; diagnostics: WorkspaceDiagnostic[] };

commit(candidate: StoredWorkspace, expectedGeneration: number): Promise<WorkspaceCommitResult>;

Requirements:

  • Generation comparison and write occur in one transaction.
  • Stale candidates never reach storage.
  • The returned current snapshot is validated before use, or a separate reload path is provided.
  • Delete should optionally accept expected generation so a stale management dialog cannot delete a workspace that changed after confirmation was opened.

Cross-tab notifications

Use BroadcastChannel where available, with an injected/testable seam.

Suggested messages:

type WorkspaceBroadcast =
  | { kind: 'committed'; workspaceId: string; key: string; generation: number; sourceTabId: string }
  | { kind: 'deleted'; workspaceId: string; key: string; sourceTabId: string }
  | { kind: 'renamed'; workspaceId: string; key: string; name: string; generation: number; sourceTabId: string };

Requirements:

  • Generate a per-tab source ID and ignore own messages.
  • Broadcast only after durable persistence succeeds.
  • A missed notification must not compromise correctness; generation checks remain authoritative.
  • Provide a fallback based on reload/visibility/focus if BroadcastChannel is unavailable. The fallback need not be instantaneous, but stale commits must still be rejected.

UI behavior

Clean tab receives a newer generation

If the tab has no local dirty drafts or pending workspace mutation:

  • reload/project the newest workspace automatically;
  • retain the current surface and mode;
  • preserve the selected/open saved query where its ID still exists;
  • show a subtle notification such as Workspace updated in another tab.
Dirty tab receives a newer generation

Do not overwrite local drafts.

  • Mark the workspace session stale.
  • Show a persistent warning/banner.
  • Disable or intercept commit actions until the conflict is resolved.
  • Offer:
    • Reload and discard local changes;
    • Keep local draft for copy/review;
    • Export local draft/workspace where practical.

A simple initial conflict flow may require the user to copy changes manually; field-level merge is not required.

Commit receives stale result

Even if no notification was received:

  • keep the local draft unchanged;
  • show a clear conflict message, never a generic persistence failure;
  • fetch/display the current workspace generation;
  • do not retry automatically with last-write-wins semantics.
Workspace deleted elsewhere
  • Stop further commits and dashboard execution once observed.
  • Render Workspace not found/deleted in another tab.
  • Preserve unsaved editor text in memory long enough for copy/export.
  • Do not silently navigate to another workspace.
View-only Dashboard tab
  • On commit notification, reload the live Dashboard automatically when safe.
  • View mode never creates conflicts because it cannot mutate.

Pending async operations

Protect against races where an operation starts on generation N and another tab commits before it finishes.

  • Candidate construction must use the current queued mutation snapshot.
  • Repository expected-generation check remains final authority.
  • On stale result, do not project the failed candidate.
  • Query execution results may finish against an older dashboard; existing stale-wave/session guards should prevent incorrect rendering where applicable.

Tests

Add unit/integration coverage for at least:

  1. Two repositories/tabs load generation 1; first commit succeeds to 2; second commit is rejected stale.
  2. Failed/stale commit leaves stored workspace unchanged.
  3. Generation increments exactly once per successful mutation.
  4. Broadcast occurs only after successful persistence.
  5. Own broadcasts are ignored.
  6. Clean receiving tab reloads newer workspace.
  7. Dirty receiving tab preserves drafts and marks session stale.
  8. A missed broadcast still results in stale commit rejection.
  9. Delete notification renders missing/deleted state without fallback.
  10. View-mode Dashboard reloads after another tab commits.
  11. Rename notification updates display name without changing workspace key.
  12. BroadcastChannel-unavailable fallback preserves correctness.
  13. Concurrent mutations to different workspaces do not conflict.
  14. Stale delete confirmation cannot delete a newer generation when expected-generation deletion is enabled.

Acceptance criteria

  • A stale browser tab cannot silently overwrite a newer workspace commit.
  • Users receive a distinct conflict state and retain local drafts.
  • Clean tabs update when another tab commits the same workspace.
  • Deletion in another tab is handled explicitly without fallback substitution.
  • Different workspaces remain independently editable across tabs.
  • Correctness does not depend solely on BroadcastChannel delivery.

Non-goals

  • Automatic SQL/spec/dashboard three-way merge.
  • Collaborative real-time editing.
  • Backend locking or distributed synchronization.
  • Cross-device conflict handling.
  • Revision history or undo across committed generations.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza localizando las rutas de commit y eliminación del repositorio del workspace, el límite de la transacción de IndexedDB y los stale-wave/session guards existentes mencionados en el issue. Después, sigue el punto de conexión de BroadcastChannel y el comportamiento de la UI de la sesión del workspace. La tarea estará terminada cuando pasen las pruebas indicadas de repositorio, notificaciones, conflictos, eliminación, fallback y entre workspaces, sin sobrescribir silenciosamente un estado más reciente ni descartar borradores locales.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
database, frontend
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
38/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.