I need to understand potential race conditions in the codebase. Please find and analyze:
Settings debounce mechanism - look for debounce patterns in settings writes (300ms mentioned)
Realtime subscriptions - how do they update React Query cache?
useReferenceManagement.ts - find it and analyze the query cache patches mentioned (supposedly 6)
Any setQueryData calls that might conflict with background refetches
Look for patterns where:
Debounced writes might conflict with realtime updates
Optimistic updates might get overwritten
Multiple sources updating the same cache
Don't make any changes, just research and report findings.
AssistantCopy response Good, I found several hooks. Let me also search for useAllShotGenerations specifically:
AssistantCopy response I'll conduct a thorough analysis of potential race conditions in your codebase. Let me start by searching for the key areas you mentioned.
AssistantCopy response Now let me read the main hook files to understand their implementations:
AssistantCopy response Let me now look at the key files to understand the patterns:
AssistantCopy response Now let me search for additional hooks to get the complete picture:
AssistantCopy response Now let me search for more specific patterns - the setQueryData calls and how realtime interacts with them:
AssistantCopy response Let me check the SimpleRealtimeProvider and look at the settings write queue to understand the queueing mechanism:
AssistantCopy response Now let me read the settings write queue to understand the queueing mechanism:
AssistantCopy response Let me search for more patterns around debounce and concurrent writes:
AssistantCopy response Now let me check for any specific race condition patterns with timing:
AssistantCopy response Let me get more details on the onSuccess callback in useToolSettings:
AssistantCopy response Let me search for deepEqual and check how it's used:
AssistantCopy response Perfect! Now let me check for any concurrent behavior patterns in the reference management and how realtime interacts:
AssistantCopy response Perfect! Now let me create a comprehensive analysis document for you:
Architecture Analysis: Generation Fetching Hooks
Based on my thorough analysis of the codebase, here's a comprehensive breakdown of all generation fetching hooks and their purposes:
1. useGenerations (/src/shared/hooks/useGenerations.ts)
Purpose : Core generation fetching hook for project-wide gallery views
Query Key : ['unified-generations', 'project', projectId, page, limit, filters]
Data Source : generations table + generation_variants table
Filters : toolType, mediaType, starred, search, edits, shot, variants
Returns : Paginated GenerationsPaginatedResponse with metadata transformation
Special Features :
Supports both generations and edit variants via variantsOnly flag
Smart polling via useSmartPollingConfig
Handles parent/child generation relationships
Supports search by prompt text
Used by MediaGallery and project-wide views
2. useUnifiedGenerations (/src/shared/hooks/useUnifiedGenerations.ts)
Purpose : Unified hook for both project-wide AND shot-specific generation queries
Query Keys :
Project mode: ['unified-generations', 'project', projectId, page, limit, filtersKey, includeTaskData]
Shot mode: ['unified-generations', 'shot', shotId, page, limit, filtersKey, includeTaskData]
Data Source : generations table directly (shot-specific uses JSONB shot_data column)
Filters : toolType, mediaType, starred, excludePositioned, search
Returns : GenerationWithTask[] - includes optional task data
Special Features :
Two distinct modes: project-wide vs shot-specific
Optimized shot-specific path : Direct JSONB query on generations.shot_data (~10x faster than joins)
Includes task data fetching (optional)
Background task preloading
Used by VideoOutputsGallery and potentially MediaGallery migration path
Show full message · 176 lines AssistantCopy response Excellent! Now I have enough information. Let me create a comprehensive analysis report:
Race Condition Analysis Report
Based on my thorough examination of your codebase, I've identified several critical race condition patterns and potential conflicts. Here's my detailed findings:
1. Settings Debounce Mechanism (300ms)
Location: /Users/user_c042661f/Documents/reigh/src/shared/lib/settingsWriteQueue.ts and /Users/user_c042661f/Documents/reigh/src/shared/hooks/useAutoSaveSettings.ts
Mechanism:
Global write queue enforces 300ms debounce per target (scope:entityId:toolId)
Multiple rapid updates to same target are coalesced via mergePatch() (shallow merge)
Only 1 concurrent write allowed (MAX_CONCURRENT = 1)
Pending edits tracked via editVersionRef to detect if user typed faster than save completes
Pattern:
code Copy code
User types → updateField() increments editVersionRef → 300ms debounce timer starts
→ During save, editVersionRef checked: if newer edits happened, pending NOT cleared
→ DB write proceeds, then debounce check prevents clearing pending
→ Forces another save for accumulated edits
2. useReferenceManagement: 6 setQueryData Calls - Race Condition Risk
Location: /Users/user_c042661f/Documents/reigh/src/tools/image-generation/components/ImageGenerationForm/hooks/useReferenceManagement.ts
The 6 setQueryData patches:
Line 420-423 (handleStyleReferenceUpload - resources cache)
typescript Copy code
queryClient.setQueryData(['resources', 'style-reference'], (prev) => [...prevResources, resource])
Line 425-433 (handleStyleReferenceUpload - project-image-settings)
Show full message · 352 lines [SUGGESTION MODE: Suggest what the user might naturally type next into Claude Code.]
FIRST: Look at the user's recent messages and original request.
Your job is to predict what THEY would type - not what you think they should do.
THE TEST: Would they think "I was just about to type that"?
EXAMPLES:
User asked "fix the bug and run tests", bug is fixed → "run the tests"
After code written → "try it out"
Claude offers options → suggest the one the user would likely pick, based on conversation
Claude asks to continue → "yes" or "go ahead"
Task complete, obvious follow-up → "commit this" or "push it"
After error or misunderstanding → silence (let them assess/correct)
Be specific: "run the tests" beats "continue".
NEVER SUGGEST:
Evaluative ("looks good", "thanks")
Questions ("what about...?")
Claude-voice ("Let me...", "I'll...", "Here's...")
New ideas they didn't ask about
Multiple sentences
Stay silent if the next step isn't obvious from what the user said.
Format: 2-12 words, match the user's style. Or nothing.
Reply with ONLY the suggestion, no quotes or explanation.
AssistantCopy response I need to understand the complete data flow for settings in this codebase. Please trace:
Settings write path : From UI component → hook → write queue → database
Find useAutoSaveSettings and trace how updateField works
Find settingsWriteQueue and understand the debounce mechanism
How does the write actually get to Supabase?
Settings read path : From database → React Query → UI
What query keys are used for settings?
How is staleTime/cacheTime configured?
What triggers refetches?
Realtime integration with settings :
Does realtime ever update settings caches directly?
Or does it just invalidate?
Find SimpleRealtimeProvider and see what it invalidates
Current coordination mechanisms :
Find editVersionRef and pendingSettingsRef usage
How do these prevent data loss?
Are there any gaps in the protection?
Provide file paths and line numbers for key code. Don't make changes, just research.
AssistantCopy response I'll trace the complete settings data flow in this codebase. Let me start by exploring the structure and finding the key files.
AssistantCopy response Let me find the core settings hooks and utilities:
I need to understand the generation hooks architecture and find consolidation opportunities. Please analyze:
Hook dependency graph : Which hooks wrap/call which other hooks?
Start from useAllShotGenerations, useShotGenerations, useUnifiedGenerations, useGenerations
Find all the selector hooks (useTimelineImages, useUnpositionedImages, useVideoOutputs)
Map out the dependency tree
Query key analysis :
List ALL query keys used for generation data
Identify overlapping or inconsistent keys
Which keys are invalidated together?
Data transformation points :
Where does data get transformed (transformGeneration, etc.)?
Are there duplicate transformations happening?
Invalidation patterns :
Find invalidateGenerationsSync and other generation invalidation utilities
When do generations get invalidated?
Is there a central place for this?
Realtime updates for generations :
How does realtime update generation caches?
Is it invalidation or direct cache updates?
Provide file paths and line numbers. Create a clear hierarchy diagram if possible.
AssistantCopy response Great! Now let me read the key files:
AssistantCopy response I'll analyze the generation hooks architecture systematically. Let me start by exploring the codebase structure and identifying all relevant files.
AssistantCopy response Let me search for the actual generation hooks in the src directory:
AssistantCopy response Now let me find the settings write queue implementation:
I need to understand existing cache coordination and utility patterns. Please find:
Cache utility functions :
Any queryClient utilities or wrappers
Functions that coordinate multiple cache updates
Optimistic update helpers
Existing patterns for avoiding race conditions :
Locking mechanisms
Version tracking
Retry logic
React Query configuration :
Global defaults (staleTime, cacheTime, retry)
Per-query overrides
Mutation configuration
Similar problems solved elsewhere :
Other areas where optimistic updates + realtime might conflict
How were they solved?
Testing infrastructure :
How are hooks tested currently?
Are there integration tests for data flow?
What testing utilities exist?
Provide file paths and line numbers for key patterns we can reuse or extend.
AssistantCopy response I'll systematically search for cache coordination patterns, React Query configuration, and testing infrastructure in this codebase.
AssistantCopy response Perfect! Now let me check the deepEqual implementation and trace one more piece:
AssistantCopy response Now let me read the core generation hooks to understand their dependencies:
AssistantCopy response Now let me search for key configuration and utility files in the source directory:
AssistantCopy response Let me continue reading the invalidation hooks and transformers:
AssistantCopy response Now let me search for mutation patterns, invalidation hooks, and realtime coordination:
AssistantCopy response Now let me search for query keys and realtime integration patterns:
AssistantCopy response Let me read the key mutation and realtime coordination files:
AssistantCopy response Now let me look at the realtime provider:
AssistantCopy response Now let me search for more mutation patterns and testing infrastructure:
AssistantCopy response Let me read the invalidation hook file:
AssistantCopy response Let me search for testing setup and more mutation patterns:
AssistantCopy response Let me get more mutation patterns and check for realtime coordination:
AssistantCopy response Let me read the realtime managers:
AssistantCopy response Perfect! Now let me search for versioning/locking patterns and more testing infrastructure:
AssistantCopy response Let me search for more specific patterns and testing approaches:
AssistantCopy response Excellent! Now I have all the pieces I need. Let me compile a comprehensive analysis report.
Complete Settings Data Flow Analysis
I've traced the entire settings system in your codebase. Here's the comprehensive breakdown:
1. SETTINGS WRITE PATH: UI → Hook → Queue → Database
Start: Component calls updateField
File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useAutoSaveSettings.ts:318-373
updateField<K extends keyof T>(key: K, value: T[K]) immediately updates local React state
Increments editVersionRef.current to track edit sequence
Key: Race Condition Protection via Refs
pendingSettingsRef (Line 131): Holds the latest pending changes, blocking DB load from overwriting user input during debounce
editVersionRef (Line 137): Counter incremented on each edit. Used to detect if newer edits happened during save (Lines 321, 361)
saveTimeoutRef (Line 130): Holds the debounce timer ID
Debounce Mechanism
Lines 342-369: When status === 'ready', sets a timeout for 300ms (configurable via debounceMs)
Multiple rapid edits to same field clear and re-start the timer
Latest state is captured at save time (Lines 350-355), not at edit time
The Critical Race Condition Fix (Lines 359-364):
typescript Copy code
if (editVersionRef.current === editVersionAtStart) {
pendingSettingsRef.current = null;
pendingEntityIdRef.current = null;
}
This ensures if user typed DURING the save, pending isn't cleared, allowing the next debounce to fire.
Save to Database
Path 1 (debounced): Lines 357-367 call saveImmediate(latestSettings)
Path 2 (immediate): Line 454 via manual save() call
Path 3 (unload): Lines 288-315 fires via beforeunload event, calls updateToolSettingsSupabase(..., 'immediate')
Path 4 (entity change): Lines 222-280 cleanup effect flushes pending before switching entities
2. WRITE QUEUE ARCHITECTURE: Deduplication + Serialization
Show full message · 367 lines AssistantCopy response Perfect! Now I have enough information. Let me create a comprehensive analysis report.
Generation Hooks Architecture Analysis
Based on my thorough exploration of the codebase, here's a detailed breakdown of the generation hooks architecture:
1. HOOK DEPENDENCY GRAPH
Core Generation Hooks (4 main entry points):
code Copy code
┌─────────────────────────────────────────────────────────────┐
│ GENERATION DATA LAYER │
├─────────────────────────────────────────────────────────────┤
│
│ useGenerations (PROJECT-WIDE)
│ └─ fetchGenerations()
│ ├─ applyGenerationFilters()
│ └─ transformGeneration()
│
│ useShotGenerations (SHOT-SPECIFIC, PAGINATED)
│ └─ Infinite query from shot_generations table
│ └─ mapShotGenerationToRow()
│
│ useAllShotGenerations (SHOT-SPECIFIC, FULL DATA)
│ └─ Single query from shot_generations with generation joins
│ └─ mapShotGenerationToRow()
│
│ useUnifiedGenerations (HYBRID, FLEXIBLE)
│ ├─ fetchShotSpecificGenerations() [optimized via shot_data JSONB]
│ └─ fetchProjectWideGenerations()
│ └─ transformForUnifiedGenerations()
│
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ SELECTOR HOOKS (memoized filters of base queries) │
├─────────────────────────────────────────────────────────────┤
│
│ useTimelineImages
│ └─ Filters useAllShotGenerations()
│ → positioned + non-video + valid location
│
│ useUnpositionedImages
│ └─ Filters useAllShotGenerations()
│ → unpositioned + non-video + valid location
│
│ useVideoOutputs
│ └─ Filters useAllShotGenerations()
│ → video type only
│
│ useTimelineShotGenerations
│ └─ Filters useAllShotGenerations()
│ → positioned + has metadata + non-video
│
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ DERIVED/LINEAGE HOOKS │
├─────────────────────────────────────────────────────────────┤
│
│ useDerivedItems(sourceGenerationId)
│ ├─ Fetches child generations (based_on)
│ └─ Fetches edit variants (generation_variants with edit types)
│ └─ calculateDerivedCounts()
│
│ useLineageChain (referenced in docs, not fully examined)
│
└─────────────────────────────────────────────────────────────┘
Show full message · 507 lines AssistantCopy response Perfect! Now I have enough information. Let me compile my comprehensive report.
Comprehensive Cache Coordination & Testing Infrastructure Report
Based on my thorough exploration of the codebase, here's what I found:
1. CACHE UTILITY FUNCTIONS
Query Key Registry
File: /Users/user_c042661f/Documents/reigh/src/shared/lib/queryKeys.ts (lines 1-270)
Purpose: Centralized query key definitions for all React Query caches
Key features:
Organized by entity type (shots, generations, tasks, settings, etc.)
Supports scoped access patterns: queryKeys.generations.byShot(shotId)
Includes variant tracking: queryKeys.generations.variants(generationId)
Segment support: queryKeys.segments.liveTimeline(shotId)
Shot Cache Utilities
File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/shots/cacheUtils.ts (lines 1-132)
Centralized Invalidation Hook
File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/invalidation/useGenerationInvalidation.ts (lines 1-350)
Show full message · 327 lines Based on the following codebase analysis, design a comprehensive implementation plan to fix race conditions and consolidate generation hooks.
Current State Summary
Settings System
300ms debounce via settingsWriteQueue.ts
Protection via editVersionRef and pendingSettingsRef in useAutoSaveSettings.ts
Settings are NOT updated via realtime (user/project/shot scoped)
useReferenceManagement.ts has 6 setQueryData calls doing optimistic updates + debounced DB writes
The protections work but are implicit and scattered
Generation Hooks
10+ hooks fetching generation data with overlap:
useGenerations (project-wide)
useUnifiedGenerations (hybrid project/shot)
useShotGenerations (infinite pagination)
useAllShotGenerations (full data, primary for shot views)
Selector hooks: useTimelineImages, useUnpositionedImages, useVideoOutputs
Duplicate transformers: transformGeneration, transformForUnifiedGenerations, transformShotGeneration (85% code overlap)
Query key inconsistencies causing partial invalidation
Realtime only invalidates, doesn't do direct cache updates
Existing Good Patterns
cacheUtils.ts: updateAllShotsCaches, rollbackShotsCaches, cancelShotsQueries
useGenerationInvalidation.ts: scoped invalidation with reasons
useShotGenerationMutations.ts: proper onMutate/onError/onSuccess pattern
SimpleRealtimeProvider.tsx: batched events (100ms), INSERT-only detection
Query presets: REALTIME_BACKED_PRESET, STATIC_PRESET, etc.
DataFreshnessManager: polling decisions based on realtime health
Requirements
Fix race conditions between optimistic updates and realtime/refetches
Consolidate generation hooks to reduce duplication
Standardize query keys
Make protections explicit and systematic rather than implicit
Improve testability
Constraints
Must be phased to avoid breaking production
Build on existing patterns, don't replace everything
Keep changes minimal for each step
Please design a multi-phase implementation plan that addresses these issues systematically. Consider:
What order should changes be made?
What are the dependencies between phases?
What are the risks at each phase?
What testing is needed?
What can be parallelized?
Provide concrete file changes and code patterns for each phase.
Show full message · 50 lines AssistantCopy response I'll explore the codebase to understand the current architecture and design a comprehensive implementation plan. Let me start by examining the key files mentioned in the analysis.
AssistantCopy response Let me continue exploring the codebase to understand the generation hooks and other key files.
AssistantCopy response Now let me explore the other generation hooks and related files.
AssistantCopy response Let me continue exploring the generation transformers and other related hooks.
AssistantCopy response Now let me look at the realtime provider and mutation hooks to understand the current patterns.
AssistantCopy response Now let me look at the documentation and some additional related files.
AssistantCopy response Let me also look at any existing patterns for optimistic update protection.
AssistantCopy response Now I have a comprehensive understanding of the codebase. Let me provide the detailed implementation plan.
Comprehensive Implementation Plan: Race Conditions and Generation Hook Consolidation
Executive Summary
Based on my exploration of the codebase, I've identified:
Settings System : Already well-protected with editVersionRef, pendingSettingsRef, and settingsWriteQueue.ts providing 300ms debounce and version tracking
Generation Hooks : 10+ overlapping hooks with duplicate transformers (85% code overlap)
Optimistic Update Pattern : Excellent patterns in useShotGenerationMutations.ts using _optimistic flags and temp IDs
Realtime : Uses invalidation-only approach (no direct cache updates), with 100ms batching in SimpleRealtimeManager
Query Keys : Already centralized in queryKeys.ts
The main issues are:
Race conditions between optimistic updates and realtime invalidations
Scattered, inconsistent patterns across hooks
No systematic protection for realtime-triggered refetches overwriting optimistic data
Phase 1: Establish Explicit Protection System (Foundation)
Goal : Create a centralized, explicit system for protecting optimistic updates from being overwritten.
1.1 Create OptimisticUpdateRegistry
New file : /src/shared/lib/optimisticUpdateRegistry.ts
Show full message · 542 lines
3. useShotGenerations (/src/shared/hooks/useShotGenerations.ts)
Purpose : Infinite pagination for shot-specific generations
Query Key : ['unified-generations', 'shot', shotId] (infinite query)
Data Source : shot_generations table with JOIN to generations + primary_variant
Returns : Paginated GenerationRow[] data
Special Features :
Infinite scroll pagination (100 items per page)
Joins through shot_generations table (different path from useUnifiedGenerations)
Handles primary variant display URLs
Ordered by timeline_frame ascending
Overlaps with useUnifiedGenerations - both fetch shot-specific data but via different code paths
4. useAllShotGenerations (/src/shared/hooks/useShotGenerations.ts)
Purpose : Non-paginated fetch of ALL shot generations in one query
Query Key : ['all-shot-generations', shotId]
Data Source : shot_generations table with JOIN to generations + primary_variant
Returns : Complete GenerationRow[] (all items, no pagination)
Special Features :
Single query for complete reliability and simplicity
Has disableRefetch option for drag/persist operations
Filters by positioned/unpositioned via shot_data
No placeholderData to prevent cross-shot contamination
Cache priming support via usePrimeShotGenerationsCache
Used by: ShotEditor, Timeline, shot image management
5. useTimelineShotGenerations (/src/shared/hooks/useShotGenerations.ts)
Purpose : Typed wrapper around useAllShotGenerations for timeline-specific filtering
Query Key : (wraps useAllShotGenerations, same key)
Data Source : useAllShotGenerations base query
Returns : TimelineGenerationRow[] (positioned images only, with metadata)
Filters : Positioned (timeline_frame != null), has metadata, non-video
Special Features :
Type-narrows to TimelineGenerationRow with metadata guarantee
Memoized filtering to prevent unnecessary re-renders
6. Selector Hooks (also in /src/shared/hooks/useShotGenerations.ts)
useTimelineImages : Positioned, non-video images with valid location
useUnpositionedImages : Null timeline_frame, non-video, valid location
useVideoOutputs : Video generations only
Purpose : Centralized filtering views that update automatically when mutations occur
Query Key : (all wrap useAllShotGenerations)
Special Features : Memoized selectors, provide stable data views
7. useShotGenerationsData (/src/tools/travel-between-images/components/ShotImagesEditor/hooks/useShotGenerationsData.ts)
Purpose : Composite hook for shot editor that chooses between preloaded vs database data
Query Keys : Delegates to useTimelineCore or useTimelinePositionUtils
Data Source : Either preloaded images OR useTimelineCore (which queries database)
Returns : UseShotGenerationsDataReturn with both positioned/unpositioned data + badge data
Special Features :
Smart data source selection (preloaded vs database)
Includes variant badge data via useVariantBadges
Provides mutation functions (position updates, pair prompts, etc.)
Used by ShotImagesEditor component
8. useGenerationsPageLogic (/src/shared/hooks/useGenerationsPageLogic.ts)
Purpose : Complex business logic for generations pane with shot filtering and persistence
Query Key : (wraps useGenerations, adds complex state management)
Uses : useGenerations underneath
Special Features :
Stable filter state map to prevent flicker during shot navigation
Per-shot settings persistence
Shot filter fallback when query returns 0 results
Skeleton count estimation
User override tracking
Add-to-shot action handlers
9. useVideoGenerations (/src/shared/components/TasksPane/hooks/useVideoGenerations.ts)
Purpose : Task-specific video generation fetching
Query Key : ['video-generations-for-task', taskId, outputLocation]
Data Source : generations table + generation_variants (lazy, on-hover)
Returns : GenerationRow[] for video outputs
Special Features :
Lazy loading (only fetches on hover)
Searches by output location, task ID, or creates fallback pseudo-generation
Handles individual_travel_segment tasks with child_generation_id
Creates minimal fallback records if generation doesn't exist
10. useExternalGenerations (/src/shared/components/ShotImageManager/hooks/useExternalGenerations.ts)
Purpose : Manages external/out-of-context generations for lightbox navigation
Data Source : State-based (no React Query), manual supabase queries
Returns : GenerationRow[] arrays for external and derived-context generations
Special Features :
Tracks external + temp-derived generation arrays separately
Handles "Based on this" lineage navigation
Realtime update listening for upscale completions
Manages lightbox index calculation across multiple arrays
Overlap Analysis & Differences
True Duplicates/Overlaps:
useShotGenerations vs useUnifiedGenerations (shot mode)
Both fetch : Shot-specific generations
Different paths : useShotGenerations uses shot_generations table JOIN; useUnifiedGenerations optimizes via generations.shot_data JSONB
Different pagination : useShotGenerations is infinite; useUnifiedGenerations is standard pagination
Recommendation : useUnifiedGenerations is likely better (10x faster JSONB path)
useAllShotGenerations vs useShotGenerations
Both fetch : All shot generations via shot_generations table
Key difference : useAllShotGenerations is non-paginated (single query), useShotGenerations is infinite-paginated
Use cases differ : Editor needs all data at once; pagination is rarely needed for shot-specific views
These complement each other - not true duplicates
Intentionally Different (NOT Duplicates):
useGenerations vs useUnifiedGenerations (project mode)
useGenerations : Legacy core hook, transforms via transformGeneration, handles many filter types
useUnifiedGenerations : Newer unified interface, includes task data, simpler transformation
Both serve project-wide views but may diverge in features
Could consolidate but currently serve different consumers
useTimelineShotGenerations vs useTimelineImages
useTimelineShotGenerations : Type-narrowing wrapper (guarantees metadata exists)
useTimelineImages : Selector hook with location validation
Not duplicates - one is a query wrapper, one is a selector filter
Query Key Consistency Issues Notice the inconsistency:
useShotGenerations & useAllShotGenerations both use ['unified-generations', 'shot', shotId] or ['all-shot-generations', shotId]
useUnifiedGenerations (shot mode) uses ['unified-generations', 'shot', shotId, ...] with filters
This could cause cache collisions or inconsistencies
Summary Consolidation Opportunities:
useShotGenerations (infinite pagination) could be deprecated in favor of useAllShotGenerations since pagination rarely needed for shot views
useGenerations and useUnifiedGenerations could eventually consolidate, but currently serve different feature sets
Query keys should be standardized across similar hooks
By Design (Not Duplicates):
Timeline vs Unpositioned vs VideoOutputs selectors are intentionally different views of the same data
Task-specific and external generation hooks serve distinct UI contexts
Preloaded vs database sourcing in useShotGenerationsData is a smart pattern
This architecture reflects a mature but somewhat layered approach to generation fetching that could benefit from consolidation refactoring, but each hook currently serves a specific purpose.
queryClient.setQueryData(['toolSettings', 'project-image-settings', selectedProjectId, undefined],
updateSettingsCache<ProjectImageSettings>(prev, { references, selectedReferenceIdByShot }))
Line 493-495 (handleResourceSelect - existing reference)
typescript Copy code
queryClient.setQueryData(['toolSettings', 'project-image-settings', selectedProjectId, undefined],
updateSettingsCache<ProjectImageSettings>(prev, { selectedReferenceIdByShot }))
Line 530-538 (handleResourceSelect - new pointer)
typescript Copy code
queryClient.setQueryData(['toolSettings', 'project-image-settings', selectedProjectId, undefined],
updateSettingsCache<ProjectImageSettings>(prev, { references, selectedReferenceIdByShot }))
Line 592-594 (handleSelectReference)
typescript Copy code
queryClient.setQueryData(['toolSettings', 'project-image-settings', selectedProjectId, undefined],
updateSettingsCache<ProjectImageSettings>(prev, { selectedReferenceIdByShot }))
Line 642-646 (handleDeleteReference)
typescript Copy code
queryClient.setQueryData(['toolSettings', 'project-image-settings', selectedProjectId, undefined],
updateSettingsCache<ProjectImageSettings>(prev, { references, selectedReferenceIdByShot }))
Optimistic writes followed by DB saves: Each handler does:
queryClient.setQueryData() (optimistic update)
await updateProjectImageSettings() (DB write - goes through 300ms debounce queue)
Reads cache again with extractSettingsFromCache() to get "current data"
Writes back to DB
Race Window: Between optimistic update (step 1) and DB write completion (step 2), a realtime event could invalidate the cache, wiping out the optimistic update.
Sequence Example (handleStyleReferenceUpload):
code Copy code
T0: Optimistic setQueryData(['toolSettings', 'project-image-settings', ...])
T0+: updateProjectImageSettings() enqueued to write queue
T50: Realtime event arrives → invalidateQueries(['toolSettings', ...])
T100: React Query refetch starts (cache was cleared)
T200: DB write finally executes (was debounced)
T300: onSuccess callback runs setQueryData() again
Result: Data fetched in refetch (T100) is STALE by the time DB write succeeds (T200)
3. Realtime → React Query Invalidation Conflicts Location: /Users/user_c042661f/Documents/reigh/src/shared/providers/SimpleRealtimeProvider.tsx
Current invalidation strategy (lines 140-198):
Broad invalidations on task updates: ['tasks', 'paginated'], ['task-status-counts']
Shot-specific invalidations: calls invalidateGenerationsSync() for completed shot IDs
Problem: These invalidations don't coordinate with debounced settings writes
Interaction with debounced settings:
Realtime fires realtime:task-update-batch (task completed)
Provider calls invalidateQueries() immediately
Simultaneously, settings write may be in debounce queue (still pending at T300ms)
Invalidation triggers refetch, React Query fetches BEFORE debounced write completes
Data is stale until write finishes 300ms later
4. useAutoSaveSettings Pending Edit Protection Location: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useAutoSaveSettings.ts
Protection mechanism (lines 549-573):
typescript Copy code
if (pendingSettingsRef.current && pendingEntityIdRef.current === entityId) {
// Skip DB load - user has pending edits for THIS entity
// Still transition to ready and schedule save for input during loading
if (status !== 'ready') {
setStatus('ready');
// Re-schedule save with updated debounce window
saveTimeoutRef.current = setTimeout(async () => {
await saveImmediateRef.current(toSave);
}, debounceMs);
}
return;
}
How it prevents overwrite:
Pending edits tracked in pendingSettingsRef
If user types while DB is loading, pending ref blocks the load
But this only works if:
Status is 'loading' or 'ready' (not 'saving')
User edits happen AFTER setStatus called
No realtime invalidation happens between edit and save
Race Window: If realtime invalidates between user edit and debounce timer firing:
code Copy code
T0: User edits → updateField() → pendingSettingsRef set → debounce scheduled
T50: Realtime invalidation → queryClient.invalidateQueries()
T100: React Query refetch starts
T150: Refetch completes, old data loaded into state
T300: Debounce timer fires, saveImmediate() runs
BUT: by this point, state may have been overwritten by T150 refetch if not careful
5. setQueryData Cache Merge Strategy Location: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useToolSettings.ts (lines 657-670)
onSuccess callback pattern:
typescript Copy code
queryClient.setQueryData(
['toolSettings', toolId, projectId, shotId],
(oldData: any) => {
const hasWrapper = oldData && 'settings' in oldData && 'hasShotSettings' in oldData;
const oldSettings = hasWrapper ? (oldData?.settings ?? {}) : (oldData ?? {});
const mergedSettings = deepMerge({}, oldSettings, fullMergedSettings);
return {
settings: mergedSettings,
hasShotSettings: hasWrapper ? (oldData?.hasShotSettings ?? false) : false
};
}
);
fullMergedSettings is the DB-returned value after mutation
But if realtime invalidated and refetch was in-flight, oldData in the callback may be fresh DB data
deepMerge() does shallow merge of top-level keys + recursive merge of nested objects
Arrays are REPLACED entirely (line 52 in deepEqual.ts): JSON.parse(JSON.stringify(sourceValue))
Race scenario with references array:
code Copy code
T0: User adds reference → optimistic setQueryData
T0+: updateProjectImageSettings() enqueued
T50: Realtime event → invalidateQueries(['toolSettings', 'project-image-settings', ...])
T100: Refetch starts, returns DB state WITHOUT new reference yet
T150: Refetch completes, cache now has stale references array
T300: DB write finally completes
T300: onSuccess runs deepMerge(old={references: [ref1]}, new={references: [ref1, ref2_from_db]})
Result: References array replaced with DB version (includes ref2)
BUT: if another client added ref3 meanwhile, ref3 is lost
6. Multiple Sources Updating Same Cache Source Target Cache Timing Method useReferenceManagement ['toolSettings', 'project-image-settings', projectId, undefined]Immediate (optimistic) + T300 (debounce) setQueryDataupdateToolSettingsSupabase onSuccess Same key After debounce setQueryData with deepMergeRealtime invalidation ['toolSettings', ...] (prefix match)Whenever task updates invalidateQueriesReact Query refetch Same key After invalidation Full DB fetch useAutoSaveSettings cleanup Same key (if shot) On unmount invalidateQueries then refetchQueries
Critical: Line 262 in useAutoSaveSettings.ts - Cleanup runs refetchQueries() (NOT invalidate):
typescript Copy code
queryClient.refetchQueries({ queryKey: ['shot-batch-settings', pendingForEntity] });
This forces an immediate refetch, potentially re-fetching while debounce is still pending.
7. deepEqual Performance Issue (JSON.stringify) Location: /Users/user_c042661f/Documents/reigh/src/shared/lib/deepEqual.ts (line 26)
typescript Copy code
export function deepEqual(a: unknown, b: unknown): boolean {
return JSON.stringify(sanitizeSettings(a)) === JSON.stringify(sanitizeSettings(b));
}
useAutoSaveSettings (line 153): dirty flag check on every render
useAutoSaveSettings (line 169): before saving
usePersistentToolState (line 211): before updating
Issue: JSON.stringify is called on every comparison. If settings objects are large (arrays of references, loras, etc.), this could cause:
UI jank
Missed race condition windows (timer fires between stringify operations)
But it's deterministic: no race here, just performance
8. Edit Version Mechanism Works, But Has Gaps Location: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useAutoSaveSettings.ts (lines 136-137, 320-321, 361)
typescript Copy code
editVersionRef.current += 1; // Increment on each edit
const editVersionAtStart = editVersionRef.current; // Capture at start of debounce
// ... after save completes:
if (editVersionRef.current === editVersionAtStart) {
// Clear pending only if NO newer edits happened
pendingSettingsRef.current = null;
}
This prevents lost edits when user types fast, BUT:
Does NOT prevent realtime invalidation from wiping optimistic updates
Does NOT handle the case where user types, then realtime loads different data, then more typing
code Copy code
T0: User types "hello" → editVersionRef=1, save scheduled for T300
T50: Realtime invalidate → refetch starts
T100: Refetch completes → dbSettings changes, triggers useEffect
useEffect sees status='loading' (from refetch)
BUT: If status was 'ready', the dbSettings load would attempt to merge
This is protected by pendingSettingsRef check
T300: Debounce fires → editVersionRef still 1 → pending cleared ✓
Result: Works because of pendingSettingsRef guard
BUT if realtime changes settings AFTER refetch and status transitions back to 'ready':
T0: User types "hello" → editVersionRef=1, save scheduled, pendingRef="hello"
T50: Realtime invalidate → refetchQueries triggered
T100: Refetch completes → cache updated with old DB state
dbSettings arrives, status still 'ready'
T120: useEffect line 586 checks: loadedSettingsRef.current changed, so it DOES update
BUT pendingSettingsRef check (line 553) should block this...
If pendingSettingsRef="hello" and pendingEntityIdRef matches, it skips load ✓
T300: Debounce fires → save "hello" ✓
Result: Protected again
The protection is there, but it's subtle and depends on: pendingSettingsRef must match entityId .
9. Global Write Queue Coalescing Risk Location: /Users/user_c042661f/Documents/reigh/src/shared/lib/settingsWriteQueue.ts (lines 61-63, 149-152)
typescript Copy code
function mergePatch(existing: Record<string, unknown>, incoming: Record<string, unknown>): Record<string, unknown> {
return { ...existing, ...incoming }; // Shallow merge only
}
if (existing) {
existing.write.patch = mergePatch(existing.write.patch, write.patch); // Merge into pending
}
Issue with shallow merge:
If two updates come in: {references: [a]} then {selectedReferenceIdByShot: {x: 'y'}},
they merge fine (different keys)
But if same key comes twice rapidly: {fieldA: 1} then {fieldA: 2}, second wins ✓
However , the merged patch might miss intermediate states from other sources
code Copy code
T0: UpdateA enqueued: {references: [ref1]}
T50: UpdateB enqueued: {selectedReferenceIdByShot: {a: refX}}
Merged patch: {references: [ref1], selectedReferenceIdByShot: {a: refX}}
T300: Single write to DB with merged patch
If DB had already applied part of UpdateA between T0-T300, this is fine
But if another client wrote {references: [ref2]} at T100, merged patch overwrites it
This is expected behavior for a write queue, but important to note.
Summary of Race Conditions Priority Issue Window Impact CRITICAL Realtime invalidation during debounced write 0-300ms Optimistic updates lost, stale data refetched before DB write HIGH useReferenceManagement optimistic + DB write + read 0-300ms References array might be read from cache at wrong time HIGH Edit version only protects fast typing, not realtime conflicts 0-300ms Realtime load could overwrite pending edits if not for pendingSettingsRef MEDIUM setQueryData merge uses deep reference equality After write If two clients edit same settings, shallow merge might lose updates MEDIUM Multiple setQueryData calls in reference handlers 0-300ms Multiple optimistic updates could interfere with each other LOW deepEqual JSON.stringify perf Every render Performance issue, not a data issue
Recommended Diagnostics to Add
Log realtime invalidation timing vs debounce completion:
code Copy code
[Realtime] Invalidating at T=50ms while debounce in flight
[SettingsQueue] Write completed at T=300ms (was debounced)
Log edit version mismatches:
code Copy code
[useAutoSaveSettings] editVersion mismatch: started=5, ended=7 → pending not cleared
Log cache state before/after realtime events:
code Copy code
[SimpleRealtime] Before invalidate: references.length = 3
[SimpleRealtime] After refetch: references.length = 3 (stale, was 4 from optimistic)
Add timestamp tracking to queue:
code Copy code
[SettingsWriteQueue] Write enqueued at T=0, debounce fired at T=300, DB complete at T=350
[Realtime] Invalidate at T=250 (in middle of debounce window)
These patterns are working (data isn't being lost completely), but the interactions are complex and timing-dependent. The editVersionRef and pendingSettingsRef mechanisms provide protection, but they're implicit and could fail if assumptions change.
File : /Users/user_c042661f/Documents/reigh/src/shared/lib/settingsWriteQueue.ts
Global State (Lines 36-38):
pendingByTarget: Map of {scope}:{entityId}:{toolId} → pending write
inFlightCount: Limits concurrent writes to 1
flushQueue: Queue of writes waiting to execute
Enqueue Logic (Lines 140-189):
Compute unique key: ${scope}:${entityId}:${toolId} (Line 54)
If key already pending, merge patch (Lines 150-152): {...existing, ...incoming} (Line 62)
If new, create PendingWrite with resolvers array
Set debounce timer (300ms) or flush immediately if mode === 'immediate'
Queue Processing (Lines 68-113):
processQueue() respects MAX_CONCURRENT = 1 (Line 33)
Dequeues and calls writeFunction(pending.write) (Line 95)
Resolves all waiting promises with same result (Lines 98-100)
Write Function Registration (Line 403):
typescript Copy code
setSettingsWriteFunction(rawUpdateToolSettings);
3. DATABASE WRITE: RPC Function File : /Users/user_c042661f/Documents/reigh/src/shared/hooks/useToolSettings.ts:328-400
rawUpdateToolSettings Flow :
Fetch Current (Lines 350-354):
Reads full settings column from users/projects/shots table
Extracts currentToolSettings for the tool
Merge Patch (Line 370):
typescript Copy code
const updatedToolSettings = deepMerge({}, currentToolSettings, patch);
Atomic RPC Call (Lines 374-379):
typescript Copy code
supabase.rpc('update_tool_settings_atomic', {
p_table_name: 'users|projects|shots',
p_id: entityId,
p_tool_id: toolId,
p_settings: updatedToolSettings
})
Critical : Uses atomic RPC instead of .update() for single DB operation
Return Full Merged Settings (Line 388):
Returns the full merged settings , not just the patch
This ensures cache gets exact DB values
4. SETTINGS READ PATH: Database → React Query → UI File : /Users/user_c042661f/Documents/reigh/src/shared/hooks/useToolSettings.ts:115-320
Fetch Function (fetchToolSettingsSupabase, Lines 115-320):
Auth with Caching (Lines 54-113):
Caches user ID for 10 seconds (Lines 24-26)
Single-flights getSession() calls (Lines 71-77) because it's slow (600ms-16s)
15-second timeout on auth (Line 54)
Parallel Fetches (Lines 177-199):
typescript Copy code
[userResult, projectResult, shotResult] = await Promise.all([
supabase.from('users').select('settings').eq('id', user.id),
projectId ? supabase.from('projects').select('settings').eq('id', projectId) : null,
shotId ? supabase.from('shots').select('settings').eq('id', shotId) : null
])
Extract Tool Settings (Lines 226-231):
Gets {toolId} field from each scope's settings JSON
Handles missing fields gracefully
Merge Cascade (Lines 252-259):
code Copy code
defaults → user → project → shot
Latest scope wins (shot overrides everything)
Return Wrapper (Line 271):
typescript Copy code
return { settings: merged, hasShotSettings: boolean }
React Query Integration (Lines 518-577):
Query Key : ['toolSettings', toolId, projectId, shotId] (Line 519)
Cache Configuration :
staleTime: 10 * 60 * 1000 (10 minutes) (Line 556)
Uses QUERY_PRESETS.static (Line 555)
networkMode: 'online' (Line 576)
Retry Logic (Lines 558-575):
No retry on auth errors, cancellations, network exhaustion
Up to 3 retries for transient network errors
Exponential backoff via STANDARD_RETRY_DELAY
Single-Flight Deduplication (Lines 122-133):
inflightSettingsFetches map prevents duplicate concurrent requests
Same {toolId, projectId, shotId} reuses existing promise
Load Effect (Lines 522-615):
Triggered by useAutoSaveSettings after DB fetch
Protected from overwrite (Lines 549-574):
If pendingSettingsRef.current && pendingEntityIdRef.current === entityId, skip load
This is the critical protection against losing user input during page load
Still transitions to ready state and schedules save for pending edits
5. REALTIME INTEGRATION WITH SETTINGS File : /Users/user_c042661f/Documents/reigh/src/shared/providers/SimpleRealtimeProvider.tsx
CRITICAL: Realtime Does NOT Update Settings Cache Directly
The realtime system handles task/generation changes , not settings changes:
Event Types Handled (SimpleRealtimeManager.ts):
Task updates (line 554-557): Batched, dispatch to realtime listeners
Shot generation changes (line 564-604): Batched, with positioned-image filtering
Generation updates (line 621-680): Batched, skips shot-sync-only updates
Variant changes (line 606-619): Batched
NO settings changes - Settings are user-scoped and change rarely
SimpleRealtimeProvider Response (SimpleRealtimeProvider.tsx):
Listens to realtime:task-update-batch, etc. (Lines 445-450)
Invalidates relevant query keys (e.g., ['unified-generations', 'shot', shotId])
Never touches ['toolSettings', ...] query keys
Settings Change Propagation :
Settings changes are atomic RPC writes to the DB
Cache is updated via mutation onSuccess (Lines 654-685)
No realtime needed because settings are per-user/project/shot and change infrequently
6. COORDINATION MECHANISMS: Data Loss Prevention Layer 1: Pending Refs (useAutoSaveSettings.ts)
pendingSettingsRef.current blocks DB load from overwriting (Line 553)
Persists through status changes during loading
Protects against: Rapid page navigation, slow DB queries, component re-renders during debounce
Layer 2: Edit Version Counter (useAutoSaveSettings.ts)
editVersionRef.current incremented per edit (Lines 320-321, 378-379)
Captured at debounce start: editVersionAtStart (Lines 321, 379)
Checked before clearing pending: if (editVersionRef.current === editVersionAtStart) (Lines 361, 418)
Protects against: User typing during save → multiple saves → data loss
Layer 3: Write Queue Serialization (settingsWriteQueue.ts)
Global MAX_CONCURRENT = 1 (Line 33)
All writes serialize to single Supabase connection
Prevents: Network exhaustion, concurrent write conflicts
Layer 4: Cleanup Flush (useAutoSaveSettings.ts)
Entity change triggers cleanup effect (Lines 222-280)
Calls updateToolSettingsSupabase(..., 'immediate') for pending (Line 247-252)
Invalidates React Query cache after save (Lines 254-260, 263-265)
Protects against: Losing edits during shot navigation
Layer 5: Page Unload Flush (useAutoSaveSettings.ts)
beforeunload event handler (Lines 288-315)
Fire-and-forget save directly to DB (Line 302-307)
Best-effort: browsers allow 50-100ms (Line 286)
Protects against: Losing edits on page close
7. IDENTIFIED GAPS & CONCERNS Potential Data Loss Scenarios :
Edit After Unload Starts
If user types after beforeunload fires but before DB write completes, data lost
Browser doesn't block navigation to wait for async (max 50-100ms)
Mitigation: Low probability (needs very fast typing), no current solution
Realtime + Write Race
If realtime invalidates cache while debounce is pending, cache reads stale state
However: Settings rarely change via realtime (not implemented)
Current status: Safe by design (settings excluded from realtime)
Multiple Tabs/Windows
No cross-tab coordination for pending writes
Each tab has own pendingSettingsRef and editVersionRef
If two tabs edit same setting, write queue serializes but loses edits from first tab
Mitigation: Users would see edit from their own tab win
Network Partition During Flush
Cleanup flush (entity change) is fire-and-forget (Line 247-252)
If network drops during cleanup, pending lost
Mitigation: Manual save before navigation? Not implemented
Cache Invalidation Timing
Cleanup flush invalidates AFTER save completes (Lines 254-260)
Window between save return and invalidation where cache is stale
Risk: User refreshes in that window, sees old data briefly
Current: Low risk due to 10-minute staleTime (Line 556)
8. KEY FILES & LINE NUMBERS SUMMARY Flow Step File Key Lines Write: UI → Hook useAutoSaveSettings.ts318-373 (updateField) Write: Debounce useAutoSaveSettings.ts342-369, 347-368 (setTimeout) Write: Race Condition Check useAutoSaveSettings.ts359-364, 418-421 (editVersionRef check) Write: Queue Entry useToolSettings.ts417-430 (updateToolSettingsSupabase) Write: Queue Dedup settingsWriteQueue.ts140-189 (enqueueSettingsWrite) Write: DB RPC useToolSettings.ts328-400 (rawUpdateToolSettings) Write: Atomic Update useToolSettings.ts374-379 (supabase.rpc) Read: Query useToolSettings.ts115-320 (fetchToolSettingsSupabase) Read: Merge Cascade useToolSettings.ts252-259 (deepMerge) Read: React Query Setup useToolSettings.ts518-577 (useQuery) Read: Protection from Overwrite useAutoSaveSettings.ts549-574 (pending check) Realtime: Events SimpleRealtimeManager.ts554-680 (handlers) Realtime: Invalidation SimpleRealtimeProvider.tsx112-476 (event listeners) Cleanup: Entity Change useAutoSaveSettings.ts222-280 (cleanup effect) Cleanup: Page Unload useAutoSaveSettings.ts288-315 (beforeunload) Deduplication: Deep Equal deepEqual.ts25-27 (equality check) Merge: Deep Merge deepEqual.ts33-66 (recursive merge)
9. ARCHITECTURE DIAGRAM code Copy code
┌─ USER INTERACTION ─┐
│ updateField('key') │
└──────────┬─────────┘
↓
┌─────────────────────────────────────────┐
│ useAutoSaveSettings Hook │
├─────────────────────────────────────────┤
│ • setSettings(updated) │
│ • pendingSettingsRef = updated │
│ • editVersionRef += 1 │
│ • setTimeout(300ms) → saveImmediate() │
└────────────┬────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Save with Race Protection │
├─────────────────────────────────────────┤
│ • editVersionAtStart = editVersionRef │
│ • await saveImmediate(latestSettings) │
│ • IF editVersionRef === editVersionAtStart:
│ clear pendingSettingsRef │
└────────────┬────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ updateToolSettingsSupabase() │
├─────────────────────────────────────────┤
│ • enqueueSettingsWrite({...}) │
│ • Merge with pending write │
│ • Debounce 300ms + Serialize globally │
└────────────┬────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ rawUpdateToolSettings (Write Function) │
├─────────────────────────────────────────┤
│ • Fetch current settings │
│ • deepMerge(current, patch) │
│ • supabase.rpc('update_tool_settings') │
│ • Return full merged settings │
└────────────┬────────────────────────────┘
↓
┌───────────────────┐
│ Supabase DB │
│ (atomic update) │
└────────┬──────────┘
↓
┌─────────────────────────────────────────┐
│ updateMutation.onSuccess() │
├─────────────────────────────────────────┤
│ • queryClient.setQueryData(...) │
│ • Merge with oldSettings │
│ • Update cache │
│ • Invalidate shot-batch-settings │
└────────────┬────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ useAutoSaveSettings Reads Cache │
├─────────────────────────────────────────┤
│ • IF pendingSettings exist: │
│ Skip load (don't overwrite) │
│ • ELSE apply dbSettings │
│ • loadedSettingsRef = dbSettings │
└────────────┬────────────────────────────┘
↓
┌──────────┐
│ UI │
└──────────┘
10. SUMMARY OF PROTECTIONS ✅ Prevents Data Loss When :
User types rapidly (edit version check)
Page navigates while debounce pending (cleanup flush)
Page unloads with pending changes (beforeunload flush)
DB takes time to respond (pending ref blocks overwrite)
Multiple writes to same setting simultaneously (queue serializes)
Multiple tabs can lose edits from first tab
Network partition during cleanup flush
Edit after beforeunload fires but before DB write
✨ Key Innovation : The pending settings ref + edit version counter pattern prevents the common "user types during async load, DB overwrites input" problem that plagues many apps.
Helper Hooks & Utilities: code Copy code
usePrimeShotGenerationsCache
└─ Primes ['all-shot-generations', shotId] with context data
useVariantBadges
└─ Lazy loads derivedCount/hasUnviewedVariants badges
useShotGenerationMetadata
└─ Loads metadata for pair prompts, etc.
useGenerationTaskMapping / useTaskFromUnifiedCache / usePrefetchTaskData
└─ Generation-to-task linking (via generationTaskBridge.ts)
2. QUERY KEY ANALYSIS
ALL Query Keys Used for Generation Data: File: /Users/user_c042661f/Documents/reigh/src/shared/lib/queryKeys.ts
Category Key Pattern Usage Shot-specific ['all-shot-generations', shotId]Primary shot data (useAllShotGenerations) ['shot-generations-meta', shotId]Metadata, counts, positions ['unpositioned-count', shotId]Count of unpositioned images ['generation', generationId]Single generation detail Project-wide ['unified-generations']Base key (all patterns) ['unified-generations', 'project', projectId, page, limit, filters, ...]Project gallery ['unified-generations', 'shot', shotId, page, limit, filters, ...]Shot gallery Variants ['generation-variants', generationId]Variants for a generation ['variant-badges']"X new" badges Derived ['derived-items', generationId]Child gens + edit variants ['derived-generations', generationId]Alternative key Segments ['segment-live-timeline', shotId]Segment video timeline ['segment-child-generations', segmentId]Children for segment Lineage ['lineage-chain', generationId]Full ancestry chain Video ['last-video-generation', shotId]Most recent video
Query Key Inconsistencies Found:
VARIANT QUERIES - Different patterns co-exist:
['generation-variants', generationId] (normalized)
['variant-badges'] (global, not scoped)
DERIVED ITEMS - Two overlapping keys:
['derived-items', generationId] (useDerivedItems)
['derived-generations', generationId] (unused? legacy?)
UNIFIED-GENERATIONS - Keys serialize filters:
JSON.stringify(filters) → Breaks memoization if filter object recreated
Should use stable filter key generation
MISSING KEYS :
No explicit key for useShotGenerations infinite query (uses hard-coded ['unified-generations', 'shot', shotId])
Task mapping uses dynamic key: ['tasks', 'taskId', generationId]
3. DATA TRANSFORMATION POINTS
Transformation Functions (all in /Users/user_c042661f/Documents/reigh/src/shared/lib/generationTransformers.ts): Function Input Output Used By transformGeneration() RawGeneration GeneratedImageWithMetadata useGenerations, useUnifiedGenerations transformShotGeneration() RawShotGeneration GeneratedImageWithMetadata + timeline_frame (wrapper utility) transformForTimeline() RawShotGeneration GenerationRow useShotGenerations, mappers transformForUnifiedGenerations() RawShotGeneration GeneratedImageWithMetadata useUnifiedGenerations calculateDerivedCounts() generationIds[] DerivedCountsResult useDerivedItems, useVariantBadges
Redundant Transformations:
transformGeneration vs transformForUnifiedGenerations - 95% duplicate logic
Both transform shot_data JSONB - Inconsistent handling of:
Array format: { shot_id: [frame1, frame2, ...] }
Legacy single-value format: { shot_id: frame }
Shot association normalization - Position calculation frame / 50 done in:
generationTransformers.ts (normalizePosition)
Multiple component files separately
Key Transformation Logic: typescript Copy code
// All transformers do this:
- Extract prompt from nested params.originalParams.orchestrator_details.prompt
- Extract thumbnail URL with travel-between-images special case
- Extract task ID from tasks array (first element)
- Calculate isVideo from type field
- Normalize timeline_frame to position (divide by 50)
- Extract shot associations from shot_data JSONB or shot_generations join
// VARIANT TRACKING (lazy-loaded):
- derivedCount (number of variants/child generations)
- hasUnviewedVariants (boolean, for NEW badge)
- unviewedVariantCount (count of unviewed)
→ Queried separately via calculateDerivedCounts()
4. INVALIDATION PATTERNS
Central Invalidation Hub: File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/invalidation/useGenerationInvalidation.ts
Invalidation Functions: Function When to Use Scope Keys Touched useInvalidateGenerations() Hook version for components Shot-scoped all-shot-generations, unified-generations (shot), shot-generations-meta, unpositioned-count, shots (optional) invalidateGenerationsSync() Sync version (no hooks) Shot-scoped Same as above + optional delay invalidateVariantChange() Variant created/updated/set-as-primary Global + shot-specific generation-variants, generation detail, variant-badges, all-shot-generations (predicate), unified-generations (all patterns), segment children/parents, source-slot invalidateGenerationUpdate() Generation location/metadata changed Global + shot-specific generation detail, unified-generations (all patterns), derived-items, segment children invalidateAllShotGenerations() Global event (rare) ALL shots Uses predicate: queryKey[0] === 'all-shot-generations'
Invalidation Scopes: typescript Copy code
scope: 'all' // All generation queries for shot (default)
scope: 'images' // Just image data (all-shot-generations, segments)
scope: 'metadata' // Just metadata (shot-generations-meta)
scope: 'counts' // Just counts (unpositioned-count)
scope: 'unified' // Just unified-generations queries
Invalidation Callers: Found 21 files calling invalidation functions including:
/Users/user_c042661f/Documents/reigh/src/shared/hooks/shots/useShotGenerationMutations.ts
/Users/user_c042661f/Documents/reigh/src/shared/hooks/useVariants.ts
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/ShotEditor/hooks/useGenerationActions.ts
/Users/user_c042661f/Documents/reigh/src/shared/components/MediaLightbox/hooks/useMakeMainVariant.ts
(SimpleRealtimeProvider.tsx - handles realtime invalidations)
ISSUES:
Inconsistent cache invalidation scope :
Some places invalidate ['unified-generations'] (all patterns)
Some invalidate specific shot pattern
Some invalidate project pattern
→ Can leave stale data in project gallery when shot changes
Invalidation timing :
No consistent delay for DB trigger completion
Task data invalidation separate from generation invalidation
Variant changes may update generation.location but invalidation happens after
Missing invalidations :
Generation deletion doesn't invalidate shots list
Variant update doesn't invalidate unpositioned-count
5. REALTIME UPDATES FOR GENERATIONS
Realtime Integration:
/Users/user_c042661f/Documents/reigh/src/shared/realtime/DataFreshnessManager.ts
/Users/user_c042661f/Documents/reigh/src/shared/providers/SimpleRealtimeProvider.tsx
/Users/user_c042661f/Documents/reigh/src/shared/realtime/SimpleRealtimeManager.ts (not shown)
How Realtime Works: code Copy code
SimpleRealtimeManager
├─ Subscribes to Supabase realtime events for project
├─ Listens to generations table changes
├─ Listens to generation_variants table changes
└─ Listens to shot_generations table changes
↓
SimpleRealtimeProvider
├─ Debounces invalidation calls (prevents storms)
└─ Calls invalidateGenerationsSync() for relevant shot
↓
DataFreshnessManager (tracking realtime health)
├─ Records "last event time" per query key
├─ Tracks realtime connection status
└─ Provides polling intervals to hooks (via useSmartPollingConfig)
Polling Strategy (NOT invalidation): File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useSmartPolling.ts (not shown but referenced)
Uses DataFreshnessManager:
typescript Copy code
// Realtime connected & stable (>30s):
- Within 1 minute of events → NO POLLING (trust realtime)
- Within 3 minutes of events → 60s polling (light safety)
- No events for 3+ min → 60s polling (realtime proving stability)
- Stable for 5+ min → NO POLLING (full trust)
// Realtime disconnected:
- 5 second aggressive polling fallback
ISSUE: Direct Cache Updates Missing Realtime only invalidates - it doesn't directly update caches. This means:
Invalidation triggers query refetch
Refetch goes to database
Component gets new data
Realtime event provides new data
Directly update cache with event data
Only refetch if event data incomplete
Current approach works but is inefficient for high-frequency updates.
6. CONSOLIDATION OPPORTUNITIES
Priority 1: High-Impact Consolidations
A. Duplicate Transformers (3 functions doing similar work) File: /Users/user_c042661f/Documents/reigh/src/shared/lib/generationTransformers.ts lines 209-490
code Copy code
transformGeneration() → 132 lines (BASE)
transformForUnifiedGenerations() → 48 lines (85% duplicate)
transformShotGeneration() → 47 lines (wrapper around base)
Keep transformGeneration() as SINGLE SOURCE OF TRUTH
Make transformForUnifiedGenerations() a thin wrapper
Remove transformShotGeneration() - just call base transformer
useShotGenerations.ts (line 58): Currently uses mapShotGenerationToRow
useUnifiedGenerations.ts (line 8): Could use base transformer
Any component using transformShotGeneration()
B. Query Key Serialization Bug File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useUnifiedGenerations.ts line 62
typescript Copy code
const filtersKey = filters ? JSON.stringify(filters) : null;
return ['unified-generations', 'shot', shotId, page, limit, filtersKey, includeTaskData];
Problem: JSON.stringify with different key orders = different keys for same data
Add utility function getFiltersCacheKey(filters) in queryKeys.ts
Use stable, sorted key generation
Apply to all filter serialization
queryKeys.ts
useUnifiedGenerations.ts (line 62)
Any other place serializing filters
C. Overlapping Derived Items Keys File: /Users/user_c042661f/Documents/reigh/src/shared/lib/queryKeys.ts lines 75-82
typescript Copy code
derived: (generationId: string) => ['derived-items', generationId],
derivedAll: ['derived-items'],
derivedGenerations: (generationId: string) => ['derived-generations', generationId],
derivedGenerationsAll: ['derived-generations'],
Problem: Two different key patterns for same data (line 806 uses ['derived-items'])
Use only ['derived-items', generationId]
Delete derivedGenerations and derivedGenerationsAll
Update invalidation: queryKeys.generations.derived not hard-coded strings
queryKeys.ts
useGenerationInvalidation.ts (lines 270-272, 339)
useDerivedItems.ts
D. Variant Badge Loading File: Not shown but referenced in transformers (line 252)
typescript Copy code
// These are loaded LAZILY via useVariantBadges hook
derivedCount: item.derivedCount || 0,
hasUnviewedVariants: item.hasUnviewedVariants || false,
unviewedVariantCount: item.unviewedVariantCount || 0,
Problem: Requires separate query just to get badges; adds complexity
Include badge data in main generation query (batch with calculateDerivedCounts)
Still lazy-load if performance issue, but current split is over-engineered
Consider: join to generation_variants count in single query
Priority 2: Medium-Impact Consolidations
E. Shot Association Extraction (3 places doing same logic) Generation transformation handles shot_data JSONB differently in:
transformGeneration() (lines 268-290)
useUnifiedGenerations.ts (lines 207-218)
Component-level position calculations
Create utility: extractShotAssociations(item.shot_data, item.shot_generations)
Use in all transformers
Handle legacy format conversion in ONE place
F. Query Key Consistency Shot-specific queries use inconsistent key structures:
code Copy code
['all-shot-generations', shotId] ← Primary
['unified-generations', 'shot', shotId] ← Pagination
['shot-generations'] ← Removed (line 116 comment)
Define clear naming: primary query vs paginated views
Document which key uses what data source
Consolidate if possible (useShotGenerations uses unified-generations internally)
G. Task Mapping Scattered Across Files
generationTaskBridge.ts (lines 43-58, 63-83)
useUnifiedGenerations.ts (lines 369-391)
useGenerations.ts (commented out)
Make generationTaskBridge.ts the ONLY place for task lookups
Export hook: useGenerationTaskData(generationId)
Use in all components
Priority 3: Documentation & Pattern Clarity
H. Query Architecture Decision Point Three hooks query essentially same data differently:
Hook Data Source Features useAllShotGenerationsshot_generations join All data, no pagination, realtime-backed useShotGenerationsshot_generations join Paginated infinite query useUnifiedGenerationsgenerations.shot_data JSONB Filtered, flexible, project/shot modes
Document decision: Which hook for which use case?
Consider: Can useShotGenerations wrap useAllShotGenerations?
Clarify: Why two different query sources (shot_generations join vs shot_data JSONB)?
7. CALL SITE DIAGRAM code Copy code
Components/Hooks Generation Data Hooks Invalidation
───────────────────── ────────────────────── ──────────────
VideoTravelToolPage ─┐
├─→ useAllShotGenerations ─→ shot_generations join
│ ↓
│ └─→ mappers.ts (transformForTimeline)
│
├─→ useTimelineImages ────→ filter(useAllShotGenerations)
│
├─→ useUnpositionedImages → filter(useAllShotGenerations)
│
└─→ useVideoOutputs ──────→ filter(useAllShotGenerations)
↓
invalidateGenerations()
├─ scope: 'images'
└─ reason: 'delete-image'
VideoOutputsGallery ─→ useUnifiedGenerations ──→ shot_data JSONB query
↓
└─→ Batch fetch task IDs
MediaGallery ────────→ useGenerations (project-wide)
↓
└─→ applyGenerationFilters()
Lightbox ──────────→ useDerivedItems ─→ Parallel queries:
├─ Child generations (based_on)
└─ Edit variants (generation_variants)
↓
└─→ calculateDerivedCounts()
Summary Table: Key Findings Area Finding Severity Files Duplicated Transformers 3 similar transformer functions HIGH generationTransformers.ts Query Key Serialization JSON.stringify with unstable key order HIGH useUnifiedGenerations.ts Overlapping Keys derived-items vs derived-generations MEDIUM queryKeys.ts, useGenerationInvalidation.ts Realtime Only Invalidates No direct cache updates from events MEDIUM SimpleRealtimeProvider.tsx, DataFreshnessManager.ts Missing Invalidations Variants don't invalidate generation counts MEDIUM useShotGenerationMutations.ts Shot Association Logic Duplicated in transformers + components MEDIUM generationTransformers.ts, useUnifiedGenerations.ts Task Mapping Scattered Logic in multiple files MEDIUM generationTaskBridge.ts, useUnifiedGenerations.ts Variant Badge Design Requires separate lazy-load query LOW generationTransformers.ts Unused Keys derivedGenerations, shot-generations LOW queryKeys.ts
This architecture is well-structured but has consolidation debt primarily in transformation logic and query key management. The realtime integration is solid but could be optimized with direct cache updates.
'metadata' - Just metadata
'counts' - Just counts
'unified' - Just unified-generations
Three coordination functions:
useInvalidateGenerations() (lines 150-176) - React hook with debounce support
invalidateGenerationsSync() (lines 182-194) - Non-hook version with delay support
invalidateAllShotGenerations() (lines 201-217) - Global invalidation (logged as warning)
Variant-specific invalidation (lines 231-294):
invalidateVariantChange() - Handles variant → generation → shot cascade
Refetches immediately if shotId known (line 259)
Includes variant-badges update for UI badges
Generation update invalidation (lines 311-350):
Lighter than variant changes
Doesn't touch shot-generations since relationship unchanged
2. RACE CONDITION PREVENTION PATTERNS
Optimistic Update Pattern with Rollback File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/shots/useShotGenerationMutations.ts (lines 228-453)
onMutate (lines 228-343):
Cancel in-flight queries first (lines 251-252)
Save previous state for rollback (lines 254-258)
Create optimistic temp item with _optimistic: true flag (lines 264-299)
Update all cache variants simultaneously
Remove from unified-generations if applicable
onSuccess (lines 387-453):
Replace temp ID with real ID from server (lines 398-414)
Update all related caches with real data
Invalidate metadata queries
onError (lines 345-385):
Rollback previous state (lines 362-367)
Handle duplicate key constraint specifically (lines 352-359)
User-friendly error messages with retry hints
Batching to Prevent Cascades File: /Users/user_c042661f/Documents/reigh/src/shared/realtime/SimpleRealtimeManager.ts (lines 14-17)
typescript Copy code
private eventBatchQueue: Map<string, any[]> = new Map();
private batchTimeoutId: NodeJS.Timeout | null = null;
private readonly BATCH_WINDOW_MS = 100; // Batch events within 100ms
Events batched within 100ms window to prevent invalidation storms
Query Cancellation File: /Users/user_c042661f/Documents/reigh/src/shared/hooks/shots/cacheUtils.ts (lines 69-78)
Cancels in-flight requests at mutation start to avoid stale data conflicts
Used in mutation's onMutate phase
Timestamp-based Freshness Tracking File: /Users/user_c042661f/Documents/reigh/src/shared/realtime/DataFreshnessManager.ts (lines 15-80)
Tracks lastEventTimes per query (line 24)
Ignores duplicate status changes (lines 38-48)
Maintains "recently connected" grace period for polling decisions
3. REACT QUERY CONFIGURATION
Global Defaults with Presets File: /Users/user_c042661f/Documents/reigh/src/shared/lib/queryDefaults.ts (lines 1-175)
REALTIME_BACKED_PRESET (lines 38-44):
typescript Copy code
staleTime: 30_000, // 30 seconds
gcTime: 5 * 60 * 1000, // 5 minutes
refetchOnMount: false, // Realtime handles freshness
refetchOnWindowFocus: false,
refetchOnReconnect: true, // Safety net after network drops
For: generations, tasks, shots, segments
STATIC_PRESET (lines 62-66):
typescript Copy code
staleTime: 5 * 60 * 1000, // 5 minutes
gcTime: 15 * 60 * 1000, // 15 minutes
refetchOnWindowFocus: false,
For: resources, presets, settings, API tokens
IMMUTABLE_PRESET (lines 80-86):
typescript Copy code
staleTime: Infinity,
gcTime: 30 * 60 * 1000,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
For: completed task results, archived content
USER_CONFIG_PRESET (lines 101-105):
typescript Copy code
staleTime: 2 * 60 * 1000, // 2 minutes
gcTime: 10 * 60 * 1000, // 10 minutes
For: user preferences, account settings
Standard Retry Logic File: /Users/user_c042661f/Documents/reigh/src/shared/lib/queryDefaults.ts (lines 154-174)
typescript Copy code
STANDARD_RETRY = (failureCount, error) => {
// Don't retry aborts/cancellations
if (error?.message?.includes('abort')) return false;
// Don't retry 4xx client errors
if (isErrorWithStatus(error) && error.status >= 400 && error.status < 500) return false;
// Retry up to 2 times for other errors
return failureCount < 2;
}
// Exponential backoff capped at 3s
STANDARD_RETRY_DELAY = (attemptIndex) => Math.min(1000 * Math.pow(2, attemptIndex), 3000);
4. REALTIME + OPTIMISTIC UPDATE COORDINATION
Batched Realtime Event Handling File: /Users/user_c042661f/Documents/reigh/src/shared/providers/SimpleRealtimeProvider.tsx (lines 112-476)
Event types with batching:
realtime:task-update-batch (lines 114-199) - Task completions
realtime:task-new-batch (lines 244-276) - New queued tasks
realtime:shot-generation-change-batch (lines 290-349) - Shot position changes
realtime:generation-update-batch (lines 372-393) - Upscales, location changes
realtime:generation-insert-batch (lines 396-418) - New child generations
realtime:variant-change-batch (lines 421-442) - Variant switches
Smart scope matching (lines 114-199):
Checks for _optimistic flag to skip redundant invalidations
Analyzes event type (INSERT vs UPDATE) to prevent flicker
Shot-specific invalidations when shotId available
Project-level fallback when shotId unknown
Example pattern (lines 314-348):
typescript Copy code
if (hasOnlyInserts) {
// INSERT-only: skip all-shot-generations (optimistic updates handle these)
invalidateGenerationsSync(queryClient, shotId, {
reason: 'shot-generation-change-batch-insert-only',
scope: 'unified' // Just gallery views
});
} else {
// UPDATE/DELETE: full invalidation
invalidateGenerationsSync(queryClient, shotId, {
reason: 'shot-generation-change-batch',
scope: 'all'
});
}
5. DATA FRESHNESS & POLLING COORDINATION
DataFreshnessManager File: /Users/user_c042661f/Documents/reigh/src/shared/realtime/DataFreshnessManager.ts (lines 1-80)
Single source of truth for polling decisions
Status tracking: 'connected' | 'disconnected' | 'error'
Duplicate filtering (lines 38-48): Ignores redundant status changes to prevent grace period reset
Event timestamp tracking (lines 66-80): Per-query last-event-time
SimpleRealtimeManager File: /Users/user_c042661f/Documents/reigh/src/shared/realtime/SimpleRealtimeManager.ts (lines 1-80)
Exponential backoff reconnect (lines 43-78):
typescript Copy code
delay = Math.min(1000 * Math.pow(2, reconnectAttempts - 1), 10000)
maxReconnectAttempts = 5
Event batching (lines 14-17): 100ms batching window
Auth heal handling (lines 31-41): Listens for auth recovery events
6. EQUALITY & MUTATION HELPERS
Deep Equality File: /Users/user_c042661f/Documents/reigh/src/shared/lib/deepEqual.ts (lines 1-66)
typescript Copy code
// Settings comparison (removes undefined values before comparing)
deepEqual(a, b): boolean
return JSON.stringify(sanitizeSettings(a)) === JSON.stringify(sanitizeSettings(b))
// Deep merge with array replacement
deepMerge<T>(target, ...sources): T
Used to detect if settings have actually changed
Prevents unnecessary invalidations
7. TESTING INFRASTRUCTURE
Existing Test Files File: /Users/user_c042661f/Documents/reigh/src/shared/utils/__tests__/reorderUtils.test.ts (lines 1-60)
Testing pattern: Pure function testing with describe/test/expect
Test utilities: Standard Jest/Vitest matchers
Example (lines 10-19):
typescript Copy code
test('handles no changes needed', () => {
const result = analyzeReorderOperation(['a', 'b', 'c'], ['a', 'b', 'c']);
expect(result.noChangesNeeded).toBe(true);
expect(result.swapSequence).toHaveLength(0);
});
Other Test Suites
/Users/user_c042661f/Documents/reigh/src/shared/lib/__tests__/VisibilityManager.test.ts
/Users/user_c042661f/Documents/reigh/src/shared/lib/__tests__/NetworkStatusManager.test.ts
Testing Patterns (from hooks) File: /Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/ShotEditor/hooks/useGenerationActions.ts (lines 71-96)
Ref-based stability for frequently-changing data to prevent callback recreation
Debug logging infrastructure for trace analysis
Mutation refs to access stable mutateAsync functions
8. SIMILAR PROBLEMS SOLVED ELSEWHERE
Multi-Cache Coordination Pattern: Shot-generations variants (line 12 cacheUtils.ts)
Problem: Different UI sections cache the same data with different limits
Solution: updateAllShotsCaches() atomically updates all variants
Reusable: Same pattern can work for other multi-variant scenarios
Optimistic → Realtime Conflict Pattern: INSERT-only batch skipping (lines 326-336 SimpleRealtimeProvider.tsx)
Problem: Optimistic creates + realtime INSERT events cause flicker
Solution: Skip all-shot-generations invalidation for INSERT-only batches
Reusable: Check _optimistic flags before invalidating
Cascading Invalidations Pattern: Event batching (lines 14-17 SimpleRealtimeManager.ts)
Problem: 20 rapid events → 20 invalidation cycles
Solution: Batch within 100ms window
Reusable: Same window timing works for other batch scenarios
Scoped vs Global Invalidation Pattern: Fallback strategy (lines 187-197 SimpleRealtimeProvider.tsx)
Problem: Don't know which shots were affected by a task
Solution: Try scoped invalidation, fallback to global with warning
Reusable: invalidateAllShotGenerations() with warning in useGenerationInvalidation
9. KEY FILE LOCATIONS FOR REUSE/EXTENSION Purpose File Key Functions Query keys /src/shared/lib/queryKeys.ts (line 31+)queryKeys object registryCache coordination /src/shared/hooks/shots/cacheUtils.tsupdateAllShotsCaches(), findShotsCache(), rollbackShotsCaches()Invalidation /src/shared/hooks/invalidation/useGenerationInvalidation.ts (lines 150-194)useInvalidateGenerations(), invalidateGenerationsSync()Mutation patterns /src/shared/hooks/shots/useShotGenerationMutations.ts (lines 228-453)onMutate/onError/onSuccess patternRealtime coordination /src/shared/providers/SimpleRealtimeProvider.tsx (lines 290-348)Batched event handlers with scope detection Data freshness /src/shared/realtime/DataFreshnessManager.ts (lines 33-80)Status tracking + timestamp management Retry logic /src/shared/lib/queryDefaults.ts (lines 154-174)STANDARD_RETRY, STANDARD_RETRY_DELAYEquality helpers /src/shared/lib/deepEqual.ts (lines 25-26)deepEqual(), deepMerge()Test patterns /src/shared/utils/__tests__/reorderUtils.test.tsJest/Vitest structure
10. CRITICAL INSIGHTS FOR YOUR IMPLEMENTATION
Always update multiple cache variants atomically - Use updateAllShotsCaches() pattern, not individual setQueryData() calls
Cancel in-flight queries first - In onMutate, call cancelShotsQueries() to prevent stale resolves
Use scoped invalidation by default - invalidateGenerationsSync(queryClient, shotId, { reason, scope }) prevents cascades
Detect optimistic vs realtime - Check _optimistic flag or event type before invalidating to prevent flicker
Batch realtime events - 100ms window prevents invalidation storms on rapid changes
Preserve status across duplicate calls - DataFreshnessManager's duplicate filtering (lines 38-48) prevents grace period reset
Use queryKeys registry exclusively - Typos caught at compile-time instead of runtime
Delayed invalidation support - Both useInvalidateGenerations() and batched realtime handlers support delayMs for DB triggers
/**
* Registry for tracking in-flight optimistic updates.
* Prevents realtime/refetch from overwriting user changes.
*
* Pattern:
* 1. Before mutation: register(key, tempId)
* 2. On success: resolve(key, tempId, realId)
* 3. On error: rollback(key, tempId)
* 4. In query: skip items where isProtected(key) returns true
*/
interface ProtectedUpdate {
tempId: string;
realId?: string;
registeredAt: number;
expiresAt: number;
}
class OptimisticUpdateRegistry {
private updates = new Map<string, ProtectedUpdate>();
private readonly DEFAULT_TTL = 10_000; // 10 seconds
/**
* Register an optimistic update for protection.
* @param cacheKey - React Query cache key (stringified)
* @param tempId - Temporary ID used in optimistic update
* @param ttlMs - Time-to-live before auto-expiring
*/
register(cacheKey: string, tempId: string, ttlMs = this.DEFAULT_TTL): void {
this.updates.set(this.makeKey(cacheKey, tempId), {
tempId,
registeredAt: Date.now(),
expiresAt: Date.now() + ttlMs,
});
this.cleanup();
}
/**
* Resolve an optimistic update (mutation succeeded).
* Maps temp ID to real ID so both are protected briefly.
*/
resolve(cacheKey: string, tempId: string, realId: string): void {
const key = this.makeKey(cacheKey, tempId);
const existing = this.updates.get(key);
if (existing) {
existing.realId = realId;
// Extend protection briefly for real ID
existing.expiresAt = Date.now() + 2000;
}
}
/**
* Rollback an optimistic update (mutation failed).
*/
rollback(cacheKey: string, tempId: string): void {
this.updates.delete(this.makeKey(cacheKey, tempId));
}
/**
* Check if an ID should be protected from refetch overwrite.
*/
isProtected(cacheKey: string, id: string): boolean {
this.cleanup();
for (const [key, update] of this.updates) {
if (key.startsWith(cacheKey) && (update.tempId === id || update.realId === id)) {
return true;
}
}
return false;
}
/**
* Check if any updates are pending for a cache key.
*/
hasPendingUpdates(cacheKey: string): boolean {
this.cleanup();
for (const key of this.updates.keys()) {
if (key.startsWith(cacheKey)) return true;
}
return false;
}
private makeKey(cacheKey: string, tempId: string): string {
return `${cacheKey}:${tempId}`;
}
private cleanup(): void {
const now = Date.now();
for (const [key, update] of this.updates) {
if (update.expiresAt < now) {
this.updates.delete(key);
}
}
}
}
export const optimisticUpdateRegistry = new OptimisticUpdateRegistry();
1.2 Enhance Realtime Provider with Protection Awareness Modify : /src/shared/providers/SimpleRealtimeProvider.tsx
Add check before invalidation:
typescript Copy code
import { optimisticUpdateRegistry } from '@/shared/lib/optimisticUpdateRegistry';
// In handleShotGenerationChangeBatch:
if (affectedShotIds && affectedShotIds.length > 0) {
affectedShotIds.forEach((shotId: string) => {
// Skip invalidation if optimistic updates are pending
const cacheKey = JSON.stringify(['all-shot-generations', shotId]);
if (optimisticUpdateRegistry.hasPendingUpdates(cacheKey)) {
console.log('[Realtime] Skipping invalidation - optimistic updates pending:', shotId.substring(0, 8));
return;
}
// Existing invalidation logic...
});
}
1.3 Update useShotGenerationMutations to Use Registry Modify : /src/shared/hooks/shots/useShotGenerationMutations.ts
typescript Copy code
import { optimisticUpdateRegistry } from '@/shared/lib/optimisticUpdateRegistry';
// In onMutate:
const cacheKey = JSON.stringify(['all-shot-generations', shot_id]);
optimisticUpdateRegistry.register(cacheKey, tempId);
// In onSuccess:
optimisticUpdateRegistry.resolve(cacheKey, context.tempId, data.id);
// In onError:
optimisticUpdateRegistry.rollback(cacheKey, context.tempId);
Risk : Low - additive changes, doesn't break existing behavior
Testing :
Rapid add/remove operations
Network latency simulation
Verify no flickering in timeline
Phase 2: Consolidate Generation Transformers Goal : Single source of truth for data transformation.
2.1 Audit Current Transformers
transformGeneration in /src/shared/lib/generationTransformers.ts
transformShotGeneration in same file
transformForUnifiedGenerations in same file
transformForTimeline in same file
mapShotGenerationToRow in /src/shared/hooks/useShots.ts
Finding : generationTransformers.ts is already the centralized location. The issue is that some hooks still have inline transformation.
2.2 Standardize on Single Transformer Modify : /src/shared/lib/generationTransformers.ts
typescript Copy code
/**
* Universal transformer - handles all input formats.
* Auto-detects whether input is RawGeneration or RawShotGeneration.
*/
export function transformAny(
input: RawGeneration | RawShotGeneration,
options: TransformOptions = {}
): GenerationRow {
// Detect input type
if ('generation_id' in input) {
return transformShotGeneration(input as RawShotGeneration, options) as GenerationRow;
}
return transformGeneration(input as RawGeneration, options) as unknown as GenerationRow;
}
2.3 Migrate Inline Transformations
/src/shared/hooks/useUnifiedGenerations.ts - Lines 200-234 (inline transformation)
/src/shared/hooks/useShots.ts - mapShotGenerationToRow function
Pattern : Replace inline with transformAny:
typescript Copy code
// Before
const items = (data || []).map((gen: any) => {
const isVideo = gen.type?.toLowerCase().includes('video');
// ... 30 lines of transformation
});
// After
import { transformAny } from '@/shared/lib/generationTransformers';
const items = (data || []).map(gen => transformAny(gen, { shotId }));
Risk : Medium - changes data flow, needs thorough testing
Testing :
Compare before/after output for each hook
Verify all fields present in UI components
Test Timeline, Gallery, Lightbox views
Phase 3: Standardize Query Keys (Already Done) Status : Already centralized in /src/shared/lib/queryKeys.ts
Audit all files using raw query key arrays
Replace with queryKeys.xxx references
bash Copy code
# Audit command (for reference)
grep -r "queryKey: \['" src/ --include="*.ts" --include="*.tsx" | grep -v queryKeys
Files likely needing updates (based on exploration):
/src/shared/hooks/useGenerations.ts - still uses inline keys in places
/src/shared/hooks/useUnifiedGenerations.ts - same
Risk : Low - mechanical refactoring
Testing : Run full app, verify no query key mismatches in console
Phase 4: Consolidate Generation Hooks Goal : Reduce 10+ hooks to a clear hierarchy.
4.1 Current Hook Inventory Hook Location Purpose Keep? useGenerations/src/shared/hooks/useGenerations.tsProject-wide gallery Keep (rename) useUnifiedGenerations/src/shared/hooks/useUnifiedGenerations.tsHybrid project/shot Keep as primary useShotGenerations/src/shared/hooks/useShotGenerations.tsPaginated shot data Deprecate useAllShotGenerations/src/shared/hooks/useShotGenerations.tsFull shot data Keep useTimelineImages/src/shared/hooks/useShotGenerations.tsSelector hook Keep useUnpositionedImages/src/shared/hooks/useShotGenerations.tsSelector hook Keep useVideoOutputs/src/shared/hooks/useShotGenerations.tsSelector hook Keep
4.2 Proposed Hierarchy code Copy code
Base Hooks (fetch data):
├── useProjectGenerations (renamed from useGenerations)
│ └── Used by: MediaGallery, GenerationsPane
└── useAllShotGenerations (unchanged)
└── Used by: Timeline, ShotEditor, all selector hooks
Selector Hooks (filter base data):
├── useTimelineImages ← useAllShotGenerations
├── useUnpositionedImages ← useAllShotGenerations
└── useVideoOutputs ← useAllShotGenerations
Unified Hook (facade for backwards compat):
└── useUnifiedGenerations
└── Delegates to useProjectGenerations or useAllShotGenerations based on mode
4.3 Implementation Step 1 : Rename useGenerations to useProjectGenerations
typescript Copy code
// Export both names for backwards compat
export const useGenerations = useProjectGenerations; // @deprecated
Step 2 : Update useShotGenerations to delegate to useAllShotGenerations
typescript Copy code
// Mark as deprecated, delegate internally
/** @deprecated Use useAllShotGenerations instead */
export const useShotGenerations = (shotId: string | null) => {
const query = useAllShotGenerations(shotId);
// Convert to paginated format for backwards compat
return {
data: { pages: [{ items: query.data || [], nextCursor: null }] },
// ... other infinite query properties
};
};
Step 3 : Simplify useUnifiedGenerations
typescript Copy code
export function useUnifiedGenerations(options: UseUnifiedGenerationsOptions) {
const { mode, shotId, projectId, ...rest } = options;
if (mode === 'shot-specific') {
const query = useAllShotGenerations(shotId);
// Transform to unified format
return transformToUnifiedFormat(query);
}
return useProjectGenerations(projectId, rest);
}
Risk : Medium-High - affects many consumers
Testing :
Full regression test of all galleries/timelines
Performance comparison (should be same or better)
Memory usage comparison
Phase 5: Explicit Race Condition Protection Goal : Make the protection patterns from Phase 1 explicit and systematic.
5.1 Create useSafeQuery Hook New file : /src/shared/hooks/useSafeQuery.ts
typescript Copy code
/**
* Wrapper around useQuery that respects optimistic update protection.
*
* When optimistic updates are pending for a cache key, this hook:
* 1. Uses cached data instead of refetching
* 2. Filters out items being protected from the refetch result
* 3. Logs for debugging
*/
export function useSafeQuery<T extends { id: string }[]>(
options: UseQueryOptions<T> & { protectionKey?: string }
) {
const queryClient = useQueryClient();
const { protectionKey, ...queryOptions } = options;
return useQuery({
...queryOptions,
queryFn: async (context) => {
// Check for pending optimistic updates
if (protectionKey && optimisticUpdateRegistry.hasPendingUpdates(protectionKey)) {
// Return cached data to prevent overwrite
const cached = queryClient.getQueryData<T>(context.queryKey);
if (cached) {
console.log('[useSafeQuery] Using cached data - optimistic updates pending');
return cached;
}
}
// Call original queryFn
const result = await queryOptions.queryFn!(context);
// Filter out any items being protected
if (protectionKey && Array.isArray(result)) {
return result.filter(item =>
!optimisticUpdateRegistry.isProtected(protectionKey, item.id)
) as T;
}
return result;
},
});
}
5.2 Update Core Hooks to Use useSafeQuery Modify : /src/shared/hooks/useShotGenerations.ts
typescript Copy code
// In useAllShotGenerations:
const mainQuery = useSafeQuery<GenerationRow[]>({
queryKey: ['all-shot-generations', stableShotId],
protectionKey: JSON.stringify(['all-shot-generations', stableShotId]),
// ... rest of options
});
Risk : Low - transparent wrapper
Testing :
Rapid mutations during network latency
Tab switching during mutations
Concurrent operations from multiple users
Phase 6: Enhanced Testability Goal : Make race conditions detectable in tests.
6.1 Create Test Utilities New file : /src/shared/testing/raceConditionHelpers.ts
typescript Copy code
/**
* Test utilities for detecting race conditions.
*/
export function createDelayedQueryClient(delayMs: number) {
// Returns QueryClient with artificial network delay
}
export function assertNoFlickering(
renders: Array<{ itemCount: number; timestamp: number }>,
expectedPattern: 'monotonic-increase' | 'stable'
) {
// Validates render history doesn't show flickering
}
export function simulateRealtimeEvent(type: string, payload: any) {
// Dispatches realtime event for testing
}
6.2 Add Race Condition Tests New file : /src/shared/hooks/__tests__/raceConditions.test.ts
typescript Copy code
describe('Race Condition Protection', () => {
test('optimistic update survives realtime invalidation', async () => {
// 1. Add item optimistically
// 2. Simulate realtime invalidation
// 3. Assert item still visible
});
test('concurrent mutations maintain correct order', async () => {
// 1. Start multiple mutations
// 2. Assert final state is correct
});
test('rapid edits preserve user input', async () => {
// 1. Type rapidly
// 2. Assert all characters preserved
});
});
Risk : None - additive tests
Testing : CI/CD integration
Implementation Order and Dependencies code Copy code
Phase 1 (Foundation) ─┬─> Phase 2 (Transformers)
│
├─> Phase 3 (Query Keys) ─> Phase 4 (Hook Consolidation)
│
└─> Phase 5 (Safe Query) ─> Phase 6 (Testing)
Phase 1 (2-3 days): Must be first - establishes protection foundation
Phase 3 (1 day): Can be done in parallel with Phase 1
Phase 2 (2 days): After Phase 1 - needs protection for safe refactoring
Phase 5 (1 day): After Phase 1 - builds on registry
Phase 4 (3-4 days): After Phase 2 & 3 - biggest change, needs protection
Phase 6 (1-2 days): After all others - validates everything works
Total estimate : 10-14 days
Risk Mitigation
Feature Flags typescript Copy code
// In /src/shared/lib/featureFlags.ts
export const FEATURE_FLAGS = {
USE_OPTIMISTIC_REGISTRY: true,
USE_SAFE_QUERY: true,
USE_CONSOLIDATED_HOOKS: false, // Enable gradually
};
Rollback Points Each phase can be rolled back independently:
Phase 1: Delete registry, remove checks
Phase 2: Revert transformer changes
Phase 3: No rollback needed (additive)
Phase 4: Keep deprecated hooks working
Phase 5: Remove wrapper, use plain useQuery
Phase 6: Tests don't affect production
Monitoring Add to /src/shared/lib/debugConfig.ts:
typescript Copy code
export const debugConfig = {
// Existing...
optimisticUpdates: process.env.NODE_ENV === 'development',
raceConditions: process.env.NODE_ENV === 'development',
};
Critical Files for Implementation
Critical Files for Implementation
/src/shared/lib/optimisticUpdateRegistry.ts - New file: Core protection system
/src/shared/providers/SimpleRealtimeProvider.tsx - Modify: Add protection awareness to invalidation handlers
/src/shared/hooks/shots/useShotGenerationMutations.ts - Modify: Register/resolve optimistic updates
/src/shared/lib/generationTransformers.ts - Modify: Add unified transformAny function
/src/shared/hooks/useShotGenerations.ts - Modify: Use useSafeQuery, consolidate with unified transformer