Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

RustManifest

A Rust review engine where no finding is a matter of taste.

RustManifest records facts about your code — call edges, reads and writes, outside-world effects, value provenance — and derives every finding from those facts. Each result carries a rule id, a severity, an exact location, and a rustmanifest:// rationale URI that resolves to the methodology section behind it, plus the engine’s own reasoning trace. Every claim is verifiable, or you did not get it from this engine.

What lives where

  • The engine (rustmanifest) — a CLI that reviews code, prints the fact base, traces effects and value provenance, and explains every rule.
  • The MCP server (rustmanifest-mcp) — the same understanding over JSON-RPC/stdio for AI agents, with thirteen tools.
  • The methodology — the documents every rationale URI resolves to, collected in the methodology section of this book.
  • The roadmap — what shipped and what is next.

Principles

  • Facts, not opinions. Rules are executable checks over a recorded fact base (AST, module graph, type graph, behavioral and value facts), not regexes over source text.
  • No clippy duplication. Where clippy is strictly better, the engine delegates (check --delegate-clippy) instead of reimplementing.
  • Every finding is traceable. The trace field shows the fact/reason chain; explain RM-SEC-001 prints severity, tier, and the methodology excerpt behind the rationale URI.
  • Built for agents. Findings, facts, overviews and intents reach LLM clients through MCP and the bundled Claude Code skill with the same rationale URIs.

Start with the Quickstart, then keep the CLI reference open.

Quickstart

Install

Not on crates.io yet; install from source:

cargo install --git https://github.com/RAprogramm/RustManifest --bin rustmanifest --bin rustmanifest-mcp

First review

rustmanifest check src/ --format tty
rustmanifest overview src/
rustmanifest explain RM-SEC-001

Exit codes: 0 clean, 1 findings present, 2 operational error, 3 question refused because facts are insufficient. In CI use --format sarif for code scanning or --format json for pipelines.

Ask the engine questions

rustmanifest ask main net          # does main reach the network, and how
rustmanifest facts src/ --filter Server   # behavioral facts per function
rustmanifest graph src/ --kind modules    # module dependency graph
rustmanifest coverage src/         # how much the fact base resolved

Full command surface: CLI reference.

Connect an agent (MCP)

rustmanifest-mcp speaks JSON-RPC over stdio and reads paths inside its workspace root. Add it to any MCP client:

{
  "mcpServers": {
    "rustmanifest": { "command": "rustmanifest-mcp" }
  }
}

Tool surface: MCP tools.

Install the Claude Code skill

/plugin marketplace add RAprogramm/RustManifest
/plugin install rustmanifest-review@rustmanifest

The skill drives the engine for reviews, effect tracing, blast-radius analysis, boundary gates, intent backlogs, store audits, onboarding tours and structural fact lookups.

Roadmap

Canonical plan for rustmanifest. Updated with every phase-completing PR.

Current status (2026-12-04): Phases 1C, 1D, 1E, 2, 2S, 2M and 2V shipped. The rules pack holds 22 rules — RM-SEC-001..003, RM-STRUCT-001..008, RM-STRUCT-010, RM-STRUCT-011, RM-MEM-001..003, RM-IO-001..004, RM-QUAL-001..002 — and tier-2 AST rules cover the implemented STRUCTURE.md sections. Phase 2S (semantic tier, per RFC 0001 and RESEARCH-2026-07): workspace type graph with derive/macro expansion absorption, module graph with cycle detection, behavioral facts (reads/writes/constructs/errors/effects), user-declared invariants, ownership facts, call graph with transitive effects. The stdio MCP server ships thirteen tools — review_file, review_path, check_rule, lint_structure, explain_rule, project_overview, function_facts, suppressions, deduce_trait, derived_intents, whence_value, why_kept, learn_conventions — and nine bundled methodology resources, so agents read the same project understanding the CLI prints. The CLI ships fifteen commands: ask, check, audit, coverage, versions, explain, document, facts, graph, learn, meaning, overview, prescribe, report, resolve. Phase 2V (value tier, per RFC 0004) adds the inward half of the fact base — what a program reads, what it computes, what it chooses among, what it hands back — and the per-function summary that carries a value’s origin across a call; rustmanifest-resolve is a second binary writing the resolution overlay every value-reading command accepts through --resolution.

Landed since the semantic tier closed: the resolved-name extractor as an opt-in SCIP overlay (--scip) reaching facts, check and the invariant surface, with edge provenance in traces; call resolution confined to cargo build-target boundaries; error-conversion edges synthesized from From implementations at ? sites; macro expansion promoted to a standard analysis mode; multi-implementor dispatch over-approximated with the modality stated in the trace; ecosystem knowledge packs (reqwest, tempfile, tokio) plus standard-library knowledge, quoted in findings from the library’s own documentation with the cost of a deviation counted rather than described; machine-applicable fixes applied by check --fix. Tooling hardening: audit subcommand as a tier-3 external-tool orchestrator, versions subcommand with --fix and RM-VERSIONS-001 integration in check, Dependabot config, periodic CI workflow (udeps/hakari/mutants/semver-checks), and CI jobs for miri/sanitizers/cargo-careful/fuzz/cargo-geiger/versions. Graph cross-module fixtures were aligned with ra_ap 0.345 qualified-path resolution. The rustmanifest-ci binary generates per-job CI configuration for GitHub/GitLab, and the mdBook documentation site is assembled from canonical repository documents for GitHub Pages deployment through the Actions workflow.

Next: Phase 3 (HTTP/OAuth — tier-3 clippy delegation already shipped as check --delegate-clippy), the value tier’s own follow-ons (the four unresolved questions of RFC 0004), and the research plan’s later phases (Ascent, tsetlin-rs ranking, MIR refiner). Planned maintenance: migrate error handling to masterror (P1, last), keep CI/tooling portable, and resolve pre-existing engine test failures observed under current toolchain.

Source layout: no source file exceeds 150 pure code lines (blank lines, /////////! and #[cfg(test)] blocks excluded); oversized modules are split into nested single-responsibility submodules, with the parent as X.rs beside the directory X/ and never a mod.rs.


Project goal

Ship a production-grade Rust review engine that:

  1. Enforces the methodology in this repository (docs/CODING-RULES.md, STRUCTURE.md, code-review-methodology/en/) as executable rules rather than prose.
  2. Exposes those rules to AI-assisted review through MCP — every finding carries a rustmanifest:// URI pointing to the relevant methodology section, so LLM clients can fetch the rationale on demand.
  3. Does not duplicate clippy. Where clippy is strictly better (e.g. unwrap_used, panic), the strategy is tier-3 delegation, not reimplementation.

The MCP server in Phase 2 is the project’s primary deliverable. Everything before it is foundation.


Phases

Phase 0 — Foundation ✅ done (#2, PR #3)

  • Cargo workspace with 8 crates.
  • Hardened CI on 4 OS (lint, test, MSRV 1.95, audit, deny, reuse, schema-drift, coverage, mcp-conformance scaffold).
  • Tag-triggered release pipeline with sigstore signing, SLSA L3 provenance, CycloneDX SBOM.
  • Schema crate (Rule, Finding, Config, MethodologyResource) with committed golden JSON Schemas and a drift gate.
  • Governance: threat model, governance doc, RFC template, security policy, issue and PR templates.
  • License: MIT with SPDX REUSE 3.x compliance, reuse lint in CI.

Hotfix — release-plz to manual ✅ done (#5, PR #6)

  • .github/workflows/release-plz.yml switched to workflow_dispatch only. No automatic publishing until the user explicitly enables it.

Phase 1A — Rules pack format ✅ done (#4, PR #7)

  • Rule schema reshaped: RuleDefinition externally tagged enum (pattern / ast / semantic) replaces the standalone Tier.
  • Per-rule directory layout under crates/rustmanifest-rules-core/rules/<RULE-ID>/{rule.toml, pass.rs, fail.rs}.
  • Build script bundles the pack into rules.json at compile time; lib.rs exposes RULES: LazyLock<Vec<Rule>>.
  • Pack-level invariants verified by integration tests.

Phase 1B — Tier-1 engine, renderers, CLI ✅ done (#8, PR #9)

  • PatternAnalyzer implementing the Analyzer trait for tier-1 (regex) rules with exclude_globs honoring.
  • Orchestrator with rayon-parallel execution, deterministic output sorting, cancellation token, per-file memory budget.
  • walker::discover — ignore-crate-based gitignore-aware file enumeration.
  • Inline pragma suppression: // rustmanifest: allow(RM-RULE-ID) reason="..." with mandatory reason.
  • Three renderers: JsonRenderer, SarifRenderer (SARIF 2.1.0), TtyRenderer (anstyle, NO_COLOR-aware).
  • CLI rustmanifest check subcommand with --format auto|json|sarif|tty, --severity-filter, --no-color, --max-file-size, --verbose.
  • Exit codes: 0 clean, 1 findings present, 2 operational error.
  • Tracing instrumentation, OpenTelemetry-friendly span fields.
  • Coverage: 11 engine unit tests, 3 engine integration tests, 4 renderer snapshot tests, 6 CLI integration tests via assert_cmd, criterion benchmark scaffold.
  • Decision recorded in memory: rules pack does NOT duplicate clippy. RM-RUST-001 (panic in production) and RM-PERF-001 (Vec::new() without with_capacity) were removed; the default pack now is RM-SEC-001/002/003.

Phase 1C — Tier-2 AST analyzer ✅ done (local)

  • AstAnalyzer implementing Analyzer for RuleDefinition::Ast { check }.
  • Built-in AST checks for the rules from STRUCTURE.md:
    • Entity naming (STRUCTURE.md §1).
    • Method naming (§2).
    • Structure size threshold (§3).
    • Public API surface (§4).
    • Constructor design (§5).
    • Delegating constructors (§6).
    • Immutability-first (§7).
    • Constant encapsulation (§8).
    • Fakes-only testing (§9).
  • Fixture coverage: each AST check ships pass/fail fixtures wired into the existing rules-core build pipeline.
  • Per-check tracing spans and memory budget integration.
  • Acceptance: every section of STRUCTURE.md corresponds to at least one shipped rule.

Phase 1D — Config, explain, cache ✅ done (local)

  • rustmanifest-config: parse rustmanifest.toml (profile selection, per-rule severity overrides, include/exclude globs).
  • Built-in profiles: strict, default, minimal, ci.
  • rustmanifest explain <RULE-ID> — prints the rule rationale and methodology section to stdout.
  • Inline unused-pragma finding (RM-META-001): pragma that references a rule that did not fire becomes a finding itself.
  • Optional persistent cache (content-addressed by (file_hash, rule_id_set)). Behind --cache <dir> flag, default off.

Phase 1E — Eval corpus and precision metrics ✅ done (local)

  • eval/ directory with 3–5 public Rust repositories as fixtures.
  • Per-rule precision / recall measurement against curated labels.
  • Baseline numbers committed; regression gate in CI for any drop > 2 percentage points.
  • Performance budget enforcement: p95 review_file < 100ms for files < 1k LOC.

Phase 1F — Reserved ✅ absorbed (cache landed in Phase 1D)

  • Reserved for cache layer landing if not absorbed by Phase 1D.

Phase 2 — MCP server (stdio) ✅ done (local; scripted stdio conformance tests shipped, external validator pending)

  • rustmanifest-mcp built on the rmcp SDK.
  • Tools (thirteen): review_file, review_path, check_rule, lint_structure, explain_rule, project_overview, function_facts, suppressions, deduce_trait, derived_intents, whence_value, why_kept, learn_conventions. The knowledge tools are the same surface the CLI prints, so an agent and a human read one understanding.
  • Resources: rustmanifest://methodology/{section} — nine English methodology documents; every rule’s rationale URI is gated against that list by test.
  • Roots: workspace root taken from the process directory at startup; every client path is joined and canonicalized against it, and a result outside the root is refused.
  • Scripted stdio conformance tests in CI; the external validator is still pending.
  • All server-facing strings are English regardless of request language.
  • Not shipped: prompts (pr-review, pre-commit-check, security-audit, structural-audit) — deferred, no prompt surface exists yet.

Phase 2S — Semantic tier: fact base, behavior, ownership ✅ done (local)

Executes the plan in RFC 0001 and RESEARCH-2026-07-behavioral-tier.md on the stable syntactic extractor.

  • Type graph (semantic/graph.rs): structs, enums, traits, impls, methods, fields, interaction edges; absorbs derive and macro expansion output so generated types count as understood.
  • Module graph (semantic/module_graph.rs): crate roots from Cargo target layout, mod/use resolution including Rust 2018 uniform paths, dependency cycle detection (RM-STRUCT-011), mermaid/dot diagrams via rustmanifest graph.
  • Behavioral facts (semantic/behavior.rs): per-function reads, writes, constructs, error types, and effects (unsafe, filesystem, network, process, env, console); let-binding type inference for field owner resolution; exported via rustmanifest facts.
  • User-declared invariants (semantic/invariant.rs): [[invariants]] in rustmanifest.toml — field writer allowlists (write-only-from) and effect bans (deny-in) — checked against the fact base, surfaced as RM-INV-* findings with full traces.
  • Ownership facts (semantic/behavior.rs, semantic/ownership.rs): parameter modes (owned / borrowed / mutably borrowed), use shapes, clone and heap-allocation call sites; first reasoning rule RM-MEM-001 — owned non-Copy parameter whose only observed use is field reads should be a borrow.
  • Call graph and transitive effects (semantic/calls.rs): call candidates recorded per function (free, associated, and method calls with receiver-type inference), resolved conservatively — an edge only on a unique match, ambiguity counted as unresolved; per-function effect sets closed over the graph to a fixpoint, so a function calling a filesystem-touching function is known to touch the filesystem.
  • Loop ownership rules (semantic/loops.rs, the §6b follow-ups): RM-MEM-002 — a read-only clone of a loop-invariant place belongs before the loop; RM-MEM-003 — a container allocated fresh every iteration that never escapes the iteration belongs outside the loop, cleared per pass.
  • Feature binarizer (semantic/features.rs, rustmanifest facts --features): fixed-order named binary features per function — boolean predicates plus thermometer-encoded counts — the substrate for the interpretable learning layer and role classification (research doc §5).
  • Role heuristics (semantic/role.rs): deterministic coarse role per function (io / mutator / constructor / accessor / pure / unknown), priority-ordered, surfaced in rustmanifest facts — the bootstrap labeling for the learning layer.
  • Interpretable learning layer (rustmanifest-learn, rustmanifest learn): one deterministic Tsetlin machine per role over the binarized features, dumped as an auditable clause list (research doc §5, admitted by the §8 gate result: +17pp macro-F1 over logistic regression). Clauses describe the codebase; they are never a source of findings.
  • Precision ceiling documented: move/borrow flow approximated by use-shape at the syntactic tier; real dataflow lands with the MIR refiner (research plan phase 6).

Phase 2M — Meaning tier: framework models, external surface, subsystem capabilities ✅ done (local)

Executes RFC 0002. The semantic tier answers structure and behavior; this phase answers what the program exposes and what each subsystem is for, deterministically and with evidence per row.

  • ✅ Framework models as data: the knowledge-pack shape extended with a crate’s registration vocabulary — router constructors, route registrations, HTTP method wrappers, composition methods (nest with prefix, merge without), extractor types, listener constructors. A construct absent from the model produces no row.
  • ✅ Route recovery (semantic/surface/): method, path, handler and byte range per registration; composition resolved through the existing call graph; a composition argument that is not a resolvable provider is reported as unresolved rather than silently dropped; runtime-assembled paths counted as dynamic; a conditionally registered route is recovered and marked, not lost. The table also counts what it could not read — unparsed sources, opaque handlers, framework vocabulary on a receiver never proven to hold a router — so silence is measured.
  • ✅ Handler contract: request body, path and query parameters, shared state and application-defined extractors read from the handler signature; response payload from the return type.
  • ✅ Observable output (RFC 0003): a fact channel recording every write site with its stream, payload, guard stack and order (semantic/behavior/output.rs), entry-point identification (semantic/entry.rs), and a reachability grade, exported through rustmanifest facts. The coarse effect category is left untouched by decision; retiring it is separate work.
  • ✅ Meaning claims (semantic/meaning/, rustmanifest meaning): one claim per write site — the stream, the text, and two certainties never merged into a score (reached from the entry, and runs on every path through its own function). A site the call graph never reaches keeps its claim and says so. The sentence degrades field by field: a weakened certainty names each construct that weakened it, a partially proven payload prints its proven text with the holes left as holes.
  • ✅ Canonical output forms (semantic/io_forms/, rules RM-IO-001..004): the forms live as data — the properties the code must satisfy, the shape that satisfies them, what one deviation costs in counted bytes or calls, and the library guarantee the cost follows from. Checks contribute only facts; the message is assembled mechanically, so a finding can never claim more than the catalogue and the fact base license.
  • ✅ Prescription (rustmanifest prescribe): the code the canonical form asks for, anchored to the line it replaces, with the counted gain stated beside it.
  • ✅ One-pass reports (rustmanifest overview, rustmanifest report): everything the engine knows about a project, behaviour first, absent sections dropped rather than printed empty.
  • ✅ Subsystem capability (semantic/capability/): what each module can do to the world outside the process — serves, fetches, stores, configures, persists, reports, spawns — read from the behavioral effect set and, where the category alone cannot tell a listening socket from a dialled one, from the written call that proved it. Each row names the function, that call, and its byte range, so a reader checks instead of believing. capabilities states it per module; started states which capabilities an entry point reaches through the call graph, keeping an unreached one as a row marked unreached rather than dropping it. A module whose functions touch nothing outside the process gets no row: silence means “no proof”, never “no capability”. unsafe proves none — it says how the code is checked, not what it can do. The proof channel itself is new fact-base surface (FunctionFacts::effect_sites), so an effect category is no longer an assertion without a citation.
  • ✅ Acceptance (route table) (rustmanifest-eval routes): precision and recall of the recovered route table against the #[utoipa::path] endpoints projects declare independently of the router chain. Measured 2026-08-05 on the two API workspaces of the corpus: ratma-studio-api recall 100.0% (139/139) at precision 91.4%, aura-api recall 98.9% (92/93) at precision 83.6%. The measurement paid for itself immediately: it found three endpoints lost behind a merge fold in a method-router chain, which is now fixed, and the single remaining disagreement is a path the two sides spell differently rather than one the engine failed to see. The two rates are never merged into one figure, and the disagreeing endpoints are named rather than counted. Both sides are named for what they are: an undeclared row is recovered and not annotated, an unrecovered row is declared and not produced — which of the two tables is wrong is the question the measurement asks, not one it answers. The measurement reports and never gates: turning it into a threshold before anyone has read what it says would invite the numbers to be chosen rather than measured.
  • ✅ Acceptance (output): the smallest program in the language — a single unconditional greeting — yields exactly one claim naming the stream, the literal payload, and certainty, and every weakening of that program (a branch, a loop, a computed string, an early exit) degrades the claim field by field instead of collapsing it.

Phase 2V — Value tier: the inward boundary, what is computed, where a value came from ✅ done (local)

Executes RFC 0004, all eight stages. The meaning tier states what a program writes out; this phase states what it takes in, what it computes from it, what it chooses among, what it hands back — and, through the per-function summary, where a written value came from when the answer lies past a call.

  • ✅ The value term (semantic/behavior/value/): where a value came from, as a written literal, one of the function’s own input slots, an index into a recorded read, operation, choice or call, or a named refusal. Inside one body it is an index and never a subtree, so two consumers of one value name one record instead of carrying two copies. FunctionFacts gains slots — one entry per declared input, receiver first — so a call site’s written arguments align with the callee’s parameters even where the profiled parameter list drops an input it cannot read.
  • ✅ Handbacks and enriched call sites (semantic/behavior/handback.rs, collector/site.rs): every site handing a value back to the caller, ? included; every call carrying the arguments it hands over, the disposal written around it, its byte range and the conditions standing over it. Disposal is stamped post-hoc by an exact byte-range match — zero or several matches is NotIdentified rather than a guess.
  • ✅ The inward boundary (semantic/behavior/input.rs, collector/input_read.rs, collector/intake_chain.rs): per read site — channel, selector, intake (text validated or raw bytes), terminator, shape, guard stack, conditions. Sources are recognized on the whole expanded path, so a configuration crate’s own lookup is never credited to the process environment. An adapter table says which adapters keep positions; one that does not degrades the selector to unidentified while the channel stays proven.
  • ✅ Operations and choices (semantic/behavior/operation.rs, choice/): language operators as a const fn over syn’s operator enums; library methods that operate through a table stating what they hand back and whether they can fail, with the guarding recorded (unchecked, checked, saturating, wrapping, reported) and integer arithmetic never called panicking, because the build decides. A choice records its scrutinee and one alternative per written arm. Closure is proven three ways and the ground is stated: a catch-all, every variant of a standard type named — the weaker proof, resting on written constructor names — or unproven, which is where a match over a workspace enum with one arm per variant lands, since nothing in the fact base enumerates a type’s variants.
  • ✅ Conversions as knowledge rows (semantic/knowledge/result.rs, std_knowledge/result.rs): a row states what a method hands back and whether it can fail. Sixteen standard-library rows ship; the target is read only where the source writes it as the call’s own type argument, never off the type a consumer declares. Deviation from the RFC, deliberate: the ecosystem packs (reqwest, tempfile, tokio) carry no method rows yet, so a conversion performed by one of them is not recorded as a conversion.
  • ✅ The condition stack (semantic/behavior/value/condition.rs): which construct each enclosing frame is, one entry per guard frame, outermost first, with equal lengths asserted. This yields arm identity without touching Guard, its const fn export contract, or a single golden file.
  • ✅ The summary tier (semantic/summary/): Tarjan condensation over the call graph emits callee-first in one pass — no fixpoint and no convergence argument — then substitutes a call’s written arguments for the callee’s slots. Every composition failure is named at the leaf rather than swallowed: recursion, unresolved or external callee, dispatch over several implementors, unwritten arguments, and a depth budget of 14 that emits its own refusal, so termination rests on the budget and not on an acyclicity argument.
  • ✅ The resolution overlay (rustmanifest-resolve, --resolution on every value-reading command): which function a call reaches, what it hands back, what type a receiver has, and — since the fact base learned to read it — which type holds each field read and what type that field has, all from a loaded cargo workspace. The field rows are what a syntactic reading cannot reach at all: a value read out of a type another crate declares. Measured on the engine’s own sources on 2026-08-06, after the reading rules had taken the syntactic tier as far as it goes: 92.3% without the overlay, 98.0% with it. Three silences of the resolver closed most of the difference once they were lifted — the test configuration, under which a well-tested workspace hides most of its code; field reads written inside a macro argument, which are exactly the positions a format string prints; and the calls written beside them. A binary of its own so the rust-analyzer libraries — weekly 0.0.x, no API stability — stay out of the tool a user runs on every save, and the engine takes the answers as plain data. A position the resolver cannot settle is absent from the overlay, so the engine reaches its own refusal instead of being handed a guess; a named overlay that cannot be read is an error and never a silent fallback.
  • ✅ Claims and the compound statement (semantic/meaning/intake.rs, claim.rs, narrative/): intake, compute, choice and handback claims field for field like the write claim, every recorded site becoming one, unreached ones included. The statement decomposes instead of weakening — a clause resting on a refusal is named together with the question it failed on, while the licensed clauses still read as sentences. A grade below certain degrades the wording and names the weakener; it does not refuse.
  • ✅ Export (facts_export/): reads, operations, choices, call sites and summaries ship on their own channels, each stamped with its recognizer-set version, so an empty channel reads as “the recognizer found none” and not as an absence of the thing.
  • ✅ Acceptance (the ladder) (crates/rustmanifest-engine/tests/ladder.rs, seven tests): a calculator traces its printed result back to the argument it was read from and states its choice is closed and which arm leaves; a create-read- update-delete store traces the written value back to the collection it came from and claims nothing about the status beyond what it leaves; a tutorial program keeps the position it read through later adapters, states both sides of its fallback, and reads through the closure written beside a combinator. Every assertion failed before the work it guards.
  • What this tier refuses, by design: a name bound or assigned more than once yields a named refusal, so an accumulator in a loop is stated as underived rather than guessed; there is no type inference, so a binding typed by a later use records no produced type; there is no rules tier over these facts — deriving comes first, cataloguing later.
  • ✅ The traced-position rate (the honesty section of rustmanifest report): of the positions a program actually prints, how many have their value traced all the way through the composition. The strict number, and the one a generation gate would stand on — the whole-statement rate saturates once no clause has to speak a refusal, and cannot stand in for it. Measured on 2026-08-06: masterror 52.7% (1177 of 2233), fork-hyper 31.2% without the overlay and 32.8% with it, the ordinary task list 8 of 8. The ladder’s own programs are fully traced: the greeting states its write with nothing left to derive, the calculator 41 of 41 positions and its one written position traced to the command line, the create-read-update-delete store 39 of 39 and 1 of 1, the task list 141 of 141 and 8 of 8. What stops the rest is one question and almost nothing else — which function a call reaches. It splits in two: a name the workspace does not declare at all now answers (the call leaves the program), and what remains is a name several workspace functions share, which only a receiver type settles. The overlay settles the receivers it can — 1609 calls of fork-hyper, 1860 of masterror — and the rest are generic-heavy sites it renders as unknown. That is where the remainder lives, and it is the resolver’s coverage rather than the reading rules.
  • ✅ A call that leaves the program is an answer, not a gap: what a function no workspace source declares hands back is decided outside the sources being read, which is as settled as the content of a field. Naming the callee states everything the program proves, and the refusal is kept for the case it was meant for — a name the workspace does declare that the binding rule cannot tie to one definition.
  • ✅ The whole-statement rate (the honesty section of rustmanifest report): how many entry points get a statement that holds together against how many decompose because a clause rests on a refusal. It is the harder of the two numbers and the one a generation gate would stand on: a tier can answer most positions and still break every sentence. Measured on 2026-08-06 after a refusal at an unreached site stopped counting against a statement about the process: masterror 6 of 11, fork-hyper 16 of 18, and an ordinary command-line task list 1 of 1 with every one of its 141 value positions derived.
  • ✅ Acceptance (origins, off our own sources): the same measurement run on three independent workspaces of the eval corpus on 2026-08-06 — masterror 88.6% (20474 of 23100), hydebar 92.8% (49086 of 52870), fork-hyper 89.1% (16121 of 18103) — against 88.3% on the engine’s own sources. The reading rules are therefore not fitted to this repository’s style: a rule that only worked on the code it was written against would show here as a rate that falls away from home. The figures report and never gate.
  • ✅ The reading rules the measurement paid for, each one general unless stated: a path the standard library defines as a value — a unit variant, an associated constant of a primitive — is that value, from a table of library names; a name the workspace declares as a constant or a static is that constant, the body being asked first so a binding still shadows it; a field names its owner wherever the collector’s own typing answers, instead of only on a parameter; what a loop hands its body is an element of what it iterates, recorded as the selection an index already is, and the same for the input of a closure written beside an adapter; a tuple pattern says which part each name holds, so taking a value apart keeps the origin; a conditional with an else chooses between two written alternatives and is recorded as that choice; a written structure is the value built at that position, and so is the value a standard macro builds; the propagating operator, an await and an unsafe block leave the same value standing; a block stands for the expression it ends with, and one that ends any other way is the unit value; a written tuple position, like an index, is a selection; a variant pattern names the payload it takes and a struct pattern the field it binds, the same rule reading a binding, a condition and an arm; a path of several segments names an item, which a binding never is; typing sees through a borrow as every other reading does; a macro of the library builds what the library says it builds, or ends the function and hands nothing back; what a resolver settled about a call and its receiver outranks the reading that infers from spelling; and two arms are two scopes, so a name bound in one never answers a reading in another — the one soundness bug the work found, which had been stating a value from the wrong branch.

Phase 3 — Streamable HTTP, OAuth, clippy delegation ⏳ in progress (clippy delegation done locally; HTTP/OAuth pending)

  • ⏳ HTTP transport with OAuth 2.1 + PKCE + RFC 8707 resource indicators.
  • ⏳ Audience-scoped tokens, TLS 1.3 only, per-client rate limiting.
  • ✅ Tier-3 delegation (check --delegate-clippy): cargo clippy --message-format=json parsed and surfaced under rustmanifest’s reporting umbrella, each delegated finding carrying a rationale URI into the clippy lint index.
  • ⏳ Optional cargo audit and cargo geiger integrations.

Phase 4 — Sampling and elicitation ⏳ planned

  • MCP sampling API for LLM-assisted classification of borderline findings.
  • elicitation flow for interactive suggested-fix application.
  • Per-prompt eval suite with golden labels; pass-rate gate before merge of any prompt change.

Phase 5 — Integrations and editors ⏳ planned

  • rust-manifest/rustmanifest-action@v1 GitHub Action (composite): runs rustmanifest check, uploads SARIF, comments on PR.
  • Pre-commit hook YAML snippet.
  • rustmanifest-lsp — LSP server reusing the engine. Diagnostics, code actions, hover. The crate today is a skeleton: it declares the targeted protocol version and nothing else, so nothing the engine knows reaches an editor over LSP yet.
  • Editor docs: Cursor, Zed, Helix, VS Code (LSP and MCP).

Phase 6 — Governance and community ⏳ planned

  • RFC process activated (template already shipped, no merged RFC yet).
  • Maintainer additions (currently solo).
  • Deprecation policy enforcement in CI.
  • Public release readiness gate (signed binaries, attested SBOM, crates.io publishing).
  • Triggers the flip of release-plz.yml back from workflow_dispatch to push: branches: [main].

Versioning, governance, security

These live alongside the roadmap and are referenced by every phase:


How to read this document

  • ✅ done — shipped in main. Issue closed, PR merged.
  • ⏳ in progress — there is an open PR or open issue actively being worked on.
  • ⏳ planned — defined scope; no PR yet.

Every phase that ships must update this file in the same PR. The PR description starts with Updates docs/ROADMAP.md status to ....

This document is the source of truth; pinned tracker issues and PR descriptions reference it, never the other way around.

rustmanifest CLI reference

Global options: -v/-vv/-vvv (verbosity). Every analysis command takes [PATHS]... defaulting to . and accepts --resolution <FILE> where noted.

Resolution overlay: a JSON file written by the resolve step (e.g. resolution.json at a workspace root) that lets a call into a library state the type it hands back instead of refusing. If such a file exists for the workspace under review, pass --resolution resolution.json to overview, report, facts, coverage, ask, and meaning for strictly more facts. An overlay written for a different workspace fails to parse — if the engine rejects the file, continue without it and say so; a stale overlay is worse than none.

check — run all bundled rules

rustmanifest check [PATHS]... --format <auto|json|sarif|tty>
                          [--severity-filter <error|warning|info|hint>]
                          [--config FILE] [--cache DIR] [--delegate-clippy]
                          [--fix] [--scip INDEX] [--max-file-size BYTES]
  • auto picks tty on a terminal, json when piped.
  • json: canonical pretty-printed array of findings (see reporting.md).
  • sarif: SARIF 2.1.0 document — use for CI integration.
  • --severity-filter sets the minimum severity to report (default hint = everything); use error or warning for a quick high-severity pass.
  • --config points at a rustmanifest.toml; defaults to one in the cwd.
  • --cache DIR enables a content-addressed persistent findings cache (never serves stale entries; the semantic tier is not cached).
  • --delegate-clippy also runs cargo clippy and surfaces its diagnostics as advisory findings; needs a Cargo.toml directly inside the first analyzed path; best-effort, never fails the run.
  • --fix applies only machine fixes proven safe, then re-runs the analysis. Requires the user’s explicit ask for fixes — it edits files.
  • --scip INDEX overlays name-resolved call edges (from rust-analyzer scip .) so invariants are checked through calls the syntactic resolver cannot bind.

Example — full workspace review to a file, then aggregate:

rustmanifest check crates --format json > /tmp/findings.json
jq -r 'group_by(.severity)[] | "\(.[0].severity): \(length)"' /tmp/findings.json

explain — rationale for one rule

rustmanifest explain <RULE_ID>        # e.g. RM-SEC-001

Prints severity, tier, rationale URI, then the methodology excerpt the URI resolves to.

overview / report — whole-project knowledge

rustmanifest overview [PATHS]... [--top N] [--resolution F]
rustmanifest report   [PATHS]... [--top N] [--resolution F]

One combined report of everything the engine knows; --top caps every ranked list (default 10).

ask — why a function carries an effect

rustmanifest ask <FUNCTION> <EFFECT> [PATHS]...

FUNCTION — qualified or bare name. EFFECT — one of fs, net, process, env, console, db-read, db-write, db (a provably sent statement with its kind unproven), unsafe. The answer is a step-by-step inference over recorded facts.

facts — behavioral facts as JSON

rustmanifest facts [PATHS]... [--filter SUBSTR] [--active] [--features]
                   [--expand] [--scip INDEX] [--resolution F]

Per function: reads, writes, constructions, error types, effects, parameter ownership, derived behavioral role. --active keeps only functions with at least one write, effect, or error type. --expand macro-expands crates via cargo +nightly rustc -Zunpretty=expanded so macro-generated functions become facts (test modules are absent from the expanded universe). --scip overlays name-resolved call edges from a rust-analyzer scip . index.

coverage — how much the engine understands

rustmanifest coverage [PATHS]... [--unresolved] [--expand] [--scip INDEX]

--unresolved lists every unresolved use target with its occurrence count — the inspectable form of the “unresolved” bucket. Run this before trusting a review of a dependency-heavy crate: low coverage means blind spots.

meaning — outside-world behavior

rustmanifest meaning [PATHS]... [--format text|json] [--resolution F]

What the program does for an observer outside the process; text is an aligned table of entry points, json one object per entry point.

graph — architecture diagram

rustmanifest graph [PATHS]... --kind <modules|types> --format <...>

modules: one node per module, one edge per resolved intra-crate dependency. types: one node per structure, one edge per aggregating field.

prescribe — the canonical form’s code

rustmanifest prescribe [PATHS]... [--why]

Prints the code the canonical form asks for and what it buys; --why adds the counts before/after and the facts each count rests on.

learn — per-role convention clauses

rustmanifest learn [PATHS]... [--clauses N] [--epochs N] [--seed N]

Deterministic training (identical seeds yield identical clauses); output is an auditable JSON rule list of conventions learned from the codebase itself.

audit — tier-3 external tool orchestration

rustmanifest audit [PATH] [--profile pr|nightly]

Runs available external verification tools and aggregates their output. pr profile runs fast checks (clippy, cargo-deny, cargo-audit, cargo-udeps); nightly adds heavier checks (miri, cargo-careful, cargo-fuzz, cargo-semver-checks, cargo-mutants, cargo-hakari). Missing tools are reported, not treated as hard failures.

versions — workspace version synchronisation

rustmanifest versions [PATH] [--fix]

Reports MSRV, toolchain channel, and ra_ap_* dependency alignment. With --fix, aligns ra_ap_* versions in the workspace manifest when possible.

document — compiler documentation index

rustmanifest document [PATH] [--toolchain nightly]

Emits the compiler documentation index for the workspace. Uses a nightly toolchain by default because the emitter is unstable. Missing toolchains or emitter failures are reported as operational errors.

resolve — resolution overlay

rustmanifest resolve [PATH] [--out FILE]

Produces a resolution overlay (default resolution.json in the workspace root) for type/call-aware analysis. Other commands consume it via --resolution.

rustmanifest-ci — CI generator

A separate binary that generates CI configuration from a job catalog; one file per job, the main workflow holds only triggers and job references.

rustmanifest-ci [-r ROOT] init --platform <github|gitlab> [--jobs a,b] [--force]
rustmanifest-ci [-r ROOT] enable --job <id> [-p <github|gitlab>]
rustmanifest-ci [-r ROOT] disable --job <id> [-p <github|gitlab>]
rustmanifest-ci [-r ROOT] list [-p <github|gitlab>]
  • init writes .github/workflows/ci.yml plus _<job>.yml per job (GitHub) or .gitlab-ci.yml plus .gitlab-ci/jobs/<job>.yml (GitLab). Existing files are never overwritten without --force; --jobs narrows the catalog, which defaults to all of: fmt, clippy, test, coverage, audit, deny, versions, docs.
  • enable/disable toggle a job by commenting its reference in the main file; the job file itself stays untouched. Provider is detected from the files present unless -p is given.
  • list prints every catalog job with its current state (enabled, disabled, not generated).

RustManifest MCP tools

All tools are read-only and restricted to paths inside the MCP server’s workspace root (its startup directory); paths outside the root are rejected — fall back to the CLI for those. Methodology documents are also exposed as MCP resources under rustmanifest://methodology/...; finding rationale URIs resolve to them.

Prefer MCP tools when the server is connected: results arrive structured, no shell quoting, no temp files. Prefer the CLI for: paths outside the root, SARIF output, --expand/--scip/--resolution overlays, and very large scopes you want to post-process with jq.

Review

  • review_file(path) — every bundled rule against one file; returns the findings list.
  • review_path(path) — every bundled rule against a file or directory.
  • check_rule(rule_id, path) — exactly one bundled rule against a path; use to re-run a single rule after a fix.
  • lint_structure(path) — only the structural rules (RM-STRUCT-*), as a JSON array.

Knowledge

  • project_overview(path) — everything the engine knows about a path as one Markdown report: module map with cycle warnings, central types, behavioral roles, outside-world boundaries, most contended state, learned conventions.
  • function_facts(path) — behavioral facts of every function under a path as a JSON array (reads, writes, constructions, error types, effects, parameter ownership, derived role).
  • suppressions(path) — every inline suppression with whether the full bundled-rules run used it, and which silences went stale.
  • deduce_trait(...) — deduce a trait impl for a workspace type and answer with the chain itself: one recorded fact per step, workspace precedent, the block installed in memory and confirmed by re-reading; nothing touches disk.
  • derived_intents(path) — every intent the written calls prove: a call only an uninstalled ability can satisfy is the author’s stated intent, each record cites the function that wrote it.
  • whence_value(...) — where the value a function hands back comes from: each written position cited with its byte range; refusals name candidates with their files.
  • why_kept(...) — why the program keeps a store: the declaration that makes it a store, every verb proven at its own bytes, the routes serving it.
  • learn_conventions(path) — per-role convention clauses as an auditable rule list; training is deterministic.

Explanation

  • explain_rule(rule_id) — identifier, title, severity, tier, rationale URI, and the methodology excerpt the URI resolves to.

Findings: format and reporting

Finding shape (check --format json)

A JSON array; each element:

FieldMeaning
rule-idRM-<CATEGORY>-<NNN>, e.g. RM-STRUCT-008
severityerror | warning | info | hint
location.filepath relative to the analyzed root
location.rangebyte range {start, end}
messagethe demand, phrased as the canonical form’s requirement
rationale-urirustmanifest://methodology/<doc>#<anchor> — resolves to the methodology excerpt behind the rule
tracearray of {fact, reason} steps — the derivation, one line per recorded fact

Convert byte offsets to line numbers before quoting a location: awk/python on the file, or quote the message with the enclosing item name instead of a raw offset.

Severity ladder

  • error — a provable defect or security exposure; always report individually.
  • warning — a deviation with a real cost; report individually when few, group by rule when many.
  • info — a measured observation; summarize.
  • hint — a canonical-form nudge with a small price; summarize with counts.

Rule categories (middle segment of the id)

  • SEC — security (hardcoded credentials, injection surfaces, leaks).
  • IO — outside-world effects and their boundaries (fs, net, process, db).
  • MEM — memory and layout costs.
  • STRUCT — module/type structure (encapsulation, layering, module size).
  • QUAL — quality and maintainability.
  • META — engine/meta rules.

Report template

Use this shape for any review answer:

# Review of <scope>

<one line: N findings — X error, Y warning, Z info, W hint>

## Errors
- `RM-SEC-001` <file>:<line> — <message>
  Why: <one line from trace> · Rationale: <rationale-uri>

## Warnings
<same shape, or grouped per rule when a rule fires many times:
`RM-STRUCT-008` fires 41× — <message>; locations: a, b, c …>

## Summarized tail
<info/hint counts per rule category, one line each>

## Coverage note
<if coverage is not full, say what the engine could not see>

Rules of honest presentation:

  • Cite rule id + location for every finding you mention; the reader must be able to re-run check and match your list.
  • Never merge two rules into one bullet, never round counts away.
  • If the engine returned zero findings, say the scope is clean per the engine — and note coverage limits if coverage shows unresolved imports.
  • When you add your own opinion beyond the engine’s output, mark it clearly as your own note, separate from findings.

Code Review Methodology Navigation

All Materials

Quick Start

quick-reference.md - Daily cheat sheet

  • 5-minute checklist
  • Quick problem-finding commands
  • Common error patterns
  • Start here!

Main Sections

1. README.md - Methodology Overview

  • General approach to code review
  • Documentation structure
  • Problem prioritization
  • Effective review principles

2. security-vulnerabilities.md - Security

  • Replay attacks
  • SQL/Command injections
  • Secret leaks
  • Cryptography issues
  • 16 KB - MOST IMPORTANT

3. performance-issues.md - Performance

  • Inefficient allocations
  • Duplicate operations
  • Algorithmic complexity
  • Blocking operations
  • 15 KB

4. code-quality.md - Code Quality

  • DRY principle
  • Readability
  • Documentation
  • Testing
  • Architectural principles
  • 16 KB

5. rust-specific.md - Rust Specifics

  • Ownership and Borrowing
  • Lifetimes
  • Panic vs Result
  • let-else vs map_err chains
  • Unsafe code
  • Traits and Generics
  • 14 KB

6. examples.md - Real Examples

  • Telegram Authentication analysis
  • N+1 Query Problem
  • Memory Leaks
  • Before/After refactoring with metrics
  • 17 KB

Usage Scenarios

Scenario 1: “Need to quickly review a PR”

  1. Open quick-reference.md
  2. Use the 5-15 minute checklist
  3. Run problem-finding commands

Scenario 2: “Found a vulnerability, need details”

  1. Open security-vulnerabilities.md
  2. Find the vulnerability type
  3. Check examples and solutions

Scenario 3: “Code is slow, where to look”

  1. Open performance-issues.md
  2. Check the section by category (allocations/algorithms/copying)
  3. Use profiling tools

Scenario 4: “Need to improve architecture”

  1. Open code-quality.md
  2. Section “Architectural principles”
  3. Check SRP, modularity, DI

Scenario 5: “Rust-specific problem”

  1. Open rust-specific.md
  2. Find the category (ownership/lifetimes/unsafe)
  3. Check correct code examples

Scenario 6: “Want to learn from examples”

  1. Open examples.md
  2. Read the Telegram Authentication example
  3. Check improvement metrics

File Sizes

code-quality.md            16 KB
examples.md                17 KB
performance-issues.md      15 KB
quick-reference.md         7.7 KB
README.md                  6.5 KB
rust-specific.md           14 KB
security-vulnerabilities.md 16 KB

Total: ~92 KB of detailed methodology


Code Review Process

+---------------------------------------------+
|  1. Open PR and read description            |
|     Time: 2-3 minutes                       |
+------------------+--------------------------+
                   |
                   v
+---------------------------------------------+
|  2. SECURITY (security-vulnerabilities.md)  |
|     - Secrets, injections, validation       |
|     Time: 5-10 minutes                      |
+------------------+--------------------------+
                   |
                   v
+---------------------------------------------+
|  3. PERFORMANCE (performance-issues.md)     |
|     - Duplication, O(n^2), allocations      |
|     Time: 5-10 minutes                      |
+------------------+--------------------------+
                   |
                   v
+---------------------------------------------+
|  4. QUALITY (code-quality.md)               |
|     - DRY, readability, tests               |
|     Time: 5-10 minutes                      |
+------------------+--------------------------+
                   |
                   v
+---------------------------------------------+
|  5. RUST-SPECIFIC (rust-specific.md)        |
|     - Ownership, unsafe, lifetimes          |
|     Time: 5 minutes                         |
+------------------+--------------------------+
                   |
                   v
+---------------------------------------------+
|  6. Write comments                          |
|     - Specific, with solution examples      |
|     Time: 5-10 minutes                      |
+------------------+--------------------------+
                   |
                   v
              Approve / Request Changes

Total time: 30-45 minutes for a thorough review


Tips

  1. Use search: All files are markdown, easy to search with Ctrl+F
  2. Start with quick-reference: For daily use
  3. Return to examples: examples.md contains real cases
  4. Copy commands: All bash commands are ready to use
  5. Take notes: Add your own findings to the methodology

How to Read

New to code review:

  1. README.md - understand the general approach
  2. quick-reference.md - memorize basic checks
  3. examples.md - learn from examples
  4. The rest - as needed

Experienced reviewer:

  1. quick-reference.md - use as a checklist
  2. Specific sections - when you need details
  3. examples.md - for metrics reference

Updating the Methodology

When you find new problem types:

  1. Add to the corresponding file
  2. Update quick-reference.md if it’s a common problem
  3. Add to examples.md if you have a good example

File Structure

code-review-methodology/
|-- en/                           # English version
|   |-- INDEX.md                  # This file - navigation
|   |-- README.md                 # General overview
|   |-- quick-reference.md        # Cheat sheet
|   |-- security-vulnerabilities.md # Security
|   |-- performance-issues.md     # Performance
|   |-- code-quality.md           # Code quality
|   |-- rust-specific.md          # Rust specifics
|   +-- examples.md               # Real examples
+-- ru/                           # Russian version
    +-- ...

Created: 2025-10-26 Version: 1.0 Author: Based on practical code review experience

Quick Reference - Code Review Cheat Sheet

Quick reference for daily use.


Critical Issues (Block Merge)

Security

# Search for secrets
rg "(?i)(password|secret|api_key|token|private_key).*=.*['\"]" --type rust

# Search for SQL injections
rg "format!.*SELECT|execute.*&format!" --type rust

# Search for command injections
rg "Command::new.*format!" --type rust

Checklist:

  • No hardcoded credentials
  • SQL queries parameterized
  • All input data validated
  • auth_date checked for replay attack protection
  • No weak algorithms (MD5, SHA1)

Panic in Production

# Find all unwrap/expect/panic
rg "\.unwrap\(\)|\.expect\(|panic!" --type rust --glob '!tests'

Rule: No panic in production code (only Result).

let-else vs map_err Chains

#![allow(unused)]
fn main() {
// Long chains
let value = parse(input).map_err(E::A)?.validate().map_err(E::B)?;

// Readable code
let Ok(value) = parse(input) else { return Err(E::A); };
let Ok(value) = value.validate() else { return Err(E::B); };
}

Rule: let-else for multiple steps, map_err for single step.


Performance Issues

Quick Checks

# Nested loops (potential O(n^2))
rg "for.*\{[\s\S]{1,200}for" --type rust

# Vec::new without with_capacity
rg "Vec::new\(\)" --type rust

# contains in loop
rg "\.contains\(" --type rust

# Unnecessary clone
rg "\.clone\(\)" --type rust

Questions:

  • Parsing happens once?
  • with_capacity used for Vec?
  • No O(n^2) where O(n) is possible?
  • Iterators used instead of intermediate Vec?

5-Minute Checklist

1. Security (2 min)

  • No secrets in code
  • No unwrap/expect
  • Input data validated
  • No SQL/Command injections

2. Performance (1 min)

  • No obvious O(n^2)
  • No duplicate operations
  • Vec::with_capacity where needed

3. Quality (2 min)

  • No code duplication (> 3 times)
  • Functions < 50 lines
  • Sensible variable names
  • Tests for new logic

Common Problem Patterns

1. Replay Attack

#![allow(unused)]
fn main() {
// BAD
fn validate(raw: &str, hash: &str) -> bool {
    compute_hash(raw) == hash  // No time check!
}

// GOOD
fn validate(raw: &str, hash: &str, max_age: u64) -> bool {
    check_timestamp(raw, max_age) && compute_hash(raw) == hash
}
}

2. Double Parsing

#![allow(unused)]
fn main() {
// BAD - parsing twice
fn validate(raw: &str) -> bool {
    let data = parse(raw);  // 1
    check(data);
    hash(raw)  // parse() called inside again! 2
}

// GOOD
fn validate(raw: &str) -> bool {
    let data = parse(raw);  // 1 time
    check(&data);
    hash(&data)  // pass reference
}
}

3. N+1 Query

#![allow(unused)]
fn main() {
// BAD
for id in ids {
    let user = db.get(id).await;  // N queries
}

// GOOD
let users = db.get_many(ids).await;  // 1 query
}

4. Unnecessary Clone

#![allow(unused)]
fn main() {
// BAD
fn process(data: Vec<String>) -> usize {
    data.len()  // Takes ownership needlessly
}

// GOOD
fn process(data: &[String]) -> usize {
    data.len()
}
}

Quick Commands

# All unwrap/expect
rg "\.unwrap\(\)|\.expect\(" --type rust --glob '!tests'

# Magic numbers
rg "\b[0-9]{3,}\b" --type rust

# TODO/FIXME
rg "TODO|FIXME" --type rust

# Long functions (>50 lines)
# (needs script or manual check)

Metrics

# Test coverage
cargo tarpaulin --out Xml

# Clippy
cargo clippy -- -D warnings

# Formatting
cargo +nightly fmt --check

# Tests
cargo test

# Benchmarks
cargo bench

Prioritization

MUST FIX (blocks merge)

  1. Security vulnerabilities
  2. Panic in production
  3. Logic errors
  4. Broken tests

SHOULD FIX (before merge)

  1. Performance issues (>10% degradation)
  2. Code duplication (>3 times)
  3. Missing tests for critical logic

NICE TO HAVE (can be separate PR)

  1. Refactoring for readability
  2. Additional tests
  3. Documentation improvements

How to Write Review Comments

Bad

  • “This is bad”
  • “Redo this”
  • “There’s a problem here”

Good

  • “SQL injection possible on line 42. Use parameterized query: query_as!(...)”
  • “This function is called in a loop, giving O(n^2). Can use HashMap for O(n)”
  • “No auth_date check - replay attack vulnerability. Add time validation per Telegram docs”

Formula:

  1. What is wrong
  2. Why it’s a problem
  3. How to fix (or suggest options)

Focus by Time

5 minutes - Critical

  • Security
  • Panic/unwrap
  • Obvious bugs

15 minutes - Add Performance

  • Duplicate operations
  • Inefficient algorithms
  • Unnecessary allocations

30 minutes - Add Quality

  • Code duplication
  • Readability
  • Tests
  • Documentation

45 minutes - Thorough Review

  • Architecture
  • Edge cases in tests
  • Long-term maintainability

Comment Template

## Security
- [ ] auth_date validation missing (replay attack) - line 42
- [ ] SQL injection in `get_user()` - line 156

## Performance
- [ ] Double parsing of initData - lines 50, 75
- [ ] O(n^2) in `remove_duplicates()` - line 200

## Quality
- [ ] Hash computation duplicated 3 times - suggest extract function
- [ ] Missing tests for error cases

## Suggestions
- Consider using HashMap instead of Vec::find for O(1) lookups
- Add doc comments for public API

Quick Start

  1. Open PR -> view diff
  2. Security (5 min):
    • rg secrets, unwrap, injections
  3. Performance (5 min):
    • Duplication, O(n^2), allocations
  4. Quality (5 min):
    • DRY, readability, tests
  5. Write comments - specific with solutions
  6. Approve or Request Changes

Total: 15-20 minutes for typical PR


Full Documentation

See details in:

Code Analysis and Vulnerability Detection Methodology

A comprehensive guide for code review, vulnerability detection, and identifying code weaknesses.

Methodology Structure

1. Security and Vulnerabilities

  • Cryptography and authentication
  • Injections and data validation
  • Replay, CSRF, XSS attacks
  • Data and secret leaks
  • Practical examples

2. Performance

  • Finding bottlenecks
  • Inefficient allocations
  • Duplicate operations
  • Algorithm optimization
  • Profiling

3. Code Quality

  • Code duplication (DRY)
  • Readability and maintainability
  • Error handling
  • Testing
  • Documentation

4. Architecture

  • Single Responsibility Principle
  • Modularity
  • Dependencies
  • Reusability
  • Scalability

5. Rust Specifics

  • Memory safety
  • Ownership and borrowing
  • Panic vs Result
  • Zero-cost abstractions
  • Unsafe code

6. Real Examples

  • Project examples
  • Before/After refactoring
  • Measurable improvements

General Code Review Approach

Stage 1: Initial Overview (5-10 minutes)

  1. Understand the overall structure of changes
  2. Read commit message and PR description
  3. Assess the scope of changes

Stage 2: Security (15-20 minutes)

  1. Vulnerability search (see security-vulnerabilities.md)
  2. Input data validation check
  3. Cryptography and authentication analysis
  4. Secret leak check

Stage 3: Correctness (10-15 minutes)

  1. Does the logic work correctly?
  2. All edge cases handled
  3. Proper error handling
  4. Tests cover functionality

Stage 4: Performance (10 minutes)

  1. Finding inefficient operations
  2. Unnecessary allocations
  3. Duplicate work
  4. Algorithmic complexity

Stage 5: Quality (10 minutes)

  1. Readability
  2. Duplication
  3. Naming
  4. Documentation

Stage 6: Architecture (5-10 minutes)

  1. SOLID principles compliance
  2. Modularity
  3. Reusability
  4. Tech debt

Quick Checklist

Critical Issues (block merge)

  • Security vulnerabilities
  • Secret leaks (passwords, tokens, keys)
  • Panic in production code
  • Improper error handling
  • Missing tests for critical logic

Important Issues (require fixing)

  • Inefficient operations (O(n^2) instead of O(n))
  • Code duplication (>3 repetitions)
  • Missing input data validation
  • Magic numbers and magic strings
  • Undocumented public API

Desired Improvements

  • Refactoring for readability
  • Additional tests
  • Documentation improvement
  • Performance optimization

Tools

Automated Checks

  • Clippy - static analyzer for Rust
  • cargo audit - dependency vulnerability check
  • cargo deny - license and security check
  • cargo tarpaulin - test coverage
  • cargo bench - performance benchmarks

Manual Analysis

  • git diff - viewing changes
  • ripgrep (rg) - code pattern search
  • tokei - code statistics
  • cargo tree - dependency tree

Prioritization

High Priority

  1. Security
  2. Correctness
  3. Critical bugs

Medium Priority

  1. Performance (if issues exist)
  2. Code quality
  3. Testing

Low Priority

  1. Code style (if autoformatter exists)
  2. Minor refactoring
  3. Documentation (if not public API)

Effective Review Principles

  1. Be specific: “SQL injection possible on line 42” instead of “Security issues”
  2. Suggest solutions: Not just “This is slow”, but “Can use HashMap instead of Vec::find”
  3. Explain why: “This will lead to replay attack because…”
  4. Use metrics: “This will increase allocations by 40%”
  5. Be positive: Note good solutions too

Next Steps

Study each section in detail:

  1. Start with security-vulnerabilities.md - this is most important
  2. Then performance-issues.md - for production-ready code
  3. Study rust-specific.md - language specifics
  4. Practice on examples.md - real cases

Finding Security Vulnerabilities

Table of Contents

  1. Authentication and Authorization
  2. Cryptography
  3. Injections
  4. Database Security
  5. Data Validation
  6. Information Leaks
  7. Availability Attacks

Authentication and Authorization

1. Replay Attack

What to look for:

  • Missing timestamp validation
  • Missing nonce (one-time tokens)
  • Infinite token lifetime

Vulnerability example:

#![allow(unused)]
fn main() {
// VULNERABLE - no data freshness check
fn validate_telegram_data(raw: &str, hash: &str, bot_token: &str) -> bool {
    let computed_hash = compute_hmac(raw, bot_token);
    computed_hash == hash  // Hash is correct, but data might be old!
}
}

How it’s exploited:

  1. Attacker intercepts a valid request (e.g., via MITM)
  2. Saves authentication data
  3. Replays it later to gain access

Correct solution:

#![allow(unused)]
fn main() {
// SECURE
fn validate_telegram_data(
    raw: &str,
    hash: &str,
    bot_token: &str,
    max_age: u64
) -> bool {
    let parsed = parse_data(raw);

    // 1. Check data freshness
    if let Some(auth_date) = parsed.get("auth_date") {
        let timestamp = auth_date.parse::<u64>()?;
        let now = current_timestamp();

        if now - timestamp > max_age {
            return false; // Data is stale
        }
    } else {
        return false; // No timestamp
    }

    // 2. Verify signature
    let computed_hash = compute_hmac(raw, bot_token);
    computed_hash == hash
}
}

Where to look:

  • Token-based authentication
  • API endpoints with signatures
  • OAuth flows
  • Webhook handlers

Search keywords:

rg "validate|auth|verify" --type rust
rg "timestamp|auth_date|created_at" --type rust

2. JWT Without Expiration Check

What to look for:

#![allow(unused)]
fn main() {
// VULNERABLE
fn decode_jwt(token: &str) -> Result<Claims> {
    jsonwebtoken::decode(
        token,
        &key,
        &Validation::default()  // Doesn't check exp!
    )
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE
fn decode_jwt(token: &str) -> Result<Claims> {
    let mut validation = Validation::default();
    validation.validate_exp = true;  // Check expiration
    validation.leeway = 60;          // 60 seconds tolerance

    jsonwebtoken::decode(token, &key, &validation)
}
}

3. Missing Rate Limiting

What to look for:

  • Authentication endpoints without limits
  • Possibility of brute-force attacks

Vulnerability example:

#![allow(unused)]
fn main() {
// VULNERABLE - can brute-force passwords
async fn login(username: &str, password: &str) -> Result<Token> {
    let user = db.find_user(username).await?;

    if verify_password(password, &user.password_hash) {
        Ok(generate_token(user.id))
    } else {
        Err(Error::InvalidCredentials)
    }
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE
async fn login(username: &str, password: &str, ip: IpAddr) -> Result<Token> {
    // 1. Check rate limit
    if !rate_limiter.check(ip, 5, Duration::from_secs(60)) {
        return Err(Error::TooManyRequests);
    }

    let user = db.find_user(username).await?;

    // 2. Use constant-time comparison
    if verify_password(password, &user.password_hash) {
        Ok(generate_token(user.id))
    } else {
        // 3. Count attempt
        rate_limiter.increment(ip);

        // 4. Add delay before response (against timing attacks)
        tokio::time::sleep(Duration::from_millis(500)).await;

        Err(Error::InvalidCredentials)
    }
}
}

Back to top


Cryptography

1. Using Weak Algorithms

What to look for:

rg "md5|sha1|DES|RC4" --type rust  # Weak algorithms

Examples:

#![allow(unused)]
fn main() {
// BAD - MD5 is cryptographically broken
use md5::Md5;
let hash = Md5::digest(password);

// BAD - SHA1 too
use sha1::Sha1;
let hash = Sha1::digest(token);

// GOOD - use modern algorithms
use sha2::Sha256;
let hash = Sha256::digest(data);

// EVEN BETTER - for passwords use specialized functions
use argon2::{Argon2, PasswordHasher};
let hash = Argon2::default().hash_password(password, &salt)?;
}

2. Hardcoded Keys and Secrets

What to look for:

# Search for potential secrets
rg "password.*=.*\"" --type rust
rg "secret.*=.*\"" --type rust
rg "api_key.*=.*\"" --type rust
rg "token.*=.*\"" --type rust
rg "private_key" --type rust

Vulnerability example:

#![allow(unused)]
fn main() {
// CRITICAL VULNERABILITY
const API_KEY: &str = "sk_live_51H...";  // Never!
const DB_PASSWORD: &str = "admin123";    // Disaster!

fn encrypt(data: &[u8]) -> Vec<u8> {
    let key = b"mysecretkey12345";  // Hardcoded key
    aes_encrypt(data, key)
}
}

Correct:

#![allow(unused)]
fn main() {
// CORRECT - from environment variables
fn get_api_key() -> Result<String> {
    std::env::var("API_KEY")
        .map_err(|_| Error::MissingApiKey)
}

fn encrypt(data: &[u8]) -> Result<Vec<u8>> {
    // Key from secure storage
    let key = get_encryption_key()?;
    aes_encrypt(data, &key)
}
}

3. Incorrect HMAC Usage

Problem from our code:

#![allow(unused)]
fn main() {
// WAS - can cause panic
let mut mac = HmacSha256::new_from_slice(&secret)
    .expect("HMAC initialization failed");
}

Why it’s bad:

  • expect() can cause panic
  • In production panic = DOS attack

Correct:

#![allow(unused)]
fn main() {
// NOW
let mac = HmacSha256::new_from_slice(&secret).ok()?;
}

Back to top


Injections

1. SQL Injection

What to look for:

rg "format!.*SELECT|query.*format!" --type rust
rg "execute.*&format!" --type rust

Vulnerability example:

#![allow(unused)]
fn main() {
// SQL INJECTION!
async fn get_user(username: &str) -> Result<User> {
    let query = format!("SELECT * FROM users WHERE username = '{}'", username);
    //                                                                ^^^^^^^^
    // If username = "admin' OR '1'='1", we'll get all users!

    db.execute(&query).await
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE - use parameterized queries
async fn get_user(username: &str) -> Result<User> {
    sqlx::query_as!(
        User,
        "SELECT * FROM users WHERE username = $1",
        username  // Automatically escaped
    )
    .fetch_one(&db)
    .await
}
}

2. Command Injection

What to look for:

rg "Command::new|std::process::Command" --type rust

Vulnerability example:

#![allow(unused)]
fn main() {
// COMMAND INJECTION!
fn resize_image(filename: &str) -> Result<()> {
    let cmd = format!("convert {} -resize 100x100 output.jpg", filename);
    //                           ^^^^^^^^
    // filename = "input.jpg; rm -rf /" will delete files!

    std::process::Command::new("sh")
        .arg("-c")
        .arg(&cmd)
        .output()?;
    Ok(())
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE
fn resize_image(filename: &str) -> Result<()> {
    // 1. Validate filename
    if !is_valid_filename(filename) {
        return Err(Error::InvalidFilename);
    }

    // 2. Don't use shell - pass arguments directly
    std::process::Command::new("convert")
        .arg(filename)        // Safe - not interpreted by shell
        .arg("-resize")
        .arg("100x100")
        .arg("output.jpg")
        .output()?;
    Ok(())
}

fn is_valid_filename(name: &str) -> bool {
    // Only letters, digits, dots, hyphens
    name.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '-')
}
}

Back to top


Database Security

Automated Analysis: Use sql-query-analyzer for static analysis of SQL queries with 18 built-in security and performance rules.

Static Analysis with sql-query-analyzer

Installation:

cargo install sql-query-analyzer

Local usage:

sql-query-analyzer analyze -s schema.sql -q queries.sql --format text

GitHub Actions integration:

- name: SQL Query Analysis
  uses: RAprogramm/sql-query-analyzer@v1
  with:
    schema: db/schema.sql
    queries: db/queries.sql
    fail-on-error: 'true'
    post-comment: 'true'
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Security Rules

SEC001: UPDATE without WHERE

Severity: Error

What to look for:

rg "UPDATE.*SET" --type rust
rg "UPDATE.*SET" --type sql

Vulnerability example:

-- DANGEROUS: affects ALL rows in the table
UPDATE users SET status = 'inactive';

Correct:

-- SAFE: explicit condition
UPDATE users SET status = 'inactive' WHERE last_login < '2024-01-01';

SEC002: DELETE without WHERE

Severity: Error

What to look for:

rg "DELETE FROM" --type rust
rg "DELETE FROM" --type sql

Vulnerability example:

-- DANGEROUS: deletes ALL rows
DELETE FROM sessions;

Correct:

-- SAFE: explicit condition
DELETE FROM sessions WHERE expired_at < NOW();

Performance Rules (Security Impact)

PERF001: SELECT * without LIMIT

Severity: Warning

Security impact: Can cause DOS through memory exhaustion

Vulnerability example:

-- CAN CAUSE OOM on large tables
SELECT * FROM logs;

Correct:

-- SAFE: bounded result set
SELECT * FROM logs LIMIT 1000;
-- OR: specific columns
SELECT id, message, created_at FROM logs LIMIT 1000;

PERF002: Leading Wildcard in LIKE

Severity: Warning

Security impact: Prevents index usage, enables DOS through slow queries

Vulnerability example:

-- SLOW: full table scan, no index usage
SELECT * FROM users WHERE email LIKE '%@gmail.com';

Correct:

-- BETTER: use suffix column or full-text search
SELECT * FROM users WHERE email_domain = 'gmail.com';

PERF004: Large OFFSET Values

Severity: Warning

Security impact: Performance degradation, DOS vector

Vulnerability example:

-- SLOW: database must scan and skip 100000 rows
SELECT * FROM products ORDER BY id LIMIT 10 OFFSET 100000;

Correct:

-- FAST: keyset pagination
SELECT * FROM products WHERE id > 100000 ORDER BY id LIMIT 10;

PERF005: Cartesian Product

Severity: Error

Security impact: Exponential result size, memory exhaustion

Vulnerability example:

-- DANGEROUS: returns rows_a * rows_b results
SELECT * FROM users, orders;

Correct:

-- SAFE: explicit join condition
SELECT * FROM users
JOIN orders ON users.id = orders.user_id;

PERF007: Scalar Subquery in SELECT

Severity: Warning

Security impact: N+1 query pattern, database overload

Vulnerability example:

-- SLOW: executes subquery for EACH row
SELECT
    id,
    name,
    (SELECT COUNT(*) FROM orders WHERE user_id = users.id) as order_count
FROM users;

Correct:

-- FAST: single query with JOIN
SELECT u.id, u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;

PERF008: Function on Indexed Column

Severity: Warning

Security impact: Index bypass, slow queries

Vulnerability example:

-- SLOW: UPPER() prevents index usage
SELECT * FROM users WHERE UPPER(email) = 'TEST@EXAMPLE.COM';

Correct:

-- FAST: store normalized data or use functional index
SELECT * FROM users WHERE email_lower = 'test@example.com';

PERF009: NOT IN with Subquery

Severity: Warning

Security impact: Unexpected NULL behavior, performance issues

Vulnerability example:

-- DANGEROUS: returns empty if subquery contains NULL
SELECT * FROM users WHERE id NOT IN (SELECT user_id FROM banned);

Correct:

-- SAFE: handles NULL correctly
SELECT * FROM users u
WHERE NOT EXISTS (SELECT 1 FROM banned b WHERE b.user_id = u.id);

PERF011: SELECT without WHERE

Severity: Info

Security impact: Full table scan on large tables

Vulnerability example:

-- SLOW: scans entire table
SELECT * FROM audit_logs;

Correct:

-- BETTER: add filtering or pagination
SELECT * FROM audit_logs
WHERE created_at > NOW() - INTERVAL '7 days'
LIMIT 1000;

Schema-Aware Rules

SCHEMA001: Missing Index on Filter Column

Severity: Warning

What to look for: WHERE/JOIN columns without indexes

Example:

-- If 'status' column has no index, this is slow
SELECT * FROM orders WHERE status = 'pending';

Fix: Add index in schema:

CREATE INDEX idx_orders_status ON orders(status);

SCHEMA002: Column Not in Schema

Severity: Warning

What to look for: References to non-existent columns

Example:

-- If 'user_name' doesn't exist (should be 'username')
SELECT user_name FROM users;

Database Security Checklist

Query Safety

  • No UPDATE without WHERE clause?
  • No DELETE without WHERE clause?
  • All queries use parameterized statements?
  • No string concatenation in SQL?
  • LIMIT applied to unbounded queries?

Performance & DOS Prevention

  • No leading wildcards in LIKE patterns?
  • Keyset pagination instead of large OFFSET?
  • No Cartesian products (missing JOIN conditions)?
  • No N+1 queries (scalar subqueries in SELECT)?
  • Indexes exist for filtered columns?

Data Integrity

  • Foreign keys defined and enforced?
  • Constraints validate data at database level?
  • Transactions used for multi-step operations?

Automated Analysis Tools

# Install sql-query-analyzer
cargo install sql-query-analyzer

# Analyze queries against schema
sql-query-analyzer analyze -s schema.sql -q queries.sql

# Output as SARIF for CI integration
sql-query-analyzer analyze -s schema.sql -q queries.sql --format sarif

# Disable specific rules if needed
sql-query-analyzer analyze -s schema.sql -q queries.sql --disabled-rules PERF003,STYLE001

GitHub Actions with SARIF upload:

- name: SQL Query Analysis
  uses: RAprogramm/sql-query-analyzer@v1
  with:
    schema: db/schema.sql
    queries: db/queries.sql
    format: sarif
    upload-sarif: 'true'
    fail-on-error: 'true'

Back to top


Data Validation

1. Missing Input Validation

What to look for in API handlers:

#![allow(unused)]
fn main() {
// NO VALIDATION
#[derive(Deserialize)]
pub struct CreateUser {
    pub email: String,      // Can be "not-an-email"
    pub age: i32,          // Can be -100
    pub username: String,  // Can be empty or 10000 characters
}

async fn create_user(Json(data): Json<CreateUser>) -> Result<Json<User>> {
    // Create directly without checks!
    let user = db.create_user(data).await?;
    Ok(Json(user))
}
}

Correct:

#![allow(unused)]
fn main() {
// WITH VALIDATION
use validator::Validate;

#[derive(Deserialize, Validate)]
pub struct CreateUser {
    #[validate(email)]
    pub email: String,

    #[validate(range(min = 0, max = 150))]
    pub age: i32,

    #[validate(length(min = 3, max = 50))]
    #[validate(regex = "USERNAME_REGEX")]
    pub username: String,
}

async fn create_user(Json(data): Json<CreateUser>) -> Result<Json<User>> {
    // 1. Validate
    data.validate()
        .map_err(|_| StatusCode::BAD_REQUEST)?;

    // 2. Additional business validation
    if db.username_exists(&data.username).await? {
        return Err(Error::UsernameTaken);
    }

    // 3. Create
    let user = db.create_user(data).await?;
    Ok(Json(user))
}
}

2. Integer Overflow

Example from real code:

#![allow(unused)]
fn main() {
// POTENTIAL PROBLEM
fn calculate_total(price: u64, quantity: u32) -> u64 {
    price * quantity as u64  // Can overflow!
    // If price = u64::MAX and quantity = 2, we get wraparound
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE
fn calculate_total(price: u64, quantity: u32) -> Result<u64> {
    price.checked_mul(quantity as u64)
        .ok_or(Error::Overflow)
}

// Or in debug/test builds will panic:
#[cfg(debug_assertions)]
fn calculate_total_debug(price: u64, quantity: u32) -> u64 {
    price * quantity as u64  // In debug - panic on overflow
}
}

Back to top


Information Leaks

1. Logging Secrets

What to look for:

rg "tracing::.*password|log.*token|debug.*secret" --type rust

Vulnerability example:

#![allow(unused)]
fn main() {
// SECRET LEAK TO LOGS
async fn login(username: &str, password: &str) -> Result<Token> {
    tracing::info!("Login attempt: {} with password {}", username, password);
    //                                                                ^^^^^^^^
    // Password will end up in logs!

    // ...
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE
async fn login(username: &str, password: &str) -> Result<Token> {
    tracing::info!("Login attempt for user: {}", username);
    // NEVER log password!

    // For debugging you can log hash (but better not)
    tracing::debug!("Password hash: {}", hash_for_debug_only(password));

    // ...
}
}

2. Exposing Internal Errors

Vulnerability example:

#![allow(unused)]
fn main() {
// EXPOSES DB STRUCTURE
async fn get_user(id: Uuid) -> Result<Json<User>, (StatusCode, String)> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_one(&db)
        .await
        .map_err(|e| (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Database error: {}", e)  // DB details to client!
        ))?;

    Ok(Json(user))
}
}

Correct:

#![allow(unused)]
fn main() {
// SECURE
async fn get_user(id: Uuid) -> Result<Json<User>, StatusCode> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_one(&db)
        .await
        .map_err(|e| {
            // Log details for developers
            tracing::error!("Failed to fetch user {}: {}", id, e);

            // Only generic message to client
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    Ok(Json(user))
}
}

Back to top


Security Checklist

Authentication

  • Token/timestamp freshness checked?
  • Rate limiting used?
  • JWT tokens have expiration?
  • Signature/HMAC verified?
  • No hardcoded credentials?

Cryptography

  • Modern algorithms used (SHA-256+, AES-256)?
  • No hardcoded keys and secrets?
  • Proper error handling (no panic)?
  • Argon2/bcrypt used for passwords?

Injections

  • SQL queries parameterized?
  • No format! in SQL?
  • Command execution is safe?
  • Filenames/paths validated?

Validation

  • All input data validated?
  • Number ranges checked?
  • Email/URL validated?
  • String length limited?

Information Leaks

  • Secrets not logged?
  • Error details not exposed to client?
  • Debug info only in development?

Automatic Check Tools

# Clippy with security
cargo clippy -- -W clippy::all -W clippy::pedantic -W clippy::nursery

# Dependency check
cargo audit

# Secret search
rg "(?i)(password|secret|api_key|token).*=.*['\"]" --type rust

Back to top

Finding Performance Issues

Table of Contents

  1. Inefficient Allocations
  2. Duplicate Operations
  3. Algorithmic Complexity
  4. Excessive Copying
  5. Blocking Operations

Inefficient Allocations

1. Repeated Allocations in Loop

Problem:

#![allow(unused)]
fn main() {
// SLOW - millions of allocations
fn process_items(items: &[Item]) -> Vec<String> {
    let mut result = Vec::new();  // Initial capacity = 0

    for item in items {
        result.push(item.to_string());  // May reallocate each time!
    }

    result
}
}

How to find:

rg "Vec::new\(\)" --type rust  # Find Vec::new() without with_capacity

Correct:

#![allow(unused)]
fn main() {
// FAST - single allocation
fn process_items(items: &[Item]) -> Vec<String> {
    let mut result = Vec::with_capacity(items.len());  // Allocate memory upfront

    for item in items {
        result.push(item.to_string());  // Never reallocates
    }

    result
}

// EVEN FASTER - use iterators
fn process_items_fast(items: &[Item]) -> Vec<String> {
    items.iter().map(|item| item.to_string()).collect()
    // collect() is smart - allocates correct size automatically
}
}

Measurable effect:

  • For 10,000 elements: 2-3x faster
  • For 100,000 elements: 5-10x faster

2. Unnecessary String Allocations

Problem:

#![allow(unused)]
fn main() {
// SLOW - creates new Strings
fn build_url(host: &str, path: &str, query: &str) -> String {
    let mut url = String::new();
    url.push_str("https://");
    url.push_str(host);
    url.push('/');
    url.push_str(path);
    url.push('?');
    url.push_str(query);
    url
}
}

Correct:

#![allow(unused)]
fn main() {
// FAST - single allocation of correct size
fn build_url(host: &str, path: &str, query: &str) -> String {
    let capacity = 8 + host.len() + 1 + path.len() + 1 + query.len();
    let mut url = String::with_capacity(capacity);

    url.push_str("https://");
    url.push_str(host);
    url.push('/');
    url.push_str(path);
    url.push('?');
    url.push_str(query);

    url
}

// OR use format! for short strings
fn build_url_simple(host: &str, path: &str, query: &str) -> String {
    format!("https://{}/{}?{}", host, path, query)
}
}

3. Creating Temporary Vec Instead of Iterators

Problem:

#![allow(unused)]
fn main() {
// SLOW - creates intermediate Vec
fn sum_even_squares(nums: &[i32]) -> i32 {
    let evens: Vec<_> = nums.iter().filter(|&n| n % 2 == 0).collect();  // Allocation!
    let squares: Vec<_> = evens.iter().map(|&n| n * n).collect();       // Another one!
    squares.iter().sum()
}
}

Correct:

#![allow(unused)]
fn main() {
// FAST - zero allocations
fn sum_even_squares(nums: &[i32]) -> i32 {
    nums.iter()
        .filter(|&n| n % 2 == 0)
        .map(|&n| n * n)
        .sum()
    // No intermediate Vec - all in single pass!
}
}

Effect:

  • For 1,000,000 elements: 10-20x faster
  • 0 allocations vs 2 large allocations

Duplicate Operations

Example from Our Project

Problem:

#![allow(unused)]
fn main() {
// SLOW - parsing initData TWICE
pub fn validate_telegram_data(raw: &str, hash: &str, bot_token: &str) -> bool {
    let parsed = parse_query_string_raw(raw);  // 1st time

    validate_auth_date(&parsed);

    let computed_hash = compute_hash(raw, bot_token);  // Parses again inside!
    //                                ^^^
}

fn compute_hash(raw: &str, bot_token: &str) -> String {
    let parsed = parse_query_string_raw(raw);  // 2nd time
    // ...
}
}

Solution:

#![allow(unused)]
fn main() {
// FAST - parse once
pub fn validate_telegram_data(raw: &str, hash: &str, bot_token: &str) -> bool {
    let parsed = parse_query_string_raw(raw);  // Once!

    validate_auth_date(&parsed);

    let computed_hash = compute_hash(&parsed, bot_token);  // Pass reference
    //                                 ^^^^^^
}

fn compute_hash(parsed: &BTreeMap<String, String>, bot_token: &str) -> String {
    // Use already parsed data
}
}

Effect:

  • -50% time on parsing
  • Especially important for hot paths (called frequently)

How to Find Duplication

1. Search for identical function calls:

# Find functions called > 1 time in same function
rg "(\w+)\(.*\).*\1\(" --type rust

2. Visual search:

  • Look for identical computations inside loops
  • Check if expensive functions are called multiple times with same arguments

Example:

#![allow(unused)]
fn main() {
// BAD - computes len() on each iteration
for i in 0..items.len() {
    if i < items.len() / 2 {  // len() called again!
        // ...
    }
}

// GOOD
let len = items.len();
let half = len / 2;
for i in 0..len {
    if i < half {
        // ...
    }
}
}

Algorithmic Complexity

1. O(n^2) Instead of O(n)

Problem:

#![allow(unused)]
fn main() {
// O(n^2) - for each element traverse entire Vec
fn remove_duplicates(items: Vec<String>) -> Vec<String> {
    let mut result = Vec::new();

    for item in items {
        if !result.contains(&item) {  // O(n) for each element!
            result.push(item);
        }
    }

    result
}
}

Correct:

#![allow(unused)]
fn main() {
use std::collections::HashSet;

// O(n) - use HashSet
fn remove_duplicates(items: Vec<String>) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut result = Vec::new();

    for item in items {
        if seen.insert(item.clone()) {  // O(1) on average
            result.push(item);
        }
    }

    result
}

// EVEN SIMPLER
fn remove_duplicates_simple(items: Vec<String>) -> Vec<String> {
    items.into_iter().collect::<HashSet<_>>().into_iter().collect()
}
}

Effect:

  • For 1,000 elements: 100x faster
  • For 10,000 elements: 1000x faster

2. Linear Search Instead of HashMap

Problem:

#![allow(unused)]
fn main() {
// O(n) for each search
fn find_user_by_id(users: &[User], id: i64) -> Option<&User> {
    users.iter().find(|u| u.id == id)  // Traverses entire array!
}

// In a loop - disaster:
for id in user_ids {
    let user = find_user_by_id(&all_users, id);  // O(n) each time!
}
// Total: O(m * n) where m = user_ids.len(), n = all_users.len()
}

Correct:

#![allow(unused)]
fn main() {
use std::collections::HashMap;

// O(1) for each search
fn build_user_map(users: Vec<User>) -> HashMap<i64, User> {
    users.into_iter().map(|u| (u.id, u)).collect()
}

let user_map = build_user_map(all_users);  // O(n) once

for id in user_ids {
    let user = user_map.get(&id);  // O(1) each time!
}
// Total: O(n + m) instead of O(m * n)
}

Effect for 10,000 searches in array of 10,000 elements:

  • Was: ~50,000,000 operations (O(m*n))
  • Now: ~20,000 operations (O(n+m))
  • 2500x faster!

How to Find Complexity Issues

1. Nested loops:

rg "for.*\{[\s\S]{1,200}for" --type rust  # Find nested loops

2. Vec::contains in loop:

rg "\.contains\(" --type rust

3. Linear search patterns:

rg "\.iter\(\)\.find|\.iter\(\)\.position" --type rust

Questions to ask yourself:

  • How many times does the innermost operation execute?
  • If data grows 10x, how much slower will it be?
  • Can I use HashMap/HashSet/BTreeMap?

Excessive Copying

1. Clone() Without Necessity

Problem:

#![allow(unused)]
fn main() {
// SLOW - copies entire Vec
fn process_items(items: Vec<String>) -> usize {
    let copy = items.clone();  // Why?
    copy.len()
}
}

How to find:

rg "\.clone\(\)" --type rust  # Check each clone!

Correct:

#![allow(unused)]
fn main() {
// FAST - use reference
fn process_items(items: &[String]) -> usize {
    items.len()
}
}

2. to_string() in Hot Path

Problem:

#![allow(unused)]
fn main() {
// SLOW - millions of allocations
fn log_items(items: &[Item]) {
    for item in items {
        tracing::debug!("Item: {}", item.id.to_string());  // Unnecessary to_string()
    }
}
}

Correct:

#![allow(unused)]
fn main() {
// FAST - Display formats itself
fn log_items(items: &[Item]) {
    for item in items {
        tracing::debug!("Item: {}", item.id);  // Without to_string()
    }
}
}

3. Owned Values Instead of References

Example from our project:

#![allow(unused)]
fn main() {
// WAS - copies Strings
let mut kv_pairs: Vec<(String, String)> = parsed.into_iter()...

// NOW - zero-copy
let mut kv_pairs: Vec<(&String, &String)> = parsed.iter()...
}

Effect:

  • For 100 key-value pairs of 20 characters each: ~4KB vs ~0 bytes allocations
  • 3-5x faster

Blocking Operations

1. Blocking I/O in Async Function

Problem:

#![allow(unused)]
fn main() {
// BLOCKS entire runtime!
async fn handle_request() -> Result<String> {
    let data = std::fs::read_to_string("file.txt")?;  // Sync I/O!
    Ok(data)
}
}

Correct:

#![allow(unused)]
fn main() {
// Async read
async fn handle_request() -> Result<String> {
    let data = tokio::fs::read_to_string("file.txt").await?;
    Ok(data)
}

// Or move to blocking pool
async fn handle_request_alt() -> Result<String> {
    tokio::task::spawn_blocking(|| {
        std::fs::read_to_string("file.txt")
    }).await?
}
}

2. Long Computations in Async

Problem:

#![allow(unused)]
fn main() {
// BLOCKS other tasks
async fn expensive_computation(n: u64) -> u64 {
    (0..n).sum()  // Can run milliseconds/seconds
}
}

Correct:

#![allow(unused)]
fn main() {
// In separate thread
async fn expensive_computation(n: u64) -> u64 {
    tokio::task::spawn_blocking(move || {
        (0..n).sum()
    }).await.unwrap()
}
}

Profiling Tools

1. Cargo Flamegraph

cargo install flamegraph
cargo flamegraph --bin your-app

# Opens flamegraph.svg - visualization of time spent

2. Cargo Bench

# Add to Cargo.toml:
# [dev-dependencies]
# criterion = "0.5"

# benches/my_benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn benchmark_parse(c: &mut Criterion) {
    let data = "auth_date=123&user=test&hash=abc";

    c.bench_function("parse_query_string", |b| {
        b.iter(|| parse_query_string_raw(black_box(data)))
    });
}

criterion_group!(benches, benchmark_parse);
criterion_main!(benches);
cargo bench

3. Cargo Asm - View Generated Code

cargo install cargo-asm
cargo asm your_crate::function_name

Performance Checklist

Allocations

  • Vec::new() replaced with Vec::with_capacity() where size is known?
  • No unnecessary .clone() and .to_string()?
  • Iterators used instead of intermediate Vec?
  • String::with_capacity() for concatenation?

Algorithms

  • No O(n^2) where O(n) is possible?
  • HashMap instead of linear search?
  • No nested loops over large data?
  • Correct data structures chosen?

Copying

  • References (&T) used instead of owned (T)?
  • No unnecessary .clone()?
  • .to_owned()/.to_string() avoided in hot paths?

Async

  • No blocking operations in async?
  • Long computations in spawn_blocking?
  • Async I/O used?

General

  • No duplicate computations?
  • Profiling showed problems?
  • Benchmarks pass within norms?

Optimization Prioritization

ONLY optimize if:

  1. Profiling showed a problem (don’t optimize blindly!)
  2. It’s a hot path (called frequently)
  3. Measurable effect (minimum 10% improvement)

DON’T optimize:

  • Cold paths (startup, rare operations)
  • Code that’s already fast enough
  • If it worsens readability without real gain

Rule: “Premature optimization is the root of all evil” - Donald Knuth

But: “Premature pessimization is also evil” - choose correct data structures from the start.

Code Quality and Maintainability

Table of Contents

  1. Code Duplication (DRY)
  2. Readability
  3. Documentation
  4. Testing
  5. Architectural Principles

Code Duplication (DRY)

Don’t Repeat Yourself - Rule of Three

Rule: If code repeats 3+ times -> extract to function.

Project Example (Before Refactoring)

#![allow(unused)]
fn main() {
// DUPLICATION - same code 3 times
#[test]
fn test_case_1() {
    let parsed = parse_query_string_raw(&raw);
    let mut kv_pairs: Vec<(String, String)> = parsed
        .into_iter()
        .filter(|(k, _)| k != "hash" && k != "signature")
        .collect();
    kv_pairs.sort_by(|a, b| a.0.cmp(&b.0));
    let data_check_string = kv_pairs.iter()...
    let secret = Sha256::digest(bot_token.as_bytes());
    let mut mac = HmacSha256::new_from_slice(&secret).unwrap();
    mac.update(data_check_string.as_bytes());
    let computed_hash = hex::encode(mac.finalize().into_bytes());
}

#[test]
fn test_case_2() {
    // ... EXACT SAME CODE ...
}

#[test]
fn test_case_3() {
    // ... AND AGAIN ...
}
}

After refactoring:

#![allow(unused)]
fn main() {
// Function used everywhere
fn compute_telegram_hash(parsed: &BTreeMap<String, String>, bot_token: &str) -> String {
    // Code in one place
}

#[test]
fn test_case_1() {
    let hash = compute_telegram_hash(&parsed, bot_token);  // One line!
}

#[test]
fn test_case_2() {
    let hash = compute_telegram_hash(&parsed, bot_token);
}
}

Benefits:

  • Code 3 times shorter
  • Changes in one place
  • Less chance of errors

How to Find Duplication

1. Visually:

  • Scroll through file, look for similar blocks
  • Watch for copy-paste

2. Automatically:

# cargo-geiger for duplicates
cargo install tokei
tokei --files

# Or cpd (copy-paste detector)

3. By patterns:

# Same call chains
rg "\.iter\(\)\.filter.*\.map.*\.collect" --type rust

Exceptions to DRY Rule

Don’t extract to function if:

  1. Code repeats < 3 times
  2. Context is different (similar syntax, different semantics)
  3. Makes code less readable

Example:

#![allow(unused)]
fn main() {
// OK - though similar, semantics are different
user.validate_email()?;
admin.validate_email()?;
// Don't need validate_any_email(user_or_admin)
}

Readability

1. Naming

Bad names:

#![allow(unused)]
fn main() {
// Unclear what this is
fn proc(d: &str) -> i32 { ... }
fn handle(x: Vec<u8>) { ... }
fn do_it(s: &State) { ... }

// Too generic
fn manager() { ... }
fn process_data() { ... }
fn helper() { ... }
}

Good names:

#![allow(unused)]
fn main() {
// Clear what it does
fn parse_user_id(raw_id: &str) -> Result<i32> { ... }
fn validate_telegram_data(init_data: &str) -> bool { ... }
fn compute_hmac_signature(message: &[u8]) -> String { ... }
}

Naming rules:

  • Functions: verb + what it does (validate_data, compute_hash)
  • Variables: noun (user_id, config, timestamp)
  • Bool variables: is_/has_/should_ (is_valid, has_permission)
  • Constants: SCREAMING_SNAKE_CASE (MAX_RETRIES, DEFAULT_TIMEOUT)

2. Magic Numbers and Magic Strings

Problem:

#![allow(unused)]
fn main() {
// What does 86400 mean? What's "hash"?
fn validate(raw: &str) -> bool {
    let age = get_age(raw);
    if age > 86400 { return false; }  // What's this number?

    let data = parse(raw);
    data.get("hash").is_some()  // Why "hash"?
}
}

Solution:

#![allow(unused)]
fn main() {
// Constants with names
const MAX_AUTH_AGE_SECONDS: u64 = 86400;  // 24 hours
const FIELD_HASH: &str = "hash";

fn validate(raw: &str) -> bool {
    let age = get_age(raw);
    if age > MAX_AUTH_AGE_SECONDS {
        return false;
    }

    let data = parse(raw);
    data.get(FIELD_HASH).is_some()
}
}

How to find:

# Numbers in code
rg "\b[0-9]{4,}\b" --type rust  # Numbers with 4+ digits

# String literals
rg '"\w+"' --type rust

3. Function Length

Rule: Function should fit on screen (~40-50 lines)

Problem:

#![allow(unused)]
fn main() {
// 200 lines - impossible to understand
fn handle_request(req: Request) -> Result<Response> {
    // 200 lines of code...
    // Parses something...
    // Validates something...
    // Saves something...
    // Sends something...
    // ...
}
}

Solution:

#![allow(unused)]
fn main() {
// Split into understandable parts
fn handle_request(req: Request) -> Result<Response> {
    let data = parse_request(&req)?;
    validate_data(&data)?;
    let result = process_data(data)?;
    save_result(&result)?;
    Ok(build_response(result))
}
}

Single Responsibility Principle: One function = one task.


4. Comments

When needed:

#![allow(unused)]
fn main() {
// Explains WHY, not WHAT
fn validate_auth_date(timestamp: u64) -> bool {
    let age = current_time() - timestamp;

    // We check freshness to prevent replay attacks.
    // According to Telegram docs: https://...
    if age > MAX_AUTH_AGE {
        return false;
    }

    true
}
}

When NOT needed:

#![allow(unused)]
fn main() {
// Comment duplicates code
// Increment counter by 1
counter += 1;

// Obvious things
// Get user from database
let user = db.get_user(id);

// BETTER rename for clarity
let authenticated_user = db.get_user(id);
}

By Development Protocol:

  • Regular comments FORBIDDEN
  • Only /// doc-comments for public API

Documentation

1. Doc-Comments for Public API

Must document:

#![allow(unused)]
fn main() {
/// Validates Telegram Mini App initData
///
/// # Arguments
///
/// * `raw` - Raw initData string from Telegram Mini App
/// * `hash` - Expected hash value extracted from initData
/// * `bot_token` - Telegram Bot API token
/// * `max_auth_age` - Maximum age of auth_date in seconds
///
/// # Returns
///
/// `true` if data is valid and fresh, `false` otherwise
///
/// # Example
///
/// ```
/// use my_crate::validate_telegram_data;
///
/// let raw = "auth_date=123&user=...";
/// let hash = "abc123...";
/// let is_valid = validate_telegram_data(raw, hash, "BOT_TOKEN", 86400, false);
/// ```
///
/// # Security
///
/// This function validates auth_date freshness to prevent replay attacks.
/// See: <https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app>
pub fn validate_telegram_data(...) -> bool {
    // ...
}
}

What to include:

  • What the function does
  • Arguments (and their format, if not obvious)
  • Return value
  • Usage example (automatically tested!)
  • Special cases (# Panics, # Errors, # Safety)

2. Examples as Tests (doctests)

#![allow(unused)]
fn main() {
/// Computes SHA-256 hash of data
///
/// # Example
///
/// ```
/// use my_crate::compute_hash;
///
/// let hash = compute_hash(b"hello");
/// assert_eq!(hash.len(), 64); // SHA-256 = 64 hex chars
/// ```
pub fn compute_hash(data: &[u8]) -> String {
    // ...
}
}

Check:

cargo test --doc

If example doesn’t compile or assertion fails -> test fails!


3. README.md for Modules

For large modules:

#![allow(unused)]
fn main() {
//! Telegram authentication module
//!
//! This module handles validation of Telegram Mini App initData.
//!
//! # Security
//!
//! - Uses HMAC-SHA256 for signature validation
//! - Validates auth_date freshness to prevent replay attacks
//!
//! # Example
//!
//! ```rust
//! use crate::telegram::validate_telegram_data;
//!
//! let is_valid = validate_telegram_data(...);
//! ```

pub mod validation;
pub mod types;
}

Testing

1. Test Structure

AAA Principle: Arrange, Act, Assert

#![allow(unused)]
fn main() {
#[test]
fn test_auth_date_expired() {
    // Arrange - prepare data
    let bot_token = "test_token";
    let old_timestamp = 1640995200;
    let raw = format!("auth_date={}&user=...", old_timestamp);

    // Act - perform action
    let result = validate_telegram_data(&raw, "hash", bot_token, 86400, false);

    // Assert - check result
    assert!(!result, "Should reject expired auth_date");
}
}

2. Edge Case Coverage

Test:

  • Normal case (happy path)
  • Boundary values (0, MAX, -1)
  • Invalid data
  • Empty values
  • All if/match branches

Example:

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normal_case() {
        // Normal case
    }

    #[test]
    fn test_empty_input() {
        // Empty string
    }

    #[test]
    fn test_missing_required_field() {
        // Missing required field
    }

    #[test]
    fn test_invalid_format() {
        // Wrong format
    }

    #[test]
    fn test_boundary_values() {
        // 0, MAX_VALUE, MIN_VALUE
    }
}
}

3. Property-Based Testing

For generating many test cases:

#![allow(unused)]
fn main() {
use proptest::prelude::*;

proptest! {
    #[test]
    fn test_parse_never_panics(s in "\\PC*") {
        // For ANY string parser should not panic
        let _ = parse_data(&s);
    }

    #[test]
    fn test_hash_is_deterministic(data in prop::collection::vec(any::<u8>(), 0..1000)) {
        // Hash of same data is always same
        let hash1 = compute_hash(&data);
        let hash2 = compute_hash(&data);
        prop_assert_eq!(hash1, hash2);
    }
}
}

4. Integration Tests

Structure:

project/
|-- src/
|   +-- lib.rs
+-- tests/              # Integration tests
    |-- auth_tests.rs
    |-- api_tests.rs
    +-- common/         # Common helpers
        +-- mod.rs

Example:

#![allow(unused)]
fn main() {
// tests/auth_tests.rs
use my_crate::*;

#[test]
fn test_full_auth_flow() {
    // Test full flow from start to finish
    let app = setup_test_app();

    let response = app.request()
        .post("/auth/telegram")
        .json(&auth_request)
        .send();

    assert_eq!(response.status(), 200);
    // ...
}
}

Architectural Principles

1. Single Responsibility Principle (SRP)

Each module/function does ONE thing:

#![allow(unused)]
fn main() {
// Too many responsibilities
fn handle_user_action(user_id: i64, action: &str, data: &str) -> Result<()> {
    // 1. Parses data
    // 2. Validates
    // 3. Updates DB
    // 4. Sends email
    // 5. Logs
    // 6. Updates cache
    // ...
}

// Separated by responsibility
mod parser { /* Parsing */ }
mod validator { /* Validation */ }
mod repository { /* DB */ }
mod notifier { /* Email */ }
}

2. Dependency Injection

Testability and flexibility:

#![allow(unused)]
fn main() {
// Tightly coupled to specific DB
fn get_user(id: i64) -> Result<User> {
    let conn = PostgresConnection::new()?;  // Can't substitute in tests
    conn.query("SELECT * FROM users WHERE id = $1", &[&id])
}

// Accept abstraction
trait UserRepository {
    fn get_user(&self, id: i64) -> Result<User>;
}

fn get_user<R: UserRepository>(repo: &R, id: i64) -> Result<User> {
    repo.get_user(id)  // Can substitute mock in tests
}
}

3. Modularity

Project structure:

src/
|-- handlers/       # HTTP handlers (one file = one endpoint)
|   |-- auth.rs
|   |-- users.rs
|   +-- profiles.rs
|-- models/         # Data structures
|   +-- user.rs
|-- repository/     # DB operations
|   +-- users.rs
|-- services/       # Business logic
|   +-- auth_service.rs
|-- utils/          # Utilities
|   +-- telegram.rs
+-- main.rs         # Entry point

Rule: Each module solves ONE task.


Code Quality Checklist

Readability

  • Function and variable names clear?
  • No magic numbers and strings?
  • Functions < 50 lines?
  • No deep nesting (< 3-4 levels)?

DRY

  • No code duplication?
  • Common logic extracted to functions?
  • Constants used?

Documentation

  • Public API documented?
  • Usage examples present?
  • Complex parts explained?

Tests

  • Happy path covered?
  • Edge cases covered?
  • Error tests present?
  • Integration tests for critical logic?

Architecture

  • Modules separated by responsibility?
  • Dependencies explicit (not global)?
  • Easy to test?
  • Easy to extend?

Quality Metrics

Goals for production code:

  • Test coverage: >= 95% (Protocol requires 100%)
  • Cyclomatic complexity: <= 10 per function
  • Function length: <= 50 lines
  • Nesting: <= 4 levels
  • Clippy warnings: 0

Tools:

# Coverage
cargo tarpaulin --out Xml

# Complexity
cargo install cargo-geiger
cargo geiger

# Metrics
cargo install tokei
tokei

# Quality
cargo clippy -- -D warnings

Rust-Specific Issues and Patterns

Table of Contents

  1. Ownership and Borrowing
  2. Lifetimes
  3. Panic vs Result
  4. let-else vs map_err Chains
  5. Unsafe Code
  6. Traits and Generics

Ownership and Borrowing

1. Unnecessary Ownership Transfer

Problem:

// Takes ownership without reason
fn process_data(data: Vec<String>) -> usize {
    data.len()  // Could just look at length!
}

fn main() {
    let my_data = vec!["a".to_string(), "b".to_string()];
    let len = process_data(my_data);
    // my_data no longer available!
    // println!("{:?}", my_data); // Compile error
}

Correct:

// Takes reference
fn process_data(data: &[String]) -> usize {
    data.len()
}

fn main() {
    let my_data = vec!["a".to_string(), "b".to_string()];
    let len = process_data(&my_data);
    println!("{:?}", my_data); // Still available
}

How to find:

rg "fn.*\(.*Vec<|fn.*\(.*String[^&]" --type rust
# Find functions taking Vec or String without &

2. Borrowing in Loop

Problem:

#![allow(unused)]
fn main() {
// Does not compile
fn update_items(items: &mut Vec<Item>) {
    for item in items {  // item - mutable reference to element
        if item.should_remove() {
            items.retain(|i| i.id != item.id);  // Trying to take another mutable reference!
        }
    }
}
}

Correct:

#![allow(unused)]
fn main() {
// Use retain with predicate
fn update_items(items: &mut Vec<Item>) {
    items.retain(|item| !item.should_remove());
}

// Or collect indices separately
fn update_items_alt(items: &mut Vec<Item>) {
    let to_remove: Vec<usize> = items
        .iter()
        .enumerate()
        .filter_map(|(i, item)| {
            if item.should_remove() {
                Some(i)
            } else {
                None
            }
        })
        .collect();

    for &i in to_remove.iter().rev() {  // From end so indices don't shift
        items.remove(i);
    }
}
}

3. Clone Instead of Copy

Problem:

#[derive(Debug, Clone)]  // Clone for simple struct
struct Point {
    x: i32,
    y: i32,
}

fn distance(p1: &Point, p2: &Point) -> f64 {
    let dx = (p2.x - p1.x) as f64;
    let dy = (p2.y - p1.y) as f64;
    (dx * dx + dy * dy).sqrt()
}

fn main() {
    let p1 = Point { x: 0, y: 0 };
    let p2 = p1.clone();  // Unnecessary explicit clone
}

Correct:

#[derive(Debug, Clone, Copy)]  // Copy for simple types
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p1 = Point { x: 0, y: 0 };
    let p2 = p1;  // Automatically copied
    println!("{:?} {:?}", p1, p2);  // Both available
}

Rule: If all struct fields are Copy, the struct should be Copy too.


Lifetimes

1. Redundant Lifetime Annotations

Problem:

#![allow(unused)]
fn main() {
// Redundant - compiler will infer
fn first_word<'a>(s: &'a str) -> &'a str {
    s.split_whitespace().next().unwrap_or("")
}
}

Correct:

#![allow(unused)]
fn main() {
// Lifetime elision works automatically
fn first_word(s: &str) -> &str {
    s.split_whitespace().next().unwrap_or("")
}
}

When explicit lifetimes are needed:

#![allow(unused)]
fn main() {
// Here it's necessary - two input references
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
}

2. ’static Everywhere

Problem:

#![allow(unused)]
fn main() {
// Unnecessary 'static requirement
fn store_callback(callback: Box<dyn Fn() + 'static>) {
    // ...
}

// Can't pass closure capturing local variables!
}

Correct:

#![allow(unused)]
fn main() {
// Accept any lifetime
fn store_callback<F: Fn() + 'a>(callback: F) {
    // ...
}

// Or if 'static is really needed, justify in comment:
/// Callback must be 'static because it's stored in global state
fn store_global_callback(callback: Box<dyn Fn() + 'static>) {
    // ...
}
}

Panic vs Result

1. unwrap() and expect() in Production

Problem:

#![allow(unused)]
fn main() {
// CRITICAL - can crash in production
async fn handle_request(req: Request) -> Response {
    let user_id = req.headers()
        .get("user-id")
        .unwrap()  // Panic if no header!
        .to_str()
        .unwrap(); // Another panic!

    let user = db.get_user(user_id).await.unwrap();  // And another!

    Response::ok(user)
}
}

How to find:

# Find all unwrap/expect
rg "\.unwrap\(\)|\.expect\(" --type rust --glob '!tests'

# Excluding tests

Correct:

#![allow(unused)]
fn main() {
// Proper error handling
async fn handle_request(req: Request) -> Result<Response, Error> {
    let user_id = req.headers()
        .get("user-id")
        .ok_or(Error::MissingHeader("user-id"))?
        .to_str()
        .map_err(|_| Error::InvalidHeader("user-id"))?;

    let user = db.get_user(user_id).await
        .map_err(Error::Database)?;

    Ok(Response::ok(user))
}
}

2. When unwrap() Is Acceptable

In tests:

#![allow(unused)]
fn main() {
#[test]
fn test_parsing() {
    let data = parse("valid_data").unwrap();  // OK in tests
    assert_eq!(data.field, "value");
}
}

After check:

#![allow(unused)]
fn main() {
fn process(opt: Option<String>) -> String {
    if opt.is_some() {
        opt.unwrap()  // OK - we just checked
    } else {
        String::new()
    }
}

// But better:
fn process_better(opt: Option<String>) -> String {
    opt.unwrap_or_default()  // Idiomatic
}
}

In constants:

#![allow(unused)]
fn main() {
const DEFAULT_PORT: u16 = "8080".parse().unwrap();  // OK - checked at compile-time
}

let-else vs map_err Chains

Why let-else Is Often Better

let-else makes code readable by humans, not just the compiler, and doesn’t turn error handling into a functional puzzle.

1. Linear Flow Instead of Spaghetti

map_err chains force you to read code right-to-left and from the end:

#![allow(unused)]
fn main() {
// Logic is scattered, error hidden in the middle of expressions
let value = parse(input)
    .map_err(Error::Parse)?
    .validate()
    .map_err(Error::Validate)?
    .normalize()
    .map_err(Error::Normalize)?;
}

With let-else the flow is normal, human:

#![allow(unused)]
fn main() {
// Reads top to bottom
let Ok(value) = parse(input) else {
    return Err(Error::Parse);
};

let Ok(value) = value.validate() else {
    return Err(Error::Validate);
};

let Ok(value) = value.normalize() else {
    return Err(Error::Normalize);
};
}

2. Explicit Exit Points

What matters is not what happened, but where we exit.

let-else:

  • explicitly marks error location
  • makes return Err(...) visible
  • simplifies audit and refactoring

In chains:

  • ? is scattered
  • map_err often loses context
  • easy to miss where exactly the error type changes

3. Less Type Magic

With map_err types dance around:

#![allow(unused)]
fn main() {
// Then From, another map_err, suddenly wrong Error
.map_err(|e| Error::Foo { source: e })
}

let-else is simple and reliable:

#![allow(unused)]
fn main() {
// Match here, return here, type is obvious
let Ok(value) = foo() else {
    return Err(Error::Foo);
};
}

4. Better for Complex Logic

As soon as logging, metrics, different handling branches appear — chains become a circus:

#![allow(unused)]
fn main() {
// Easy to add side effects
let Ok(value) = parse(input) else {
    metrics::inc("parse_fail");
    tracing::warn!("Failed to parse input");
    return Err(Error::Parse);
};
}

Try doing this elegantly in map_err. Don’t.


5. When map_err Is Still OK

map_err is appropriate when:

  • single step
  • simple error transformation
  • code is short and local
#![allow(unused)]
fn main() {
// Once, not a half-screen chain
let value = parse(input).map_err(Error::Parse)?;
}

6. Under the Hood — Identical

Both variants compile identically:

#![allow(unused)]
fn main() {
let x = foo().map_err(Error::A)?;
// and
let Ok(x) = foo() else {
    return Err(Error::A);
};
}

After HIR → MIR → LLVM:

  • same branches
  • same br / return
  • zero allocations
  • zero overhead

No “imperative slowness” exists.


7. What’s Used in Practice

SituationRecommendation
Single step? / map_err
Multiple steps, different contextlet-else
Branching, logging, metricsonly let-else or match

Summary

  • Yes, let-else is professional
  • Yes, zero-cost
  • Yes, compiler does the same thing
  • The only difference is who finds it easier to read

Functional chains look smart. let-else looks like code that won’t fail you in production.


Unsafe Code

1. Unjustified Unsafe

Problem:

#![allow(unused)]
fn main() {
// Unsafe WITHOUT necessity
fn get_first<T>(slice: &[T]) -> Option<&T> {
    if slice.is_empty() {
        None
    } else {
        unsafe {
            Some(slice.get_unchecked(0))  // Why unsafe?
        }
    }
}
}

Correct:

#![allow(unused)]
fn main() {
// Safe version
fn get_first<T>(slice: &[T]) -> Option<&T> {
    slice.first()  // Already in standard library!
}
}

2. Unsafe Without Documentation

Problem:

#![allow(unused)]
fn main() {
// Unsafe without explanations
unsafe fn do_something(ptr: *const u8, len: usize) {
    // What's guaranteed? Why is it safe?
}
}

Correct:

#![allow(unused)]
fn main() {
// With detailed explanation
/// # Safety
///
/// Caller must ensure that:
/// - `ptr` is valid and properly aligned
/// - `ptr` points to at least `len` initialized bytes
/// - `ptr` remains valid for the duration of this call
/// - No other threads access the memory during this call
unsafe fn read_bytes(ptr: *const u8, len: usize) -> Vec<u8> {
    // SAFETY: Caller guarantees ptr validity and len correctness
    std::slice::from_raw_parts(ptr, len).to_vec()
}
}

3. Unsafe Code Checklist

Before using unsafe:

  • Can it be done without unsafe? (95% of cases - YES)
  • Are invariants documented in # Safety?
  • Are there tests (including miri)?
  • Are all edge cases checked?
  • Is there UB (undefined behavior)?

Test with Miri:

cargo +nightly miri test

Traits and Generics

1. Excessive Trait Bounds

Problem:

#![allow(unused)]
fn main() {
// Too many requirements
fn print_items<T: Debug + Display + Clone + Send + Sync>(items: &[T]) {
    for item in items {
        println!("{:?}", item);  // Only using Debug!
    }
}
}

Correct:

#![allow(unused)]
fn main() {
// Minimal requirements
fn print_items<T: Debug>(items: &[T]) {
    for item in items {
        println!("{:?}", item);
    }
}
}

2. impl Trait vs dyn Trait

When to use:

#![allow(unused)]
fn main() {
// impl Trait - return concrete type (known at compile-time)
fn get_iterator(data: Vec<i32>) -> impl Iterator<Item = i32> {
    data.into_iter().filter(|&x| x > 0)
}

// Pros: zero-cost, monomorphization
// Cons: can't return different types

// dyn Trait - return trait object (chosen at runtime)
fn get_shape(shape_type: &str) -> Box<dyn Shape> {
    match shape_type {
        "circle" => Box::new(Circle { radius: 10 }),
        "square" => Box::new(Square { side: 5 }),
        _ => Box::new(Circle { radius: 1 }),
    }
}

// Pros: flexibility, can return different types
// Cons: dynamic dispatch (slower), requires allocation
}

3. AsRef and Borrow for Generalization

Good pattern:

use std::path::Path;

// Accepts &str, String, &Path, and PathBuf
fn read_file<P: AsRef<Path>>(path: P) -> Result<String> {
    std::fs::read_to_string(path.as_ref())
}

fn main() {
    read_file("file.txt")?;               // &str
    read_file(String::from("file.txt"))?; // String
    read_file(Path::new("file.txt"))?;    // &Path
    read_file(PathBuf::from("file.txt"))?;// PathBuf
}

Rust-Specific Patterns

1. NewType Pattern

For type safety:

#![allow(unused)]
fn main() {
// Easy to confuse
fn transfer_money(from: i64, to: i64, amount: i64) -> Result<()> {
    // transfer_money(amount, from, to) - error is invisible!
}

// NewType makes confusion impossible
struct UserId(i64);
struct Amount(i64);

fn transfer_money(from: UserId, to: UserId, amount: Amount) -> Result<()> {
    // transfer_money(amount, from, to) - compile error!
}
}

2. Builder Pattern

#![allow(unused)]
fn main() {
// For structs with many optional fields
#[derive(Default)]
struct ServerConfig {
    host: String,
    port: u16,
    timeout: Duration,
    tls: bool,
}

impl ServerConfig {
    fn builder() -> ServerConfigBuilder {
        ServerConfigBuilder::default()
    }
}

#[derive(Default)]
struct ServerConfigBuilder {
    host: Option<String>,
    port: Option<u16>,
    timeout: Option<Duration>,
    tls: bool,
}

impl ServerConfigBuilder {
    fn host(mut self, host: impl Into<String>) -> Self {
        self.host = Some(host.into());
        self
    }

    fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    fn build(self) -> Result<ServerConfig> {
        Ok(ServerConfig {
            host: self.host.ok_or("host is required")?,
            port: self.port.unwrap_or(8080),
            timeout: self.timeout.unwrap_or(Duration::from_secs(30)),
            tls: self.tls,
        })
    }
}

// Usage:
let config = ServerConfig::builder()
    .host("localhost")
    .port(3000)
    .build()?;
}

3. Phantom Types

For compile-time guarantees:

#![allow(unused)]
fn main() {
use std::marker::PhantomData;

struct Sealed;
struct Open;

// File with state in type
struct File<State> {
    inner: std::fs::File,
    _state: PhantomData<State>,
}

impl File<Open> {
    fn new(path: &str) -> Result<Self> {
        Ok(File {
            inner: std::fs::File::open(path)?,
            _state: PhantomData,
        })
    }

    fn write(&mut self, data: &[u8]) -> Result<()> {
        // Can only write to open file
        Ok(())
    }

    fn seal(self) -> File<Sealed> {
        File {
            inner: self.inner,
            _state: PhantomData,
        }
    }
}

impl File<Sealed> {
    // Cannot modify sealed file
    // No write() method!
}

// file.write() // OK
// file.seal().write() // Compile error!
}

Rust Code Review Checklist

Ownership

  • No unnecessary .clone()?
  • Functions take references where possible?
  • Copy types marked as Copy?
  • No fighting borrow checker with hacks?

Error Handling

  • Result used instead of panic?
  • No unwrap/expect in production code?
  • Errors handled correctly?
  • ? operator used?
  • let-else instead of long map_err chains?

Unsafe

  • Unsafe really necessary?
  • # Safety documentation present?
  • Tested with miri?

Generics & Traits

  • Minimal trait bounds?
  • Correct choice of impl/dyn Trait?
  • AsRef/Borrow for flexibility?

Patterns

  • NewType for important IDs/values?
  • Builder for complex constructors?

Real Project Examples

Example 1: Telegram Authentication - Full Analysis

Initial Problem

A critical vulnerability was discovered in Telegram initData validation.

Code BEFORE Fix

#![allow(unused)]
fn main() {
// src/utils/telegram.rs (simplified)
pub fn validate_telegram_data(
    raw: &str,
    hash: &str,
    bot_token: &str,
    skip_validation: bool,
) -> bool {
    if skip_validation {
        return true;
    }

    let parsed = parse_query_string_raw(raw);

    // PROBLEM 1: NO auth_date CHECK!
    // Old data accepted as valid = Replay Attack

    // PROBLEM 2: Double parsing
    let computed_hash = compute_telegram_hash(raw, bot_token);
    //                                        ^^^
    // Inside compute_telegram_hash() parses again!

    computed_hash == hash
}

fn compute_telegram_hash(raw: &str, bot_token: &str) -> String {
    let parsed = parse_query_string_raw(raw);  // Parsing #2

    let mut kv_pairs: Vec<(String, String)> = parsed.into_iter()...  // Copies String
    kv_pairs.sort_by(...);

    let data_check_string = kv_pairs.iter()...

    let secret = Sha256::digest(bot_token.as_bytes());
    let mut mac = HmacSha256::new_from_slice(&secret)
        .expect("HMAC initialization failed");  // PROBLEM 3: expect()!

    // ...
    hex::encode(mac.finalize().into_bytes())
}
}

Found Issues

1. CRITICAL VULNERABILITY: Replay Attack

What’s wrong:

#![allow(unused)]
fn main() {
// NO auth_date check
// Means: if attacker intercepts initData, they can
// use it FOREVER for authentication!
}

How it’s exploited:

  1. Victim logs into Telegram Mini App
  2. Attacker intercepts request (MITM, compromised Wi-Fi)
  3. Saves initData with valid signature
  4. Month later uses same data to log in as victim

Consequences:

  • Complete account compromise
  • CVSS Score: 9.1 (Critical)
  • Violates official Telegram documentation

Vulnerability proof:

#![allow(unused)]
fn main() {
#[test]
fn test_replay_attack_vulnerability() {
    let bot_token = "real_token";

    // Create initData with old date (2 years ago)
    let old_timestamp = 1640995200; // 2022-01-01
    let raw = format!("auth_date={}&user=...", old_timestamp);

    // Compute correct hash
    let hash = compute_telegram_hash(&raw, bot_token);

    // VULNERABILITY: Validation passes for old data!
    assert!(validate_telegram_data(&raw, &hash, bot_token, false));

    // Expected behavior: should have returned false!
}
}

2. PERFORMANCE: Double Parsing

Metrics:

Benchmark: validate_telegram_data (1000 calls)
BEFORE optimization:  847.3 us
AFTER:                412.1 us
Improvement:          51.4% faster

Explanation:

  • parse_query_string_raw() called 2 times
  • For 200-character string that’s ~100 parse operations instead of 50

3. PROTOCOL VIOLATION: expect()

Development Protocol section 4:

“No panics except tests and unreachable!()”

Code:

#![allow(unused)]
fn main() {
.expect("HMAC initialization failed")  // FORBIDDEN!
}

Why it’s a problem:

  • In production panic = DOS attack
  • If attacker crafts data causing panic -> server crashes
  • Violates graceful degradation principle

4. OPTIMIZATION: Excessive Copying

Was:

#![allow(unused)]
fn main() {
let mut kv_pairs: Vec<(String, String)> = parsed.into_iter()
    .filter(|(k, _)| k != "hash" && k != "signature")
    .collect();
// For 10 pairs of 20 characters = ~400 bytes copying
}

Now:

#![allow(unused)]
fn main() {
let mut kv_pairs: Vec<(&String, &String)> = parsed.iter()
    .filter(|(k, _)| k.as_str() != FIELD_HASH && k.as_str() != FIELD_SIGNATURE)
    .collect();
// Zero-copy! 0 bytes copying
}

Effect: 3-5x faster vector creation


Fixed Code

#![allow(unused)]
fn main() {
// Constants instead of magic strings
pub const DEFAULT_MAX_AUTH_AGE_SECONDS: u64 = 86400;
const FIELD_AUTH_DATE: &str = "auth_date";
const FIELD_HASH: &str = "hash";
const FIELD_SIGNATURE: &str = "signature";

/// Validates auth_date freshness to prevent replay attacks
fn validate_auth_date_freshness(
    parsed: &BTreeMap<String, String>,
    max_age_seconds: u64,
) -> bool {
    if let Some(auth_date_str) = parsed.get(FIELD_AUTH_DATE) {
        if let Ok(auth_date) = auth_date_str.parse::<u64>() {
            let current_time = get_current_timestamp();
            let age = current_time.saturating_sub(auth_date);

            if age > max_age_seconds {
                tracing::warn!(
                    "auth_date too old: {} seconds (max: {})",
                    age,
                    max_age_seconds
                );
                return false;  // Replay attack protection
            }
            return true;
        } else {
            tracing::warn!("Invalid auth_date format: {}", auth_date_str);
            return false;
        }
    }

    tracing::warn!("Missing auth_date in initData");
    false
}

/// Computes Telegram hash - now without expect()
fn compute_telegram_hash(
    parsed: &BTreeMap<String, String>,  // Accept reference
    bot_token: &str,
) -> Option<String> {  // Return Option instead of panic
    let mut kv_pairs: Vec<(&String, &String)> = parsed.iter()  // Zero-copy
        .filter(|(k, _)| k.as_str() != FIELD_HASH && k.as_str() != FIELD_SIGNATURE)
        .collect();

    kv_pairs.sort_by(|a, b| a.0.cmp(b.0));

    let data_check_string = kv_pairs
        .iter()
        .map(|(k, v)| format!("{}={}", k, v))
        .collect::<Vec<_>>()
        .join("\n");

    let secret = Sha256::digest(bot_token.as_bytes());
    let mac = HmacSha256::new_from_slice(&secret).ok()?;  // Without expect()
    let mut mac = mac;
    mac.update(data_check_string.as_bytes());

    Some(hex::encode(mac.finalize().into_bytes()))
}

/// Main validation function
pub fn validate_telegram_data(
    raw: &str,
    hash: &str,
    bot_token: &str,
    max_auth_age_seconds: u64,  // New parameter
    skip_validation: bool,
) -> bool {
    if skip_validation {
        tracing::warn!("Telegram validation SKIPPED (development mode)");
        return true;
    }

    let parsed = parse_query_string_raw(raw);  // Parse ONCE

    // Check data freshness
    if !validate_auth_date_freshness(&parsed, max_auth_age_seconds) {
        return false;
    }

    // Pass reference instead of re-parsing
    let computed_hash = match compute_telegram_hash(&parsed, bot_token) {
        Some(h) => h,
        None => {
            tracing::error!("Failed to compute HMAC hash");
            return false;  // Graceful error handling
        }
    };

    tracing::debug!("Telegram auth validation:");
    tracing::debug!("  computed_hash: {}", computed_hash);
    tracing::debug!("  provided_hash: {}", hash);

    computed_hash == hash
}
}

Tests for New Functionality

#![allow(unused)]
fn main() {
#[test]
fn test_auth_date_expired() {
    let bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11";
    let old_timestamp = 1685644800; // Old date

    let raw = format!("auth_date={}&query_id=AAF&user=%7B%22id%22%3A123%7D", old_timestamp);

    let parsed = parse_query_string_raw(&raw);
    let computed_hash = compute_telegram_hash(&parsed, bot_token).unwrap();

    // Should reject old data
    assert!(!validate_telegram_data(
        &raw,
        &computed_hash,
        bot_token,
        DEFAULT_MAX_AUTH_AGE_SECONDS,
        false
    ));
}

#[test]
fn test_missing_auth_date() {
    let bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11";
    let raw = "query_id=AAF&user=%7B%22id%22%3A123%7D"; // No auth_date

    // Should reject data without timestamp
    assert!(!validate_telegram_data(raw, "somehash", bot_token, DEFAULT_MAX_AUTH_AGE_SECONDS, false));
}

#[test]
fn test_auth_date_within_limit() {
    let bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11";
    let recent_time = get_current_timestamp() - 60; // 1 minute ago

    let raw = format!("auth_date={}&query_id=AAF&user=%7B%22id%22%3A123%7D", recent_time);

    let parsed = parse_query_string_raw(&raw);
    let computed_hash = compute_telegram_hash(&parsed, bot_token).unwrap();

    // Should accept fresh data
    assert!(validate_telegram_data(
        &raw,
        &computed_hash,
        bot_token,
        DEFAULT_MAX_AUTH_AGE_SECONDS,
        false
    ));
}
}

Improvement Results

Security

IssueStatusCVSS
Replay AttackFIXED9.1 -> 0.0
expect() panicFIXED5.3 -> 0.0

Performance

MetricBEFOREAFTERImprovement
initData parsing2x1x-50%
String allocations~400 bytes0 bytes-100%
Validation time847 us412 us+51%

Code Quality

AspectBEFOREAFTER
Lines in main function6725
Reusable functions03
Magic strings6 places0 places
Magic numbers5 places0 places
Test coverage2 tests6 tests

Example 2: Finding N+1 Query Problem

Original Code (Typical Problem)

#![allow(unused)]
fn main() {
// N+1 QUERY PROBLEM
async fn get_users_with_posts(user_ids: &[i64]) -> Result<Vec<UserWithPosts>> {
    let mut result = Vec::new();

    for user_id in user_ids {
        // 1 query for user
        let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", user_id)
            .fetch_one(&db)
            .await?;

        // N queries for each user's posts
        let posts = sqlx::query_as!(Post, "SELECT * FROM posts WHERE user_id = $1", user_id)
            .fetch_all(&db)
            .await?;

        result.push(UserWithPosts { user, posts });
    }

    Ok(result)
}

// For 100 users = 1 + 100 + 100 = 201 DB queries!
}

Problem:

  • For 100 users: 201 queries to DB
  • Time: ~2-3 seconds
  • DB load: critical

Fixed Code

#![allow(unused)]
fn main() {
// OPTIMIZED - 2 queries
async fn get_users_with_posts(user_ids: &[i64]) -> Result<Vec<UserWithPosts>> {
    // 1. One query for all users
    let users = sqlx::query_as!(
        User,
        "SELECT * FROM users WHERE id = ANY($1)",
        user_ids
    )
    .fetch_all(&db)
    .await?;

    // 2. One query for all posts
    let posts = sqlx::query_as!(
        Post,
        "SELECT * FROM posts WHERE user_id = ANY($1)",
        user_ids
    )
    .fetch_all(&db)
    .await?;

    // 3. Group in memory
    let mut posts_by_user: HashMap<i64, Vec<Post>> = HashMap::new();
    for post in posts {
        posts_by_user.entry(post.user_id).or_default().push(post);
    }

    // 4. Assemble result
    let result = users
        .into_iter()
        .map(|user| UserWithPosts {
            user: user.clone(),
            posts: posts_by_user.remove(&user.id).unwrap_or_default(),
        })
        .collect();

    Ok(result)
}

// For 100 users = 2 queries instead of 201!
}

Result:

  • Queries: 201 -> 2 (99% less!)
  • Time: 2-3 sec -> 50-100 ms (20-30x faster)
  • DB load: critical -> minimal

Example 3: Memory Leak via Circular References

Problematic Code

#![allow(unused)]
fn main() {
use std::rc::Rc;
use std::cell::RefCell;

struct Node {
    value: i32,
    next: Option<Rc<RefCell<Node>>>,
    prev: Option<Rc<RefCell<Node>>>,  // Circular reference!
}

fn create_circular_list() {
    let node1 = Rc::new(RefCell::new(Node {
        value: 1,
        next: None,
        prev: None,
    }));

    let node2 = Rc::new(RefCell::new(Node {
        value: 2,
        next: Some(node1.clone()),
        prev: None,
    }));

    // Create cycle
    node1.borrow_mut().prev = Some(node2.clone());  // MEMORY LEAK!

    // node1 and node2 will never be freed!
    // Rc count will never reach 0
}
}

How to detect:

# Use Valgrind or cargo-leak
RUSTFLAGS="-Z sanitizer=leak" cargo +nightly run

Fix:

#![allow(unused)]
fn main() {
use std::rc::{Rc, Weak};  // Use Weak for back references
use std::cell::RefCell;

struct Node {
    value: i32,
    next: Option<Rc<RefCell<Node>>>,
    prev: Option<Weak<RefCell<Node>>>,  // Weak instead of Rc!
}

fn create_circular_list() {
    let node1 = Rc::new(RefCell::new(Node {
        value: 1,
        next: None,
        prev: None,
    }));

    let node2 = Rc::new(RefCell::new(Node {
        value: 2,
        next: Some(node1.clone()),
        prev: None,
    }));

    // Weak doesn't increment reference count
    node1.borrow_mut().prev = Some(Rc::downgrade(&node2));  // OK

    // Now memory will be freed correctly!
}
}

Lesson: Code Review Process

1. Start with Security (15-20 minutes)

  • Look for vulnerabilities using checklist
  • Check authentication/authorization
  • Input data validation

2. Performance (10 minutes)

  • Duplicate operations
  • Inefficient algorithms
  • Unnecessary allocations

3. Quality (10 minutes)

  • Protocol violations (expect, unwrap)
  • Code duplication
  • Readability

4. Tests (5 minutes)

  • Do they cover critical logic?
  • Are there error tests?

Total: ~40-45 minutes for thorough review


Success Metrics

A good code review should find:

  • 1-2 critical issues (security, correctness)
  • 3-5 important (performance, quality)
  • 5-10 minor (style, naming)

If you found nothing - either code is perfect (rare), or you weren’t looking carefully.