Retrieved data is not cached #7
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#7
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 do not cache responses from Katana.
Intrasession caching would be a nice start but we could go even further and implement a sqlite database to store responses. This is obviously a much more complex refactor.
@coderabbitai plan
Coding Plan
Summary
Design Choices
Design Choice 1: Where to implement caching (katana-client vs CLI)?
Options Considered:
katana-clientpackage (shared by all consumers)katana-mo-clionly (CLI-specific wrapper layer)Chosen Option: 2
Rationale: Implement caching in the CLI package only. The katana-client should remain a stateless API client, and the MCP server has different lifecycle requirements (stateless per-call). Caching the CLI wrapper layer targets the specific use case mentioned in the ticket.
Design Choice 2: Cache storage location strategy
Options Considered:
.cache/in working directory)~/.cache/katana-mo/)Chosen Option: 3
Rationale: Use XDG-compliant default (
~/.cache/katana-mo/cache.db) with environment variable override (KATANA_CACHE_DIR). This follows standard conventions and keeps cache data separate from project files while remaining configurable.Design Choice 3: Primary caching strategy for date-ranged queries
Options Considered:
Chosen Option: 2
Rationale: Incremental range caching as the primary architecture. Historical records (sales order rows, inventory movements) are immutable once created—a record from 30 days ago will never change. By tracking which date ranges are already cached, we only fetch truly new data (records created since last run). This reduces a 90-day lookback from ~140 pages to ~4-7 pages after initial load.
💡 User Tips
Regenerate the plan with different choices with
@coderabbitai <feedback>.Implementation Steps
Phase 1: Range-Based Cache Infrastructure
Build the foundational caching system centered on incremental range tracking. The core concept: track which date ranges have been cached for each query type, detect gaps when new queries arrive, and only fetch missing portions. Historical records are immutable, so once cached, they don't need re-fetching.
Task 1: Create SQLite Cache Storage Layer
Implement persistent storage using Bun's native SQLite module. This stores both the cached records and metadata about what date ranges are covered.
packages/katana-mo-cli/src/cache/sqliteCache.tsimplementing aSqliteCacheclasscached_records:id(INTEGER PRIMARY KEY from API),query_type(TEXT),data(TEXT/JSON),created_at_api(INTEGER - the record's created_at from Katana),cached_at(INTEGER)cached_ranges:query_type(TEXT),params_hash(TEXT for non-date params),range_start(INTEGER timestamp),range_end(INTEGER timestamp),cached_at(INTEGER), PRIMARY KEY (query_type,params_hash,range_start)cached_records(query_type, created_at_api)for range queries,cached_ranges(query_type, params_hash)for range lookups~/.cache/katana-mo/cache.dborKATANA_CACHE_DIRenv var)Task 2: Implement Date Range Gap Detection
Build logic to calculate which portions of a requested date range are missing from cache, enabling minimal API fetches.
packages/katana-mo-cli/src/cache/rangeUtils.tswith range calculation utilitiesfindUncachedRanges(requestedStart, requestedEnd, cachedRanges[]): given a target range and list of cached ranges, return array of gap ranges that need fetchingmergeOverlappingRanges(ranges[]): consolidate adjacent/overlapping ranges into minimal setrange_endby 0-2 hours randomly to prevent synchronized expiration across queriesTask 3: Implement Record Deduplication and Storage
Build the record storage layer that handles deduplication by ID and efficient range-based retrieval.
packages/katana-mo-cli/src/cache/recordStore.tsimplementing aRecordStoreclassstoreRecords(queryType, records[], rangeStart, rangeEnd): upsert records by API ID (deduplicate), then record the cached range incached_rangestablegetRecordsInRange(queryType, paramsHash, start, end): retrieve all cached records within date rangecreated_at, not by cached range)getCachedRanges(queryType, paramsHash): return all cached range metadata for gap detectionclearByQueryType(queryType)andclearAll()for cache invalidationTask 4: Create Cache Manager for Range Queries
Build the coordinating layer that orchestrates gap detection, partial fetching, and result merging.
packages/katana-mo-cli/src/cache/cacheManager.tsimplementing aCacheManagerclassgetCachedOrFetch(queryType, params, fetchFn)with this flow:created_at_min,created_at_max)findUncachedRanges()fetchFnwith modified date params, store resultsgenerateParamsHash(params): exclude date params, sort remaining keys, create deterministic hashcreateCacheManager(options)that initializes all layersTask 5: Define Query Type Configuration
Establish which endpoints use range caching and configure their behaviors.
packages/katana-mo-cli/src/cache/queryConfig.tswith configuration per query typesalesOrderRows: primary demand data, 90-day lookback, ~100+ pages typicalinventoryMovements: consumption analysis, 90-365 day lookback, ~40+ pages typicalisRangeCacheable(queryType)andgetDateParamNames(queryType)helpers🤖 Prompt for AI agents
Phase 2: CLI Integration
Integrate the range caching infrastructure into the CLI's existing API wrapper layer. This phase modifies date-ranged queries to utilize incremental fetching and provides cache management utilities.
Task 1: Create Cached API Wrapper for Range Queries
Wrap the date-ranged API functions to leverage incremental range caching, fetching only missing data.
packages/katana-mo-cli/src/api/cachedKatana.tswith cached versions of range-queryable functionsfetchHistoricalDemand()(sales order rows with 90-day lookback):CacheManager.getCachedOrFetch()with query type and paramsfetchConsumptionFromInventoryMovements()(inventory movements with 90/365-day lookback):fetchHistoricalDemandForVariants()(per-variant sales order rows):bypassCacheparameter to force fresh fetch when neededTask 2: Update Pipeline Data Fetching to Use Cached Functions
Modify the pipeline orchestration to use cached API wrappers for date-ranged queries.
packages/katana-mo-cli/src/runPipeline.tsto import cached versions fromcachedKatana.tsfetchPipelineData(): use cachedfetchHistoricalDemand,fetchConsumptionFromInventoryMovementsfetchSoPipelineData(): use cachedfetchHistoricalDemandForVariantsfetchPurchasePipelineData(): use cached consumption and demand functionsTask 3: Add Cache Invalidation for Write Operations
Ensure cache consistency when the CLI creates new manufacturing or purchase orders.
packages/katana-mo-cli/src/api/cachedKatana.ts, wrap the create functions (createManufacturingOrder,createPurchaseOrder)createManufacturingOrder: invalidate manufacturing orders cache, inventory cache (MO affects committed quantities)createPurchaseOrder: invalidate purchase orders cache, inventory cache (PO affects expected quantities)CacheManager.invalidateByEntityType()for targeted invalidationTask 4: Add Cache Management CLI Flag and Configuration
Provide a simple mechanism for users to clear the cache and configure cache behavior.
--clear-cacheCLI flag inpackages/katana-mo-cli/src/index.tsthat clears all cached data before runningpackages/katana-mo-cli/src/config.tsto add cache-related constants and environment variable reading:KATANA_CACHE_DIR: override default cache directoryKATANA_CACHE_ENABLED: boolean to disable caching entirely (default: true)SettingsConfigtype inpackages/katana-mo-cli/src/types.tsto include cache settingsKATANA_CACHE_ENABLED🤖 Prompt for AI agents
Research
The monorepo contains three relevant packages:
katana-client(pure API client with rate limiting and retry logic),katana-mcp(MCP server for AI tools), andkatana-mo-cli(CLI for manufacturing/purchase order planning). The CLI uses wrapper functions insrc/api/katana.tsthat orchestrate multiple API calls for planning operations, primarily using date-ranged queries (created_at_min/max) for historical demand analysis (90-day lookback) and consumption tracking (90-day/365-day lookback). Currently, no caching exists—each run fetches all pages fresh. The key insight is that historical records (sales order rows, inventory movements) are immutable once created, making incremental range caching highly effective.🚀 Next Steps
🤖 All AI agent prompts combined
💡 Iterate on the plan with:
@coderabbitai <feedback>💬 Have feedback or questions? Drop into our discord!
@coderabbitai is it more idiomatic to incorporate this sort of caching into the CLI or would it be better suited towards being implemented within our KatanaClient package? Or is there any benefit to the caching layer being its own package?
@chris-kreidlGreat architectural question! Let me break down the tradeoffs between these approaches:Three Approaches Analyzed
1. CLI-Level Caching (Current Plan)
Pros:
katana-clientas a clean, stateless HTTP client focused on API communication, rate limiting, and retry logicCons:
2. KatanaClient-Level Caching
Pros:
Cons:
3. Separate Package (
@katana/cacheor similar)Pros:
Cons:
Recommendation
The current plan's choice (CLI-level) is most idiomatic for your situation because:
Different lifecycle requirements: The CLI runs long-lived planning sessions where cross-session cache persistence (SQLite) makes sense. The MCP server is stateless per-call—caching would need to be purely in-memory if used at all.
Specialized cache policies: The CLI's TTL strategy (24h for products, 30min for inventory) is specific to manufacturing planning use cases and shouldn't be imposed on all consumers.
YAGNI principle: Until the MCP server or another consumer demonstrates a need for caching, implementing it at the client level is premature optimization.
However, if you find yourself implementing caching in a second package (e.g., MCP server later needs in-memory caching), then refactor to a separate package at that point. This follows the "rule of three" for refactoring—don't abstract until you have at least two concrete implementations.
Would you like me to adjust the plan to use a different approach, or does this clarification help validate the current design choice?
🧠 Learnings used
@coderabbitai We'll proceed with CLI-level caching. I'll ask you to revisit this after another project is finished as I'm sure some of the specifics will have changed.
@chris-kreidlPerfect! I've confirmed the approach is well-suited for your codebase architecture. When you're ready to revisit this after your other project wraps up, just tag me and I'll be happy to refresh the plan based on any changes in your codebase or requirements.The foundational design decisions should remain solid regardless—CLI-level caching keeps your concerns properly separated and avoids forcing cache lifecycle management on the MCP server.
Looking forward to helping implement this when the time comes! 🚀
🧠 Learnings used
@coderabbitai Please refresh the plan, the other work I mentioned is completed and merged.
I've updated the plan above based on your feedback. Ready to proceed when you are!
@coderabbitai i'm looking back at the revised plan before we begin implementation and i'm curious how we actually would incorporate cached data into our data retrieval API. if i'm not mistaken, most of our data retrieval from Katana is based on date spans rather than individual record IDs.
🧩 Analysis chain
🏁 Script executed:
Length of output: 24511
🏁 Script executed:
Length of output: 12245
🏁 Script executed:
Length of output: 6161
🏁 Script executed:
Length of output: 24640
@chris-kreidlGreat observation! You're absolutely right that date-span queries present a caching challenge. Let me break down what the current plan would do and propose a refined approach:How Caching Works With Your Current API Patterns
After examining your code, here's what I found:
Queries Without Date Filters (80%+ of calls) ✅ Cache Effectively
These will cache perfectly with the current plan:
listAllProducts- filtered by flags likeis_producible,is_purchasablelistSuppliers- no date filterslistInventoryForVariants- current snapshot by variant IDslistBomRowsForVariants- no date filterslistOpenManufacturingOrderVariants- filtered by statuslistOpenSalesOrders- filtered byproduct_availabilityCache keys for these would be like:
listAllProducts:{"is_producible":true,"include_deleted":false}listInventoryForVariants:{"variant_ids":[123,456],"location_id":1}Date-Span Queries (The Challenge) ⚠️
These three functions use
created_at_min/created_at_max:fetchHistoricalDemand- sales order rows over lookback periodfetchHistoricalDemandForVariants- sales order rows for specific variantsfetchConsumptionFromInventoryMovements- inventory movements over lookback periodCurrent behavior: Each run generates new dates → new cache key → cache miss
Proposed Solution: Pragmatic Hybrid Approach
Given your CLI's usage patterns, here's what I recommend:
Option 1: Rolling Window Cache Keys (Recommended)
Instead of caching by exact dates, normalize to configuration-based windows:
Benefits:
Tradeoffs:
Option 2: Accept Per-Query Caching (Simplest)
Keep the current plan as-is and accept that date-span queries generate unique cache keys.
Benefits:
When this works well:
Option 3: Selective Caching
Don't cache the date-span queries at all—only cache reference data.
My Recommendation
Start with Option 1 (Rolling Window) because:
Implementation Adjustment
I'd modify the plan's cache key generation to detect date-range parameters:
Would you like me to update the implementation plan with this rolling-window approach for date-span queries, or would you prefer one of the other options?
@coderabbitai to the contrary, reference data fetches (products, BOMs) are the quick ones -- these only have a few pages worth of results each. it's the historical data (sales order rows, inventory movements) that are the bottleneck. as an example: our sales order row fetch, when calculating "general manufacturing orders", can itself be over 140 pages.
@chris-kreidlThank you for that crucial clarification! That completely flips the priority. If historical data fetches are 140+ pages while reference data is only a few pages, then caching the date-span queries becomes the critical performance optimization, not just a nice-to-have.Updated Analysis
With this new information, here's the corrected picture:
The Real Bottleneck (140+ pages) 🔥
fetchHistoricalDemand- sales order rowsfetchHistoricalDemandForVariants- sales order rows for variantsfetchConsumptionFromInventoryMovements- inventory movementsThese are exactly the ones with
created_at_min/created_at_maxdate spans that need smart caching.Fast Reference Data (few pages) ⚡
Strong Recommendation: Rolling Window (Option 1)
Given this bottleneck, Option 1 (Rolling Window) becomes essential:
Why this solves your bottleneck:
If you run the CLI 3-5 times per day during planning sessions, this gives you:
Future Enhancement: Incremental Caching
For even better performance long-term, consider partition-based caching:
Benefits:
Complexity:
I'd suggest starting with rolling window caching to get immediate 3-5x improvement, then consider incremental caching if you need further optimization.
Proposed Plan Update
I'll update Phase 1, Task 3 to include rolling-window logic for date-span queries:
Cache Manager changes:
created_at_min/created_at_maxparameters${endpoint}:date_window:${today}:${lookbackDays}d:...This targets the 140-page bottleneck while keeping implementation simple.
Should I update the plan with this rolling-window approach, or would you like to explore the incremental caching option right away?
@coderabbitai what i had envisioned, and please correct me if this is what you've already suggested, is that when the cache manager receives a request it hits the cache for the nearest date min/max entries, and fetches any records that fall outside what the cache claims to contain.
@chris-kreidlYes! What you're describing is exactly the incremental/partition-based caching I mentioned as a "future enhancement"—but your vision is much clearer than how I explained it. And given the 140-page bottleneck, this should be the primary strategy, not a future optimization.Your Approach (Incremental Range Caching)
You're describing a smart range-query cache:
Result: After initial cache population, daily queries fetch ~4-7 pages instead of 140 pages (20-35x improvement).
Implementation Complexity
This is more sophisticated than rolling-window caching, but the benefits justify it for your 140-page bottleneck. Here's what it requires:
Cache Entry Structure
Core Logic Changes
1. Range Overlap Detection
2. Gap Calculation
3. Merge Strategy
4. Cache Update
Challenges
Recommendation
Your approach is absolutely the right one for the 140-page bottleneck. Here's what I'd suggest:
Phase 1: Implement Basic Incremental Caching
Phase 2: Add Optimizations
Implementation Priority
Given the 140-page problem, I'd recommend:
Updated Plan Structure
I can revise the implementation plan to:
Would you like me to rewrite the plan with incremental range caching as the core architecture? This is the right approach for your use case—I should have recommended it more strongly from the start given your 140-page bottleneck.
@coderabbitai please rewrite the plan to use incremental range caching. i assume we'd incorporate some jitter into the fetched range, and we should be able to dedupe by looking at retrieved record IDs
I've updated the plan above based on your feedback. Ready to proceed when you are!