# Cloud Cost Allocation Gap Finder (`afkdigital/newapi93-cloud-cost-allocation-gap-finder`) Actor

Analyze FOCUS CSV allocation gaps, missing tags and rule conflicts. Exact shared-cost splits and per-currency cost-center reconciliation.

- **URL**: https://apify.com/afkdigital/newapi93-cloud-cost-allocation-gap-finder.md
- **Developed by:** [AFK Digital](https://apify.com/afkdigital) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / billing-period analysis

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Cloud Cost Allocation Gap Finder

Audit customer-supplied FOCUS cloud cost CSV files for unallocated spend, missing ownership tags, overlapping allocation rules and shared-cost allocation. No AWS, Azure, GCP or other cloud-account credentials are needed.

### Scope and supported FOCUS versions

Version 0.1.0 accepts the **Cost and Usage CSV common subset of FOCUS 1.0, 1.1, 1.2, 1.3 and 1.4**. Official specifications were checked on 2026-11-12:

- https://focus.finops.org/docs/specification/v1-0/
- https://focus.finops.org/docs/specification/v1-1/
- https://focus.finops.org/docs/specification/v1-2/
- https://focus.finops.org/docs/specification/v1-3/
- https://focus.finops.org/docs/specification/v1-4/
- https://focus.finops.org/docs/specification/v1-4/columns/

This is an allocation audit, **not a full FOCUS conformance validator or certification**. It does not analyze the Contract Commitment, Invoice Detail or Billing Period supplemental datasets. Newer columns may be used as exact-match selectors, but do not activate additional version-specific accounting logic. FOCUS 0.5, preview releases and unverified future versions are rejected. Provider-generated allocation (AllocatedMethodId in 1.3+) blocks a second shared split; the row is flagged for review. Original ResourceId and Tags are retained as the matching context; AllocatedResourceId/AllocatedTags are not automatically substituted.

Required columns: BillingAccountId, ServiceName, BillingCurrency, BillingPeriodStart, BillingPeriodEnd, ChargeCategory and the chosen cost basis. ResourceId may be absent or blank without error. Tags is optional; missing/blank means an empty map. Nonempty Tags must be a JSON object mapping strings to strings or null. UTF-8 CSV, comma delimiter, header names case-sensitive; duplicate headers or malformed rows fail.

### Upload your file

1. In Apify Console, create a **private key-value store** in the account running the Actor.
2. Upload your UTF-8 CSV as a raw record with key BILLING_CSV (text/csv or application/octet-stream). The key must contain letters, digits, underscore or hyphen.
3. Set billingFile to {"storeId":"YOUR_STORE_ID","key":"BILLING_CSV"}. Only that Apify store is accessed using the run's existing storage permission; arbitrary URLs and filesystem paths are not accepted.
4. Select the matching **billingStoreId** storage picker to grant this run read-only access to that uploaded store. No full-account permission is requested.
5. Select focusVersion and costBasis, and supply your own rules. Use one file and one billing period per run.

Small files may use {"csvText":"CSV CONTENT"} up to 1 MiB. {"demo":true} loads a bundled, entirely synthetic example. The example rules and cost centers are fictional, not ownership recommendations.

### Inputs

| Field | Meaning |
|---|---|
| billingFile | Private Apify storeId/key reference, csvText, or demo |
| billingStoreId | Select the same private store to authorize read access for uploaded CSV |
| focusVersion | 1.0, 1.1, 1.2, 1.3 or 1.4 |
| allocationRules | Object with rules array and optional requiredTags array |
| costBasis | Exactly one of BilledCost, EffectiveCost, ListCost, ContractedCost |
| sharedCostRules | Explicit weighted target rules |
| billingPeriod | Optional {start,end} timezone-aware timestamps |
| maxRows | 1–100,000; hard failure rather than truncation |

With billingPeriod omitted, the first row establishes the period. Every other row must have the same start/end instants. An explicitly supplied period must match all rows exactly. No implicit filtering, proration or multiple-period merging occurs. The displayed period preserves the supplied timestamps.

### Rules and priority

See examples/demo-input.json for a complete example.
allocationRules:
{
"requiredTags": \["owner","cost_center"],
"rules": \[
{"id":"product-a","priority":10,"match":{"Tags.owner":"team-a"},"costCenter":"PRODUCT-A"},
{"id":"explicit-tag","priority":20,"match":{},"costCenterTag":"cost_center"}
]
}

Matches use exact, case-sensitive strings. All match fields are ANDed; an empty match object matches every row. Tags.owner accesses the JSON Tags field. Other keys select CSV columns. A missing referenced CSV column fails validation. Missing tags do not match an equality condition.

All direct and shared rules compete together. **Lower integer priority wins.** All matching rule IDs are reported. More than one match is flagged even when priority resolves it. If multiple rules share the winning priority, the row remains unallocated with conflict_unresolved, regardless of whether their targets happen to agree. Input order never breaks a tie. No matching rule means unallocated. Missing costCenterTag leaves the row unallocated. No ownership is inferred from resource names, account IDs or services.

sharedCostRules:
\[
{"id":"shared-network","priority":1,"match":{"ServiceName":"Network"},
"targets":\[{"costCenter":"PRODUCT-A","weight":"2"},{"costCenter":"PRODUCT-B","weight":"1"}]}
]

Targets require unique cost centers and positive plain-decimal weights. They need not sum to 1. Shared splits use supplied ratios, truncate toward zero at the greater of source precision and two decimal places, and assign the exact signed residual to the last listed target. No source precision is discarded; every row and currency total reconciles exactly.

requiredTags is the explicit tag-presence policy. Missing keys, null and empty string values are reported. Missing tags may coexist with a valid allocation: allocation_status describes rule resolution; missing_tags and review_reasons describe additional review needs.

### Accounting

Only the selected source column is used. BilledCost, EffectiveCost, ListCost and ContractedCost are never added together or substituted. Pricing-currency metrics are not supported. BillingCurrency remains separate throughout; there is no currency conversion or global mixed-currency total.

Signed source credits, refunds, adjustments and discounts use the same explicit matching/priority rules. ChargeCategory can be included in match. Negative source values remain negative; the Actor does not manufacture credits or subtract discounts already embedded in the selected source cost. Commitment purchases and usage are not re-derived. Select EffectiveCost when appropriate for your intended amortized allocation; this Actor does not reconcile invoices or decide which basis your accounting policy requires.

Money is returned as a decimal **string** to preserve precision. Inputs accept up to 18 integer and 12 fractional digits, no exponent notation, NaN, Infinity or locale currency separators. Internal Decimal precision is 80 digits.

### Outputs

Default Dataset contains JSON records with billing_account, resource_id, service, cost_center, allocation_status, matched_rule, cost_amount, cost_basis, currency, evidence_rows, plus matched_rules, missing_tags, review_reasons and charge_category. evidence_rows is the 1-based CSV logical record index including the header, not a raw physical line for multiline fields.

Key-value store records:

- ALLOCATIONS.csv: formula-safe CSV export.
- ALLOCATIONS.jsonl: streaming JSON records.
- COST-CENTERS.csv: grouped by currency, center and allocation status.
- SUMMARY: cost center totals, status counts, limits and per-currency source/allocation reconciliation.
- RUN-STATUS: complete=true only after all exports finish.

Default Dataset can also be exported as CSV through Apify. For spreadsheet use, prefer ALLOCATIONS.csv: textual dimensions beginning with formula characters are prefixed with an apostrophe. Numeric cost strings retain their sign. Exact unmodified dimension values remain in JSON.

Use outputs only from a SUCCEEDED run with RUN-STATUS.complete=true and conserved=true for every currency. An export failure can leave partial Dataset items; discard them.

### Limits and privacy

One CSV <=25 MiB, <=100,000 source records, <=100 combined rules, <=10 shared targets per rule, <=200,000 output allocations, <=5,000 summary groups and <=250 MiB JSONL. Inline CSV <=1 MiB; CSV fields <=128 KiB. Default 512 MiB RAM, 300-second platform timeout, 240-second processing deadline and 285-second application deadline. The CSV, exports and source validation are streamed or spooled to ephemeral disk; Dataset pushes are capped at 500 records and approximately 1 MiB serialized data per batch (an individual larger record is sent alone).

The limits are hard caps, not a guarantee that every possible rule/record combination finishes within the deadline. Large shared expansions may hit the output limit before the source-row limit. No proxy or external enrichment is used. No account/resource values, source rows or authentication tokens are intentionally written to Actor logs; outputs deliberately contain customer evidence. Private Apify storage access and retention are controlled by your account settings. Do not publish customer inputs or run outputs.

### Pricing

Charge event: billing-period-analysis, **USD 2.00 per successfully completed analysis**, including runtime usage. One unit covers one file, one billing period and one selected basis, subject to the limits above. Dataset items and shared split rows do not create extra events. The owner approved USD 2.00 per completed analysis and paid publication on 2026-11-12. Failed validation never reaches the charge call. Post-run storage access can incur Apify's standard charges.

Apify pricing sources checked 2026-11-12:
https://docs.apify.com/actors/monetize
https://docs.apify.com/actors/monetize/pricing-and-costs
https://docs.apify.com/actors/monetize/set-up-monetization
https://apify.com/pricing
Apify commission is 20%; seller proceeds before platform usage are $1.60 per $2 analysis. Actual run costs are recorded in the release report. No savings or revenue is promised.

### Development

docker run --rm newapi93:0.1.0 python -m unittest discover -s tests -v
docker build -t newapi93:0.1.0 .

### Measured validation

22 automated tests passed in Docker and Apify build. Synthetic demo: 6 input rows, 7 allocations, 2.828 seconds, $0.000472 platform usage. Uploaded CSV: passed with limited-permission read picker. 100,000-row / 15.5 MB CSV: 36.722 seconds, 126.51 MiB peak Actor memory, $0.514553 platform usage; source and allocation totals reconcile exactly. These are measured examples, not a guarantee for every input.

# Actor input Schema

## `billingFile` (type: `object`):

Upload CSV to your private Apify key-value store, then enter {"storeId":"...","key":"BILLING_CSV"}. Or use {"csvText":"..."} (1 MiB) or {"demo":true}. No cloud account access.

## `focusVersion` (type: `string`):

Cost and Usage common allocation subset only; not conformance certification.

## `allocationRules` (type: `object`):

{requiredTags:\[],rules:\[{id,priority,match,costCenter OR costCenterTag}]}. Exact case-sensitive match; Tags.key accesses JSON tags. Lower priority wins; equal-priority ties unresolved.

## `costBasis` (type: `string`):

One basis per run. No fallback, summing bases, or exchange-rate conversion.

## `sharedCostRules` (type: `array`):

\[{id,priority,match,targets:\[{costCenter,weight:"1"}]}]. Competes with allocation rules by priority. Max 10 targets. Existing provider allocation prevents a second split.

## `billingPeriod` (type: `object`):

Optional {start,end} timezone-aware timestamps. All source rows must match exactly. If omitted, one period is detected; mixed periods fail.

## `maxRows` (type: `integer`):

Hard cap; oversized files fail, never truncate. One file <=25 MiB per billing-period analysis.

## `billingStoreId` (type: `string`):

For uploaded files select the same private store as billingFile.storeId. Grants this run read-only access; no full account permission required.

## Actor input object example

```json
{
  "billingFile": {
    "demo": true
  },
  "focusVersion": "1.2",
  "allocationRules": {
    "requiredTags": [
      "owner",
      "cost_center"
    ],
    "rules": []
  },
  "costBasis": "BilledCost",
  "sharedCostRules": [],
  "maxRows": 100000
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

## `csv` (type: `string`):

No description

## `summary` (type: `string`):

No description

## `centers` (type: `string`):

No description

## `status` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "billingFile": {
        "demo": true
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("afkdigital/newapi93-cloud-cost-allocation-gap-finder").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "billingFile": { "demo": True } }

# Run the Actor and wait for it to finish
run = client.actor("afkdigital/newapi93-cloud-cost-allocation-gap-finder").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "billingFile": {
    "demo": true
  }
}' |
apify call afkdigital/newapi93-cloud-cost-allocation-gap-finder --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,afkdigital/newapi93-cloud-cost-allocation-gap-finder"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/U3DMhi2dopr90DhRr/builds/0Z06EG0c7S2gjOXI0/openapi.json
