BOM Rows should be cached #12

Closed
opened 2026-02-13 14:47:51 +00:00 by chris-kreidl · 4 comments
chris-kreidl commented 2026-02-13 14:47:51 +00:00 (Migrated from github.com)

Except for just a few products, BOM rows typically do not change. Those that do change (Tea of the Month boxes) only really chance once a month when we roll over to the next month's contents. We should extend our caching to include BOM rows to speed up MO generation as these are fetched from Katana every time we enter the MO module.

Except for just a few products, BOM rows typically do not change. Those that do change (Tea of the Month boxes) only really chance once a month when we roll over to the next month's contents. We should extend our caching to include BOM rows to speed up MO generation as these are fetched from Katana every time we enter the MO module.
chris-kreidl commented 2026-02-13 14:51:32 +00:00 (Migrated from github.com)

@coderabbitai plan

@coderabbitai plan
coderabbitai[bot] commented 2026-02-13 14:56:12 +00:00 (Migrated from github.com)

Coding Plan

Summary

  • Extend the existing SQLite cache infrastructure with entity-based (non-range) caching support, keeping it separate from the time-series range-based logic
  • Cache all BOM rows as a single entity with TTL-based expiration (24 hours default), matching the "fetch all" pattern already used in general mode
  • Create cached wrapper functions that integrate with the pipeline's existing caching patterns (null check for disabled cache, same function signatures)
  • Leverage existing invalidation mechanisms (clearByQueryType, --clearCache) without requiring new CLI options
Design Choices
Design Choice 1: Caching strategy for BOM data

Options Considered:

  1. Full dataset cache: Cache all BOM rows as a single cached entity with TTL-based expiration
  2. Per-variant cache: Cache BOM rows keyed by individual product_variant_id
  3. Hybrid: Support both full and per-variant caching with cross-population

Chosen Option: 1

Rationale: This matches the dominant "fetch all" pattern in listBomRowsForVariants(), minimizes complexity, and aligns with the ticket's observation that BOM rows are stable data. A single cache check replaces all BOM API calls.

💡 User Tips

Regenerate the plan with different choices with @coderabbitai <feedback>.

Implementation Steps

Phase 1: Extend Cache Infrastructure for Entity-Based Data

Add support for non-range-based caching to the existing cache infrastructure. The current design is optimized for time-series data with date ranges; BOM rows require simpler entity-based caching with TTL expiration.

Task 1: Add BOM Configuration to Query Config

Define BOM rows as a cacheable query type with entity-based (non-range) semantics.

  • Update packages/katana-mo-cli/src/cache/queryConfig.ts to add bomRows query type
  • Add a flag or property to distinguish entity-based queries from range-based queries (e.g., isRangeBased: false)
  • Define default TTL for BOM cache (e.g., 24 hours) as BOM data changes infrequently
Task 2: Add Entity-Based Storage Methods to RecordStore

Extend the data access layer to support storing and retrieving entity-based cached data without range tracking.

  • Update packages/katana-mo-cli/src/cache/recordStore.ts to add methods for entity-based caching
  • Add method to store records without range metadata (reuse cached_records table)
  • Add method to retrieve all records for a query type and params hash
  • Add method to check if entity cache exists and is within TTL
  • Add method to clear entity cache by query type
Task 3: Add Entity Caching Methods to CacheManager

Provide high-level API for entity-based caching that mirrors the existing getCachedOrFetch pattern but without range logic.

  • Update packages/katana-mo-cli/src/cache/cacheManager.ts to add entity-based caching method
  • Create getEntityCachedOrFetch<T>() method that checks for valid cached entity data, fetches if missing/expired, and stores results
  • Include in-flight request deduplication using the existing pattern (in-memory Map)
  • Support TTL-based expiration checking at retrieval time
  • Integrate with existing clearByQueryType() for invalidation
🤖 Prompt for AI agents
Extend the existing cache infrastructure to support entity-based (non-range)
caching for BOM data. This phase adds the foundational caching capabilities
needed for stable reference data that doesn't require range tracking.

**Task 1: Update Query Configuration**
- In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add a new `bomRows`
query type configuration
- Add a flag or property to distinguish entity-based queries from range-based
queries (e.g., `isRangeBased: false`)
- Set a default TTL of 24 hours for BOM cache since BOM data changes
infrequently

**Task 2: Extend RecordStore for Entity Storage**
- In `packages/katana-mo-cli/src/cache/recordStore.ts`, implement methods for
entity-based caching:
- Method to store records without range metadata (reusing the `cached_records`
table)
  - Method to retrieve all records for a given query type and params hash
  - Method to check if entity cache exists and is within TTL
  - Method to clear entity cache by query type

**Task 3: Add Entity Caching to CacheManager**
- In `packages/katana-mo-cli/src/cache/cacheManager.ts`, implement entity-based
caching API:
- Create `getEntityCachedOrFetch<T>()` method that mirrors the existing
`getCachedOrFetch` pattern but without range logic
- Check for valid cached entity data, fetch if missing/expired, and store
results
- Include in-flight request deduplication using the existing in-memory Map
pattern
  - Support TTL-based expiration checking at retrieval time
  - Integrate with existing `clearByQueryType()` for cache invalidation

Phase 2: Implement Cached BOM Fetching

Create cached wrapper functions for BOM fetching and integrate them into the MO generation pipeline.

Task 1: Create Cached BOM Fetch Functions

Add cached wrappers for BOM fetching that use the new entity-based caching infrastructure.

  • Create cached BOM function in packages/katana-mo-cli/src/api/cachedKatana.ts
  • Implement fetchBomRowsCached() that wraps listBomRowsForVariants() with entity caching
  • Use the CacheManager.getEntityCachedOrFetch() method with bomRows query type
  • Ensure the function signature matches what the pipeline expects (accepts client, variantIds, returns BomMapPayload)
  • The cached version should still filter to requested variantIds after cache retrieval (since we cache all BOM rows)
Task 2: Update Pipeline to Use Cached BOM Fetching

Integrate cached BOM fetching into both MO generation pipelines.

  • Update packages/katana-mo-cli/src/runPipeline.ts to use cached BOM functions
  • Modify fetchPipelineData() (general mode) to call cached BOM function instead of direct listBomRowsForVariants()
  • Modify fetchSoPipelineData() (sales orders mode) to use cached BOM data with filtering
  • Pass cacheManager to the cached BOM function (following existing pattern from demand fetching)
  • Maintain fallback to direct API calls when caching is disabled (cacheManager is null)
Task 3: Ensure Cache Invalidation Support

Verify BOM cache integrates properly with existing invalidation mechanisms.

  • Update packages/katana-mo-cli/src/cache/cacheManager.ts invalidation mappings if needed
  • Add bomRows to the entity type mapping in invalidateByEntityType()
  • Ensure --clearCache CLI flag clears BOM cache along with other cached data
  • Document that BOM cache can be manually cleared if recipes change mid-session
🤖 Prompt for AI agents
Implement cached BOM fetching and integrate it into the MO generation pipeline.
This phase creates the wrapper functions and connects them to the existing
pipeline flows.

**Task 1: Create Cached BOM Wrapper**
- In `packages/katana-mo-cli/src/api/cachedKatana.ts`, implement
`fetchBomRowsCached()`:
- Wrap `listBomRowsForVariants()` with the new entity-based caching
infrastructure
  - Use `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type
- Match the existing function signature: accept client and variantIds, return
BomMapPayload
- After retrieving from cache (all BOM rows), filter to the requested variantIds
since we cache the full dataset

**Task 2: Integrate into Pipeline**
- In `packages/katana-mo-cli/src/runPipeline.ts`, update both pipeline modes:
- Modify `fetchPipelineData()` (general mode) to call `fetchBomRowsCached()`
instead of direct `listBomRowsForVariants()`
- Modify `fetchSoPipelineData()` (sales orders mode) to use the cached BOM
function with filtering
- Pass `cacheManager` to the cached BOM function following the existing pattern
from demand fetching
- Maintain fallback to direct API calls when caching is disabled (when
`cacheManager` is null)

**Task 3: Configure Cache Invalidation**
- In `packages/katana-mo-cli/src/cache/cacheManager.ts`, ensure proper
invalidation support:
- Add `bomRows` to the entity type mapping in `invalidateByEntityType()` if such
mapping exists
- Verify that the `--clearCache` CLI flag will clear BOM cache along with other
cached data
- Add code comments documenting that BOM cache can be manually cleared if
recipes change mid-session
Research

The codebase has a sophisticated file-based SQLite caching system in packages/katana-mo-cli/src/cache/ that currently supports range-based caching for time-series data (inventoryMovements). Key components include:

  • SqliteCache for database operations
  • RecordStore for data access
  • CacheManager for orchestration
  • queryConfig.ts for defining cacheable query types

BOM rows are fetched via two patterns:

  1. listBomRowsForVariants() which fetches all rows and filters client-side
  2. listBomRowsForVariantIds() which fetches per-variant

Both functions reside in packages/katana-mo-cli/src/api/katana.ts and are called from packages/katana-mo-cli/src/runPipeline.ts.


🚀 Next Steps

🤖 All AI agent prompts combined
Task: 1

Extend the existing cache infrastructure to support entity-based (non-range)
caching for BOM data. This phase adds the foundational caching capabilities
needed for stable reference data that doesn't require range tracking.

**Task 1: Update Query Configuration**
- In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add a new `bomRows`
query type configuration
- Add a flag or property to distinguish entity-based queries from range-based
queries (e.g., `isRangeBased: false`)
- Set a default TTL of 24 hours for BOM cache since BOM data changes
infrequently

**Task 2: Extend RecordStore for Entity Storage**
- In `packages/katana-mo-cli/src/cache/recordStore.ts`, implement methods for
entity-based caching:
- Method to store records without range metadata (reusing the `cached_records`
table)
  - Method to retrieve all records for a given query type and params hash
  - Method to check if entity cache exists and is within TTL
  - Method to clear entity cache by query type

**Task 3: Add Entity Caching to CacheManager**
- In `packages/katana-mo-cli/src/cache/cacheManager.ts`, implement entity-based
caching API:
- Create `getEntityCachedOrFetch<T>()` method that mirrors the existing
`getCachedOrFetch` pattern but without range logic
- Check for valid cached entity data, fetch if missing/expired, and store
results
- Include in-flight request deduplication using the existing in-memory Map
pattern
  - Support TTL-based expiration checking at retrieval time
  - Integrate with existing `clearByQueryType()` for cache invalidation
===============================================================================

Task: 2

Implement cached BOM fetching and integrate it into the MO generation pipeline.
This phase creates the wrapper functions and connects them to the existing
pipeline flows.

**Task 1: Create Cached BOM Wrapper**
- In `packages/katana-mo-cli/src/api/cachedKatana.ts`, implement
`fetchBomRowsCached()`:
- Wrap `listBomRowsForVariants()` with the new entity-based caching
infrastructure
  - Use `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type
- Match the existing function signature: accept client and variantIds, return
BomMapPayload
- After retrieving from cache (all BOM rows), filter to the requested variantIds
since we cache the full dataset

**Task 2: Integrate into Pipeline**
- In `packages/katana-mo-cli/src/runPipeline.ts`, update both pipeline modes:
- Modify `fetchPipelineData()` (general mode) to call `fetchBomRowsCached()`
instead of direct `listBomRowsForVariants()`
- Modify `fetchSoPipelineData()` (sales orders mode) to use the cached BOM
function with filtering
- Pass `cacheManager` to the cached BOM function following the existing pattern
from demand fetching
- Maintain fallback to direct API calls when caching is disabled (when
`cacheManager` is null)

**Task 3: Configure Cache Invalidation**
- In `packages/katana-mo-cli/src/cache/cacheManager.ts`, ensure proper
invalidation support:
- Add `bomRows` to the entity type mapping in `invalidateByEntityType()` if such
mapping exists
- Verify that the `--clearCache` CLI flag will clear BOM cache along with other
cached data
- Add code comments documenting that BOM cache can be manually cleared if
recipes change mid-session
💡 Iterate on the plan with: @coderabbitai <feedback>
Example Feedback
- `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2.
- `@coderabbitai` For design choice 1 go ahead with option 3 and replan.

💬 Have feedback or questions? Drop into our discord!

<!-- This is an auto-generated reply by CodeRabbit --> ## Coding Plan ### Summary - Extend the existing SQLite cache infrastructure with entity-based (non-range) caching support, keeping it separate from the time-series range-based logic - Cache all BOM rows as a single entity with TTL-based expiration (24 hours default), matching the "fetch all" pattern already used in general mode - Create cached wrapper functions that integrate with the pipeline's existing caching patterns (null check for disabled cache, same function signatures) - Leverage existing invalidation mechanisms (`clearByQueryType`, `--clearCache`) without requiring new CLI options <details> <summary><b>Design Choices</b></summary> <details> <summary><b>Design Choice 1: Caching strategy for BOM data</b></summary> **Options Considered:** 1. Full dataset cache: Cache all BOM rows as a single cached entity with TTL-based expiration 2. Per-variant cache: Cache BOM rows keyed by individual `product_variant_id` 3. Hybrid: Support both full and per-variant caching with cross-population **Chosen Option:** 1 **Rationale:** This matches the dominant "fetch all" pattern in `listBomRowsForVariants()`, minimizes complexity, and aligns with the ticket's observation that BOM rows are stable data. A single cache check replaces all BOM API calls. </details> </details> <b>💡 User Tips</b> Regenerate the plan with different choices with `@coderabbitai <feedback>`. ## Implementation Steps ### Phase 1: Extend Cache Infrastructure for Entity-Based Data Add support for non-range-based caching to the existing cache infrastructure. The current design is optimized for time-series data with date ranges; BOM rows require simpler entity-based caching with TTL expiration. <details> <summary><b>Task 1: Add BOM Configuration to Query Config</b></summary> Define BOM rows as a cacheable query type with entity-based (non-range) semantics. - Update `packages/katana-mo-cli/src/cache/queryConfig.ts` to add `bomRows` query type - Add a flag or property to distinguish entity-based queries from range-based queries (e.g., `isRangeBased: false`) - Define default TTL for BOM cache (e.g., 24 hours) as BOM data changes infrequently </details> <details> <summary><b>Task 2: Add Entity-Based Storage Methods to RecordStore</b></summary> Extend the data access layer to support storing and retrieving entity-based cached data without range tracking. - Update `packages/katana-mo-cli/src/cache/recordStore.ts` to add methods for entity-based caching - Add method to store records without range metadata (reuse `cached_records` table) - Add method to retrieve all records for a query type and params hash - Add method to check if entity cache exists and is within TTL - Add method to clear entity cache by query type </details> <details> <summary><b>Task 3: Add Entity Caching Methods to CacheManager</b></summary> Provide high-level API for entity-based caching that mirrors the existing `getCachedOrFetch` pattern but without range logic. - Update `packages/katana-mo-cli/src/cache/cacheManager.ts` to add entity-based caching method - Create `getEntityCachedOrFetch<T>()` method that checks for valid cached entity data, fetches if missing/expired, and stores results - Include in-flight request deduplication using the existing pattern (in-memory Map) - Support TTL-based expiration checking at retrieval time - Integrate with existing `clearByQueryType()` for invalidation </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` Extend the existing cache infrastructure to support entity-based (non-range) caching for BOM data. This phase adds the foundational caching capabilities needed for stable reference data that doesn't require range tracking. **Task 1: Update Query Configuration** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add a new `bomRows` query type configuration - Add a flag or property to distinguish entity-based queries from range-based queries (e.g., `isRangeBased: false`) - Set a default TTL of 24 hours for BOM cache since BOM data changes infrequently **Task 2: Extend RecordStore for Entity Storage** - In `packages/katana-mo-cli/src/cache/recordStore.ts`, implement methods for entity-based caching: - Method to store records without range metadata (reusing the `cached_records` table) - Method to retrieve all records for a given query type and params hash - Method to check if entity cache exists and is within TTL - Method to clear entity cache by query type **Task 3: Add Entity Caching to CacheManager** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, implement entity-based caching API: - Create `getEntityCachedOrFetch<T>()` method that mirrors the existing `getCachedOrFetch` pattern but without range logic - Check for valid cached entity data, fetch if missing/expired, and store results - Include in-flight request deduplication using the existing in-memory Map pattern - Support TTL-based expiration checking at retrieval time - Integrate with existing `clearByQueryType()` for cache invalidation ``` </details> ### Phase 2: Implement Cached BOM Fetching Create cached wrapper functions for BOM fetching and integrate them into the MO generation pipeline. <details> <summary><b>Task 1: Create Cached BOM Fetch Functions</b></summary> Add cached wrappers for BOM fetching that use the new entity-based caching infrastructure. - Create cached BOM function in `packages/katana-mo-cli/src/api/cachedKatana.ts` - Implement `fetchBomRowsCached()` that wraps `listBomRowsForVariants()` with entity caching - Use the `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type - Ensure the function signature matches what the pipeline expects (accepts client, variantIds, returns BomMapPayload) - The cached version should still filter to requested variantIds after cache retrieval (since we cache all BOM rows) </details> <details> <summary><b>Task 2: Update Pipeline to Use Cached BOM Fetching</b></summary> Integrate cached BOM fetching into both MO generation pipelines. - Update `packages/katana-mo-cli/src/runPipeline.ts` to use cached BOM functions - Modify `fetchPipelineData()` (general mode) to call cached BOM function instead of direct `listBomRowsForVariants()` - Modify `fetchSoPipelineData()` (sales orders mode) to use cached BOM data with filtering - Pass `cacheManager` to the cached BOM function (following existing pattern from demand fetching) - Maintain fallback to direct API calls when caching is disabled (`cacheManager` is null) </details> <details> <summary><b>Task 3: Ensure Cache Invalidation Support</b></summary> Verify BOM cache integrates properly with existing invalidation mechanisms. - Update `packages/katana-mo-cli/src/cache/cacheManager.ts` invalidation mappings if needed - Add `bomRows` to the entity type mapping in `invalidateByEntityType()` - Ensure `--clearCache` CLI flag clears BOM cache along with other cached data - Document that BOM cache can be manually cleared if recipes change mid-session </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` Implement cached BOM fetching and integrate it into the MO generation pipeline. This phase creates the wrapper functions and connects them to the existing pipeline flows. **Task 1: Create Cached BOM Wrapper** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, implement `fetchBomRowsCached()`: - Wrap `listBomRowsForVariants()` with the new entity-based caching infrastructure - Use `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type - Match the existing function signature: accept client and variantIds, return BomMapPayload - After retrieving from cache (all BOM rows), filter to the requested variantIds since we cache the full dataset **Task 2: Integrate into Pipeline** - In `packages/katana-mo-cli/src/runPipeline.ts`, update both pipeline modes: - Modify `fetchPipelineData()` (general mode) to call `fetchBomRowsCached()` instead of direct `listBomRowsForVariants()` - Modify `fetchSoPipelineData()` (sales orders mode) to use the cached BOM function with filtering - Pass `cacheManager` to the cached BOM function following the existing pattern from demand fetching - Maintain fallback to direct API calls when caching is disabled (when `cacheManager` is null) **Task 3: Configure Cache Invalidation** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, ensure proper invalidation support: - Add `bomRows` to the entity type mapping in `invalidateByEntityType()` if such mapping exists - Verify that the `--clearCache` CLI flag will clear BOM cache along with other cached data - Add code comments documenting that BOM cache can be manually cleared if recipes change mid-session ``` </details> <details> <summary><b>Research</b></summary> The codebase has a sophisticated file-based SQLite caching system in `packages/katana-mo-cli/src/cache/` that currently supports range-based caching for time-series data (`inventoryMovements`). Key components include: - `SqliteCache` for database operations - `RecordStore` for data access - `CacheManager` for orchestration - `queryConfig.ts` for defining cacheable query types BOM rows are fetched via two patterns: 1. `listBomRowsForVariants()` which fetches all rows and filters client-side 2. `listBomRowsForVariantIds()` which fetches per-variant Both functions reside in `packages/katana-mo-cli/src/api/katana.ts` and are called from `packages/katana-mo-cli/src/runPipeline.ts`. </details> --- ### 🚀 Next Steps <details> <summary><b>🤖 All AI agent prompts combined</b></summary> ``` Task: 1 Extend the existing cache infrastructure to support entity-based (non-range) caching for BOM data. This phase adds the foundational caching capabilities needed for stable reference data that doesn't require range tracking. **Task 1: Update Query Configuration** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add a new `bomRows` query type configuration - Add a flag or property to distinguish entity-based queries from range-based queries (e.g., `isRangeBased: false`) - Set a default TTL of 24 hours for BOM cache since BOM data changes infrequently **Task 2: Extend RecordStore for Entity Storage** - In `packages/katana-mo-cli/src/cache/recordStore.ts`, implement methods for entity-based caching: - Method to store records without range metadata (reusing the `cached_records` table) - Method to retrieve all records for a given query type and params hash - Method to check if entity cache exists and is within TTL - Method to clear entity cache by query type **Task 3: Add Entity Caching to CacheManager** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, implement entity-based caching API: - Create `getEntityCachedOrFetch<T>()` method that mirrors the existing `getCachedOrFetch` pattern but without range logic - Check for valid cached entity data, fetch if missing/expired, and store results - Include in-flight request deduplication using the existing in-memory Map pattern - Support TTL-based expiration checking at retrieval time - Integrate with existing `clearByQueryType()` for cache invalidation =============================================================================== Task: 2 Implement cached BOM fetching and integrate it into the MO generation pipeline. This phase creates the wrapper functions and connects them to the existing pipeline flows. **Task 1: Create Cached BOM Wrapper** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, implement `fetchBomRowsCached()`: - Wrap `listBomRowsForVariants()` with the new entity-based caching infrastructure - Use `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type - Match the existing function signature: accept client and variantIds, return BomMapPayload - After retrieving from cache (all BOM rows), filter to the requested variantIds since we cache the full dataset **Task 2: Integrate into Pipeline** - In `packages/katana-mo-cli/src/runPipeline.ts`, update both pipeline modes: - Modify `fetchPipelineData()` (general mode) to call `fetchBomRowsCached()` instead of direct `listBomRowsForVariants()` - Modify `fetchSoPipelineData()` (sales orders mode) to use the cached BOM function with filtering - Pass `cacheManager` to the cached BOM function following the existing pattern from demand fetching - Maintain fallback to direct API calls when caching is disabled (when `cacheManager` is null) **Task 3: Configure Cache Invalidation** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, ensure proper invalidation support: - Add `bomRows` to the entity type mapping in `invalidateByEntityType()` if such mapping exists - Verify that the `--clearCache` CLI flag will clear BOM cache along with other cached data - Add code comments documenting that BOM cache can be manually cleared if recipes change mid-session ``` </details> <details> <summary><b>💡 Iterate on the plan with: <code>@coderabbitai &lt;feedback&gt;</code> </b></summary> ``` Example Feedback - `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2. - `@coderabbitai` For design choice 1 go ahead with option 3 and replan. ``` </details> --- 💬 Have feedback or questions? Drop into our [discord](https://discord.gg/coderabbit)! <!-- <agentComponentType>plan-edits</agentComponentType> --> <!-- <rawResChunk><planningResult>## Coding Plan ### Summary - Extend the existing SQLite cache infrastructure with entity-based (non-range) caching support, keeping it separate from the time-series range-based logic - Cache all BOM rows as a single entity with TTL-based expiration (24 hours default), matching the "fetch all" pattern already used in general mode - Create cached wrapper functions that integrate with the pipeline's existing caching patterns (null check for disabled cache, same function signatures) - Leverage existing invalidation mechanisms (`clearByQueryType`, `--clearCache`) without requiring new CLI options <details> <summary><b>Design Choices</b></summary> <details> <summary><b>Design Choice 1: Caching strategy for BOM data</b></summary> **Options Considered:** 1. Full dataset cache: Cache all BOM rows as a single cached entity with TTL-based expiration 2. Per-variant cache: Cache BOM rows keyed by individual `product_variant_id` 3. Hybrid: Support both full and per-variant caching with cross-population **Chosen Option:** 1 **Rationale:** This matches the dominant "fetch all" pattern in `listBomRowsForVariants()`, minimizes complexity, and aligns with the ticket's observation that BOM rows are stable data. A single cache check replaces all BOM API calls. </details> </details> <b>💡 User Tips</b> Regenerate the plan with different choices with `@coderabbitai <feedback>`. ## Implementation Steps ### Phase 1: Extend Cache Infrastructure for Entity-Based Data Add support for non-range-based caching to the existing cache infrastructure. The current design is optimized for time-series data with date ranges; BOM rows require simpler entity-based caching with TTL expiration. <details> <summary><b>Task 1: Add BOM Configuration to Query Config</b></summary> Define BOM rows as a cacheable query type with entity-based (non-range) semantics. - Update `packages/katana-mo-cli/src/cache/queryConfig.ts` to add `bomRows` query type - Add a flag or property to distinguish entity-based queries from range-based queries (e.g., `isRangeBased: false`) - Define default TTL for BOM cache (e.g., 24 hours) as BOM data changes infrequently </details> <details> <summary><b>Task 2: Add Entity-Based Storage Methods to RecordStore</b></summary> Extend the data access layer to support storing and retrieving entity-based cached data without range tracking. - Update `packages/katana-mo-cli/src/cache/recordStore.ts` to add methods for entity-based caching - Add method to store records without range metadata (reuse `cached_records` table) - Add method to retrieve all records for a query type and params hash - Add method to check if entity cache exists and is within TTL - Add method to clear entity cache by query type </details> <details> <summary><b>Task 3: Add Entity Caching Methods to CacheManager</b></summary> Provide high-level API for entity-based caching that mirrors the existing `getCachedOrFetch` pattern but without range logic. - Update `packages/katana-mo-cli/src/cache/cacheManager.ts` to add entity-based caching method - Create `getEntityCachedOrFetch<T>()` method that checks for valid cached entity data, fetches if missing/expired, and stores results - Include in-flight request deduplication using the existing pattern (in-memory Map) - Support TTL-based expiration checking at retrieval time - Integrate with existing `clearByQueryType()` for invalidation </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` Extend the existing cache infrastructure to support entity-based (non-range) caching for BOM data. This phase adds the foundational caching capabilities needed for stable reference data that doesn't require range tracking. **Task 1: Update Query Configuration** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add a new `bomRows` query type configuration - Add a flag or property to distinguish entity-based queries from range-based queries (e.g., `isRangeBased: false`) - Set a default TTL of 24 hours for BOM cache since BOM data changes infrequently **Task 2: Extend RecordStore for Entity Storage** - In `packages/katana-mo-cli/src/cache/recordStore.ts`, implement methods for entity-based caching: - Method to store records without range metadata (reusing the `cached_records` table) - Method to retrieve all records for a given query type and params hash - Method to check if entity cache exists and is within TTL - Method to clear entity cache by query type **Task 3: Add Entity Caching to CacheManager** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, implement entity-based caching API: - Create `getEntityCachedOrFetch<T>()` method that mirrors the existing `getCachedOrFetch` pattern but without range logic - Check for valid cached entity data, fetch if missing/expired, and store results - Include in-flight request deduplication using the existing in-memory Map pattern - Support TTL-based expiration checking at retrieval time - Integrate with existing `clearByQueryType()` for cache invalidation ``` </details> ### Phase 2: Implement Cached BOM Fetching Create cached wrapper functions for BOM fetching and integrate them into the MO generation pipeline. <details> <summary><b>Task 1: Create Cached BOM Fetch Functions</b></summary> Add cached wrappers for BOM fetching that use the new entity-based caching infrastructure. - Create cached BOM function in `packages/katana-mo-cli/src/api/cachedKatana.ts` - Implement `fetchBomRowsCached()` that wraps `listBomRowsForVariants()` with entity caching - Use the `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type - Ensure the function signature matches what the pipeline expects (accepts client, variantIds, returns BomMapPayload) - The cached version should still filter to requested variantIds after cache retrieval (since we cache all BOM rows) </details> <details> <summary><b>Task 2: Update Pipeline to Use Cached BOM Fetching</b></summary> Integrate cached BOM fetching into both MO generation pipelines. - Update `packages/katana-mo-cli/src/runPipeline.ts` to use cached BOM functions - Modify `fetchPipelineData()` (general mode) to call cached BOM function instead of direct `listBomRowsForVariants()` - Modify `fetchSoPipelineData()` (sales orders mode) to use cached BOM data with filtering - Pass `cacheManager` to the cached BOM function (following existing pattern from demand fetching) - Maintain fallback to direct API calls when caching is disabled (`cacheManager` is null) </details> <details> <summary><b>Task 3: Ensure Cache Invalidation Support</b></summary> Verify BOM cache integrates properly with existing invalidation mechanisms. - Update `packages/katana-mo-cli/src/cache/cacheManager.ts` invalidation mappings if needed - Add `bomRows` to the entity type mapping in `invalidateByEntityType()` - Ensure `--clearCache` CLI flag clears BOM cache along with other cached data - Document that BOM cache can be manually cleared if recipes change mid-session </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` Implement cached BOM fetching and integrate it into the MO generation pipeline. This phase creates the wrapper functions and connects them to the existing pipeline flows. **Task 1: Create Cached BOM Wrapper** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, implement `fetchBomRowsCached()`: - Wrap `listBomRowsForVariants()` with the new entity-based caching infrastructure - Use `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type - Match the existing function signature: accept client and variantIds, return BomMapPayload - After retrieving from cache (all BOM rows), filter to the requested variantIds since we cache the full dataset **Task 2: Integrate into Pipeline** - In `packages/katana-mo-cli/src/runPipeline.ts`, update both pipeline modes: - Modify `fetchPipelineData()` (general mode) to call `fetchBomRowsCached()` instead of direct `listBomRowsForVariants()` - Modify `fetchSoPipelineData()` (sales orders mode) to use the cached BOM function with filtering - Pass `cacheManager` to the cached BOM function following the existing pattern from demand fetching - Maintain fallback to direct API calls when caching is disabled (when `cacheManager` is null) **Task 3: Configure Cache Invalidation** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, ensure proper invalidation support: - Add `bomRows` to the entity type mapping in `invalidateByEntityType()` if such mapping exists - Verify that the `--clearCache` CLI flag will clear BOM cache along with other cached data - Add code comments documenting that BOM cache can be manually cleared if recipes change mid-session ``` </details> <details> <summary><b>Research</b></summary> The codebase has a sophisticated file-based SQLite caching system in `packages/katana-mo-cli/src/cache/` that currently supports range-based caching for time-series data (`inventoryMovements`). Key components include: - `SqliteCache` for database operations - `RecordStore` for data access - `CacheManager` for orchestration - `queryConfig.ts` for defining cacheable query types BOM rows are fetched via two patterns: 1. `listBomRowsForVariants()` which fetches all rows and filters client-side 2. `listBomRowsForVariantIds()` which fetches per-variant Both functions reside in `packages/katana-mo-cli/src/api/katana.ts` and are called from `packages/katana-mo-cli/src/runPipeline.ts`. </details> --- ### 🚀 Next Steps <details> <summary><b>🤖 All AI agent prompts combined</b></summary> ``` Task: 1 Extend the existing cache infrastructure to support entity-based (non-range) caching for BOM data. This phase adds the foundational caching capabilities needed for stable reference data that doesn't require range tracking. **Task 1: Update Query Configuration** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add a new `bomRows` query type configuration - Add a flag or property to distinguish entity-based queries from range-based queries (e.g., `isRangeBased: false`) - Set a default TTL of 24 hours for BOM cache since BOM data changes infrequently **Task 2: Extend RecordStore for Entity Storage** - In `packages/katana-mo-cli/src/cache/recordStore.ts`, implement methods for entity-based caching: - Method to store records without range metadata (reusing the `cached_records` table) - Method to retrieve all records for a given query type and params hash - Method to check if entity cache exists and is within TTL - Method to clear entity cache by query type **Task 3: Add Entity Caching to CacheManager** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, implement entity-based caching API: - Create `getEntityCachedOrFetch<T>()` method that mirrors the existing `getCachedOrFetch` pattern but without range logic - Check for valid cached entity data, fetch if missing/expired, and store results - Include in-flight request deduplication using the existing in-memory Map pattern - Support TTL-based expiration checking at retrieval time - Integrate with existing `clearByQueryType()` for cache invalidation =============================================================================== Task: 2 Implement cached BOM fetching and integrate it into the MO generation pipeline. This phase creates the wrapper functions and connects them to the existing pipeline flows. **Task 1: Create Cached BOM Wrapper** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, implement `fetchBomRowsCached()`: - Wrap `listBomRowsForVariants()` with the new entity-based caching infrastructure - Use `CacheManager.getEntityCachedOrFetch()` method with `bomRows` query type - Match the existing function signature: accept client and variantIds, return BomMapPayload - After retrieving from cache (all BOM rows), filter to the requested variantIds since we cache the full dataset **Task 2: Integrate into Pipeline** - In `packages/katana-mo-cli/src/runPipeline.ts`, update both pipeline modes: - Modify `fetchPipelineData()` (general mode) to call `fetchBomRowsCached()` instead of direct `listBomRowsForVariants()` - Modify `fetchSoPipelineData()` (sales orders mode) to use the cached BOM function with filtering - Pass `cacheManager` to the cached BOM function following the existing pattern from demand fetching - Maintain fallback to direct API calls when caching is disabled (when `cacheManager` is null) **Task 3: Configure Cache Invalidation** - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, ensure proper invalidation support: - Add `bomRows` to the entity type mapping in `invalidateByEntityType()` if such mapping exists - Verify that the `--clearCache` CLI flag will clear BOM cache along with other cached data - Add code comments documenting that BOM cache can be manually cleared if recipes change mid-session ``` </details> <details> <summary><b>💡 Iterate on the plan with: <code>@coderabbitai &lt;feedback&gt;</code> </b></summary> ``` Example Feedback - `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2. - `@coderabbitai` For design choice 1 go ahead with option 3 and replan. ``` </details> --- 💬 Have feedback or questions? Drop into our [discord](https://discord.gg/coderabbit)!</planningResult></rawResChunk> -->
chris-kreidl commented 2026-02-13 15:18:54 +00:00 (Migrated from github.com)

@coderabbitai while we will be caching each individual record, our call to Katana's API in listBomRowsForVariants simply requests all BOM Rows by not specifying any parameters. are we just going to pretend new records within Katana don't exist if there's cached records within the TTL?

@coderabbitai while we will be caching each individual record, our call to Katana's API in `listBomRowsForVariants` simply requests _all_ BOM Rows by not specifying any parameters. are we just going to pretend new records within Katana don't exist if there's cached records within the TTL?
coderabbitai[bot] commented 2026-02-13 15:19:58 +00:00 (Migrated from github.com)
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Fetch issue `#12` details to understand the context
gh issue view 12 --json title,body,labels,comments --jq '{title, body, labels: [.labels[].name], commentCount: (.comments | length)}'

Length of output: 410


@chris-kreidl Yes, that's exactly the trade-off with TTL-based caching. During the 24-hour TTL window, any new BOM rows created in Katana won't be visible until either:

  1. The cache expires naturally after 24 hours
  2. You manually clear the cache with --clearCache
  3. You restart the process (which creates a fresh cache)

Based on issue #12, this seems like an acceptable trade-off for your use case since:

  • You noted BOM rows "typically do not change"
  • The main exception (Tea of the Month boxes) changes predictably ~once per month
  • The performance benefit of eliminating repeated BOM API calls outweighs the staleness risk

Mitigation strategies we could consider:

  1. Manual invalidation (already in plan): When you know recipes changed (e.g., updating Tea of the Month), run with --clearCache to force a refresh

  2. Shorter TTL: We could reduce from 24 hours to something like 4-6 hours if you want fresher data while still getting cache benefits

  3. Force-refresh flag: Add a specific --refreshBom flag to invalidate just BOM cache without clearing everything

  4. Hybrid approach: Cache per-variant with cross-population (Design Choice 1, Option 3), which could allow partial cache invalidation - but adds complexity

My recommendation: Stick with the current plan (24-hour TTL, manual --clearCache) since your BOM changes are infrequent and predictable. If you find the staleness problematic in practice, we can always add more granular controls later.

Does this trade-off work for your workflow, or would you prefer a different approach?

<!-- This is an auto-generated reply by CodeRabbit --> <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Fetch issue `#12` details to understand the context gh issue view 12 --json title,body,labels,comments --jq '{title, body, labels: [.labels[].name], commentCount: (.comments | length)}' ``` Length of output: 410 --- </details> `@chris-kreidl` Yes, that's exactly the trade-off with TTL-based caching. During the 24-hour TTL window, any new BOM rows created in Katana won't be visible until either: 1. The cache expires naturally after 24 hours 2. You manually clear the cache with `--clearCache` 3. You restart the process (which creates a fresh cache) Based on issue `#12`, this seems like an acceptable trade-off for your use case since: - You noted BOM rows "typically do not change" - The main exception (Tea of the Month boxes) changes predictably ~once per month - The performance benefit of eliminating repeated BOM API calls outweighs the staleness risk **Mitigation strategies we could consider:** 1. **Manual invalidation (already in plan)**: When you know recipes changed (e.g., updating Tea of the Month), run with `--clearCache` to force a refresh 2. **Shorter TTL**: We could reduce from 24 hours to something like 4-6 hours if you want fresher data while still getting cache benefits 3. **Force-refresh flag**: Add a specific `--refreshBom` flag to invalidate just BOM cache without clearing everything 4. **Hybrid approach**: Cache per-variant with cross-population (Design Choice 1, Option 3), which could allow partial cache invalidation - but adds complexity **My recommendation**: Stick with the current plan (24-hour TTL, manual `--clearCache`) since your BOM changes are infrequent and predictable. If you find the staleness problematic in practice, we can always add more granular controls later. Does this trade-off work for your workflow, or would you prefer a different approach? <!-- <agentComponentType>chat-answer</agentComponentType> --> <!-- <rawResChunk><answer><details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Fetch issue `#12` details to understand the context gh issue view 12 --json title,body,labels,comments --jq '{title, body, labels: [.labels[].name], commentCount: (.comments | length)}' ``` Length of output: 410 --- </details> `@chris-kreidl` Yes, that's exactly the trade-off with TTL-based caching. During the 24-hour TTL window, any new BOM rows created in Katana won't be visible until either: 1. The cache expires naturally after 24 hours 2. You manually clear the cache with `--clearCache` 3. You restart the process (which creates a fresh cache) Based on issue `#12`, this seems like an acceptable trade-off for your use case since: - You noted BOM rows "typically do not change" - The main exception (Tea of the Month boxes) changes predictably ~once per month - The performance benefit of eliminating repeated BOM API calls outweighs the staleness risk **Mitigation strategies we could consider:** 1. **Manual invalidation (already in plan)**: When you know recipes changed (e.g., updating Tea of the Month), run with `--clearCache` to force a refresh 2. **Shorter TTL**: We could reduce from 24 hours to something like 4-6 hours if you want fresher data while still getting cache benefits 3. **Force-refresh flag**: Add a specific `--refreshBom` flag to invalidate just BOM cache without clearing everything 4. **Hybrid approach**: Cache per-variant with cross-population (Design Choice 1, Option 3), which could allow partial cache invalidation - but adds complexity **My recommendation**: Stick with the current plan (24-hour TTL, manual `--clearCache`) since your BOM changes are infrequent and predictable. If you find the staleness problematic in practice, we can always add more granular controls later. Does this trade-off work for your workflow, or would you prefer a different approach?</answer></rawResChunk> -->
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ckreidl/katana#12
No description provided.