omi
omi copied to clipboard
[Bounty proposal] fix(database): sanitize plan_key attribution and guard hourly usage increments ( proposed)
Summary
Hardens ackend/database/hourly_usage_updates.py::prepare_hourly_usage_updates against map hierarchy corruption, timezone partition skew, and non-positive/non-finite usage rollups.
Problem Analysis
- Dotted plan_key Breaks Nested Field Structure: est_usage_fields expands dotted field paths into nested dictionaries for set(merge=True). Its documentation explicitly specifies that plan keys must be sanitized of . before interpolation. Because prepare_hourly_usage_updates interpolates raw plan_key directly into 'plan_usage.{plan_key}', any plan key with a dot (e.g. pro.monthly, ier.1, or Stripe subscription product keys) gets split by path.split('.'). This creates an invalid nested dict (e.g. plan_usage.pro.monthly) rather than the expected single-level plan_usage[plan_id] mapping, causing downstream readers like get_plan_usage_report to skip the counters and report empty usage.
- Timezone Partition Skew: When date has a non-UTC timezone, date.year, date.month, date.day, and date.hour are evaluated in the local offset while last_updated is UTC, skewing the document ID and hourly aggregation partitions.
- Missing Type & Finite Clamping on Increments: alue > 0 allows boolean values (isinstance(True, int) == True) to increment counters, and raises an unhandled TypeError if non-numeric values like strings are passed in updates.
- Unguarded cost_usd: cost_usd was passed directly to irestore.Increment(cost_usd) without checking for negative values or NaN/Inf floats, creating potential FinOps billing corruption.
Proposed Solution
- Sanitize plan_key using standard Firestore-safe segment replacement (., /, ~, *, [, ], ` -> _), defaulting empty/whitespace strings to _unattributed.
- Normalize timezone-aware date instances to UTC before computing doc_id and partition fields.
- Type-guard metric increment values with is_valid_positive_increment (rejecting booleans, strings, and non-positive/non-finite values).
- Validate and clamp cost_usd to non-negative finite floats.
- Add comprehensive unit tests in ackend/tests/unit/test_hourly_usage_updates.py.
Proposed bounty:
Thanks for putting this together. We aren't doing bounties at the moment, so we're closing the bounty proposal issues for now — thanks for the fix! 🙏