Skip to content

About

Fast polyglot (Python/Rust/React/Vite/TS/Go) AST dependency graph, speculative background pytest/cargo/vitest runner, Ruff/ESLint/Clippy pre-check, and <1ms incremental test cache for VS Code & GitHub Copilot

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Test Context — instant polyglot AST test cache for AI coding agents

Test Context (tctx)

Sub-millisecond polyglot AST dependency graph, speculative background test runner, pre-flight linter, and Merkle test cache for GitHub Copilot & AI coding agents.

GitHub Pages Benchmarks VS Code Native Tools Rust MIT License

Test Context (tctx) is a local Rust accelerator for Python (pytest + ruff), Rust (cargo test + clippy), Frontend (React, Vite, TypeScript/JavaScript, Vue/Svelte, CSS/SCSS, Vitest/Jest/Node test, ESLint/Biome), and Polyglot (C/C++, C#, Protobuf, GraphQL) workflows — built as the companion to code-context (cctx) for VS Code, GitHub Copilot, and CLI agents.

Live Documentation & Interactive Benchmarks: https://dotnetpower.github.io/test-context/

Instead of re-running entire test suites or paying interpreter/compiler startup costs on every edit, tctx maintains an in-memory polyglot AST reverse dependency graph, computes comment/whitespace-normalized Merkle dependency hashes (dep_hash), pre-checks modified files with Ruff / ESLint / Biome / Clippy, adapts concurrency to live CPU/memory/I/O pressure, and runs affected tests speculatively in the background as files are saved.

How Every Test Call Accelerates

Mode Trigger Typical Latency Behavior
instant_cache_hit All targeted/affected tests match live Merkle dep_hash < 1 ms (median 0.81 ms) Returns verified cached results immediately without spawning a runner
hybrid_delta Subset of tests uncached or modified (0 ms post-edit) ~108 ms median (leaf delta) Reuses cached passes, joins in-flight background work (Singleflight), prioritizes prior failures (Fail-First), and executes only the uncached delta
affected_graph Reverse impact analysis + cached pre-flight lints ~0.65 ms median Traverses compact u32 reverse adjacency lists with hop-ranked chains & file:row:col diagnostics
ruff_fix: true Pre-flight auto-remediation (--ruff-fix) Inline before delta Auto-fixes safe Ruff / ESLint / Biome lint & import issues before executing tests

Architecture Overview

VS Code Native LM Tools (#tctxNative*)  ·  MCP (tctx shared-mcp)  ·  Drop-In CLI (tctx pytest / cargo-test / vitest / jest)
                                                 │
                                  Unix Socket / WSL Native Bridge
                                                 ▼
┌─────────────────────────────────────── tctx daemon (Rust) ───────────────────────────────────────┐
│  Adaptive Pressure Controller (PSI / loadavg / meminfo / cgroup v2 → 4 tiers, dynamic cargo -j)  │
│  ┌──────────────────────────┐  ┌───────────────────────────┐  ┌───────────────────────────────┐  │
│  │ Polyglot AST Graph (u32) │  │ Speculative Worker & Pool │  │ WAL-Backed Merkle Cache       │  │
│  │ • Py / Rs / TS / CSS / C │  │ • Singleflight + Fail-1st │  │ • SHA-256 dep_hash history    │  │
│  │ • 2-hop barrel shake     │  │ • Warm Pytest Zygote      │  │ • Flaky-test quarantine       │  │
│  │ • Streaming AST snapshot │  │ • Ruff/Clippy/ESLint/Biome│  │ • Portable CI cache bundles   │  │
│  └──────────────────────────┘  └───────────────────────────┘  └───────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘

Key Features

1. Polyglot AST Reverse Dependency Graph & Semantic Merkle Hashing

  • Python (pytest): Extracts import x, from x import y, relative imports, multi-line parenthesized imports, in-function lazy imports, conftest.py fixture hierarchies (connecting only tests that actually use a defined @pytest.fixture or autouse/hook), and pyproject.toml/pytest.ini configs while excluding if TYPE_CHECKING:-only imports from false test invalidation. Uses zero-allocation PyAliasSet alias tracking and bounded nested f-string lexing (fail-closed py_dynamic_import on extreme nesting).
  • Rust (cargo test): Parses mod foo;, #[path = "..."] mod, nested use crate::{...} trees, #[test] / #[tokio::test] / #[rstest] / #[test_case] symbols, #[ignore] / #[serial] attributes, tests/common/mod.rs helpers, build.rs, and include_str! / include_bytes! compile-time data dependencies. Decouples non-barrel lib.rs / mod.rs module mounts (pub mod <child>;) and performs 2-hop pub use barrel tree-shaking so shared types (use crate::Result) never couple unrelated sibling modules.
  • Frontend (React / Vite / TS / JS / CSS / SCSS): Resolves ES/CJS/dynamic import(...), excludes import type / export type, tree-shakes nested barrel (index.ts / index.tsx) named and wildcard re-exports via zero-clone nested HashMap lookups, and supports tsconfig.json (paths & extends), package.json (imports #subpath & exports), Vite asset queries (?raw, ?url, ?worker), import.meta.glob(...), Web Workers, SIMD-scanned CSS/SCSS @import/@use/@forward/partials (_tokens.scss), Next.js App Router (app/**/layout.tsx -> page.tsx), and Storybook *.stories.tsx play interaction tests.
  • C/C++ / C# / Protobuf / GraphQL: Tracks C/C++ #include "..." / <...> across source-relative, workspace-root, and include//inc//src/ directories (including nonstandard .inc headers, header-to-implementation linking, CMakeLists.txt scoping, and GoogleTest TEST/TEST_F), C# namespace / using / global using / using static / aliases, [Fact]/[Theory]/[Test]/[TestMethod], and .sln/.csproj/Directory.Build.props config isolation, plus .proto (import, import public, import weak) definitions and .graphql #import edges.
  • Cross-Language & Full-Stack Bridges (O(1) BridgeProviderIndex):
    • PyO3 / Maturin: Links Rust cdylib / [tool.maturin] / #[pymodule] crates to Python importers so editing a .rs kernel marks dependent Python pytest files as affected alongside Rust unit tests.
    • Full-Stack API Routes: Links backend route definitions (@app.get('/api/v1/orders')) to frontend tests calling fetch('/api/v1/orders') or axios.
    • WebAssembly & Protobuf & React Context: Links Rust #[wasm_bindgen] exports to frontend Wasm imports, .proto schemas to generated _pb2.py/_pb.ts consumers, and React createContext providers to useContext consumers.
  • Semantic AST Hashing (semantic_sha256): Strips ordinary comments and non-semantic blank lines via SIMD memchr fast paths so comment/formatting edits preserve dep_hash and never invalidate cached test passes, while preserving directive comments (noqa, type:, pragma, eslint, @ts-, biome-, and Rust doctest fences).
  • Environment Variable & Data File Tracking: Tracks referenced os.getenv, os.environ, env!, env::var, import.meta.env, and process.env keys (including multi-line wrapped calls and scoped .env files) plus .json, .yaml, .toml, .sql, .snap, .golden, .csv, and .proto data files in each test's Merkle dep_hash.

2. Adaptive High-Throughput Background Daemon (tctx daemon)

  • 4-Tier Adaptive Resource Pressure Control (pressure.rs): Reads Linux PSI (cpu/io/memory), /proc/loadavg, /proc/meminfo, and cgroup v2 limits via singleflight caching to dynamically scale CARGO_BUILD_JOBS, parallel worker counts, child process niceness, watcher debounce intervals, and background pausing (Normal → Elevated → High → Critical) without penalizing single-file interactive saves.
  • Multi-Core Parallel Indexing & Streaming AST Snapshots: Parallelizes file reading, SHA-256 hashing, AST parsing, direct dependency resolution, and per-test Merkle BFS across worker threads (std::thread::scope), persisting graphs via bounded 64 KiB streaming bincode snapshots with full u32 edge bounds validation on load.
  • Zero-Clone Parent-Pointer BFS: Reverse impact analysis (affected_tests, affected_modules, untested_modified_files) traverses contiguous u32 adjacency arrays with flat parent_id pointers, reconstructing dependency chains only for matched test files.
  • Rust Multi-Target Precompilation & Indexed Demux: Pre-compiles --lib and --test <integration> targets in a single multi-core cargo test --no-run pass, filters with -- <mod_filters...>, and attributes test cases back to source modules in O(cases) via first-segment prefix indexing.
  • Hardened Warm Pytest Zygote: Materializes its content-addressed 0600 worker script in a per-UID private directory (eliminating Linux 128 KiB MAX_ARG_STRLEN E2BIG errors), pre-imports safe third-party packages (fastapi, pydantic, numpy, pandas, sqlalchemy, etc.) in a single-threaded fork-verified (/proc/self/status fail-closed) parent process with reusable select.poll(), PR_SET_PDEATHSIG, pid > 1 process-group reaping, non-finite/circular JSON sanitization, and POSIX 8-bit exit-code preservation.
  • Hardened WAL, Security & Fault Tolerance: O_NOFOLLOW + regular-file verification across WAL, snapshots, metrics, and .gitignore; stack-encoded SHA-256 WAL checksums; import_bundle path-traversal & orphan-quarantine guards; per-root singleflight load/worktree gates; automatic PoisonError recovery and catch_unwind isolation; O(1) incremental cache memory accounting; and automatic idle Zygote reclamation.
  • Watch Lifecycle Cleanup: Deleted or moved-out directory subtrees are unwatched and removed from the dependency graph, freeing watch capacity for recreated paths. Overflow recovery, periodic safety reconciliation, and explicit sync also prune missing watch directories.

3. VS Code GitHub Copilot Native Integration (dotnetpower.test-context-native)

  • 7 Native VS Code Language Model Tools:
Tool Purpose
#tctxNativeRun Run pytest, cargo test, vitest, jest, and node --test incrementally (< 1 ms cache hits, hybrid_delta, language_filter, ruff_fix)
#tctxNativeAffected Discover tests transitively impacted by modified files or git diff, ranked by hop distance with cached lints
#tctxNativeGraph Inspect imports, reverse importers, transitive dependencies, setup/conftest chains, cross-language bridges, and dep_hash
#tctxNativeStatus Non-blocking daemon health, pressure tier, indexed counts, cache hit stats, background queue, and Zygote metrics
#tctxNativeSync Synchronize the polyglot AST dependency graph with disk and schedule speculative background verification
#tctxNativeInvalidate Invalidate cached results for specific files or the entire workspace
#tctxNativeWorkspaces List explicitly registered workspace roots, scopes, globs, and detected runners
  • Rich Status Bar Hover Tooltip & Revision Caching: Live daemon polling with a Markdown dashboard tooltip (time saved, cache hit rate, ecosystem breakdown, adaptive pressure tier, Zygote RSS, and per-tool breakdown) cached by monotonic revision counter.
  • Agent-Friendly Path & Root Resolution: Automatically strips workspace-root prefixes from absolute target paths (/path/to/repo/src/daemon/tests.rs::test_fn -> src/daemon/tests.rs::test_fn), enforces strict .. / NUL / control-character containment, and infers the active workspace root from target path hints, vscode-remote:// URIs, Windows WSL UNC paths (\\wsl.localhost\...), and session history.
  • Smart Git-Dirty Delta Scoping: In large repositories (> 64 test files), omitting targets in #tctxNativeRun automatically scopes execution to tests affected by uncommitted git status changes rather than running thousands of unrelated tests.
  • Context Window Token Optimization (92.7% Reduction): Strips passing test boilerplate (test ... ok, compiler progress lines) while preserving 100% of warnings, failures, and skips, and bounds large #tctxNativeAffected / #tctxNativeGraph outputs to stay inline (< 8 KB) without /tmp file offloading.
  • Culprit Attribution & CI Cache Sharing: Extracts workspace-local stack frames (structured_failures), cross-references git diff with transitive dependencies to identify suspected_culprit_files, exports JUnit XML / SARIF v2.1.0 reports, and supports portable CI cache bundles (cache-export / cache-import).

tctx learns invocation patterns routed through its Native, MCP, or CLI surfaces. Use tctx pytest, tctx cargo-test, tctx vitest, or tctx jest (or their symlinks tctx-pytest, tctx-cargo-test, tctx-vitest, tctx-jest) for drop-in CLI acceleration.


Measured Performance

1. Python FastAPI Suite (aks-store-demo, 320 Paired Observations)

Across 8 independent daemon sessions (320 paired observations) on AKS Store Demo (src/ai-service) measured against the current release build:

Test execution and query latency and paired-session speedup with 95% confidence intervals

Task TCTX off (pytest) TCTX on Speedup [95% CI]
Warm suite (warm_suite) 1,125.77 ms 1.18 ms (median 0.81 ms) 957.44× [613.12, 1362.80]
Post-edit background pre-run (bg_speculative) 1,168.57 ms 1.19 ms (median 0.86 ms) 980.98× [812.85, 1171.15]
Reverted edit Merkle hit (merkle_revert) 1,141.21 ms 4.27 ms (median 1.04 ms) 267.21× [141.37, 627.02]
Immediate 0ms-delay leaf edit (leaf_delta) 1,156.31 ms 135.45 ms (median 108.38 ms) 8.54× [6.88, 9.89]
Impact query + Ruff pre-check (affected_graph) 1,096.90 ms 0.86 ms (median 0.65 ms) 1,274.04× [1054.57, 1506.24]
Fixed mixed suite (all, 320 pairs) 1,137.75 ms 28.59 ms (median 0.89 ms) 39.80× [32.22, 45.46] (1,132.71× median)

2. Rust (cargo test) & Enterprise Monorepo (9,042 files / 3,434 tests) Benchmarks

Scenario Baseline / Unoptimized With tctx Speedup / Improvement
Enterprise monorepo (9,042 files, 3,434 tests) cold AST load 6,047.38 ms 670.33 ms (parallel multi-core build) 9.0× faster cold load (-88.9%)
Enterprise monorepo core module test_affected (67 affected tests) 256.80 ms 5.17 ms (u32 reverse_adj parent-pointer BFS) 49.7× faster impact query
Enterprise monorepo test_affected (2,363 affected tests) payload 1,400,000 B (/tmp offloaded) 5,320 B (hop-ranked inline < 8 KB) 263× smaller inline payload
4 Rust modules (25 unit tests) cold batch ~5,800 ms (4× cargo test) 1,254.64 ms (cargo test --lib demux) 4.6× faster cold batch
2 Rust modules (27 unit tests) targeted harness filter 1,110.00 ms (full crate 53 tests) 90.00 ms (-- <mod_filters...>) 12.3× faster module run
6 Rust files (53 unit tests) warm cache hit 6,606.00 ms 0.87 ms (instant_cache_hit) 7,593× speedup
Single Rust test node (src/runner.rs::demux_...) 1,254.64 ms 0.23 ms (cached_node) 5,455× speedup

See docs/BENCHMARKS.md or the GitHub Pages benchmark gallery for methodology, cold-start measurements, raw samples, and reproduction instructions.


Quick Start & CLI Reference

# 1. Build and install tctx + user systemd service (or macOS LaunchAgent)
./scripts/install.sh

# 2. Register a Python, Rust, Frontend, or Polyglot workspace
tctx --root /path/to/repo register

# 3. Inspect daemon health, AST dependency graph, affected tests, or lint diagnostics
tctx --root /path/to/repo doctor
tctx --root /path/to/repo status
tctx --root /path/to/repo affected --file src/my_pkg/core.py
tctx --root /path/to/repo graph src/my_pkg/core.py
tctx --root /path/to/repo ruff --fix

# 4. Run tests incrementally across Python, Rust, and Frontend
tctx --root /path/to/repo run --ruff-fix
tctx --root /path/to/repo pytest -q
tctx --root /path/to/repo cargo-test
tctx --root /path/to/repo vitest
tctx --root /path/to/repo jest

# 5. Diagnose failures, export JUnit/SARIF reports, or share cache bundles in CI/CD
tctx --root /path/to/repo explain
tctx --root /path/to/repo run --report-format=sarif --report-out=results.sarif
tctx --root /path/to/repo cache-export --out=tctx-cache.json
tctx --root /path/to/repo cache-import --input=tctx-cache.json

# 6. Install Git pre-commit/pre-push hooks or authorize Git worktrees
tctx --root /path/to/repo hook-install
tctx --root /path/to/repo authorize-worktrees

# 7. Package and install the VS Code Native Extension (Linux & Windows WSL)
./scripts/install-vscode-extension.sh

Verification Suite

# Rust unit, integration, safety/cancellation tests & strict clippy
cargo clippy --all-targets --locked -- -D warnings
cargo test --locked

# Python benchmark parity & subagent configuration tests
python3 -m unittest discover -s tests -p 'test_*.py'

# VS Code extension lint, typecheck, unit tests & VSIX integrity verification
npm --prefix vscode-extension run lint
npm --prefix vscode-extension run check
npm --prefix vscode-extension test
npm --prefix vscode-extension run package
python3 scripts/verify_vsix.py vscode-extension/dist/test-context-native.vsix

Companion & Links

About

Fast polyglot (Python/Rust/React/Vite/TS/Go) AST dependency graph, speculative background pytest/cargo/vitest runner, Ruff/ESLint/Clippy pre-check, and <1ms incremental test cache for VS Code & GitHub Copilot

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages