Inventory movement calls are not cached. #10
Labels
No labels
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
ckreidl/katana#10
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
We currently only cache calls to Katana's
sales_order_rowsendpoint. 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_movementsendpoint. The difficulty is that A) we can and do include differentresource_types in our request, B) thevariant_idsarray passed is likely to be different for each invocation of the tool.@coderabbitai plan
⚠️ Possible Duplicate Issue(s)
📝 Issue Planner
Check the box below or use the
@coderabbitai plancommand to generate an implementation plan and prompts that you can use with your favorite coding assistant.🧪 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:💬 Have feedback or questions? Drop into our discord!
Coding Plan
Summary
resource_type/variant_idscombination creates a separate cache entry) to full-dataset caching with client-side filteringresource_typeandvariant_idsDesign Choices
Design Choice 1: Should the full-dataset fetch include the `location_id` filter or fetch all locations?
Options Considered:
location_idfilter in API request, cache per-location datasetslocation_idfilter, cache all-locations dataset and filter client-sideChosen Option: 1
Rationale: Keep
location_idin 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_typeorvariant_idsfilters. 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_typeorvariant_idsfilters.packages/katana-mo-cli/src/api/cachedKatana.ts(e.g.,collectAllInventoryMovements) that calls the API with onlylocation_id,created_at_min, andcreated_at_maxparameterscollectInventoryMovementsbut without the restrictive filtersTask 2: Update Cache Key Generation for Inventory Movements
Modify the parameter hashing behavior for inventory movements to exclude
variant_idsandresource_typefrom the cache key, ensuring all queries for the same location and date range share the same cache entry.packages/katana-mo-cli/src/cache/queryConfig.tsto define excluded parameters for inventory movements (similar to how date params are already excluded)generateParamsHashinpackages/katana-mo-cli/src/cache/cacheManager.tsto respect these query-type-specific exclusionslocation_idcontributes to the hash for inventory movements queries🤖 Prompt for AI agents
Phase 2: Implement Client-Side Filtering Layer
Add filtering capabilities to process the full cached dataset and extract records matching the requested
resource_typeandvariant_idsfilters.Task 1: Create Inventory Movement Filtering Utilities
Implement reusable filtering functions for inventory movement records that can filter by
resource_typeandvariant_ids.packages/katana-mo-cli/src/api/cachedKatana.ts(or a new utility file if preferred)filterByResourceTypes(movements, resourceTypes)to filter by allowed resource typesfilterByVariantIds(movements, variantIds)to filter by variant ID setTask 2: Integrate Full-Dataset Caching with Client-Side Filtering
Refactor
fetchConsumptionFromInventoryMovementsto use the full-dataset caching strategy with client-side filtering instead of the current per-parameter-combination caching.fetchConsumptionFromInventoryMovementsto fetch the complete dataset once via the cache managerresourceTypesandvariantIdsresourceTypesand variant ID chunks when caching is enabledcacheManageris not provided orbypassCacheis true🤖 Prompt for AI agents
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
cacheManagerparameter.assemblyConsumptioncall inpackages/katana-mo-cli/src/runPipeline.ts(around line 91-98) to include thecacheManagerparameterlongConsumptionfallback call inpackages/katana-mo-cli/src/runPipeline.ts(around line 107-114) to include thecacheManagerparameterfetchPurchasePipelineDatacalls (lines 290-312) which already correctly passcacheManagercacheManageris 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.
materialConsumptioncalls infetchPurchasePipelineData(lines 290-312) will share cached data withassemblyConsumptioncalls when they query overlapping date ranges and locationsresourceTypesarrays (e.g.,["ProductionIngredient"]vs["ProductionIngredient", "Production"]) will hit the same cache entryvariantIdsbenefit from the cached full dataset🤖 Prompt for AI agents
Research
The caching infrastructure is implemented in
packages/katana-mo-cli/src/cache/using SQLite for storage. TheCacheManagerclass provides range-based caching with intelligent gap detection. Currently, cache keys are generated by hashing all non-date parameters, which means differentresource_typeandvariant_idscombinations 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
💡 Iterate on the plan with:
@coderabbitai <feedback>💬 Have feedback or questions? Drop into our discord!
@coderabbitai since
variant_idswill very likely be different for different tool invocations wouldn't that mean that we essentially never get a cache hit?🧩 Analysis chain
@chris-kreidlThat's an excellent observation! Let me investigate the actual cache key generation logic to understand how this works.🏁 Script executed:
Length of output: 9249
🏁 Script executed:
Length of output: 8493
🏁 Script executed:
Length of output: 3767
🏁 Script executed:
Length of output: 5507
🏁 Script executed:
Length of output: 3412
@chris-kreidlYou'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_idresource_typeAdditionally,
variant_idsare 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:
Within a single run:
producibleVariantIdsandmaterialVariantIdszeroConsumptionVariantIdsmight re-query some of the same variantsDate-range extensions:
Retry/failure protection:
Identical re-runs:
When Cache Doesn't Help
variant_ids, resulting in cache missesThe 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:
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?
@coderabbitai My thought is that we drop the
resource_typeandvariant_idsparameters from our request and cache all inventory movements, and then parse out what we need client side. and since theinventory_movementsendpoint 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.I've updated the plan above based on your feedback. Ready to proceed when you are!