tested – Code Guilds https://codeguilds.com Thu, 26 Nov 2026 21:20:18 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.5 From Repetitive Bash Scripts to a Tested Open-Source CLI: The Evolution of Init Flow https://codeguilds.com/from-repetitive-bash-scripts-to-a-tested-open-source-cli-the-evolution-of-init-flow/ https://codeguilds.com/from-repetitive-bash-scripts-to-a-tested-open-source-cli-the-evolution-of-init-flow/#respond Thu, 26 Nov 2026 21:20:18 +0000 https://codeguilds.com/from-repetitive-bash-scripts-to-a-tested-open-source-cli-the-evolution-of-init-flow/ In the modern software development landscape, automation is a cornerstone of DevOps and systems engineering. Organizations invest heavily in automating complex infrastructure, continuous integration pipelines, and multi-cloud deployment workflows. Yet, paradoxically, software engineers and infrastructure operators frequently accept unnecessary friction at the very beginning of a software project lifecycle. The routine actions required to spin up a new repository—such as manually constructing directory trees, initializing local version control systems, configuring remote repository parameters, and launching integrated development environments—represent a persistent, albeit minor, operational drag.

While each individual command requires minimal effort, the cumulative repetition introduces human error, environment drift, and workflow inconsistencies. Recognizing this pervasive inefficiency, telecommunications and DevOps engineer Jacivaldo Carvalho designed Init Flow, a lightweight, open-source command-line interface (CLI) written entirely in Bash to standardize and automate project bootstrapping. Combining native Linux system utilities, Git, the official GitHub CLI (gh), robust software engineering principles, and continuous integration workflows, Init Flow has evolved significantly with its latest release, version v0.2.0.

The Operational Friction of Project Initialization

The genesis of Init Flow stems from a common engineering anti-pattern: copy-pasting ad-hoc shell commands or writing unmaintained shell scripts whenever a new repository is required. A typical manual initialization workflow on a Linux workstation involves a predictable sequence of operations:

mkdir -p ~/projects/my-project
cd ~/projects/my-project
git init -b main
gh repo create my-project --public --source=. --remote=origin
code .

Although these steps appear straightforward, executing them manually or through fragile, unvalidated scripts introduces several hidden assumptions. This workflow assumes that the target directory does not already exist, that Git and the GitHub CLI are correctly installed and authenticated, that network connectivity to GitHub is stable, and that the preferred integrated development environment (IDE)—such as Visual Studio Code—is accessible in the system path.

Without proper validation, error handling, and defensive programming checks, executing these commands blindly can lead to aborted states, corrupted local repositories, or conflicting directory structures. The engineering challenge was not merely aggregating commands into a single script, but architecting a reliable, predictable, and maintainable utility capable of handling edge cases gracefully.

Architecture and Design Evolution of Init Flow

Init Flow addresses these operational hurdles by providing a unified command structure. Executing a single command encapsulates the entire bootstrapping process:

initflow create my-project

By default, this command establishes the local directory structure, initializes a Git repository with the main branch, provisions a corresponding public GitHub repository via the GitHub CLI, and opens the workspace in Visual Studio Code. Carvalho released Init Flow under the open-source MIT License, tailoring its initial focus toward Linux-based development environments.

The architectural design of Init Flow prioritizes simplicity without compromising operational reliability. Rather than introducing heavy external frameworks or runtime dependencies that complicate installation, the project leverages standard POSIX tools and native Bash features. The repository structure strictly separates concerns to maintain high code readability and testability:

init-flow/
├── .github/
│   └── workflows/
│       └── ci.yml
├── assets/
├── docs/
├── examples/
├── scripts/
│   ├── initflow
│   ├── install.sh
│   └── uninstall.sh
├── tests/
│   ├── test_initflow.sh
│   ├── test_create.sh
│   ├── test_install.sh
│   └── test_uninstall.sh
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
└── README.md

The core executable manages command execution and flow control, while installation routines, uninstallation scripts, and test suites remain strictly modular.

Key Enhancements in Version v0.2.0

While the initial v0.1.0 release established a functional baseline for project initialization, version v0.2.0—officially dubbed the Configuration and Customization release—introduces seven powerful command-line options that adapt the tool to diverse engineering workflows.

Building Init Flow: Automating Project Initialization with Bash, GitHub CLI, and DevOps Practices
Option Description
--private Provisions a private GitHub repository instead of a public one
--readme Generates a local README.md file within the project directory
--description TEXT Sets the remote repository metadata description
--local Initializes a local Git project entirely decoupled from GitHub integration
--path DIRECTORY Specifies a custom base directory for project creation
--no-editor Bypasses launching Visual Studio Code upon completion
--dry-run Previews the execution plan without modifying the filesystem or interacting with APIs

These options empower developers to customize their environments. For instance, creating an internal utility with restricted visibility requires a straightforward flag addition:

initflow create internal-tool --private

Similarly, developers can generate documentation placeholders and descriptive metadata simultaneously:

initflow create automation-tool 
  --readme 
  --description "Linux automation utilities"

For offline work, sandboxing, or local experimentation, the --local flag enables project initialization without requiring GitHub CLI authentication or an active internet connection:

initflow create local-lab 
  --local 
  --readme 
  --no-editor

Furthermore, users can direct projects to custom file paths—overriding the default $HOME/projects location via the CLI flag or the INITFLOW_PROJECTS_DIR environment variable—and preview execution steps using the --dry-run flag to ensure operational safety before committing changes.

Defensive Programming and Security Considerations

Shell script automation carries inherent risks, particularly when user-supplied inputs pass directly to system binaries without sanitization. To mitigate these risks, Init Flow adopts rigorous defensive programming practices.

The script execution utilizes Bash strict mode:

set -euo pipefail

However, relying solely on strict mode is insufficient for production-grade shell scripting. Init Flow implements centralized argument parsing and validation before executing filesystem modifications or external API calls. This validation layer catches logical contradictions early. For example, combining the --local flag with the --private flag triggers an immediate error, as repository visibility parameters are irrelevant when no remote repository is being provisioned.

Conditional dependency management further optimizes execution by checking for required binaries—such as Git, the GitHub CLI, or VS Code—only when specific flags demand them. A dry run requires no external binaries, whereas default operations verify the entire toolchain before proceeding.

Automated Testing, Continuous Integration, and Lessons Learned

A distinguishing feature of Init Flow is its commitment to rigorous testing and software engineering standards, proving that shell-based tools benefit immensely from automated quality assurance. The project expanded from 30 automated tests in v0.1.0 to 58 comprehensive tests in v0.2.0.

The test suite is partitioned into four distinct operational areas:

  • test_initflow.sh: Validates CLI argument parsing and error handling.
  • test_create.sh: Tests project creation and integration workflows using mocks.
  • test_install.sh: Verifies correct symbolic linking and PATH integration during installation.
  • test_uninstall.sh: Ensures clean removal of installation artifacts.

Integration tests utilize mocking frameworks to simulate external commands like Git, GitHub CLI, and Visual Studio Code. This design prevents automated test suites from inadvertently creating live GitHub repositories or modifying user environments during CI runs.

Building Init Flow: Automating Project Initialization with Bash, GitHub CLI, and DevOps Practices

Static code analysis plays an equally vital role. Developers utilize shellcheck across all scripts and test files to detect subtle quoting issues, unsafe variable expansions, and portability bottlenecks. Syntax validation is enforced locally and within continuous integration pipelines using GitHub Actions:

(
    for file in scripts/initflow scripts/*.sh tests/*.sh; do
        bash -n "$file" || exit 1
    .done
)

Despite robust local testing, the v0.2.0 release cycle provided a valuable lesson in cross-platform portability. During initial GitHub Actions runs, integration tests failed unexpectedly despite passing seamlessly on the author’s local workstation. The root cause was an undeclared dependency on ripgrep (rg), a high-performance search utility present in the developer’s local environment but absent from the default GitHub Actions runner.

An integration test relying on ripgrep:

rg -q -- '--private' "$MOCK_LOG"

Was refactored to use standard POSIX-compliant utilities universally available across Unix-like systems:

grep -Fq -- '--private' "$MOCK_LOG"

Additionally, pipeline subshells used for validating dry-run outputs occasionally triggered broken pipe errors under strict mode. Replacing piped commands with direct variable assignment and conditional evaluation resolved the issue while preserving strict assertions:

preview_output="$("$CLI" create remote-preview --dry-run --no-editor)"

if [[ "$preview_output" == *'Remote availability has not been verified'* ]]; then
    # Assertion passed
fi

This experience reinforced foundational engineering principles: minimizing external dependencies in testing suites, ensuring strict POSIX compliance for portable tooling, and utilizing Conventional Commits to document bug fixes clearly, such as the corresponding patch: fix(test): remove ripgrep dependency from integration tests.

Broader Impact and Future Roadmap

The maturation of Init Flow from a rudimentary set of shell commands into a structured, tested, and versioned open-source utility illustrates the value of applying rigorous software engineering methodologies to developer tooling. By eliminating repetitive initialization friction, engineering teams can reduce cognitive overhead and enforce consistent project layouts across organizational silos.

Looking forward, the roadmap for Init Flow outlines several potential enhancements aimed at extending its utility. Future iterations may explore support for custom project templates, interactive configuration wizards, integration with additional version control platforms beyond GitHub, and broader operating system compatibility.

However, the primary long-term objective remains achieving a stable v1.0.0 release while steadfastly preserving the tool’s core tenets: simplicity, operational reliability, and ease of maintenance. For systems engineers, DevOps practitioners, and developers operating within Linux environments, Init Flow offers a compelling open-source utility to streamline daily workflows and standardize the inception of software architecture.

]]>
https://codeguilds.com/from-repetitive-bash-scripts-to-a-tested-open-source-cli-the-evolution-of-init-flow/feed/ 0
Does ‘rtk’ skill really cut agent tokens by 60–90%? We tested it. https://codeguilds.com/does-rtk-skill-really-cut-agent-tokens-by-60-90-we-tested-it/ https://codeguilds.com/does-rtk-skill-really-cut-agent-tokens-by-60-90-we-tested-it/#respond Tue, 21 Jul 2026 10:45:45 +0000 https://codeguilds.com/does-rtk-skill-really-cut-agent-tokens-by-60-90-we-tested-it/ Independent rigorous benchmarking by JetBrains AI has revealed that the much-touted ‘rtk’ (Rust Token Killer) skill for AI coding agents, despite its innovative compression techniques, failed to deliver its advertised 60–90% token savings when applied to real-world agentic coding tasks. In fact, comprehensive testing showed a marginal cost increase of 7.6% at low reasoning effort and no significant change at high effort, casting a critical light on how AI tool efficiency claims are often evaluated.

The Quest for LLM Efficiency: A Growing Imperative

In the rapidly evolving landscape of artificial intelligence, large language models (LLMs) are increasingly being deployed as autonomous agents capable of performing complex tasks, from code generation and debugging to system administration. A critical factor in the practical and economic viability of these agents is their token consumption. Every interaction with an LLM incurs a cost, measured in "tokens" – the fundamental units of text that LLMs process. High token usage translates directly to higher operational costs, increased latency, and limitations on the agent’s contextual understanding due to finite context windows. This makes any tool promising significant token savings immensely appealing to developers and organizations leveraging AI agents.

JetBrains, a leading developer of intelligent software development tools, has been at the forefront of integrating AI into its product ecosystem. Recognizing the importance of empirical validation in this space, the company has undertaken a methodical series of benchmarks to assess the real-world performance of various AI agent optimization tools. This particular study marks the second installment in this series, following a previous evaluation of a "caveman skill" which claimed 65% savings but measured a modest 8.5%. The consistent methodology underscores JetBrains’ commitment to providing data-driven insights for the AI development community.

The ‘rtk’ tool, an open-source command-line interface (CLI) proxy available on GitHub, presented a compelling value proposition. Its core function is to intercept standard shell commands executed by an AI agent (such as git status or python -m pytest), execute them, and then return a significantly compressed, human-readable summary of the output to the LLM. For instance, a verbose git status output with eleven lines of "porcelain" might be condensed to a concise * master / M a.txt / ?? b.txt. The tool’s documentation specifically highlighted a session where 118,000 tokens of command output were reduced to 24,000, promising a dramatic 60–90% reduction in token consumption. This mechanism, facilitated by a Claude Code PreToolUse hook, transparently rewrites eligible shell commands, theoretically allowing the agent to benefit from compression without needing explicit awareness of rtk‘s presence.

While the compression itself appeared technically sound and often elegant in its summarization, JetBrains’ researchers posed two fundamental questions that the public documentation did not adequately address: Firstly, what proportion of a typical AI agent’s session actually involves Bash output that rtk can intercept and compress? Secondly, does this compression, which inherently involves making "editorial judgments" about the output, compromise the correctness or quality of the agent’s work? Token savings at the expense of task accuracy would negate any perceived benefit.

A Rigorous Benchmark: Unpacking the Methodology

To answer these questions, JetBrains deployed a robust, paired A/B benchmarking framework designed to isolate the effects of rtk with high statistical confidence. The setup was meticulously controlled to ensure objective and reproducible results:

  • Harness: Harbor 0.18, a specialized testing environment providing Docker sandboxes, comprehensive task verifiers, and the capability for paired runs. This ensured identical execution environments for both control and experimental arms.
  • Agent: Claude Code 2.1.201, run in a headless configuration with bypassPermissions enabled, and strictly pinned in both arms to eliminate agent version variability. Claude Code is a sophisticated AI assistant designed for coding tasks, making it an ideal candidate for this evaluation.
  • Model: claude-sonnet-5, a mid-tier LLM from Anthropic, chosen for its balance of performance and cost-effectiveness. The benchmark was run twice – once at "low reasoning effort" and again at "high reasoning effort" – to observe if the model’s cognitive load influenced its interaction with compressed output.
  • Benchmark Suite: SkillsBench, a collection of 87 diverse coding tasks (86 were used in the final analysis), auto-graded with a 0–1 score and partial credit for granular evaluation of task completion quality.
  • Arms:
    • Arm A (Control): Stock Claude Code, representing the baseline performance.
    • Arm B (Experimental): rtk v0.43.0, installed exactly as shipped by rtk init -g, including the binary, the PreToolUse hook, and the RTK.md documentation. This ensured that the test measured rtk‘s "as-shipped ceiling" without any user-induced configuration variations.
  • Volume and Cost: The study involved four paired runs: a 10-task "smoke test," the same 10 tasks at k=3 (multiple attempts), and full 86-task runs at both low and high reasoning efforts. This amounted to 425 billed trials, incurring an estimated cost of approximately $320 (Harbor-recorded $317 plus reconstructed subagent spend), demonstrating a significant investment in empirical validation.

Crucially, every trial in the rtk arm persisted rtk‘s own audit log and analytics database, providing verifiable proof that the treatment (compression) was indeed applied and allowing for a direct comparison with rtk‘s self-reported metrics.

Finding 1: The Limited Addressable Surface Area

Before incurring the full cost of the benchmark, JetBrains’ researchers performed an initial analysis by replaying 83 existing baseline transcripts. This revealed a fundamental structural limitation of rtk‘s potential impact:

  • Bypassed Tools: Claude Code, like many sophisticated agents, uses its built-in Read and Grep tools for file operations. These tools directly access the file system and completely bypass the Bash shell and, consequently, rtk‘s Bash hook. rtk‘s own documentation acknowledges this limitation in a footnote.
  • Uncovered Commands: A significant portion of shell commands executed by agents consists of python3 ... calls and other commands that rtk does not currently cover. Additionally, a substantial fraction involves complex shell constructs like pipes-to-files, heredocs, and command substitutions, which rtk deliberately avoids rewriting to prevent potential correctness issues.

The cumulative effect of these limitations meant that only approximately 33% of Bash calls in the baseline transcripts were even eligible for rtk‘s intervention. More critically, these eligible calls carried just under 20% of the total tool-result characters. Furthermore, tool results themselves represent only a fraction of the total "input tokens" billed in a session, as the same contextual information (e.g., source code, previous interactions) is often re-read and billed on every turn. Factoring in these layers, even if rtk achieved its advertised 70% compression on its "whole share," the maximum potential token savings for a real agent session was projected to be less than 3% of total input tokens. This pre-benchmark analysis proved remarkably prescient in predicting the study’s outcome.

Finding 2: A Cost Increase, Not a Saving

The full benchmark results confirmed the initial structural analysis. Across 80 clean paired trials, the rtk arm exhibited a median +7.6% increase in cost per task compared to the baseline (with a statistical significance of p=0.004). This increase was accompanied by a median +13.8% more turns (p=0.03) and +14.3% more cache reads (p=0.008). In stark contrast, the "new input" token class – the only category rtk directly compresses – showed a negligible +3.2% change (p=0.23), effectively a flat null result where all the purported benefit was expected to reside.

Further analysis revealed a correlation between rtk‘s intervention and the cost penalty: tasks with heavy rtk exposure (i.e., where the hook rewrote many commands) were approximately 24% more expensive than baseline, compared to a 5% increase for tasks where rtk was barely touched. While harder tasks might naturally use more Bash, controlling for task difficulty did not explain this pattern. Transcript forensics, a detailed examination of agent interactions, uncovered a "thin, systematic tax" rather than a single catastrophic failure. This included one genuinely broken rewrite (a complex find command that generated usage errors and forced retries), a few instances of the agent re-reading files due to overly compressed or ambiguous output, and a general increase in "ordinary variance" as the model explored different solution paths. The core issue was not a dramatic breakdown but a subtle cumulative effect of increased interaction complexity.

rtk Claude Code Token Savings: A Skill Trial Benchmark

Finding 3: High Effort, Neutral Impact

Anticipating the critique that the initial findings might be specific to "low reasoning effort," JetBrains conducted a full re-run of all 86 tasks at "high reasoning effort." This represented the most expensive single run of the entire series. Interestingly, at high effort, the observed cost penalty did not replicate. The median paired delta for cost was +0.1% (p=0.99), with turns showing +0.0 (p=0.74), and task quality remaining tied.

This suggests that at higher reasoning efforts, the claude-sonnet-5 model might be more robust to the nuances of compressed output, potentially requiring fewer exploratory turns or being more adept at inferring necessary information despite summarization. While a single run at high effort cannot definitively prove a difference between effort regimes, it strongly indicates that rtk did not provide any cost savings even under optimal conditions for agent performance.

Finding 4: Quality Preservation

A critical concern with any compression or summarization tool is the potential degradation of output quality or task correctness. The study found that rtk largely preserved task quality. A forensic review of transcripts, including those with the largest turn deltas, identified only one recurring broken rewrite (the compound find failure) and one instance of the agent deliberately bypassing the hook across approximately 150 Bash calls. Crucially, there were no widespread reports of agents recovering by reading raw files or misinterpreting compressed pipe output. The additional turns observed were primarily due to the model choosing alternative solution paths, not from rtk-induced confusion or errors.

Across the full runs, task scores (with partial credit) landed at 5 better / 4 worse / 71 tied at low effort, and 5 / 4 / 62 tied at high effort. A sign test yielded p=1.0 for both, indicating that the two arms were statistically indistinguishable on task quality.

It is important to note one specific compatibility issue: on the dialogue-parser task, rtk‘s binary failed to start within the task’s Docker image due to a glibc dependency. This caused the rtk trial to fail at setup in both full runs, while the plain arm successfully scored 0.667. While paired analysis typically excludes such tasks, even if this errored rtk trial were scored as zero, the overall arms would still remain tied on quality (sign test p=1.0), underscoring that this was a compatibility failure, not a compression-induced quality issue.

Finding 5: The Disconnect Between Self-Reported and Actual Savings

Perhaps the most illuminating finding concerned the significant discrepancy between rtk‘s internal scoreboard and the actual observed billable token usage. Across the low-effort full run, rtk‘s built-in analytics (rtk gain) reported a staggering 96.2 million tokens saved, claiming to compress 99.8% of everything it touched. Yet, the measured bill for these same trials went up. This stark divergence can be attributed to three primary mechanisms by which rtk‘s internal scoreboard inflates its reported savings:

  1. Counterfactual Mismatch: rtk counts the full raw output of a command as its counterfactual "saved" amount. However, LLMs like Claude Code have internal truncation limits for tool results. For example, a cat command on a 1.2 MB CSV file might log 320,000 "saved" tokens by rtk, but the LLM would have only received a few thousand tokens of that output anyway due to its truncation. The benchmark observed 190 such large reads, averaging approximately 506,000 "saved" tokens each by rtk, which were never actually billable to the LLM in their full raw form.
  2. Inaccurate Token Estimation: rtk estimates tokens simply as characters divided by four at the moment of execution. This is a heuristic that does not reflect the actual tokenization process of LLMs, which varies by model and can lead to significant discrepancies.
  3. Ignoring Cached Re-reads: The majority of an agent session’s input cost often comes from cached re-reads of the prompt, context, and previous turns. These cached tokens are typically billed at a significantly lower rate (e.g., one-tenth the price) than new input tokens. rtk‘s hook, operating on fresh command output, simply never "sees" or accounts for this dominant cost component, nor can it influence its billing.

In essence, rtk‘s scoreboard was "grading its own homework" based on an idealized, raw counterfactual that did not align with how LLMs actually process and are billed for information.

Verdict: Honest Engineering, Misleading Counterfactual

The JetBrains AI team’s verdict on rtk is one of "honest engineering, wrong counterfactual." The tool itself is a well-crafted piece of software. Its filters are functional and often elegant in their summarization; it does not compromise task quality; and its hook mechanism operates precisely as designed. The problem lies not in rtk‘s technical execution, but in the fundamental assumptions underpinning its advertised savings.

On real agentic coding tasks with Claude Code, the promised 60–90% token savings simply had no viable pathway to materialize. The rtk hook only ever addresses a fraction (approximately one-fifth) of the total tool output, much of which is already truncated by the LLM itself. Furthermore, the dominant cost driver – cached re-reads of context – is entirely outside rtk‘s purview and billed at a much lower rate. What remains is a measured median +7.6% cost increase at low effort and a flat zero at high effort, representing a thin, systematic tax rather than a saving. This tax stems from minor inefficiencies like an occasional broken rewrite or the agent taking an extra turn to explore.

Broader Implications for AI Development

This study carries significant implications for the broader AI development community:

  1. The Criticality of Independent Benchmarking: The stark contrast between advertised claims and empirical results underscores the absolute necessity of independent, rigorous benchmarking for any AI optimization tool. Developers cannot rely solely on a tool’s self-reported metrics, which can be based on idealized or incomplete counterfactuals.
  2. Understanding LLM Billing Models: AI developers must gain a deep understanding of how LLMs are actually billed. Simple token counts are insufficient; nuances like truncation limits, different rates for input vs. output, and the cost of cached context are paramount. A tool that compresses raw output effectively might have minimal impact on the final bill if that raw output would have been truncated anyway or if the primary cost comes from other token categories.
  3. The "Counterfactual Problem": This research highlights a common pitfall in evaluating optimization tools – the "counterfactual problem." The definition of "saved" tokens or resources can vary wildly between a tool’s internal logic and the real-world billing mechanisms. Developers should always measure the actual bill or the actual performance metric that matters, rather than a tool’s internal "diff."
  4. Architectural Limitations: The study also points to inherent architectural limitations in how current AI agents interact with their environment and LLMs. As long as agents rely heavily on built-in file reading tools or if a significant portion of their context is repeatedly sent to the LLM, optimizations focused solely on shell command output will have a limited overall impact.
  5. Future of AI Agent Optimization: The search for true efficiency in AI agents continues. Future innovations might need to focus on more holistic context management, smarter agent architectures that reduce redundant communication, or more tightly integrated tool systems that provide truly token-efficient interfaces to external environments.

JetBrains concludes with a firm piece of advice: "a tool’s self-reported savings are a claim about its counterfactual, not about your bill." For any context-compression or efficiency tool in the AI domain, the only reliable evaluation is to measure the paired bill directly, not the tool’s internal diff. The company remains committed to its rigorous testing methodology and invites suggestions for the next AI optimization tool to put on its evaluation ladder.

]]>
https://codeguilds.com/does-rtk-skill-really-cut-agent-tokens-by-60-90-we-tested-it/feed/ 0
Replay Brings Battle-Tested HTTP Recording to Swift Development https://codeguilds.com/replay-brings-battle-tested-http-recording-to-swift-development/ https://codeguilds.com/replay-brings-battle-tested-http-recording-to-swift-development/#respond Sat, 18 Jul 2026 10:25:17 +0000 https://codeguilds.com/replay-brings-battle-tested-http-recording-to-swift-development/ The year is 2025, and Swift developers building networked applications face a persistent challenge: ensuring the reliability and speed of their automated tests. The traditional approaches to testing networking code often fall short, leading to slow, brittle test suites that are susceptible to the vagaries of live third-party services. While stubbing URLSession can offer a degree of isolation, it necessitates the maintenance of duplicate networking logic. Manually curating JSON fixtures, though a common practice, is prone to becoming outdated, leaving tests susceptible to unexpected failures without immediate indication. A more robust and efficient methodology, long established in other programming languages, is now accessible to the Swift ecosystem: recording real HTTP traffic once and replaying it instantly for every subsequent test run. This principle is embodied by the newly released Replay library, which brings this proven pattern to Swift development.

The genesis of this approach can be traced back to February 2010, when Myron Marston introduced VCR for Ruby. Drawing a parallel to the functionality of a videocassette recorder, VCR enabled developers to capture HTTP interactions, thereby allowing tests to replay these interactions without needing to establish live network connections. The mantra was simple and effective: "Record once, play back forever."

This innovative concept rapidly gained traction and inspired similar implementations across diverse programming languages. Python saw the emergence of VCR.py and pytest-recording, extending the VCR paradigm to its developers. The home video theme continued with Java’s Betamax, while Go adopted its own version with go-vcr. For years, developers like the author of this article had utilized these tools in their respective environments, often expressing a desire for a comparable solution within the Swift community. While Venmo’s DVR project offered a partial solution, leveraging the same URLProtocol injection point as Replay, it was developed in an earlier era of Swift, before the advent of modern tooling that could facilitate a truly seamless and intuitive experience.

A Nod to the Past, a Leap to the Future

The development of Replay is deeply informed by its predecessors. A key question guiding its creation was, "What has changed to allow for a superior implementation today?" Two significant advancements stand out.

Firstly, the HTTP Archive (HAR) format has solidified its position as a de facto standard for archiving HTTP traffic. When Myron Marston initially developed VCR, a widely adopted format for such archives did not exist, leading him to create a custom YAML-based solution, which inspired the "cassette" terminology. However, around the same period, Jan Odvarko, a member of the Firefox developer tools team, was instrumental in developing the HAR format. Today, HAR files are universally supported, exported by all major web browsers and widely adopted by network debugging tools such as Charles Proxy, Proxyman, mitmproxy, and Postman. Replay’s decision to utilize HAR streamlines the process of integrating real-world network traffic into tests. Developers can now capture traffic directly from browser developer tools and seamlessly incorporate it into their test fixtures, which can be easily inspected and edited with any standard text editor.

Secondly, Swift has evolved to provide the necessary extension points for building sophisticated testing tools. Swift’s testing framework, particularly the TestScoping protocol introduced in Swift 6.1, enables declarative, per-test configuration that mirrors the capabilities of pytest fixtures. Furthermore, the integration of Swift Package Manager plugins allows for the development of tooling that feels intrinsically native to the Swift development environment. These advancements, which were not readily available in a convenient or intuitive form previously, have paved the way for Replay’s architecture.

The Mechanics of Replay: Seamless Integration

Replay operates by integrating seamlessly with Swift’s testing framework. By applying the .replay trait to a test case, Replay intercepts HTTP requests and serves responses directly from a HAR file, effectively bypassing the need to interact with the live network.

Consider the following example of a Swift test:

import Testing
import Replay

struct User: Codable 
    let id: Int
    let name: String
    let email: String


@Test(.replay("fetchUser"))
func fetchUser() async throws 
    let (data, _) = try await URLSession.shared.data(
        from: URL(string: "https://api.example.com/users/42")!
    )
    let user = try JSONDecoder().decode(User.self, from: data)
    #expect(user.id == 42)

In this code snippet, the .replay("fetchUser") trait instructs Replay to load responses from a file named Replays/fetchUser.har. The application’s production code continues to use URLSession as usual, eliminating the need for custom protocols or injected mocks. Replay’s interception mechanism leverages the built-in affordances of the Foundation URL Loading System, ensuring compatibility with URLSession.shared, custom URLSession instances, and popular networking libraries like Alamofire.

The Recording Workflow: A Deliberate Process

The initial execution of a test marked with .replay is intentionally designed to fail. This deliberate failure is a crucial security feature, preventing the accidental recording of sensitive information such as credentials, Personally Identifiable Information (PII), or session tokens.

Upon the first run, a test might produce output similar to this:

➜  Example_Tests.swift  Test fetchUser() recorded an issue at Example_Tests.swift
--------------------------------------------------------------------------
  No Matching Entry in Archive
--------------------------------------------------------------------------
Request: GET https://api.example.com/users/42
Archive: /path/to/.../Replays/fetchUser.har

This request was not found in the replay archive.

Options:
1. Run against the live network:
   REPLAY_PLAYBACK_MODE=live swift test --filter <test-name>

2. Record the archive:
   REPLAY_RECORD_MODE=once swift test --filter <test-name>

This "failure" serves as an explicit prompt for the developer to initiate the recording process. By requiring explicit opt-in for recording, Replay ensures that developers are always aware when network traffic is being captured.

To proceed with recording, the following command is executed:

REPLAY_RECORD_MODE=once swift test --filter fetchUser

This command directs Replay to hit the actual API endpoint, capture the resulting response, and save it to the Replays/fetchUser.har file. Subsequently, all test runs for fetchUser will execute instantaneously by replaying this recorded fixture. The efficiency gains are palpable, transforming test suites that once took minutes to complete into operations that finish in mere seconds.

The Structure of a HAR File: Transparency and Interoperability

A HAR file is fundamentally a JSON document, making it human-readable and easily inspectable. This transparency is a cornerstone of Replay’s design, fostering trust and simplifying debugging. A typical HAR file structure includes:


  "log": 
    "version": "1.2",
    "creator":  "name": "Replay", "version": "1.0" ,
    "entries": [
      
        "request": 
          "method": "GET",
          "url": "https://api.example.com/users/42",
          "headers": [ "name": "Accept", "value": "application/json" ]
        ,
        "response": 
          "status": 200,
          "content": 
            "mimeType": "application/json",
            "text": ""id":42,"name":"Alice""
          
        
      
    ]
  

This JSON format is not only human-readable but also compatible with a broad ecosystem of tools, further enhancing its utility. The inclusion of fields like version, creator (detailing the tool used for generation), and entries (representing individual request-response pairs) provides a comprehensive record of network interactions.

Managing Sensitive Data: Enhanced Security with Filters

HAR files, by their nature, can inadvertently capture sensitive information embedded within request headers or query parameters, such as session cookies, authorization tokens, and API keys. Replay addresses this potential vulnerability through its robust filtering capabilities, allowing developers to redact sensitive data during the recording process.

This is achieved by configuring filters directly within the @Test annotation:

@Test(
    .replay(
        "fetchUser",
        filters: [
            .headers(removing: ["Authorization", "Cookie"]),
            .queryParameters(removing: ["token", "api_key"])
        ]
    )
)
func fetchUser() async throws  /* ... */ 

The guiding principle here is to establish filters before recording commences, ensuring that sensitive data is never captured in the first place. This proactive approach to data security is a critical component of Replay’s design.

Flexible Matching Strategies: Adapting to Dynamic APIs

By default, Replay matches incoming HTTP requests against recorded entries based on the HTTP method and the complete URL. However, for APIs that incorporate dynamic query parameters, such as pagination cursors, timestamps, or cache-busting tokens, this strict matching can lead to test failures. To accommodate such scenarios, Replay offers flexible matching strategies.

Developers can configure looser matching criteria, for instance, by focusing on the HTTP method and the URL path:

@Test(.replay("fetchUser", matching: [.method, .path]))
func fetchUser() async throws  /* ... */ 

Replay provides a comprehensive set of matchers, including .method, .url, .host, .path, .query, .headers([...]), .body, and a .custom(...) option for implementing arbitrary matching logic. This flexibility ensures that Replay can adapt to a wide array of API structures and behaviors.

Inline Stubs: Targeted Test Scenarios

Beyond recording real network traffic, Replay also supports inline stubbing for specific test cases. This feature is particularly useful for simulating error conditions, testing edge cases, or scenarios where the exact response content is less critical than the status code or headers.

An example of inline stubbing:

@Test(
    .replay(
        stubs: [
            .get("https://api.example.com/health", 200, ["Content-Type": "application/json"]) 
                #""status": "ok""#
            
        ]
    )
)
func testHealthCheck() async throws 
    let (data, _) = try await URLSession.shared.data(
        from: URL(string: "https://api.example.com/health")!
    )
    #expect(String(data: data, encoding: .utf8) == #""status": "ok""#)

This capability allows developers to precisely control the simulated network responses, facilitating more targeted and comprehensive testing of application logic.

A Maturation of Testing Practices for Swift

The refinement of HTTP recording practices over fifteen years across various programming language ecosystems—including Ruby, Python, and JavaScript—has established a set of clear best practices. These include the imperative to capture real network traffic, diligently strip sensitive data, implement mechanisms for failing fast when fixtures are absent, and provide informative error messages when issues arise. Replay synthesizes these well-honed principles and delivers them to the Swift development community.

For developers who have grappled with the unreliability of API tests or have postponed the essential task of testing their network code due to perceived high overhead, Replay presents a compelling solution. By embracing this tool, developers can significantly enhance the stability, speed, and maintainability of their Swift applications.

Replay is available as an open-source project on GitHub. Developers are encouraged to explore its capabilities and provide feedback.

]]>
https://codeguilds.com/replay-brings-battle-tested-http-recording-to-swift-development/feed/ 0