Skip to content

feat(tf): infracost finops cloud cost estimation and reporting - #97

Merged
dan-petty merged 5 commits into
release/v0.2.15from
feat/tf-infracost-finops-cloud-cost
Sep 10, 2026
Merged

dan-petty merged 5 commits into
release/v0.2.15from
feat/tf-infracost-finops-cloud-cost

Conversation

@dan-petty

Copy link
Copy Markdown
Owner

Summary

Closes #90

Implements OpenTofu / Terraform Infracost FinOps cloud cost estimation, diff analysis, and budget validation engine for workstation automation and CI pipelines.

Features & Architecture

  • Pydantic Models: Added TFCostResource and TFCostBreakdownResult in src/devops_cli/models/tf.py.
  • Infracost FinOps Engine: Implemented parse_infracost_breakdown, parse_infracost_diff, validate_cost_budget, run_infracost_breakdown, and run_infracost_diff in src/devops_cli/tf/cost.py. Includes offline deterministic mock mode (--mock) for environments without the Infracost binary or cloud API credentials.
  • Output Subsystem: Built format_tf_cost_table in src/devops_cli/output/formatters/tables.py conforming to project-wide TablePayload output invariants.
  • CLI Commands: Registered devops tf cost breakdown and devops tf cost diff subcommands with --json, --mock, and --max-monthly-cost budget threshold assertions (exiting code 1 if budget exceeded).
  • FastMCP Integration: Exposed tf_cost_estimate MCP tool in src/devops_cli/ai/mcp/server.py and exported JSON schemas.
  • Comprehensive Quality Gates: 100% test coverage on cost.py, passing all 10 CI quality gates.

Copilot AI lite review requested due to automatic review settings September 10, 2026 13:19
@dan-petty dan-petty added this to the v0.2.15 milestone Sep 10, 2026
@dan-petty dan-petty added type/feature Type feature: a new function status/in-review Status In Review: the pull request of the item is open scope/terraform OpenTofu modules and the infrastructure they declare labels Sep 10, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved issues remain in execution error handling, diff baseline support, budget and currency reporting, MCP resource coverage, and documentation synchronization.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds Terraform/OpenTofu Infracost cost estimation, diff reporting, budget validation, CLI commands, MCP integration, tests, and documentation.

Changes:

  • Added cost models, parsing, execution, mock mode, and budget checks.
  • Added tf cost breakdown/diff commands and cost table formatting.
  • Added the tf_cost_estimate MCP tool and related documentation.
File summaries
File Description
tests/test_tf_cost.py Cost engine, CLI, and budget validation tests
src/devops_cli/tf/cost.py Infracost execution, parsing, and validation
src/devops_cli/tf/__init__.py Terraform package marker
src/devops_cli/output/formatters/tables.py Cost table formatter
src/devops_cli/output/formatters/__init__.py Formatter exports
src/devops_cli/output/formatter.py Formatter integration
src/devops_cli/output/__init__.py Output exports
src/devops_cli/models/tf.py Cost result and resource models
src/devops_cli/commands/tf.py Terraform cost CLI commands
src/devops_cli/ai/mcp/server.py Cost estimation MCP tool
README.md CLI command documentation
docs/MCP_TOOLS.md MCP tool documentation
docs/commands/tf.md Terraform command documentation
docs/CLI_REFERENCE.md CLI reference updates
docs/agent/task.md Task tracking update
Review details

Suppressed comments (9)

docs/agent/task.md:965

  • This marks the FinOps engine complete while the canonical roadmap still lists Infracost FinOps Cloud Cost Engine as 📋 Scheduled (P1) at docs/ROADMAP.md:461. Update the roadmap status and detailed checklist as part of the claimed documentation synchronization to avoid contradictory project state.
- [x] Phase 50.16: Infracost FinOps Cloud Cost Engine (`devops tf cost`) (Closes #90)

src/devops_cli/commands/tf.py:686

  • The diff command serializes the result before applying validate_cost_budget, so its JSON output also reports budget_exceeded: false for a failing threshold. Apply the validation mutation before serializing/rendering to keep the JSON contract consistent with the non-zero exit.
    result = run_infracost_diff(target, offline_mock=mock)
    if json_output:
        write_stdout(result.model_dump_json(indent=2) + "\n")

src/devops_cli/commands/tf.py:653

  • This budget error message also hard-codes $ even though the parsed result can use another currency, so a non-USD budget failure is reported with the wrong unit. Use result.currency (or a validated symbol) consistently with the cost table.
            f"Monthly cost budget exceeded: ${result.total_monthly_cost:.2f} > ${max_monthly_cost:.2f}"

src/devops_cli/commands/tf.py:692

  • The diff budget failure message has the same incorrect hard-coded $ unit. Use the result currency so the assertion is understandable for non-USD Infracost output.
            f"Monthly cost budget exceeded: ${result.total_monthly_cost:.2f} > ${max_monthly_cost:.2f}"

src/devops_cli/output/formatters/tables.py:885

  • The parsed result preserves an arbitrary currency, but every resource, total, and diff amount is hard-coded with $. EUR/GBP estimates will therefore be displayed as dollar amounts, making the FinOps report financially misleading; format all amounts with the result currency code or a validated symbol.
                f"${res.hourly_cost:.2f}",
                f"${res.monthly_cost:.2f}",

src/devops_cli/tf/cost.py:153

  • This duplicates the implicit-mock failure mode from breakdown: a real tf cost diff invocation silently reports the fabricated $144/$36 diff whenever Infracost is absent. That makes CI cost regressions non-authoritative unless callers happen to know they must pass --mock; keep fallback behavior explicit and fail when the binary is unavailable.
    if offline_mock or not check_binary("infracost"):

src/devops_cli/tf/cost.py:185

  • The diff path has the same failure masking: any non-zero Infracost exit becomes an apparently successful zero-cost report with source="infracost_error". In CI this can hide a failed diff and incorrectly satisfy the budget gate; surface the subprocess failure through the command's exit status.
    if proc.returncode != 0:
        return TFCostBreakdownResult(
            directory=str(target_dir),
            currency="USD",
            source="infracost_error",
        )

src/devops_cli/tf/cost.py:96

  • When no threshold is supplied this returns without clearing budget_exceeded. Reusing a result after an over-budget check therefore serializes budget_exceeded: true even though the current validation has no budget; reset the flag before returning.
    if max_monthly_cost is None:
        return True

src/devops_cli/tf/cost.py:70

  • The diff parser has the same unhandled malformed-output path: invalid JSON or non-numeric total cost fields raise raw JSONDecodeError/ValueError instead of the repository's structured domain error. Normalize these failures before they reach the CLI or MCP tool.
    data = json.loads(json_data) if isinstance(json_data, str) else json_data
    currency = str(data.get("currency", "USD"))
    total_hourly = float(data.get("totalHourlyCost") or 0.0)
    total_monthly = float(data.get("totalMonthlyCost") or 0.0)

  • Files reviewed: 14/15 changed files
  • Comments generated: 6
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/devops_cli/tf/cost.py Resolved
Comment thread src/devops_cli/tf/cost.py Resolved
Comment thread src/devops_cli/ai/mcp/server.py Resolved
Comment thread src/devops_cli/commands/tf.py Resolved
Comment thread src/devops_cli/tf/cost.py Resolved
Comment thread src/devops_cli/tf/cost.py Resolved
- Enforce DependencyError when Infracost binary is missing in non-mock execution
- Raise typed SubprocessError on non-zero Infracost breakdown/diff subprocess exit
- Add ToolExecutionError error boundaries around breakdown and diff JSON deserialization
- Add --compare-to baseline option to run_infracost_diff and CLI command
- Validate budget thresholds before rendering and serializing JSON output
- Register dynamic MCP resource resource://tf/cost/latest
- Add comprehensive unit tests covering parsing, baseline diffs, and budget serialization
@dan-petty
dan-petty merged commit 8d3e26f into release/v0.2.15 Sep 10, 2026
4 checks passed
@dan-petty
dan-petty deleted the feat/tf-infracost-finops-cloud-cost branch September 10, 2026 19:08
dan-petty added a commit that referenced this pull request Sep 10, 2026
* fix(review): remediate security findings and enhance review feedback loop

- Remediate all 11 verified findings across security, sandbox isolation, and resource bounds:
  - CodeMode: Remove reflection primitives (getattr, hasattr, type) and sys module from safe_builtins to prevent sandbox escape
  - K8s: Remove hardcoded default password for Open-WebUI admin account, generating a cryptographically secure random token when omitted
  - SSH: Mask secrets in key rotation error messages and provide actionable connectivity guidance
  - Harness Memory: Enforce bounded LIMIT clause and cursor iteration on SQLite search queries
  - Pydantic AI Tools: Enforce unconditional path traversal validation across all tool parameters regardless of schema presence
  - Harness Compaction: Enforce bounded capacity and FIFO eviction for overflow fallback memory using OrderedDict
  - Pipeline Protocol: Sanitize stage exception messages using mask_secrets in StageExecutionRecord
  - Ollama Models: Add URL scheme validation and block link-local cloud metadata (169.254.169.254) in base_url
  - Ollama Client: Sanitize HTTP status and streaming error messages using mask_secrets
  - Valkey: Centralize and sanitize error messages across all Valkey CLI commands using mask_secrets
- Update DevSecOps review prompts, verification falsification rules, and task manuals for the closed-loop feedback loop
- Export verified findings into the continuous learning feedback dataset
- Bump version to 0.2.15 in pyproject.toml and package init
- Synchronize CLI documentation and README

Closes #87

* fix(review): address copilot feedback on sandbox isolation, credential masking, and query bounds

* feat(security): complete security scanner migration to BaseSecurityScanner and ScannerRegistry (#93)

* feat(security): complete security scanner migration to BaseSecurityScanner and ScannerRegistry

* fix(security): address review feedback on security scanner base migration

* refactor(core): eliminate obsolete shims, aliases, proxy wrappers, and backwards compatibility remnants (#95)

* refactor(core): eliminate obsolete shims, aliases, proxy wrappers, and backwards compatibility remnants

- Strip unicode icons and emojis from README bullets and markdown files
- Remove numeric counts, timestamps, and arbitrary identifiers from test names, variables, and documentation
- Remove legacy __getattr__ proxies, wrapper functions, and private aliases across commands and AI modules
- Replace private re-exports with canonical functions in security.sanitizer
- Extract clean GhCliClient and eliminate inner class shims in GitHub commands
- Clean up stopwatch timers and semantic schema variable identifiers
- Update all impacted tests and verify complete 10-gate CI suite

Closes #94

* fix(review): address copilot feedback on paginated json, adapter tests, and git boundary

- Add parse_paginated_json to handle concatenated multi-page JSON arrays from gh api --paginate in GhCliClient and gh commands
- Implement edit_milestone method on GhCliClient for full synchronizer compatibility
- Author focused unit tests for GhCliClient and parse_paginated_json in test_github_client.py
- Exercise real git repository boundary and gitignore filtering in test_review_runner.py

* refactor(pages,review): eliminate legacy config paths and harden secret redaction

* fix(review,security): decouple secret redaction and resolve CodeQL clear-text false positives

* feat(k8s): centralized kubernetes logging stack and LogQL integration (#96)

* feat(k8s): centralized kubernetes logging stack and LogQL integration

- Add declarative Loki and Fluent Bit manifests under k8s/logging with PSA labels and network isolation
- Register logging stack in deploy-stack and teardown-stack lifecycle
- Implement native LogQL query parser, line filter evaluator, and stream engine in k8s.logql
- Add OpenTelemetry trace_id extraction and trace correlation in LogQL entries and Grafana Loki datasource
- Support live follow and transparent fallback to kubectl logs in devops k8s logs
- Register FastMCP tools k8s_logs_query and k8s_logs_tail
- Author unit tests and verify 10-gate CI suite

Closes #89

* fix(k8s): remediate code review findings on centralized logging stack and logql integration

* feat(k8s): configure qdrant service with nodePort 31744 for direct host RAG access

* fix(k8s): resolve code review feedback on centralized logging stack and logql integration

* fix(k8s): confine rich markup escaping to output submodule and restore qdrant clusterip security perimeter

* feat(tf): infracost finops cloud cost estimation and reporting (#97)

* feat(tf): infracost finops cloud cost estimation and reporting

* fix(tf): address code review feedback on Infracost FinOps cost engine

- Enforce DependencyError when Infracost binary is missing in non-mock execution
- Raise typed SubprocessError on non-zero Infracost breakdown/diff subprocess exit
- Add ToolExecutionError error boundaries around breakdown and diff JSON deserialization
- Add --compare-to baseline option to run_infracost_diff and CLI command
- Validate budget thresholds before rendering and serializing JSON output
- Register dynamic MCP resource resource://tf/cost/latest
- Add comprehensive unit tests covering parsing, baseline diffs, and budget serialization

* feat(argo): multi-cluster argocd fleet synchronization and rollouts (#98)

* feat(argo): multi-cluster argocd fleet synchronization and rollouts

- Implement multi-cluster fleet coordination engine with bounded concurrency under devops argo fleet sync
- Add progressive delivery rollout controls (promote, abort, restart) wrapping kubectl argo rollouts
- Introduce automated metric-driven rollback gates evaluating Prometheus/LogQL error rates with auto-abort capability
- Add format_argo_fleet_sync_table and format_argo_rollout_analysis_table formatters
- Register argo_fleet_sync, argo_rollout_analyze FastMCP tools and resource://argo/fleet/status resource
- Add comprehensive test suite with 98%+ code coverage adhering to strict architectural invariants

* fix(argo): address review feedback on fleet sync and rollouts

* perf(ci): optimize caching configuration across all github workflows (#100)

* perf(ci): optimize caching configuration across all github workflows

* fix(ci): bound tooling cache key and enforce exact devcontainer cacheFrom assertion

* refactor(agent): modularize task tracking to eliminate merge conflicts

- Decompose monolithic docs/agent/task.md into isolated per-task tracking files under docs/agent/tasks/ (task-<issue>-<slug>.md)
- Update GitHub Projects v2 parser (src/devops_cli/github/projects.py) to recursively scan and parse docs/agent/tasks/ by default while excluding archives and READMEs
- Decompose parser functions to enforce cyclomatic complexity <= 10 and nesting depth <= 5
- Archive historical phases 1-50 in docs/agent/archive/historical-phases-1-to-50.md
- Replace docs/agent/task.md with a lean index table pointing to modular task files
- Update AGENTS.md, ROUTINE_TASKS.md, and Knowledge Base Task Manual 13 with the modular task architecture and commit context mandate
- Author comprehensive unit tests in tests/test_github_projects.py

Closes #101

* feat(ai): strengthen target-agnostic review prompts and feedback dataset synchronization

* feat(ai): generalize devops ai review for target-agnostic evaluation and multi-convention discovery

* fix(telemetry): optimize jaeger memory sizing, exception span hygiene, and embedding fast failover

- Update k8s/otel/jaeger.yaml to configure MEMORY_MAX_TRACES to 10000 and scale memory limits to 1024Mi to eliminate OOMKills
- Refactor telemetry tracer span exception handling to avoid attaching stack traces to handled CLI exits (typer.Exit)
- Add DEFAULT_RAG_EMBEDDING_TIMEOUT (15.0s) and rapid 2.0s connect timeouts for fast Ollama multi-node failover
- Author comprehensive unit tests in tests/test_telemetry.py and tests/test_rag_embeddings.py
- Ground and deliver GitHub task 104 in docs/agent/tasks/task-104-telemetry-trace-optimizations.md (Closes #104)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope/terraform OpenTofu modules and the infrastructure they declare status/in-review Status In Review: the pull request of the item is open type/feature Type feature: a new function

Projects

No open projects

Development

Successfully merging this pull request may close these issues.

2 participants