Inventory movement calls are not cached. #10

Closed
opened 2026-02-12 14:25:58 +00:00 by chris-kreidl · 7 comments
chris-kreidl commented 2026-02-12 14:25:58 +00:00 (Migrated from github.com)

We currently only cache calls to Katana's sales_order_rows endpoint. Which is great, as each run was resulting in ~140 API calls and now we're at just a few.

I'd like to extend this caching to include the inventory_movements endpoint. The difficulty is that A) we can and do include different resource_types in our request, B) the variant_ids array passed is likely to be different for each invocation of the tool.

We currently only cache calls to Katana's `sales_order_rows` endpoint. Which is great, as each run was resulting in ~140 API calls and now we're at just a few. I'd like to extend this caching to include the `inventory_movements` endpoint. The difficulty is that A) we can and do include different `resource_type`s in our request, B) the `variant_ids` array passed is likely to be different for each invocation of the tool.
chris-kreidl commented 2026-02-12 14:26:09 +00:00 (Migrated from github.com)

@coderabbitai plan

@coderabbitai plan
coderabbitai[bot] commented 2026-02-12 14:27:02 +00:00 (Migrated from github.com)
⚠️ Possible Duplicate Issue(s)

📝 Issue Planner

Check the box below or use the @coderabbitai plan command to generate an implementation plan and prompts that you can use with your favorite coding assistant.

  • Create Plan

🧪 Issue enrichment is currently in open beta.

You can configure auto-planning by selecting labels in the issue_enrichment configuration.

To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

issue_enrichment:
  auto_enrich:
    enabled: false

💬 Have feedback or questions? Drop into our discord!

<!-- This is an auto-generated issue plan by CodeRabbit --> <details> <summary>⚠️ Possible Duplicate Issue(s)</summary> - https://github.com/chris-kreidl/katana/issues/7 </details> --- <details> <summary>📝 Issue Planner</summary> <sub>Check the box below or use the `@coderabbitai plan` command to generate an implementation plan and prompts that you can use with your favorite coding assistant.</sub> - [x] <!-- {"checkboxId": "8d4f2b9c-3e1a-4f7c-a9b2-d5e8f1c4a7b9"} --> Create Plan </details> --- <details> <summary> 🧪 Issue enrichment is currently in open beta.</summary> You can configure auto-planning by selecting labels in the issue_enrichment configuration. To disable automatic issue enrichment, add the following to your `.coderabbit.yaml`: ```yaml issue_enrichment: auto_enrich: enabled: false ``` </details> 💬 Have feedback or questions? Drop into our [discord](https://discord.gg/coderabbit)!
coderabbitai[bot] commented 2026-02-12 14:31:36 +00:00 (Migrated from github.com)

Coding Plan

Summary

  • Change from parameter-based caching (where each resource_type/variant_ids combination creates a separate cache entry) to full-dataset caching with client-side filtering
  • Fetch all inventory movements for a location and date range without restrictive filters, cache once
  • Filter the cached results client-side to match requested resource_type and variant_ids
  • This enables cache hits across calls with different filter parameters, dramatically improving cache effectiveness for the varying-parameter scenario described in the ticket
Design Choices
Design Choice 1: Should the full-dataset fetch include the `location_id` filter or fetch all locations?

Options Considered:

  1. Keep location_id filter in API request, cache per-location datasets
  2. Remove location_id filter, cache all-locations dataset and filter client-side

Chosen Option: 1

Rationale: Keep location_id in the API request to limit data volume and match existing workflow patterns that operate on single locations.

💡 User Tips

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

Implementation Steps

Phase 1: Implement Full-Dataset Fetch for Inventory Movements

Modify the inventory movements data fetching to retrieve the complete dataset for a location and date range, without resource_type or variant_ids filters. This enables caching a single dataset that can serve multiple filtered queries.

Task 1: Create Unfiltered Inventory Movements Collector

Create a new collection function that fetches all inventory movements for a location and date range without applying resource_type or variant_ids filters.

  • Add a new function in packages/katana-mo-cli/src/api/cachedKatana.ts (e.g., collectAllInventoryMovements) that calls the API with only location_id, created_at_min, and created_at_max parameters
  • This function should handle pagination to collect all records across pages
  • Follow the pattern of existing collectInventoryMovements but without the restrictive filters
Task 2: Update Cache Key Generation for Inventory Movements

Modify the parameter hashing behavior for inventory movements to exclude variant_ids and resource_type from the cache key, ensuring all queries for the same location and date range share the same cache entry.

  • Update packages/katana-mo-cli/src/cache/queryConfig.ts to define excluded parameters for inventory movements (similar to how date params are already excluded)
  • Modify generateParamsHash in packages/katana-mo-cli/src/cache/cacheManager.ts to respect these query-type-specific exclusions
  • Ensure only location_id contributes to the hash for inventory movements queries
🤖 Prompt for AI agents
This phase modifies inventory movements caching to fetch the full dataset for a
location and date range, enabling a single cache entry to serve multiple queries
with different filters.

**Task 1: Create unfiltered collector**
- In `packages/katana-mo-cli/src/api/cachedKatana.ts`, add a new function (e.g.,
`collectAllInventoryMovements`)
- This function should fetch inventory movements with only `location_id`,
`created_at_min`, and `created_at_max` parameters
- Do not include `resource_type` or `variant_ids` filters in the API request
- Implement pagination handling to collect all records across pages
- Follow the existing pattern used by `collectInventoryMovements` for structure
and error handling

**Task 2: Modify cache key generation**
- In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add configuration to
exclude `variant_ids` and `resource_type` from cache key generation for
inventory movements queries
- In `packages/katana-mo-cli/src/cache/cacheManager.ts`, update the
`generateParamsHash` function to respect query-type-specific parameter
exclusions
- Ensure that for inventory movements, only `location_id` (plus date range
implicitly) contributes to the cache key hash
- This allows different queries with varying `resource_type` and `variant_ids`
to share the same cache entry

Phase 2: Implement Client-Side Filtering Layer

Add filtering capabilities to process the full cached dataset and extract records matching the requested resource_type and variant_ids filters.

Task 1: Create Inventory Movement Filtering Utilities

Implement reusable filtering functions for inventory movement records that can filter by resource_type and variant_ids.

  • Create filtering utilities in packages/katana-mo-cli/src/api/cachedKatana.ts (or a new utility file if preferred)
  • Implement filterByResourceTypes(movements, resourceTypes) to filter by allowed resource types
  • Implement filterByVariantIds(movements, variantIds) to filter by variant ID set
  • Use Set-based lookups for efficient filtering of potentially large datasets
Task 2: Integrate Full-Dataset Caching with Client-Side Filtering

Refactor fetchConsumptionFromInventoryMovements to use the full-dataset caching strategy with client-side filtering instead of the current per-parameter-combination caching.

  • Modify the cached path in fetchConsumptionFromInventoryMovements to fetch the complete dataset once via the cache manager
  • Apply client-side filtering using the utilities from Task 2.1 to extract records matching the requested resourceTypes and variantIds
  • Remove the current loop that iterates over resourceTypes and variant ID chunks when caching is enabled
  • Maintain the existing uncached fallback path for when cacheManager is not provided or bypassCache is true
🤖 Prompt for AI agents
This phase implements client-side filtering to process the full cached dataset
and extract records matching specific filter criteria.

**Task 1: Create filtering utilities**
- In `packages/katana-mo-cli/src/api/cachedKatana.ts` (or new utility file),
create filtering functions
- Implement `filterByResourceTypes(movements, resourceTypes)` that filters
inventory movement records to only those matching the provided resource types
array
- Implement `filterByVariantIds(movements, variantIds)` that filters records to
only those matching the provided variant IDs
- Use Set-based lookups (e.g., `new Set(variantIds)`) for O(1) lookup
performance when filtering large datasets
- Functions should return filtered arrays of inventory movement records

**Task 2: Refactor main fetching function**
- In `fetchConsumptionFromInventoryMovements` in
`packages/katana-mo-cli/src/api/cachedKatana.ts`, modify the cached code path
- When caching is enabled, fetch the complete unfiltered dataset once using the
cache manager (call the collector from Phase 1, Task 1)
- Apply the filtering utilities from Task 2.1 to filter by the requested
`resourceTypes` and `variantIds`
- Remove the existing loop that iterates over `resourceTypes` and variant ID
chunks when caching is enabled
- Keep the uncached fallback path unchanged (when `cacheManager` is not provided
or `bypassCache` is true)
- Ensure the filtered results match the expected data structure for downstream
consumption

Phase 3: Enable and Verify Pipeline Integration

Connect the refactored caching to the pipeline and verify that both MO and PO generation workflows benefit from the unified cached dataset.

Task 1: Pass Cache Manager to All Inventory Movement Calls

Enable caching for the two inventory movement calls that currently bypass the cache by not passing the cacheManager parameter.

  • Update the assemblyConsumption call in packages/katana-mo-cli/src/runPipeline.ts (around line 91-98) to include the cacheManager parameter
  • Update the longConsumption fallback call in packages/katana-mo-cli/src/runPipeline.ts (around line 107-114) to include the cacheManager parameter
  • Both calls should follow the same pattern as the existing fetchPurchasePipelineData calls (lines 290-312) which already correctly pass cacheManager
  • Verify that cacheManager is available in the function scope (it should be, as other calls in the same function already use it)
Task 2: Verify Unified Data Source Across Workflows

Ensure that both PO generation and MO generation workflows can leverage the same cached inventory movements data.

  • Verify that materialConsumption calls in fetchPurchasePipelineData (lines 290-312) will share cached data with assemblyConsumption calls when they query overlapping date ranges and locations
  • Confirm that different resourceTypes arrays (e.g., ["ProductionIngredient"] vs ["ProductionIngredient", "Production"]) will hit the same cache entry
  • Test that subsequent runs with different variantIds benefit from the cached full dataset
🤖 Prompt for AI agents
This phase connects the refactored caching infrastructure to the pipeline and
ensures both MO and PO workflows benefit from unified caching.

**Task 1: Enable caching in pipeline calls**
- In `packages/katana-mo-cli/src/runPipeline.ts`, locate the
`assemblyConsumption` call (around line 91-98)
- Add the `cacheManager` parameter to this call to enable caching
- Locate the `longConsumption` fallback call (around line 107-114)
- Add the `cacheManager` parameter to this call as well
- Follow the same pattern as existing `fetchPurchasePipelineData` calls (lines
290-312) that already pass `cacheManager`
- Confirm `cacheManager` is available in scope (it should be since other calls
use it)

**Task 2: Verify cache sharing**
- Review the `materialConsumption` calls in `fetchPurchasePipelineData` (lines
290-312) to confirm they will share cached data with `assemblyConsumption` calls
for overlapping date ranges and locations
- Verify that queries with different `resourceTypes` arrays (e.g.,
`["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit
the same cache entry due to the cache key changes in Phase 1
- Add comments or test cases documenting that subsequent runs with different
`variantIds` will benefit from the cached full dataset
- No code changes should be needed for this task—it's verification that the
architecture changes in Phases 1-2 enable cross-workflow cache sharing
Research

The caching infrastructure is implemented in packages/katana-mo-cli/src/cache/ using SQLite for storage. The CacheManager class provides range-based caching with intelligent gap detection. Currently, cache keys are generated by hashing all non-date parameters, which means different resource_type and variant_ids combinations create separate cache entries. This design causes poor cache hit rates when these parameters vary between calls—which is the exact scenario described in the ticket. The solution requires changing the inventory movements caching strategy to fetch unfiltered data (only date range + location) and filter client-side, enabling a single cached dataset to serve multiple queries with different filters.


🚀 Next Steps

🤖 All AI agent prompts combined
Task: 1

This phase modifies inventory movements caching to fetch the full dataset for a
location and date range, enabling a single cache entry to serve multiple queries
with different filters.

**Task 1: Create unfiltered collector**
- In `packages/katana-mo-cli/src/api/cachedKatana.ts`, add a new function (e.g.,
`collectAllInventoryMovements`)
- This function should fetch inventory movements with only `location_id`,
`created_at_min`, and `created_at_max` parameters
- Do not include `resource_type` or `variant_ids` filters in the API request
- Implement pagination handling to collect all records across pages
- Follow the existing pattern used by `collectInventoryMovements` for structure
and error handling

**Task 2: Modify cache key generation**
- In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add configuration to
exclude `variant_ids` and `resource_type` from cache key generation for
inventory movements queries
- In `packages/katana-mo-cli/src/cache/cacheManager.ts`, update the
`generateParamsHash` function to respect query-type-specific parameter
exclusions
- Ensure that for inventory movements, only `location_id` (plus date range
implicitly) contributes to the cache key hash
- This allows different queries with varying `resource_type` and `variant_ids`
to share the same cache entry
===============================================================================

Task: 2

This phase implements client-side filtering to process the full cached dataset
and extract records matching specific filter criteria.

**Task 1: Create filtering utilities**
- In `packages/katana-mo-cli/src/api/cachedKatana.ts` (or new utility file),
create filtering functions
- Implement `filterByResourceTypes(movements, resourceTypes)` that filters
inventory movement records to only those matching the provided resource types
array
- Implement `filterByVariantIds(movements, variantIds)` that filters records to
only those matching the provided variant IDs
- Use Set-based lookups (e.g., `new Set(variantIds)`) for O(1) lookup
performance when filtering large datasets
- Functions should return filtered arrays of inventory movement records

**Task 2: Refactor main fetching function**
- In `fetchConsumptionFromInventoryMovements` in
`packages/katana-mo-cli/src/api/cachedKatana.ts`, modify the cached code path
- When caching is enabled, fetch the complete unfiltered dataset once using the
cache manager (call the collector from Phase 1, Task 1)
- Apply the filtering utilities from Task 2.1 to filter by the requested
`resourceTypes` and `variantIds`
- Remove the existing loop that iterates over `resourceTypes` and variant ID
chunks when caching is enabled
- Keep the uncached fallback path unchanged (when `cacheManager` is not provided
or `bypassCache` is true)
- Ensure the filtered results match the expected data structure for downstream
consumption
===============================================================================

Task: 3

This phase connects the refactored caching infrastructure to the pipeline and
ensures both MO and PO workflows benefit from unified caching.

**Task 1: Enable caching in pipeline calls**
- In `packages/katana-mo-cli/src/runPipeline.ts`, locate the
`assemblyConsumption` call (around line 91-98)
- Add the `cacheManager` parameter to this call to enable caching
- Locate the `longConsumption` fallback call (around line 107-114)
- Add the `cacheManager` parameter to this call as well
- Follow the same pattern as existing `fetchPurchasePipelineData` calls (lines
290-312) that already pass `cacheManager`
- Confirm `cacheManager` is available in scope (it should be since other calls
use it)

**Task 2: Verify cache sharing**
- Review the `materialConsumption` calls in `fetchPurchasePipelineData` (lines
290-312) to confirm they will share cached data with `assemblyConsumption` calls
for overlapping date ranges and locations
- Verify that queries with different `resourceTypes` arrays (e.g.,
`["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit
the same cache entry due to the cache key changes in Phase 1
- Add comments or test cases documenting that subsequent runs with different
`variantIds` will benefit from the cached full dataset
- No code changes should be needed for this task—it's verification that the
architecture changes in Phases 1-2 enable cross-workflow cache sharing
💡 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 - Change from parameter-based caching (where each `resource_type`/`variant_ids` combination creates a separate cache entry) to full-dataset caching with client-side filtering - Fetch all inventory movements for a location and date range without restrictive filters, cache once - Filter the cached results client-side to match requested `resource_type` and `variant_ids` - This enables cache hits across calls with different filter parameters, dramatically improving cache effectiveness for the varying-parameter scenario described in the ticket <details> <summary><b>Design Choices</b></summary> <details> <summary><b>Design Choice 1: Should the full-dataset fetch include the `location_id` filter or fetch all locations?</b></summary> **Options Considered:** 1. Keep `location_id` filter in API request, cache per-location datasets 2. Remove `location_id` filter, cache all-locations dataset and filter client-side **Chosen Option:** 1 **Rationale:** Keep `location_id` in the API request to limit data volume and match existing workflow patterns that operate on single locations. </details> </details> <b>💡 User Tips</b> Regenerate the plan with different choices with `@coderabbitai <feedback>`. ## Implementation Steps ### Phase 1: Implement Full-Dataset Fetch for Inventory Movements Modify the inventory movements data fetching to retrieve the complete dataset for a location and date range, without `resource_type` or `variant_ids` filters. This enables caching a single dataset that can serve multiple filtered queries. <details> <summary><b>Task 1: Create Unfiltered Inventory Movements Collector</b></summary> Create a new collection function that fetches all inventory movements for a location and date range without applying `resource_type` or `variant_ids` filters. - Add a new function in `packages/katana-mo-cli/src/api/cachedKatana.ts` (e.g., `collectAllInventoryMovements`) that calls the API with only `location_id`, `created_at_min`, and `created_at_max` parameters - This function should handle pagination to collect all records across pages - Follow the pattern of existing `collectInventoryMovements` but without the restrictive filters </details> <details> <summary><b>Task 2: Update Cache Key Generation for Inventory Movements</b></summary> Modify the parameter hashing behavior for inventory movements to exclude `variant_ids` and `resource_type` from the cache key, ensuring all queries for the same location and date range share the same cache entry. - Update `packages/katana-mo-cli/src/cache/queryConfig.ts` to define excluded parameters for inventory movements (similar to how date params are already excluded) - Modify `generateParamsHash` in `packages/katana-mo-cli/src/cache/cacheManager.ts` to respect these query-type-specific exclusions - Ensure only `location_id` contributes to the hash for inventory movements queries </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase modifies inventory movements caching to fetch the full dataset for a location and date range, enabling a single cache entry to serve multiple queries with different filters. **Task 1: Create unfiltered collector** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, add a new function (e.g., `collectAllInventoryMovements`) - This function should fetch inventory movements with only `location_id`, `created_at_min`, and `created_at_max` parameters - Do not include `resource_type` or `variant_ids` filters in the API request - Implement pagination handling to collect all records across pages - Follow the existing pattern used by `collectInventoryMovements` for structure and error handling **Task 2: Modify cache key generation** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add configuration to exclude `variant_ids` and `resource_type` from cache key generation for inventory movements queries - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, update the `generateParamsHash` function to respect query-type-specific parameter exclusions - Ensure that for inventory movements, only `location_id` (plus date range implicitly) contributes to the cache key hash - This allows different queries with varying `resource_type` and `variant_ids` to share the same cache entry ``` </details> ### Phase 2: Implement Client-Side Filtering Layer Add filtering capabilities to process the full cached dataset and extract records matching the requested `resource_type` and `variant_ids` filters. <details> <summary><b>Task 1: Create Inventory Movement Filtering Utilities</b></summary> Implement reusable filtering functions for inventory movement records that can filter by `resource_type` and `variant_ids`. - Create filtering utilities in `packages/katana-mo-cli/src/api/cachedKatana.ts` (or a new utility file if preferred) - Implement `filterByResourceTypes(movements, resourceTypes)` to filter by allowed resource types - Implement `filterByVariantIds(movements, variantIds)` to filter by variant ID set - Use Set-based lookups for efficient filtering of potentially large datasets </details> <details> <summary><b>Task 2: Integrate Full-Dataset Caching with Client-Side Filtering</b></summary> Refactor `fetchConsumptionFromInventoryMovements` to use the full-dataset caching strategy with client-side filtering instead of the current per-parameter-combination caching. - Modify the cached path in `fetchConsumptionFromInventoryMovements` to fetch the complete dataset once via the cache manager - Apply client-side filtering using the utilities from Task 2.1 to extract records matching the requested `resourceTypes` and `variantIds` - Remove the current loop that iterates over `resourceTypes` and variant ID chunks when caching is enabled - Maintain the existing uncached fallback path for when `cacheManager` is not provided or `bypassCache` is true </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase implements client-side filtering to process the full cached dataset and extract records matching specific filter criteria. **Task 1: Create filtering utilities** - In `packages/katana-mo-cli/src/api/cachedKatana.ts` (or new utility file), create filtering functions - Implement `filterByResourceTypes(movements, resourceTypes)` that filters inventory movement records to only those matching the provided resource types array - Implement `filterByVariantIds(movements, variantIds)` that filters records to only those matching the provided variant IDs - Use Set-based lookups (e.g., `new Set(variantIds)`) for O(1) lookup performance when filtering large datasets - Functions should return filtered arrays of inventory movement records **Task 2: Refactor main fetching function** - In `fetchConsumptionFromInventoryMovements` in `packages/katana-mo-cli/src/api/cachedKatana.ts`, modify the cached code path - When caching is enabled, fetch the complete unfiltered dataset once using the cache manager (call the collector from Phase 1, Task 1) - Apply the filtering utilities from Task 2.1 to filter by the requested `resourceTypes` and `variantIds` - Remove the existing loop that iterates over `resourceTypes` and variant ID chunks when caching is enabled - Keep the uncached fallback path unchanged (when `cacheManager` is not provided or `bypassCache` is true) - Ensure the filtered results match the expected data structure for downstream consumption ``` </details> ### Phase 3: Enable and Verify Pipeline Integration Connect the refactored caching to the pipeline and verify that both MO and PO generation workflows benefit from the unified cached dataset. <details> <summary><b>Task 1: Pass Cache Manager to All Inventory Movement Calls</b></summary> Enable caching for the two inventory movement calls that currently bypass the cache by not passing the `cacheManager` parameter. - Update the `assemblyConsumption` call in `packages/katana-mo-cli/src/runPipeline.ts` (around line 91-98) to include the `cacheManager` parameter - Update the `longConsumption` fallback call in `packages/katana-mo-cli/src/runPipeline.ts` (around line 107-114) to include the `cacheManager` parameter - Both calls should follow the same pattern as the existing `fetchPurchasePipelineData` calls (lines 290-312) which already correctly pass `cacheManager` - Verify that `cacheManager` is available in the function scope (it should be, as other calls in the same function already use it) </details> <details> <summary><b>Task 2: Verify Unified Data Source Across Workflows</b></summary> Ensure that both PO generation and MO generation workflows can leverage the same cached inventory movements data. - Verify that `materialConsumption` calls in `fetchPurchasePipelineData` (lines 290-312) will share cached data with `assemblyConsumption` calls when they query overlapping date ranges and locations - Confirm that different `resourceTypes` arrays (e.g., `["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit the same cache entry - Test that subsequent runs with different `variantIds` benefit from the cached full dataset </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase connects the refactored caching infrastructure to the pipeline and ensures both MO and PO workflows benefit from unified caching. **Task 1: Enable caching in pipeline calls** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `assemblyConsumption` call (around line 91-98) - Add the `cacheManager` parameter to this call to enable caching - Locate the `longConsumption` fallback call (around line 107-114) - Add the `cacheManager` parameter to this call as well - Follow the same pattern as existing `fetchPurchasePipelineData` calls (lines 290-312) that already pass `cacheManager` - Confirm `cacheManager` is available in scope (it should be since other calls use it) **Task 2: Verify cache sharing** - Review the `materialConsumption` calls in `fetchPurchasePipelineData` (lines 290-312) to confirm they will share cached data with `assemblyConsumption` calls for overlapping date ranges and locations - Verify that queries with different `resourceTypes` arrays (e.g., `["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit the same cache entry due to the cache key changes in Phase 1 - Add comments or test cases documenting that subsequent runs with different `variantIds` will benefit from the cached full dataset - No code changes should be needed for this task—it's verification that the architecture changes in Phases 1-2 enable cross-workflow cache sharing ``` </details> <details> <summary><b>Research</b></summary> The caching infrastructure is implemented in `packages/katana-mo-cli/src/cache/` using SQLite for storage. The `CacheManager` class provides range-based caching with intelligent gap detection. Currently, cache keys are generated by hashing all non-date parameters, which means different `resource_type` and `variant_ids` combinations create separate cache entries. This design causes poor cache hit rates when these parameters vary between calls—which is the exact scenario described in the ticket. The solution requires changing the inventory movements caching strategy to fetch unfiltered data (only date range + location) and filter client-side, enabling a single cached dataset to serve multiple queries with different filters. </details> --- ### 🚀 Next Steps <details> <summary><b>🤖 All AI agent prompts combined</b></summary> ``` Task: 1 This phase modifies inventory movements caching to fetch the full dataset for a location and date range, enabling a single cache entry to serve multiple queries with different filters. **Task 1: Create unfiltered collector** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, add a new function (e.g., `collectAllInventoryMovements`) - This function should fetch inventory movements with only `location_id`, `created_at_min`, and `created_at_max` parameters - Do not include `resource_type` or `variant_ids` filters in the API request - Implement pagination handling to collect all records across pages - Follow the existing pattern used by `collectInventoryMovements` for structure and error handling **Task 2: Modify cache key generation** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add configuration to exclude `variant_ids` and `resource_type` from cache key generation for inventory movements queries - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, update the `generateParamsHash` function to respect query-type-specific parameter exclusions - Ensure that for inventory movements, only `location_id` (plus date range implicitly) contributes to the cache key hash - This allows different queries with varying `resource_type` and `variant_ids` to share the same cache entry =============================================================================== Task: 2 This phase implements client-side filtering to process the full cached dataset and extract records matching specific filter criteria. **Task 1: Create filtering utilities** - In `packages/katana-mo-cli/src/api/cachedKatana.ts` (or new utility file), create filtering functions - Implement `filterByResourceTypes(movements, resourceTypes)` that filters inventory movement records to only those matching the provided resource types array - Implement `filterByVariantIds(movements, variantIds)` that filters records to only those matching the provided variant IDs - Use Set-based lookups (e.g., `new Set(variantIds)`) for O(1) lookup performance when filtering large datasets - Functions should return filtered arrays of inventory movement records **Task 2: Refactor main fetching function** - In `fetchConsumptionFromInventoryMovements` in `packages/katana-mo-cli/src/api/cachedKatana.ts`, modify the cached code path - When caching is enabled, fetch the complete unfiltered dataset once using the cache manager (call the collector from Phase 1, Task 1) - Apply the filtering utilities from Task 2.1 to filter by the requested `resourceTypes` and `variantIds` - Remove the existing loop that iterates over `resourceTypes` and variant ID chunks when caching is enabled - Keep the uncached fallback path unchanged (when `cacheManager` is not provided or `bypassCache` is true) - Ensure the filtered results match the expected data structure for downstream consumption =============================================================================== Task: 3 This phase connects the refactored caching infrastructure to the pipeline and ensures both MO and PO workflows benefit from unified caching. **Task 1: Enable caching in pipeline calls** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `assemblyConsumption` call (around line 91-98) - Add the `cacheManager` parameter to this call to enable caching - Locate the `longConsumption` fallback call (around line 107-114) - Add the `cacheManager` parameter to this call as well - Follow the same pattern as existing `fetchPurchasePipelineData` calls (lines 290-312) that already pass `cacheManager` - Confirm `cacheManager` is available in scope (it should be since other calls use it) **Task 2: Verify cache sharing** - Review the `materialConsumption` calls in `fetchPurchasePipelineData` (lines 290-312) to confirm they will share cached data with `assemblyConsumption` calls for overlapping date ranges and locations - Verify that queries with different `resourceTypes` arrays (e.g., `["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit the same cache entry due to the cache key changes in Phase 1 - Add comments or test cases documenting that subsequent runs with different `variantIds` will benefit from the cached full dataset - No code changes should be needed for this task—it's verification that the architecture changes in Phases 1-2 enable cross-workflow cache sharing ``` </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 - Change from parameter-based caching (where each `resource_type`/`variant_ids` combination creates a separate cache entry) to full-dataset caching with client-side filtering - Fetch all inventory movements for a location and date range without restrictive filters, cache once - Filter the cached results client-side to match requested `resource_type` and `variant_ids` - This enables cache hits across calls with different filter parameters, dramatically improving cache effectiveness for the varying-parameter scenario described in the ticket <details> <summary><b>Design Choices</b></summary> <details> <summary><b>Design Choice 1: Should the full-dataset fetch include the `location_id` filter or fetch all locations?</b></summary> **Options Considered:** 1. Keep `location_id` filter in API request, cache per-location datasets 2. Remove `location_id` filter, cache all-locations dataset and filter client-side **Chosen Option:** 1 **Rationale:** Keep `location_id` in the API request to limit data volume and match existing workflow patterns that operate on single locations. </details> </details> <b>💡 User Tips</b> Regenerate the plan with different choices with `@coderabbitai <feedback>`. ## Implementation Steps ### Phase 1: Implement Full-Dataset Fetch for Inventory Movements Modify the inventory movements data fetching to retrieve the complete dataset for a location and date range, without `resource_type` or `variant_ids` filters. This enables caching a single dataset that can serve multiple filtered queries. <details> <summary><b>Task 1: Create Unfiltered Inventory Movements Collector</b></summary> Create a new collection function that fetches all inventory movements for a location and date range without applying `resource_type` or `variant_ids` filters. - Add a new function in `packages/katana-mo-cli/src/api/cachedKatana.ts` (e.g., `collectAllInventoryMovements`) that calls the API with only `location_id`, `created_at_min`, and `created_at_max` parameters - This function should handle pagination to collect all records across pages - Follow the pattern of existing `collectInventoryMovements` but without the restrictive filters </details> <details> <summary><b>Task 2: Update Cache Key Generation for Inventory Movements</b></summary> Modify the parameter hashing behavior for inventory movements to exclude `variant_ids` and `resource_type` from the cache key, ensuring all queries for the same location and date range share the same cache entry. - Update `packages/katana-mo-cli/src/cache/queryConfig.ts` to define excluded parameters for inventory movements (similar to how date params are already excluded) - Modify `generateParamsHash` in `packages/katana-mo-cli/src/cache/cacheManager.ts` to respect these query-type-specific exclusions - Ensure only `location_id` contributes to the hash for inventory movements queries </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase modifies inventory movements caching to fetch the full dataset for a location and date range, enabling a single cache entry to serve multiple queries with different filters. **Task 1: Create unfiltered collector** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, add a new function (e.g., `collectAllInventoryMovements`) - This function should fetch inventory movements with only `location_id`, `created_at_min`, and `created_at_max` parameters - Do not include `resource_type` or `variant_ids` filters in the API request - Implement pagination handling to collect all records across pages - Follow the existing pattern used by `collectInventoryMovements` for structure and error handling **Task 2: Modify cache key generation** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add configuration to exclude `variant_ids` and `resource_type` from cache key generation for inventory movements queries - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, update the `generateParamsHash` function to respect query-type-specific parameter exclusions - Ensure that for inventory movements, only `location_id` (plus date range implicitly) contributes to the cache key hash - This allows different queries with varying `resource_type` and `variant_ids` to share the same cache entry ``` </details> ### Phase 2: Implement Client-Side Filtering Layer Add filtering capabilities to process the full cached dataset and extract records matching the requested `resource_type` and `variant_ids` filters. <details> <summary><b>Task 1: Create Inventory Movement Filtering Utilities</b></summary> Implement reusable filtering functions for inventory movement records that can filter by `resource_type` and `variant_ids`. - Create filtering utilities in `packages/katana-mo-cli/src/api/cachedKatana.ts` (or a new utility file if preferred) - Implement `filterByResourceTypes(movements, resourceTypes)` to filter by allowed resource types - Implement `filterByVariantIds(movements, variantIds)` to filter by variant ID set - Use Set-based lookups for efficient filtering of potentially large datasets </details> <details> <summary><b>Task 2: Integrate Full-Dataset Caching with Client-Side Filtering</b></summary> Refactor `fetchConsumptionFromInventoryMovements` to use the full-dataset caching strategy with client-side filtering instead of the current per-parameter-combination caching. - Modify the cached path in `fetchConsumptionFromInventoryMovements` to fetch the complete dataset once via the cache manager - Apply client-side filtering using the utilities from Task 2.1 to extract records matching the requested `resourceTypes` and `variantIds` - Remove the current loop that iterates over `resourceTypes` and variant ID chunks when caching is enabled - Maintain the existing uncached fallback path for when `cacheManager` is not provided or `bypassCache` is true </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase implements client-side filtering to process the full cached dataset and extract records matching specific filter criteria. **Task 1: Create filtering utilities** - In `packages/katana-mo-cli/src/api/cachedKatana.ts` (or new utility file), create filtering functions - Implement `filterByResourceTypes(movements, resourceTypes)` that filters inventory movement records to only those matching the provided resource types array - Implement `filterByVariantIds(movements, variantIds)` that filters records to only those matching the provided variant IDs - Use Set-based lookups (e.g., `new Set(variantIds)`) for O(1) lookup performance when filtering large datasets - Functions should return filtered arrays of inventory movement records **Task 2: Refactor main fetching function** - In `fetchConsumptionFromInventoryMovements` in `packages/katana-mo-cli/src/api/cachedKatana.ts`, modify the cached code path - When caching is enabled, fetch the complete unfiltered dataset once using the cache manager (call the collector from Phase 1, Task 1) - Apply the filtering utilities from Task 2.1 to filter by the requested `resourceTypes` and `variantIds` - Remove the existing loop that iterates over `resourceTypes` and variant ID chunks when caching is enabled - Keep the uncached fallback path unchanged (when `cacheManager` is not provided or `bypassCache` is true) - Ensure the filtered results match the expected data structure for downstream consumption ``` </details> ### Phase 3: Enable and Verify Pipeline Integration Connect the refactored caching to the pipeline and verify that both MO and PO generation workflows benefit from the unified cached dataset. <details> <summary><b>Task 1: Pass Cache Manager to All Inventory Movement Calls</b></summary> Enable caching for the two inventory movement calls that currently bypass the cache by not passing the `cacheManager` parameter. - Update the `assemblyConsumption` call in `packages/katana-mo-cli/src/runPipeline.ts` (around line 91-98) to include the `cacheManager` parameter - Update the `longConsumption` fallback call in `packages/katana-mo-cli/src/runPipeline.ts` (around line 107-114) to include the `cacheManager` parameter - Both calls should follow the same pattern as the existing `fetchPurchasePipelineData` calls (lines 290-312) which already correctly pass `cacheManager` - Verify that `cacheManager` is available in the function scope (it should be, as other calls in the same function already use it) </details> <details> <summary><b>Task 2: Verify Unified Data Source Across Workflows</b></summary> Ensure that both PO generation and MO generation workflows can leverage the same cached inventory movements data. - Verify that `materialConsumption` calls in `fetchPurchasePipelineData` (lines 290-312) will share cached data with `assemblyConsumption` calls when they query overlapping date ranges and locations - Confirm that different `resourceTypes` arrays (e.g., `["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit the same cache entry - Test that subsequent runs with different `variantIds` benefit from the cached full dataset </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase connects the refactored caching infrastructure to the pipeline and ensures both MO and PO workflows benefit from unified caching. **Task 1: Enable caching in pipeline calls** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `assemblyConsumption` call (around line 91-98) - Add the `cacheManager` parameter to this call to enable caching - Locate the `longConsumption` fallback call (around line 107-114) - Add the `cacheManager` parameter to this call as well - Follow the same pattern as existing `fetchPurchasePipelineData` calls (lines 290-312) that already pass `cacheManager` - Confirm `cacheManager` is available in scope (it should be since other calls use it) **Task 2: Verify cache sharing** - Review the `materialConsumption` calls in `fetchPurchasePipelineData` (lines 290-312) to confirm they will share cached data with `assemblyConsumption` calls for overlapping date ranges and locations - Verify that queries with different `resourceTypes` arrays (e.g., `["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit the same cache entry due to the cache key changes in Phase 1 - Add comments or test cases documenting that subsequent runs with different `variantIds` will benefit from the cached full dataset - No code changes should be needed for this task—it's verification that the architecture changes in Phases 1-2 enable cross-workflow cache sharing ``` </details> <details> <summary><b>Research</b></summary> The caching infrastructure is implemented in `packages/katana-mo-cli/src/cache/` using SQLite for storage. The `CacheManager` class provides range-based caching with intelligent gap detection. Currently, cache keys are generated by hashing all non-date parameters, which means different `resource_type` and `variant_ids` combinations create separate cache entries. This design causes poor cache hit rates when these parameters vary between calls—which is the exact scenario described in the ticket. The solution requires changing the inventory movements caching strategy to fetch unfiltered data (only date range + location) and filter client-side, enabling a single cached dataset to serve multiple queries with different filters. </details> --- ### 🚀 Next Steps <details> <summary><b>🤖 All AI agent prompts combined</b></summary> ``` Task: 1 This phase modifies inventory movements caching to fetch the full dataset for a location and date range, enabling a single cache entry to serve multiple queries with different filters. **Task 1: Create unfiltered collector** - In `packages/katana-mo-cli/src/api/cachedKatana.ts`, add a new function (e.g., `collectAllInventoryMovements`) - This function should fetch inventory movements with only `location_id`, `created_at_min`, and `created_at_max` parameters - Do not include `resource_type` or `variant_ids` filters in the API request - Implement pagination handling to collect all records across pages - Follow the existing pattern used by `collectInventoryMovements` for structure and error handling **Task 2: Modify cache key generation** - In `packages/katana-mo-cli/src/cache/queryConfig.ts`, add configuration to exclude `variant_ids` and `resource_type` from cache key generation for inventory movements queries - In `packages/katana-mo-cli/src/cache/cacheManager.ts`, update the `generateParamsHash` function to respect query-type-specific parameter exclusions - Ensure that for inventory movements, only `location_id` (plus date range implicitly) contributes to the cache key hash - This allows different queries with varying `resource_type` and `variant_ids` to share the same cache entry =============================================================================== Task: 2 This phase implements client-side filtering to process the full cached dataset and extract records matching specific filter criteria. **Task 1: Create filtering utilities** - In `packages/katana-mo-cli/src/api/cachedKatana.ts` (or new utility file), create filtering functions - Implement `filterByResourceTypes(movements, resourceTypes)` that filters inventory movement records to only those matching the provided resource types array - Implement `filterByVariantIds(movements, variantIds)` that filters records to only those matching the provided variant IDs - Use Set-based lookups (e.g., `new Set(variantIds)`) for O(1) lookup performance when filtering large datasets - Functions should return filtered arrays of inventory movement records **Task 2: Refactor main fetching function** - In `fetchConsumptionFromInventoryMovements` in `packages/katana-mo-cli/src/api/cachedKatana.ts`, modify the cached code path - When caching is enabled, fetch the complete unfiltered dataset once using the cache manager (call the collector from Phase 1, Task 1) - Apply the filtering utilities from Task 2.1 to filter by the requested `resourceTypes` and `variantIds` - Remove the existing loop that iterates over `resourceTypes` and variant ID chunks when caching is enabled - Keep the uncached fallback path unchanged (when `cacheManager` is not provided or `bypassCache` is true) - Ensure the filtered results match the expected data structure for downstream consumption =============================================================================== Task: 3 This phase connects the refactored caching infrastructure to the pipeline and ensures both MO and PO workflows benefit from unified caching. **Task 1: Enable caching in pipeline calls** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `assemblyConsumption` call (around line 91-98) - Add the `cacheManager` parameter to this call to enable caching - Locate the `longConsumption` fallback call (around line 107-114) - Add the `cacheManager` parameter to this call as well - Follow the same pattern as existing `fetchPurchasePipelineData` calls (lines 290-312) that already pass `cacheManager` - Confirm `cacheManager` is available in scope (it should be since other calls use it) **Task 2: Verify cache sharing** - Review the `materialConsumption` calls in `fetchPurchasePipelineData` (lines 290-312) to confirm they will share cached data with `assemblyConsumption` calls for overlapping date ranges and locations - Verify that queries with different `resourceTypes` arrays (e.g., `["ProductionIngredient"]` vs `["ProductionIngredient", "Production"]`) will hit the same cache entry due to the cache key changes in Phase 1 - Add comments or test cases documenting that subsequent runs with different `variantIds` will benefit from the cached full dataset - No code changes should be needed for this task—it's verification that the architecture changes in Phases 1-2 enable cross-workflow cache sharing ``` </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> --> <!-- <agentComponentType>plan-edits</agentComponentType> -->
chris-kreidl commented 2026-02-12 14:34:34 +00:00 (Migrated from github.com)

@coderabbitai since variant_ids will very likely be different for different tool invocations wouldn't that mean that we essentially never get a cache hit?

@coderabbitai since `variant_ids` will very likely be different for different tool invocations wouldn't that mean that we essentially never get a cache hit?
coderabbitai[bot] commented 2026-02-12 14:37:00 +00:00 (Migrated from github.com)
🧩 Analysis chain

@chris-kreidl That's an excellent observation! Let me investigate the actual cache key generation logic to understand how this works.


🏁 Script executed:

#!/bin/bash

# First, let's look at the cache key generation logic
echo "=== Cache Key Generation Logic ==="
rg -n -A 10 "generateCacheKey|cache.*key" packages/katana-mo-cli/src/cache/ --type ts

echo -e "\n=== How variant_ids is used in fetchConsumptionFromInventoryMovements ==="
rg -n -B 5 -A 15 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/cachedKatana.ts

echo -e "\n=== Query Config for inventory_movements ==="
rg -n -B 3 -A 10 "inventory_movements" packages/katana-mo-cli/src/cache/queryConfig.ts

echo -e "\n=== Check CacheManager class implementation ==="
ast-grep --pattern 'class CacheManager {
  $$$
}'

Length of output: 9249


🏁 Script executed:

#!/bin/bash

# Look for generateParamsHash function
echo "=== generateParamsHash Function ==="
rg -n -B 3 -A 15 "function generateParamsHash|const generateParamsHash|generateParamsHash.*=" packages/katana-mo-cli/src/cache/ --type ts

# Look at actual calls to fetchConsumptionFromInventoryMovements in runPipeline.ts
echo -e "\n=== Calls to fetchConsumptionFromInventoryMovements in runPipeline.ts ==="
rg -n -B 10 -A 5 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/runPipeline.ts

# Check if there are multiple calls with the same variant_ids
echo -e "\n=== Context around assemblyConsumption and longConsumption ==="
cat packages/katana-mo-cli/src/runPipeline.ts | sed -n '80,120p'

Length of output: 8493


🏁 Script executed:

#!/bin/bash

# Let's check if there are any scenarios where the same variant_ids might be queried multiple times
echo "=== Look at how settings and variant_ids are determined ==="
rg -n -B 5 -A 5 "producibleVariantIds|materialVariantIds" packages/katana-mo-cli/src/runPipeline.ts | head -60

# Check if there are other calls in the codebase that might reuse these params
echo -e "\n=== Check fetchConsumptionFromInventoryMovements implementation ==="
fd "cachedKatana.ts" --exec cat {} | grep -A 30 "fetchConsumptionFromInventoryMovements"

Length of output: 3767


🏁 Script executed:

#!/bin/bash

# Let's understand the cache persistence and whether it survives across runs
echo "=== Check how cache is initialized and if it persists ==="
rg -n -B 5 -A 10 "new CacheManager|CacheManager\(" packages/katana-mo-cli/src/ --type ts | head -80

# Look for any cache file location or persistence configuration
echo -e "\n=== Check for cache file paths ==="
rg -n "\.db|cache.*path|cache.*file" packages/katana-mo-cli/src/cache/ --type ts

Length of output: 5507


🏁 Script executed:

#!/bin/bash

# Let's see the full implementation to understand the date-range caching
echo "=== Full fetchConsumptionFromInventoryMovements implementation ==="
cat packages/katana-mo-cli/src/api/cachedKatana.ts | grep -A 60 "export async function fetchConsumptionFromInventoryMovements"

# Check if there's batching or chunking of variant_ids
echo -e "\n=== Check if variant_ids are batched ==="
rg -n -B 3 -A 10 "batch|chunk|cluster" packages/katana-mo-cli/src/api/cachedKatana.ts

Length of output: 3412


@chris-kreidl You're absolutely right to question this! After examining the cache implementation, I can confirm your concern is valid. Here's what's happening:

Cache Key Generation

The cache key is created by hashing ALL non-date parameters (lines 127-141 in cacheManager.ts), which includes:

  • variant_ids (the actual array of IDs)
  • location_id
  • resource_type

Additionally, variant_ids are chunked into batches of 50, so each chunk gets its own cache key.

When Cache DOES Help

Despite your valid concern, the cache provides value in these scenarios:

  1. Within a single run:

    • If there's overlap between producibleVariantIds and materialVariantIds
    • The "zero consumption fallback" queries (lines 107-114) for zeroConsumptionVariantIds might re-query some of the same variants
  2. Date-range extensions:

    • If you query Jan 1-30, then later Jan 1-Feb 15, the Jan 1-30 data is reused from cache
    • The cache detects "gaps" and only fetches missing date ranges
  3. Retry/failure protection:

    • If the tool crashes mid-run and you restart, previously fetched chunks are cached
    • Protects against API rate limits during retries
  4. Identical re-runs:

    • Running the exact same analysis again with the same variant_ids will hit cache

When Cache Doesn't Help

  • Different product selections across runs: If you run the tool for different suppliers or products, you'll get mostly different variant_ids, resulting in cache misses
  • Variant ID order changes: Even the same products in different order produce different cache keys

The Trade-off

The current design optimizes for date-range queries (which is the primary use case for time-series data) rather than arbitrary variant_id combinations.

An alternative approach would cache individual variant records, allowing any combination to benefit—but that would require a more complex cache structure and potentially more storage.

Bottom line: The cache is most effective when:

  • Re-running the same analysis
  • Extending time ranges
  • Recovering from failures
  • There's variant overlap within a single run

But you're correct that cache hits will be limited when analyzing completely different sets of products across runs.

Would you like to explore alternative caching strategies, or is the current approach acceptable given these trade-offs?

<!-- This is an auto-generated reply by CodeRabbit --> <details> <summary>🧩 Analysis chain</summary> `@chris-kreidl` That's an excellent observation! Let me investigate the actual cache key generation logic to understand how this works. --- 🏁 Script executed: ``` #!/bin/bash # First, let's look at the cache key generation logic echo "=== Cache Key Generation Logic ===" rg -n -A 10 "generateCacheKey|cache.*key" packages/katana-mo-cli/src/cache/ --type ts echo -e "\n=== How variant_ids is used in fetchConsumptionFromInventoryMovements ===" rg -n -B 5 -A 15 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/cachedKatana.ts echo -e "\n=== Query Config for inventory_movements ===" rg -n -B 3 -A 10 "inventory_movements" packages/katana-mo-cli/src/cache/queryConfig.ts echo -e "\n=== Check CacheManager class implementation ===" ast-grep --pattern 'class CacheManager { $$$ }' ``` Length of output: 9249 --- 🏁 Script executed: ``` #!/bin/bash # Look for generateParamsHash function echo "=== generateParamsHash Function ===" rg -n -B 3 -A 15 "function generateParamsHash|const generateParamsHash|generateParamsHash.*=" packages/katana-mo-cli/src/cache/ --type ts # Look at actual calls to fetchConsumptionFromInventoryMovements in runPipeline.ts echo -e "\n=== Calls to fetchConsumptionFromInventoryMovements in runPipeline.ts ===" rg -n -B 10 -A 5 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/runPipeline.ts # Check if there are multiple calls with the same variant_ids echo -e "\n=== Context around assemblyConsumption and longConsumption ===" cat packages/katana-mo-cli/src/runPipeline.ts | sed -n '80,120p' ``` Length of output: 8493 --- 🏁 Script executed: ``` #!/bin/bash # Let's check if there are any scenarios where the same variant_ids might be queried multiple times echo "=== Look at how settings and variant_ids are determined ===" rg -n -B 5 -A 5 "producibleVariantIds|materialVariantIds" packages/katana-mo-cli/src/runPipeline.ts | head -60 # Check if there are other calls in the codebase that might reuse these params echo -e "\n=== Check fetchConsumptionFromInventoryMovements implementation ===" fd "cachedKatana.ts" --exec cat {} | grep -A 30 "fetchConsumptionFromInventoryMovements" ``` Length of output: 3767 --- 🏁 Script executed: ``` #!/bin/bash # Let's understand the cache persistence and whether it survives across runs echo "=== Check how cache is initialized and if it persists ===" rg -n -B 5 -A 10 "new CacheManager|CacheManager\(" packages/katana-mo-cli/src/ --type ts | head -80 # Look for any cache file location or persistence configuration echo -e "\n=== Check for cache file paths ===" rg -n "\.db|cache.*path|cache.*file" packages/katana-mo-cli/src/cache/ --type ts ``` Length of output: 5507 --- 🏁 Script executed: ``` #!/bin/bash # Let's see the full implementation to understand the date-range caching echo "=== Full fetchConsumptionFromInventoryMovements implementation ===" cat packages/katana-mo-cli/src/api/cachedKatana.ts | grep -A 60 "export async function fetchConsumptionFromInventoryMovements" # Check if there's batching or chunking of variant_ids echo -e "\n=== Check if variant_ids are batched ===" rg -n -B 3 -A 10 "batch|chunk|cluster" packages/katana-mo-cli/src/api/cachedKatana.ts ``` Length of output: 3412 --- </details> `@chris-kreidl` You're absolutely right to question this! After examining the cache implementation, I can confirm your concern is valid. Here's what's happening: ## Cache Key Generation The cache key is created by **hashing ALL non-date parameters** (lines 127-141 in `cacheManager.ts`), which includes: - `variant_ids` (the actual array of IDs) - `location_id` - `resource_type` Additionally, `variant_ids` are chunked into batches of 50, so each chunk gets its own cache key. ## When Cache DOES Help Despite your valid concern, the cache provides value in these scenarios: 1. **Within a single run**: - If there's overlap between `producibleVariantIds` and `materialVariantIds` - The "zero consumption fallback" queries (lines 107-114) for `zeroConsumptionVariantIds` might re-query some of the same variants 2. **Date-range extensions**: - If you query Jan 1-30, then later Jan 1-Feb 15, the Jan 1-30 data is reused from cache - The cache detects "gaps" and only fetches missing date ranges 3. **Retry/failure protection**: - If the tool crashes mid-run and you restart, previously fetched chunks are cached - Protects against API rate limits during retries 4. **Identical re-runs**: - Running the exact same analysis again with the same variant_ids will hit cache ## When Cache Doesn't Help - **Different product selections across runs**: If you run the tool for different suppliers or products, you'll get mostly different `variant_ids`, resulting in cache misses - **Variant ID order changes**: Even the same products in different order produce different cache keys ## The Trade-off The current design optimizes for **date-range queries** (which is the primary use case for time-series data) rather than **arbitrary variant_id combinations**. An alternative approach would cache individual variant records, allowing any combination to benefit—but that would require a more complex cache structure and potentially more storage. **Bottom line**: The cache is most effective when: - Re-running the same analysis - Extending time ranges - Recovering from failures - There's variant overlap within a single run But you're correct that cache hits will be limited when analyzing completely different sets of products across runs. Would you like to explore alternative caching strategies, or is the current approach acceptable given these trade-offs? <!-- <agentComponentType>chat-answer</agentComponentType> --> <!-- <rawResChunk><answer><details> <summary>🧩 Analysis chain</summary> `@chris-kreidl` That's an excellent observation! Let me investigate the actual cache key generation logic to understand how this works. --- 🏁 Script executed: ``` #!/bin/bash # First, let's look at the cache key generation logic echo "=== Cache Key Generation Logic ===" rg -n -A 10 "generateCacheKey|cache.*key" packages/katana-mo-cli/src/cache/ --type ts echo -e "\n=== How variant_ids is used in fetchConsumptionFromInventoryMovements ===" rg -n -B 5 -A 15 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/cachedKatana.ts echo -e "\n=== Query Config for inventory_movements ===" rg -n -B 3 -A 10 "inventory_movements" packages/katana-mo-cli/src/cache/queryConfig.ts echo -e "\n=== Check CacheManager class implementation ===" ast-grep --pattern 'class CacheManager { $$$ }' ``` Length of output: 9249 --- 🏁 Script executed: ``` #!/bin/bash # Look for generateParamsHash function echo "=== generateParamsHash Function ===" rg -n -B 3 -A 15 "function generateParamsHash|const generateParamsHash|generateParamsHash.*=" packages/katana-mo-cli/src/cache/ --type ts # Look at actual calls to fetchConsumptionFromInventoryMovements in runPipeline.ts echo -e "\n=== Calls to fetchConsumptionFromInventoryMovements in runPipeline.ts ===" rg -n -B 10 -A 5 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/runPipeline.ts # Check if there are multiple calls with the same variant_ids echo -e "\n=== Context around assemblyConsumption and longConsumption ===" cat packages/katana-mo-cli/src/runPipeline.ts | sed -n '80,120p' ``` Length of output: 8493 --- 🏁 Script executed: ``` #!/bin/bash # Let's check if there are any scenarios where the same variant_ids might be queried multiple times echo "=== Look at how settings and variant_ids are determined ===" rg -n -B 5 -A 5 "producibleVariantIds|materialVariantIds" packages/katana-mo-cli/src/runPipeline.ts | head -60 # Check if there are other calls in the codebase that might reuse these params echo -e "\n=== Check fetchConsumptionFromInventoryMovements implementation ===" fd "cachedKatana.ts" --exec cat {} | grep -A 30 "fetchConsumptionFromInventoryMovements" ``` Length of output: 3767 --- 🏁 Script executed: ``` #!/bin/bash # Let's understand the cache persistence and whether it survives across runs echo "=== Check how cache is initialized and if it persists ===" rg -n -B 5 -A 10 "new CacheManager|CacheManager\(" packages/katana-mo-cli/src/ --type ts | head -80 # Look for any cache file location or persistence configuration echo -e "\n=== Check for cache file paths ===" rg -n "\.db|cache.*path|cache.*file" packages/katana-mo-cli/src/cache/ --type ts ``` Length of output: 5507 --- 🏁 Script executed: ``` #!/bin/bash # Let's see the full implementation to understand the date-range caching echo "=== Full fetchConsumptionFromInventoryMovements implementation ===" cat packages/katana-mo-cli/src/api/cachedKatana.ts | grep -A 60 "export async function fetchConsumptionFromInventoryMovements" # Check if there's batching or chunking of variant_ids echo -e "\n=== Check if variant_ids are batched ===" rg -n -B 3 -A 10 "batch|chunk|cluster" packages/katana-mo-cli/src/api/cachedKatana.ts ``` Length of output: 3412 --- </details> `@chris-kreidl` You're absolutely right to question this! After examining the cache implementation, I can confirm your concern is valid. Here's what's happening: ## Cache Key Generation The cache key is created by **hashing ALL non-date parameters** (lines 127-141 in `cacheManager.ts`), which includes: - `variant_ids` (the actual array of IDs) - `location_id` - `resource_type` Additionally, `variant_ids` are chunked into batches of 50, so each chunk gets its own cache key. ## When Cache DOES Help Despite your valid concern, the cache provides value in these scenarios: 1. **Within a single run**: - If there's overlap between `producibleVariantIds` and `materialVariantIds` - The "zero consumption fallback" queries (lines 107-114) for `zeroConsumptionVariantIds` might re-query some of the same variants 2. **Date-range extensions**: - If you query Jan 1-30, then later Jan 1-Feb 15, the Jan 1-30 data is reused from cache - The cache detects "gaps" and only fetches missing date ranges 3. **Retry/failure protection**: - If the tool crashes mid-run and you restart, previously fetched chunks are cached - Protects against API rate limits during retries 4. **Identical re-runs**: - Running the exact same analysis again with the same variant_ids will hit cache ## When Cache Doesn't Help - **Different product selections across runs**: If you run the tool for different suppliers or products, you'll get mostly different `variant_ids`, resulting in cache misses - **Variant ID order changes**: Even the same products in different order produce different cache keys ## The Trade-off The current design optimizes for **date-range queries** (which is the primary use case for time-series data) rather than **arbitrary variant_id combinations**. An alternative approach would cache individual variant records, allowing any combination to benefit—but that would require a more complex cache structure and potentially more storage. **Bottom line**: The cache is most effective when: - Re-running the same analysis - Extending time ranges - Recovering from failures - There's variant overlap within a single run But you're correct that cache hits will be limited when analyzing completely different sets of products across runs. Would you like to explore alternative caching strategies, or is the current approach acceptable given these trade-offs?</answer></rawResChunk> -->
chris-kreidl commented 2026-02-12 14:39:52 +00:00 (Migrated from github.com)

@coderabbitai My thought is that we drop the resource_type and variant_ids parameters from our request and cache all inventory movements, and then parse out what we need client side. and since the inventory_movements endpoint also returns movements due to a SKUs presence in a sales order row, we can use the same data set to calculate total consumption between sales and assemblies, allowing this data set to be used for both PO and MO generation.

@coderabbitai My thought is that we drop the `resource_type` and `variant_ids` parameters from our request and cache _all_ inventory movements, and then parse out what we need client side. and since the `inventory_movements` endpoint also returns movements due to a SKUs presence in a sales order row, we can use the same data set to calculate total consumption between sales and assemblies, allowing this data set to be used for both PO and MO generation.
coderabbitai[bot] commented 2026-02-12 14:45:05 +00:00 (Migrated from github.com)

I've updated the plan above based on your feedback. Ready to proceed when you are!

<!-- This is an auto-generated reply by CodeRabbit --> I've updated the plan above based on your feedback. Ready to proceed when you are!
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#10
No description provided.