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=integrationCORESDK_COVERAGE=true go test ./... -run Integration -vCORESDK_COVERAGE=true cargo test --test integrationCoverage 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 reportCoreSDK 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 testsJSON 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 listGitHub 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:50051Interpreting results
Not every never-called function is dead code. Consider the context:
| Situation | Action |
|---|---|
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 cases | Accept the gap; add a comment explaining why |
| Function was replaced by a newer implementation | Safe to delete |
| Function is a public SDK method tested by callers, not your suite | Exclude it (see below) |
| Function is called only in other test suites | Merge 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.jsonDifference from static analysis
| Static analysis | CoreSDK coverage | |
|---|---|---|
| What it finds | Functions never referenced in source | Functions never executed in tests |
| False positives | High (misses dynamic dispatch, decorators, plugins) | Low (only real execution counts) |
| Requires annotation | No | Yes (@trace) |
| Works across languages | Per-language tool required | Single report across all services |
| Reflects real traffic | No | Yes (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
- Intent Annotations — full reference for
@traceand span attributes - CLI Reference —
core coveragecommand flags and output formats - OpenTelemetry — how coverage spans flow through the OTel pipeline