Skip to main content
CoreSDK
Guides

Runtime Coverage & Dead Code Detection

Use CoreSDK's trace-based coverage mode to find functions that are never called during integration testing — across any language, without static analysis.

Phase 2 feature. Coverage mode (core coverage report, multi-language manifests) is not yet available. The @trace decorator for Python is available in Phase 1b. The CLI coverage commands ship in Phase 2.

Runtime Coverage & Dead Code Detection

Static analysis tools (ts-prune, vulture, deadcode) find functions that are never referenced in source. CoreSDK's coverage mode finds functions that are never executed — a stronger signal, especially after integration testing, because it reflects real call paths rather than import graphs.

Rust API

CoverageCollector and CoverageSpanProcessor

Coverage mode is implemented as an OTel SpanProcessor. When CORESDK_COVERAGE_MODE=enabled, the SDK registers CoverageSpanProcessor in the pipeline:

use coresdk_coverage::{CoverageCollector, CoverageSpanProcessor, CoverageReport};

// Build the collector (shared state across all spans)
let collector = CoverageCollector::new();

// Register as a SpanProcessor — receives every span on end
let processor = CoverageSpanProcessor::new(collector.clone());
sdk.register_span_processor(processor);

// After your test suite runs, extract the report
let report: CoverageReport = collector.report();

// Print JSON summary
println!("{}", report.as_json()?);

CoverageSpanProcessor records the coresdk.coverage.function_id span attribute on every span. Functions annotated with @trace / #[trace] set this attribute automatically. The attribute value is a stable hash of (intent, file, line) — the same function emits the same ID across runs.

CoverageReport

// CoverageReport fields:
// report.total          — number of declared functions
// report.called         — functions seen at least once in the trace stream
// report.never_called   — Vec<FunctionInfo> for unreached functions
// report.coverage_pct   — f64, 0.0–100.0

let json = report.as_json()?;
// → { "total": 47, "called": 39, "never_called": [...], "coverage_pct": 83.0 }

Enabling via environment variable

CORESDK_COVERAGE_MODE=enabled pytest tests/integration/

When CORESDK_COVERAGE_MODE is unset or set to disabled, the CoverageSpanProcessor is not registered and there is zero runtime overhead.


How it works

Every function annotated with @trace emits an OTel span when it runs. Coverage mode collects the full set of declared intents, runs your test suite, and diffs what was declared against what was actually seen in the trace stream.

Annotate functions with @trace(intent="...")

Run integration tests with CORESDK_COVERAGE=true

CoreSDK records every span emitted (intent + file + line)

core coverage report

  Called:       39 / 47  (83%)
  Never called:  8 / 47  (17%)
    apply_refund          payments/service.py:142
    cancel_subscription   billing/service.py:87
    export_csv            reports/service.py:203
    ...

Step 1 — Annotate your functions

Add @trace to every function you want tracked. Use the intent string to describe what the function does, not how.

from coresdk.tracing.decorator import trace

@trace(intent="process payment")
async def process_payment(order: Order) -> Receipt: ...

@trace(intent="apply refund")
async def apply_refund(order_id: str) -> None: ...

@trace(intent="export orders as csv")
async def export_csv(tenant_id: str) -> bytes: ...
import { trace } from "@coresdk/sdk";

class PaymentService {
  @trace({ intent: "process payment" })
  async processPayment(order: Order): Promise<Receipt> { ... }

  @trace({ intent: "apply refund" })
  async applyRefund(orderId: string): Promise<void> { ... }

  @trace({ intent: "export orders as csv" })
  async exportCsv(tenantId: string): Promise<Buffer> { ... }
}
import "github.com/coresdk-dev/sdk-go"

func ProcessPayment(ctx context.Context, order Order) (Receipt, error) {
    ctx, span := coresdk.Trace(ctx, "process payment")
    defer span.End()
    // ...
}

func ApplyRefund(ctx context.Context, orderID string) error {
    ctx, span := coresdk.Trace(ctx, "apply refund")
    defer span.End()
    // ...
}

func ExportCSV(ctx context.Context, tenantID string) ([]byte, error) {
    ctx, span := coresdk.Trace(ctx, "export orders as csv")
    defer span.End()
    // ...
}
use coresdk_engine::trace;

#[trace(intent = "process payment")]
async fn process_payment(order: Order) -> Result<Receipt, Error> { ... }

#[trace(intent = "apply refund")]
async fn apply_refund(order_id: &str) -> Result<(), Error> { ... }

#[trace(intent = "export orders as csv")]
async fn export_csv(tenant_id: &str) -> Result<Vec<u8>, Error> { ... }

You don't need to annotate every private helper — focus on public service methods, API handlers, background jobs, and any function you might want to remove if it's never used.

Step 2 — Run tests in coverage mode

Set CORESDK_COVERAGE=true before running your integration test suite. CoreSDK captures every span emitted during the run and writes a coverage manifest to .coresdk/coverage.json.

CORESDK_COVERAGE=true pytest tests/integration/ -v
# → ...
# → CoreSDK coverage: 39/47 functions reached. Run `core coverage report` to view.
CORESDK_COVERAGE=true npx vitest run tests/integration
# or
CORESDK_COVERAGE=true npx jest --testPathPattern=integration
CORESDK_COVERAGE=true go test ./... -run Integration -v
CORESDK_COVERAGE=true cargo test --test integration

Coverage mode does not slow down test execution — the span data is already being collected; coverage mode just writes a manifest at the end.

Step 3 — View the report

core coverage report
CoreSDK Runtime Coverage Report
════════════════════════════════════════════════════════════
Run:          2026-03-19T14:32:01Z
Test suite:   pytest tests/integration/
Functions:    47 declared   39 called   8 never called

NEVER CALLED (8)
────────────────────────────────────────────────────────────
  apply_refund              payments/service.py:142
  cancel_subscription       billing/service.py:87
  export_csv                reports/service.py:203
  archive_tenant            tenants/service.py:311
  send_invoice_reminder     notifications/email.py:78
  rotate_api_key            auth/keys.py:44
  reprocess_failed_webhook  webhooks/handler.py:199
  bulk_import_users         users/import.py:55

CALLED (39)
────────────────────────────────────────────────────────────
  process_payment           payments/service.py:98    (called 142×)
  create_tenant             tenants/service.py:44     (called 18×)
  verify_token              auth/jwt.py:21            (called 891×)
  ...
════════════════════════════════════════════════════════════
Coverage: 83%  |  8 functions never reached by integration tests

JSON output for CI

core coverage report --format json > coverage.json
{
  "run_at": "2026-03-19T14:32:01Z",
  "total": 47,
  "called": 39,
  "never_called": 8,
  "coverage_pct": 83.0,
  "never_called_functions": [
    {
      "intent": "apply refund",
      "file": "payments/service.py",
      "line": 142,
      "function": "apply_refund"
    }
  ]
}

CI integration

Fail the build if coverage drops below a threshold:

# In your CI pipeline (GitHub Actions, GitLab CI, etc.)
CORESDK_COVERAGE=true pytest tests/integration/
core coverage report --min-coverage 80 --ci
# exits 1 if coverage < 80%, prints the never-called list

GitHub Actions example:

- name: Integration tests with coverage
  run: |
    CORESDK_COVERAGE=true pytest tests/integration/
    core coverage report --min-coverage 80 --ci
  env:
    CORESDK_ENV: test
    CORESDK_SIDECAR_ADDR: localhost:50051

Interpreting results

Not every never-called function is dead code. Consider the context:

SituationAction
Function exists for error recovery (e.g. reprocess_failed_webhook)Write a test that triggers the error path
Function is called only in production edge casesAccept the gap; add a comment explaining why
Function was replaced by a newer implementationSafe to delete
Function is a public SDK method tested by callers, not your suiteExclude it (see below)
Function is called only in other test suitesMerge coverage runs (see below)

Excluding functions

Use @trace(intent="...", coverage=False) to exclude a function from the coverage denominator — useful for intentionally untested escape hatches or adapter stubs:

from coresdk.tracing.decorator import trace

@trace(intent="emergency stop all jobs", coverage=False)
async def emergency_stop() -> None:
    # Only called via ops runbook — not in integration tests
    ...
@trace({ intent: "emergency stop all jobs", coverage: false })
async emergencyStop(): Promise<void> { ... }
ctx, span := coresdk.Trace(ctx, "emergency stop all jobs",
    coresdk.WithCoverage(false))
defer span.End()
#[trace(intent = "emergency stop all jobs", coverage = false)]
async fn emergency_stop() -> Result<(), Error> { ... }

Merging coverage runs

If you run integration tests across multiple services or test suites, merge the manifests before reporting:

# Run each suite separately
CORESDK_COVERAGE=true CORESDK_COVERAGE_OUT=.coresdk/coverage-api.json \
  pytest tests/integration/api/

CORESDK_COVERAGE=true CORESDK_COVERAGE_OUT=.coresdk/coverage-workers.json \
  pytest tests/integration/workers/

# Merge and report
core coverage merge \
  .coresdk/coverage-api.json \
  .coresdk/coverage-workers.json \
  --output .coresdk/coverage-merged.json

core coverage report --input .coresdk/coverage-merged.json

Difference from static analysis

Static analysisCoreSDK coverage
What it findsFunctions never referenced in sourceFunctions never executed in tests
False positivesHigh (misses dynamic dispatch, decorators, plugins)Low (only real execution counts)
Requires annotationNoYes (@trace)
Works across languagesPer-language tool requiredSingle report across all services
Reflects real trafficNoYes (can run against staging too)

For maximum confidence, run both: static analysis to catch unreferenced exports, CoreSDK coverage to catch unreachable execution paths.

Next steps

On this page