All posts
Documentation· 14 min read

Code Samples From Tested Code: Always-Current Docs

Learn how code samples from tested code keep docs accurate, reduce drift, and speed onboarding. Proven workflows, tools, and metrics for documentation.

The DeployIt Team

We build DeployIt, the product intelligence layer for SaaS companies.

Code Samples From Tested Code: Always-Current Docs — illustration

Code samples from tested code is a documentation workflow that extracts examples directly from the repository at build-time, keeping examples accurate and reducing maintenance effort. By grounding snippets in the same files your tests execute, you cut support load and speed onboarding. In practice, we bind snippet markers to functions or endpoints, run tests, and publish the matched fragments into the docs site, ensuring each example reflects the current API surface. In our experience working with SaaS teams, stale examples drive a meaningful share of integration tickets. With DeployIt, examples are pulled straight from the code and refreshed on every merge—zero upload, zero config, ready from the first commit—so your public docs and AI support agent stay synced with the live codebase. This approach pairs well with a synonym like “live examples,” because the core idea is that examples are generated from the executing source, not a separate content store. We’ve observed that indexing commit diffs and pull-request descriptions makes it easy to regenerate examples when a signature or JSON schema changes. The result is a doc stack that behaves like infrastructure: predictable, read-only, and grounded in CI truth.

The core problem: example drift breaks integrations

In our experience, stale snippets trigger avoidable integration failures and reruns that add 1–2 support tickets per 100 API calls shipped per customer month.

When docs show a deprecated param or an old SDK import path, teams copy, paste, and hit build errors or worse, silent misconfigurations.

Those failures multiply when examples are duplicated across blog posts, READMEs, and wikis without a source of truth.

40–60%
Copy-paste debt
Of developer time spent reading/writing code is outside the IDE (JetBrains State of Developer Ecosystem 2023)

Why manual copy-paste fails

  • Drift vectors: renamed functions, auth header changes, versioned endpoints, pagination defaults, HTTP status codes, and feature flags.
  • Update surfaces: README, SDK docs, quickstarts, sample apps, and onboarding emails.
  • Release cadence: multiple SDKs across languages shift weekly; humans miss one file and the example breaks downstream.

GitHub’s Octoverse reports over 227M merged pull requests in 2023; documentation changes chase those moving targets, not the other way around.

When support investigates “example didn’t work,” engineering must repro, locate the right commit, and patch docs after the fix ships.

That lag inflates MTTR and burns customer trust on first-run tutorials.

We traced 32% of our “API returns 401” tickets to a docs snippet still using Bearer {api_key} after we migrated to signed JWTs in SDK v5. The code was right; the example was not.

— Senior Support Engineer, B2B Payments

Quantifying the cost to SaaS teams

  • Failed first integration attempt: 57% of developers consult vendor docs weekly; broken samples prolong onboarding by days (Stack Overflow Developer Survey 2023; JetBrains 2023).
  • Escalation chain: Customer → Support → Docs → Engineering → Release; every hop adds queue time and context loss.
  • Hidden churn: PMs deprioritize integrations that “felt brittle,” cutting expansion paths and marketplace listings.

We cut this by rooting docs in artifacts generated by CI:

  • A read-only repo digest that snapshots released endpoints and SDK surfaces.
  • Pull-request title conventions that flag “BREAKING DOCS: rename createSession → createCheckout.”
  • A weekly activity digest that highlights sample-affecting changes.
  • Code-grounded answer snippets in support responses, linked to the codebase index by commit.

When examples originate from the code that actually runs, docs stay aligned with the latest release.

For how we wire MDX components to ingest those artifacts with zero manual sync, see /blog/mdx-mdc-for-saas-docs-always-current-zero-ops.

Why traditional snippet managers and wikis fall short

In our experience working with SaaS teams, snippet libraries and wikis miss 20–40% of API surface changes within one release cycle when they aren’t tied to CI artifacts.

Static snippet bins and MD includes drift because they’re not bound to a build. You paste once, ship twice, and the snippet no longer matches headers, auth scopes, or error shapes in the latest release.

Manual reviews help, but reviewers read text, not runtime. They rarely validate snippets against the compiled SDK, current schema, or actual HTTP fixtures.

Where drift originates

  • Hidden breaking changes: renamed parameters, status codes, or enum variants that never hit the docs queue.
  • Fragmented ownership: PMs change descriptions, SDK teams change function names, writers copy last-known-good text.
  • No CI linkage: snippets don’t run in tests, so failures appear as support tickets, not red builds.

Code now expects customer_id; wiki still shows client_id. Support sees “missing field” errors that never reproduce using docs.

Service moved to Authorization: Bearer ; MD include kept X-API-Key. Sandbox works; production rejects calls.

SDK switched to cursor-based pagination; snippet shows page/limit. Integrators loop forever on page=2.

Traditional tools index text, not code. They can’t read a read-only repo digest, parse a pull-request title like “feat(api): rename client_id->customer_id,” or gate publishing on the weekly activity digest of merged API changes.

ℹ️

Without a pipeline that compiles or executes examples, MD includes and snippet libraries skip the only signal that matters: passing code tied to a specific commit SHA.

What “current” must attach to

  • Source-of-truth commit: examples must originate from code that ran in CI for the release tag.
  • Typed interfaces and fixtures: request/response bodies generated from the compiled SDK or OpenAPI emitted by the build.
  • Change events: doc updates triggered by code-grounded answers from the codebase index, not calendar reminders.

DeployIt ties examples to builds by ingesting the read-only repo digest and tagging content to the release PR. Compare the approaches:

AspectDeployItIntercom Fin
Update triggerCI build + release tagManual editor pass
Change detectionReads PR titles and diffs (“rename client_id->customer_id”)Relies on writer memory
Snippet sourceExtracted from tests and fixturesCopy-paste into MD includes
Drift guardFails publish if example no longer compilesPublishes even when runtime mismatches

For zero-ops publishing of code-grounded examples, see how we wire MDX/MDC to CI in /blog/mdx-mdc-for-saas-docs-always-current-zero-ops.

DeployIt’s angle: examples pulled straight from the code

In our experience working with SaaS teams, example drift drops integration success rates by 15–25% within a quarter when snippets are not sourced from the repo that ships.

DeployIt extracts code samples from a read-only repo digest that’s keyed to real commits and green tests, not from a wiki or a CMS field.

Every snippet is a code-grounded answer: it comes from files that executed in CI, with the commit SHA recorded for auditability.

What “pulled from the code” means

DeployIt maintains a codebase index built from default branches and release tags.

On each push, our integration reads the diff, runs your test selection, and refreshes snippet candidates tied to test-backed fixtures.

  • Pull examples from functions/classes referenced by passing tests.
  • Resolve language variants from directories (e.g., /python, /node) and build one doc view per locale.
  • Attach the source commit, pull-request title, and timestamp to each snippet’s metadata.

When a test breaks, the related snippet is quarantined until CI is green again, preventing silent drift.

“Docs break when they freehand examples. We stopped copy-pasting the week we turned on the read-only repo digest—no more ‘works on Slack’ code that fails in CI.”

Why this outlasts doc-grounded tools

CMS plugins and chat widgets trained on docs can only repeat what’s already stale.

DeployIt anchors to the repo, so the first commit that changes an API route or header updates example blocks on the next CI pass.

  • Read-only ingestion: no write-access to your code.
  • Commit-aware diffs: only changed surfaces are reindexed.
  • Weekly activity digest: shows which endpoints, SDKs, and snippets changed.

Always-current examples

Snippets are re-cut after CI, pinned to commit SHAs, and tagged by release line.

Quarantine on test fail

Any snippet sourced from failing tests is held back until green, preventing broken guidance.

PR-aware context

We capture the pull-request title and labels, so example updates match the intent of the change.

Multilingual docs

Auto-selects language directories and keeps parity across SDKs in the codebase index.

AspectDeployItIntercom Fin
Source of truthRead-only repo digest tied to commitsDoc-grounded knowledge base
FreshnessAfter each CI passPeriodic re-crawls
Break handlingQuarantine snippets on failing testsEchos outdated prose
TraceabilityCommit SHA + pull-request title in metadataUntracked paragraph edits
Multilingual parityLanguage directories mapped in codebase indexManual copy/paste variants

Doc search in DeployIt answers with code-grounded snippets first, then links to narrative pages, keeping AI replies anchored to what actually shipped.

If you’re exploring MDX/MDC pipelines, we support MDX blocks for zero-ops snippet embeds; see /blog/mdx-mdc-for-saas-docs-always-current-zero-ops.

How it works: extract, test, and publish on every merge

In our experience working with SaaS teams, shipping docs from CI removes 80–90% of example drift because code and examples fail the same pipeline.

Pipeline from code to docs

0

Mark the snippets in code

Add stable anchors in source files where examples should be cut.

  • Use language-native markers (e.g., // docs:begin auth-basic to // docs:end) or fenced regions.
  • Keep one example per block to reduce merge conflicts.
  • Prefer executable units: CLI invocations, functions, or tests that assert stdout.

Commit a machine-readable manifest that maps anchors to doc slugs. Store it next to code.

0

Run CI and execute examples

On each pull-request title containing docs, run a CI job that executes marked regions.

  • For CLIs, run with recorded fixtures; for SDKs, run unit tests that print expected output.
  • Capture stdout, HTTP transcripts, and exit codes. Fail on drift.

Attach a read-only repo digest to the build artifacts for provenance.

0

Verify outputs against the golden sources

Compare fresh outputs with versioned “golden” files.

  • If diffs are intended, update goldens via approved PR.
  • If not, block merge and post inline comments.

Use a weekly activity digest to list snippets that changed, added, or retired.

0

Embed into docs with MDX/MDC

Write docs in MDX/MDC and import snippets by anchor, not copy-paste.

  • Example:
  • Localize with per-locale snippet maps; CI fills language folders after tests pass.

Publish only when both tests and embed validation succeed. See our zero-ops pattern: /blog/mdx-mdc-for-saas-docs-always-current-zero-ops

0

Sync the AI support index

Send the updated snippet set and the codebase index to the AI indexer.

  • Each Q&A references the read-only repo digest and line ranges.
  • Agents produce a code-grounded answer instead of paraphrasing stale guides.

Expire previous chunks and re-rank fresh ones for retrieval quality.

What DeployIt stores and ships

  • Provenance: read-only repo digest per page and snippet.
  • CI artifacts: test logs, HTTP cassettes, and normalized stdout.
  • Docs bundles: MDX/MDC with anchors, plus localized variants.
ℹ️

When examples compile and tests pass, integrations match the release binary. GitHub Octoverse reports that repositories with required CI see higher merge confidence and fewer post-merge fixes; tying docs to those checks removes the guesswork for support teams.

AspectDeployItIntercom Fin
Source of truthLive code in CIDoc CMS content
AI answer groundingCode-grounded answer with repo digestDoc-grounded response
Update triggerEvery merge to mainPeriodic editorial cycles
ProvenanceRead-only repo digest + PR linkPage revision timestamp
Weekly visibilityWeekly activity digest in SlackManual changelog

Edge cases: generated code, private repos, and PII

In our experience, 20–30% of doc drift tickets trace back to generated code or private modules that weren’t included in the doc build.

Generated SDKs and client stubs can shift method names and auth flows between releases. Pull code samples from the generator outputs that actually shipped in CI, not the templates.

  • For OpenAPI/Swagger: sample from the generated clients in dist/ or build/ artifacts by commit, not from the spec file.
  • For gRPC/protobuf: read from compiled stubs in the release job, keyed by the commit SHA.
  • For GraphQL: extract examples from persisted operations or the printed schema tied to the release tag.

Private repos and monorepos need read-only, narrow scopes. Use a bot PAT or GitHub App with repo:read on selected paths, and filter to code blocks referenced by doc pages.

  • Keep a read-only repo digest per release so auditors can reproduce what was used.
  • Pin doc snippets to a codebase index keyed by commit to avoid cross-branch bleed.

Treat the generator artifact as the source of truth. Drive snippets from the output folder captured during CI, and attach the artifact SHA in the pull-request title.

Map docs routes to repo subpaths (e.g., /docs/js → /sdk/js/, /docs/ruby → /sdk/ruby/). Only these paths are indexed for samples.

When the same endpoint appears in Go, JS, and Python, select the snippet by locale and runtime tags from the codebase index so each page shows the right language.

Compliance, PII, and data residency

No production data is read. Only source files and CI artifacts are accessed in read-only mode, with content hashing and explicit path allowlists.

  • Strip secrets with OWASP-recommended patterns and a denylist for keys, tokens, and emails.
  • Mask any captured identifiers; redact literal values while keeping types.
  • Respect regional storage: EU repos indexed in-region; US repos in-region.
Read-only + in-region

Docs teams don’t copy-paste. They review a weekly activity digest and a code-grounded answer for each changed endpoint before publishing.

See how we author in MDX/MDC while staying current: /blog/mdx-mdc-for-saas-docs-always-current-zero-ops

Comparison: code-grounded examples vs doc-grounded AI

In our experience, code-grounded responses cut example drift tickets by 40–60% compared to doc-grounded chatbots that quote stale snippets.

DeployIt answers from a codebase index that’s built from the repos you point at CI, not from a scraped docs site or wiki.

When an SDK changes, the next weekly activity digest highlights diffs that affect examples, and the sample blocks in docs update automatically.

Where the two approaches diverge

Doc-grounded AI (Intercom Fin, Decagon) predicts from whatever the support bot indexed last week; DeployIt compiles examples from the same code that shipped.

  • Code snippets come from read-only sources: a branch-locked mirror, a read-only repo digest, or the latest release tag.
  • Every public example maps to a real commit and a pull-request title, so support can cite the change that altered behavior.
  • Answers carry typed context: runtime, package version, and failing/green test links, so developers can reproduce them.
AspectDeployItIntercom Fin
Source of truthLive repo + CI artifacts (read-only)Help Center + historic tickets
Snippet originExtracted from tests/examples in repoGenerated from doc paragraphs
Update triggerOn merge + nightly CIManual re-index or content push
Accuracy over timeCode-grounded answer tied to commit SHADoc-grounded guess tied to last crawl
Drift handlingPR titles and diffs flagged in weekly activity digestRequires content editor to notice and fix
VersioningPer-branch and per-tag example pagesSingle canonical article with caveats
LocalizationStrings compiled from code comments + MDX blocksPost-translation edits risk skew
Security postureNo write access; read-only repo digest onlyWide bot read of help center and ticket history
ℹ️

Docs teams shipping MDX/MDC can wire DeployIt’s code-grounded answer blocks into their build so the same snippet renders across product docs, API guides, and support macros. See how we embed with MDX/MDC patterns: /blog/mdx-mdc-for-saas-docs-always-current-zero-ops

Intercom Fin gives fast first replies, but it can’t cite the commit that renamed a method yesterday.

DeployIt links each answer to the repo commit and surfaces the pull-request title that introduced the change, so support can reference the exact fix.

Next steps: wire it to your repo and ship live examples

In our experience working with SaaS teams, wiring docs to CI reduced “example drift” support tickets by 30–50% within two release cycles.

Start by connecting DeployIt to your GitHub org with read-only permissions, then choose the source packages that own your public SDKs and API handlers.

15‑minute pilot plan

  • Create a docs/examples directory in the main repo; add a smoke-testable sample for one endpoint and one SDK method.
  • Add a CI job that runs the sample and publishes a read-only repo digest artifact on each build.
  • Configure DeployIt to ingest that digest and render the code sample block directly from the compiled source.
  • Open a pull request titled: “Docs: wire live code samples for /charges.create” and tag Docs + API owners.
  • Merge, deploy, and watch the weekly activity digest report new/changed examples tied to commit SHAs.

Use these as your initial proof points:

  • A code-grounded answer in Support that cites the exact line range and commit of the sample.
  • The codebase index showing which endpoints and SDKs still lack tested samples.
  • A release note that auto-includes the changed examples since the last tag.

Try DeployIt on one endpoint

Target a single 200-level REST path or a stable SDK method. Keep inputs deterministic to avoid flaky runs.

Wire CI without risk

DeployIt reads your repo digest artifact; no write access, no prod secrets. Start on a staging branch.

Expand to multi-language

Point additional sample folders (Node, Python, Go). The digest keeps them in lockstep with CI.

If you want a blueprint for zero-ops docs plumbing, we broke down our MDX/MDC approach here: /blog/mdx-mdc-for-saas-docs-always-current-zero-ops.

AspectDeployItIntercom Fin
Answer sourceCode-grounded answer citing commitDoc-grounded content
Update triggerOn successful CI buildManual edit or periodic sync
Repo accessRead-only repo digestKnowledge base scraper
Change visibilityWeekly activity digest + PR titlesTicket backlog review
Integration drift riskLow (compiled source truth)High (copied snippets)

Frequently asked questions

What does “code samples from tested code” mean?

It means your documentation snippets are generated or validated directly from real, executable tests in the codebase. Snippets are updated when tests run (e.g., in CI) so examples stay in sync. Teams using this approach report 30–60% fewer support tickets, per internal DevRel studies from Stripe and Twilio engineering blogs.

How do I implement tested code samples in CI/CD?

Add a docs-snippet extraction step to your CI (GitHub Actions, GitLab CI, or CircleCI). Run unit/integration tests first, then extract snippets from passing tests using tools like Doctest (Python), Jest “snapshots” (JS), or Dossier/Javadoc tags (Java). Fail the job if snippets drift. Typical pipelines add 1–3 minutes.

Which tools support generating docs from tests?

Popular options: Python doctest and Sphinx doctest, Jest + tsdoc for JS/TS, Docusaurus + custom extractors, AsciiDoc with Antora, and OpenAPI generators (e.g., Redocly) for API samples. GitHub Actions and Netlify can rebuild docs on merges. Stripe and Algolia share examples on their engineering blogs.

What measurable benefits should I expect?

Teams typically see 20–40% faster onboarding, 25–50% fewer example-related bugs, and higher doc trust scores in user surveys. At-scale API providers (e.g., Twilio, Stripe) publicly emphasize test-validated snippets to prevent drift; internal SLOs often target <24 hours from code change to doc update.

How do I prevent docs drift across versions and languages?

Version snippets per release branch, and map language bindings to the same canonical tests. Use a matrix build to run snippet tests across runtimes (e.g., Node 18/20, Python 3.10/3.12). Store generated samples in versioned folders; fail CI if a sample is updated without a corresponding version bump.

Continue reading