← all publishers

ctoth

@ctoth source repo

91 published skills

  1. SQL JSON · ctoth bundle
    Guides standard SQL/JSON (SQL:2016 functions, SQL:2023 type) instead of reflexive vendor operators — use the constructors (JSON_OBJECT/JSON_ARRAY/JSON_OBJECTAGG/JSON_ARRAYAGG), and the query functions JSON_VALUE (for a scalar) vs JSON_QUERY (for an object/array) vs JSON_EXISTS (for a path test) rather than `- greater than `/`- greater than greater than `/`# greater than greater than `/JSON_EXTRACT; shred documents into joinable rows with JSON_TABLE. Auto-invokes when writing or editing JSON columns/queries, `- greater than `/`- greater than greater than `/`# greater than greater than `/JSON_EXTRACT, JSON_VALUE/JSON_QUERY/JSON_TABLE, JSON path expressions, JSON aggregation, or on "extract from JSON" / "store JSON" / "query a JSON column" requests.
    0
    installs
  2. SQL Joins · ctoth bundle
    Guides correct join composition and the single most damaging join bug — putting a filter on the null-able side of an outer join in WHERE instead of ON, which silently demotes a LEFT JOIN to an INNER JOIN and drops the very rows you were looking for. Covers INNER/LEFT/RIGHT/FULL/CROSS semantics with wrong/right SQL, ON vs USING vs NATURAL (and why NATURAL JOIN is a schema-change landmine that joins on every same-named column), self-joins, detecting accidental cross products from a missing or typo'd predicate, one-to-many fan-out that silently inflates SUM/COUNT, and join-key nullability under three-valued logic. Auto-invokes when writing or editing JOIN clauses, ON/USING/NATURAL conditions, queries filtering an outer-joined table, multi-table FROM lists, or on "my LEFT JOIN is dropping rows" / "duplicate rows after join" / "my totals doubled" / "why did I get a cross product" symptoms. Builds on sql-relational-and-null-discipline.
    0
    installs
  3. SQL Set Operations · ctoth bundle
    Guides SQL set operations and the default-to-UNION cost trap — UNION sorts and de-duplicates its whole combined result (expensive) while UNION ALL just appends, so use UNION ALL whenever duplicates are impossible or wanted. Covers INTERSECT/EXCEPT (native set intersection and difference, so they aren't reinvented with joins or NOT EXISTS) and their [ALL] multiset forms, union-compatibility (columns align by position not name, equal count, compatible types), where ORDER BY/FETCH are legal (only on the final compound query — parentheses isolate a branch), the precedence rule (INTERSECT binds tighter than UNION/EXCEPT in standard SQL), that set ops treat NULLs as NOT distinct (two NULLs collapse — the opposite of `=`), and VALUES as an inline table constructor. Auto-invokes when writing or editing UNION/UNION ALL/INTERSECT/EXCEPT, compound SELECTs, VALUES row-set constructors, or on "combine two queries" / "rows in A but not B" / "why are my duplicates gone" / "MINUS" requests.
    0
    installs
  4. SQL Match Recognize · ctoth bundle
    Guides `MATCH_RECOGNIZE` (SQL:2016 row pattern recognition) — regex-style pattern matching across ordered rows for time-series problems (V-shapes/dip-and-recovery, trend reversals, threshold breaches, complex sessionization) — instead of convoluted self-joins or nested LAG/CASE window gymnastics. Auto-invokes when writing or editing time-series pattern detection, row-sequence matching, trend-reversal/dip detection, complex multi-state sessionization, or "find this shape/sequence in rows" requests. CAVEAT — confirm engine support before recommending; when the target engine lacks it, route to `sql-gaps-and-islands` for the portable window-function fallback.
    0
    installs
  5. SQL Temporal Tables · ctoth bundle
    Guides SQL:2011 temporal tables — system-versioned tables (`PERIOD FOR SYSTEM_TIME` + `WITH SYSTEM VERSIONING`) that make the engine auto-record a full history so you query past states with `FOR SYSTEM_TIME AS OF / FROM..TO / BETWEEN / ALL` instead of hand-rolling trigger-based history tables, application-time period tables (`PERIOD FOR name`, `UPDATE/DELETE ... FOR PORTION OF`, `WITHOUT OVERLAPS`) for valid-time, and the system-time vs valid-time vs bitemporal distinction. Auto-invokes when writing or editing audit-history / "as-of" / point-in-time queries, system- or valid-time period tables, slowly-changing-dimension history, temporal primary keys, or "track every change" / "what did this row look like last March" requests. Owns the standard DDL and query syntax only — versioning/storage mechanics, snapshot semantics, and retention/GC horizon belong to the sibling mvcc-time-travel-queries.
    0
    installs
  6. SQL Gaps And Islands · ctoth bundle
    Guides the canonical "gaps and islands" pattern family — detecting unbroken runs of consecutive values (islands — active streaks, sessions, contiguous date/number ranges) and the missing stretches between them (gaps) — with the portable set-based solution instead of brittle self-joins or procedural row-by-row loops. Auto-invokes when writing or editing queries for consecutive sequences, streaks/runs, longest-active-streak, sessionization, collapsing or merging adjacent date/number ranges, finding missing IDs/dates, or "group consecutive rows" / "find gaps" / "count consecutive days" requests.
    0
    installs
  7. SQL Merge And Upsert · ctoth bundle
    Guides atomic upsert — never a race-prone "SELECT then INSERT-or-UPDATE" in application code. Teaches the standard `MERGE` statement (`USING ... ON ...` with `WHEN MATCHED THEN UPDATE/DELETE` and `WHEN NOT MATCHED THEN INSERT`) and maps the real-world alternatives — `INSERT ... ON CONFLICT (col) DO UPDATE/DO NOTHING` in PostgreSQL/SQLite (with `excluded.col`) and `INSERT ... ON DUPLICATE KEY UPDATE` in MySQL/MariaDB (with the `new.col` row alias) — since `MERGE` is unevenly adopted (PostgreSQL only since v15. Auto-invokes when writing or editing `MERGE`, `INSERT ... ON CONFLICT` / `ON DUPLICATE KEY UPDATE`, any upsert / "insert-or-update" / "create-or-update" logic, or check-then-act read-modify-write code that selects a row and then decides to insert or update.
    0
    installs
  8. SQL Style And Naming · ctoth bundle
    Guides readable, reviewable SQL and the one genuine correctness trap in formatting — `'single quotes'` are string literals and `"double quotes"` are delimited identifiers per the SQL standard, so `WHERE name = "John"` references a column named John (error on PostgreSQL, silent misbehavior on MySQL until ANSI_QUOTES flips it). Covers keyword casing (UPPER keywords, lower names), snake_case identifier naming so columns never need permanent double-quoting, why a CamelCase name forces forever-quoting via case-folding, reserved-word collisions, leading-vs-trailing comma style, and multi-line layout instead of single-line mega-queries. Auto-invokes when writing or editing SQL with string-vs-identifier quoting, choosing identifier names, formatting/laying out a query, or on "clean up / format this SQL" requests. A foundation-level style policy.
    0
    installs
  9. SQL Window Functions · ctoth bundle
    Guides window functions — the highest-leverage modern-SQL technique and the frame-clause traps LLMs reliably botch. A window function computes across related rows without collapsing them (PARTITION BY is not GROUP BY). The centerpiece — the default frame with ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which makes LAST_VALUE return the current row, not the partition's last, and makes running totals jump on tied sort keys; fix with an explicit ROWS frame (or MAX() OVER). Covers ROW_NUMBER/RANK/DENSE_RANK/NTILE tie behavior, LAG/LEAD offsets, FIRST_VALUE/LAST_VALUE/NTH_VALUE, ROWS vs RANGE vs GROUPS, named WINDOW reuse, EXCLUDE, and that a window result cannot be filtered in WHERE/HAVING (wrap in a CTE/subquery — the top-N-per-group pattern). Auto-invokes when writing or editing OVER (...), PARTITION BY, frame clauses (ROWS/RANGE/GROUPS), ranking/offset/value functions, running or moving totals, "top-N per group", or "filter on row_number" / "WHERE row_number() = 1" requests.
    0
    installs
  10. SQL Cte And Recursion · ctoth bundle
    Guides common table expressions for readable query decomposition (`WITH`) and `WITH RECURSIVE` for hierarchies, transitive closure, and series generation — always with a termination or cycle guard so recursion cannot run away. Auto-invokes when writing or editing `WITH`/`WITH RECURSIVE`, hierarchy/tree/graph traversal, transitive-closure or generate-series logic, deeply nested subqueries that want flattening, or on "infinite recursion" / "query runs forever" / "tree query" / "recursive query" requests.
    0
    installs
  11. SQL Data Modification · ctoth bundle
    Guides the core write statements — INSERT, UPDATE, DELETE — as set-based operations the database serializes, not row-by-row loops. Teaches the INSERT forms (single-row VALUES, multi-row VALUES in ONE statement, INSERT ... SELECT for bulk copy, DEFAULT VALUES) and bans the nightly job that fires 100k single-row INSERTs instead of one. Centers the
    0
    installs
  12. SQL Pagination And Keyset · ctoth bundle
    Guides correct, scalable pagination and the row-value machinery behind it. Prefer keyset/seek pagination — `WHERE (sort_key, id) greater than (:last_key, :last_id) ORDER BY sort_key, id FETCH FIRST n ROWS ONLY` — over `LIMIT n OFFSET m`, because `OFFSET` makes the server fetch-and-discard the first m rows (O(offset), so deep pages time out) and is unstable — an insert or delete between page loads shifts the window so the reader skips a row or sees one twice. Teaches the standard `OFFSET. Auto-invokes when writing or editing pagination, `LIMIT`/`OFFSET`/`FETCH` queries, infinite-scroll or cursor/keyset endpoints, multi-column `ORDER BY` with paging, row-value comparisons, or `VALUES` bulk row sets.
    0
    installs
  13. SQL Subqueries And Exists · ctoth bundle
    Guides correct subquery use and owns the deep dive the foundation defers — the `NOT IN` + NULL trap, where a single NULL anywhere in the list or subquery collapses `NOT IN` to zero rows because `NOT IN` expands to a chain of `not equal to` comparisons AND'd together and the NULL conjunct is forever UNKNOWN, so `NOT EXISTS` is the safe portable anti-join (EXISTS never returns UNKNOWN). Auto-invokes when writing or editing subqueries, `IN (SELECT ...)`, `NOT IN`, `EXISTS`/`NOT EXISTS`, correlated subqueries, `ANY`/`SOME`/`ALL`, scalar subqueries in SELECT/WHERE, or on "NOT IN returns nothing" / "my orphan/anti-join query is empty" / "subquery returned more than one row" symptoms.
    0
    installs
  14. SQL Datetime And Intervals · ctoth bundle
    Guides standard temporal handling in SQL — the temporal types (DATE, TIME, TIMESTAMP, and crucially TIMESTAMP WITH TIME ZONE), typed literals (DATE '...', TIMESTAMP '...', INTERVAL '...'), EXTRACT, the standard CURRENT_DATE/CURRENT_TIMESTAMP keywords, and INTERVAL arithmetic — instead of jamming dates into strings or reaching for vendor functions (NOW()/GETDATE()/SYSDATE, DATEADD/DATEDIFF, STRFTIME). Auto-invokes when writing or editing date/time columns or literals, EXTRACT, INTERVAL arithmetic, time-zone-sensitive comparisons, date truncation/bucketing, or age/duration calculations, and on "store a timestamp", "add a day/month", "why is my time off by an hour", or "yesterday's rows" requests.
    0
    installs
  15. SQL Property Graph Queries · ctoth bundle
    Guides SQL:2023 SQL/PGQ (ISO/IEC 9075-16, Part 16) — define a property graph as a metadata overlay over existing relational tables with `CREATE PROPERTY GRAPH ... VERTEX TABLES (...) EDGE TABLES (...)`, then query it with `GRAPH_TABLE (graph MATCH (a)-[e]- greater than (b) WHERE ... COLUMNS (...))` using ASCII-art vertex/edge patterns in the FROM clause — and explains its relationship to the standalone GQL language (ISO/IEC 39075:2024), with which it shares the graph-pattern sub-language (GPML). Auto-invokes when writing or editing graph-pattern queries over relational data, `GRAPH_TABLE`/`CREATE PROPERTY GRAPH`, friend-of-friend / reachability / recommendation traversals, or on "can I do graph / Cypher-style queries in SQL" requests. Prevents the LLM failure of hallucinating Cypher or Gremlin syntax where SQL/PGQ (or a recursive CTE) is what's meant. Confirm engine support before recommending.
    0
    installs
  16. SQL Data Types And Numerics · ctoth bundle
    Guides standard-SQL type selection so the storage matches the data's meaning — exact `NUMERIC`/`DECIMAL(p,s)` for money and counts (never `FLOAT`/`REAL`/`DOUBLE`, whose binary floating point cannot store 0.1 exactly and whose rounding error compounds when summed), `SMALLINT`/`INTEGER`/`BIGINT` chosen by the value range (the `INTEGER` ceiling is +2,147,483,647), `CHARACTER VARYING` sized to a real domain limit instead of a cargo-culted `VARCHAR(255)`, fixed-width `CHARACTER(n)` only for. Auto-invokes when writing or editing column type declarations, `CREATE TABLE`/`ALTER TABLE` type choices, `CAST` targets, money/currency/price fields, high-precision or large-range numbers, identifier/key column widths, or string-length and boolean columns. Routes dialect spellings (BIT, TINYINT(1), bytea) to sql-standard-vs-dialect-map.
    0
    installs
  17. SQL Standard Vs Dialect Map · ctoth bundle
    The portability index for SQL — maps each standard feature to whether the readable engines (PostgreSQL, SQLite, MySQL/MariaDB, plus notes on SQL Server / Oracle / DuckDB) support it and how they spell it. Covers `OFFSET … FETCH` vs `LIMIT`, `GENERATED AS IDENTITY` vs `SERIAL`/`AUTO_INCREMENT`/`IDENTITY(1,1)`, `MERGE` vs `ON CONFLICT` vs `ON DUPLICATE KEY UPDATE`, `||` vs `+` vs `CONCAT()`, `IS DISTINCT FROM` vs `at most greater than `, `LISTAGG`/`STRING_AGG`/`GROUP_CONCAT`, `INFORMATION_SCHEMA`. Auto-invokes when porting SQL between engines, targeting a specific database, choosing between a standard and a vendor spelling, or on "does Postgres/MySQL/SQLite support X" / "is this portable" / "how does engine Y spell Z" questions. The index every other SQL skill's Portability section routes to.
    0
    installs
  18. SQL Views And Introspection · ctoth bundle
    Guides SQL views and portable schema introspection — a view is a stored query (`CREATE VIEW`), not a table, re-run on every reference; only simple single-table views are automatically updatable while joins/aggregates/DISTINCT/GROUP BY/set-operation views are read-only by default; `WITH [LOCAL|CASCADED] CHECK OPTION` rejects an INSERT/UPDATE through a filtered view whose new row would fall outside the view (so it can't silently vanish or escape a security filter); and schema discovery should query the SQL-standard `INFORMATION_SCHEMA` (portable across PostgreSQL/MySQL/MariaDB/SQL Server) rather than vendor catalogs (`pg_catalog`, `sqlite_master`, `SHOW TABLES`, `PRAGMA`). Notes that SQLite has no `INFORMATION_SCHEMA` at all. Auto-invokes when writing or editing `CREATE VIEW`, updatable/security views, `WITH CHECK OPTION`, querying catalog/metadata, `INFORMATION_SCHEMA`/`SHOW`/`PRAGMA`/`pg_catalog`/`sqlite_master`, or generating schema-discovery or migration tooling queries.
    0
    installs
  19. SQL Aggregation And Grouping · ctoth bundle
    Guides aggregation correctness — every column in the SELECT list of a grouped query must be either named in GROUP BY or wrapped in an aggregate (the functional-dependency rule), because a non-grouped, non-aggregated column has no single value per group. Bans the "ambiguous groups" antipattern that errors on standard-conformant engines but silently returns an arbitrary row's value on MySQL with ONLY_FULL_GROUP_BY disabled. Auto-invokes when writing or editing GROUP BY/HAVING, aggregate functions (SUM/COUNT/AVG/MIN/MAX), FILTER, LISTAGG/STRING_AGG/GROUP_CONCAT/ARRAY_AGG, ROLLUP/CUBE/GROUPING SETS, percentile/WITHIN GROUP, or any multi-level subtotal report, and on "only_full_group_by" / "must appear in the GROUP BY clause" / "subtotal" / "rollup" requests.
    0
    installs
  20. SQL Indexing And Sargability · ctoth bundle
    Guides portable index design and the sargability rule — an index is a sorted B-tree, so the database can use it only when the predicate leaves the indexed column bare. Bans the recurring index-killers — wrapping an indexed column in a function or expression (`WHERE LOWER(email) = …`, `WHERE DATE(ts) = …`, `WHERE col + 0 = …`) and leading-wildcard `LIKE '%term'`, both of which force a full table scan. Auto-invokes when writing or editing `CREATE INDEX`, a slow `WHERE`/`ORDER BY`/`JOIN`/`GROUP BY`, a function or arithmetic applied to a filtered column, a `LIKE` pattern, or on "why is this query slow" / "what index do I need" / "this query does a full table scan" requests. The highest-leverage performance skill, taught vendor-neutrally.
    0
    installs
  21. SQL Constraints And Integrity · ctoth bundle
    Guides database-enforced data integrity — push the rules into the schema as declarative constraints rather than re-checking them in every application that writes. Covers PRIMARY KEY (= UNIQUE + NOT NULL, one per table) vs UNIQUE (many per table, and by default permits multiple NULLs — the SQL:2023 NULLS NOT DISTINCT lever fixes the duplicate-"unique"-emails trap), CHECK constraints and the pitfall that a CHECK passes when it evaluates to UNKNOWN/NULL (so pair it with NOT NULL), NOT. Auto-invokes when writing or editing CREATE TABLE/ALTER TABLE constraints, FOREIGN KEY/REFERENCES, CHECK/UNIQUE/NOT NULL/DEFAULT, or on "enforce this in the DB or the app" / "why are there orphaned rows" / "why did duplicate emails get in" decisions.
    0
    installs
  22. SQL Transactions And Isolation · ctoth bundle
    Guides the SQL-statement surface of transactions — wrap any multi-statement invariant or check-then-act sequence in `START TRANSACTION`/`COMMIT`/`ROLLBACK` so it is atomic (all-or-nothing), use `SAVEPOINT`/`ROLLBACK TO` for partial rollback, set the isolation level with `SET TRANSACTION ISOLATION LEVEL`, and know the four standard level names (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE), autocommit, READ ONLY/DEFERRABLE, and that DDL is not transactional everywhere (MySQL. Auto-invokes when writing or editing `BEGIN`/`START TRANSACTION`/`COMMIT`/`ROLLBACK`/`SAVEPOINT`, `SET TRANSACTION`, a multi-statement write sequence, a debit/credit or check-then-act flow, or on "should this be in a transaction" / "which isolation level" / "why did half my migration apply" requests.
    0
    installs
  23. SQL Select And Query Processing · ctoth bundle
    Guides the logical clause-evaluation order of a SELECT — FROM → WHERE → GROUP BY/aggregates → HAVING → SELECT-list/window → DISTINCT → UNION → ORDER BY → OFFSET/FETCH — and why that order, not the written order, decides what each clause can reference. A SELECT-list alias is computed late, so it is illegal in WHERE/HAVING (write out the expression) but legal in ORDER BY; aggregate conditions belong in HAVING, not WHERE; DISTINCT dedups the WHOLE row, not one column; and SELECT * is the "Implicit Columns" antipattern that breaks on schema change. Auto-invokes when writing or editing SELECT statements, WHERE/GROUP BY/HAVING/DISTINCT/ORDER BY clauses, column aliases referenced in another clause, ORDER BY ordinals or NULLS FIRST/LAST, or on "column alias does not exist" / "must appear in the GROUP BY" / "why is this column not allowed here" errors. Builds on the sql-relational-and-null-discipline foundation.
    0
    installs
  24. SQL Privileges And Access Control · ctoth bundle
    Guides the standard SQL access-control model — `GRANT` adds privileges, `REVOKE` removes them, roles are the grant targets (a role is a user or a group), and access is default-deny so every privilege must be explicitly granted. Drives toward least privilege — the application connects as a dedicated login role holding ONLY the privileges it needs (`SELECT/INSERT/UPDATE/DELETE` on specific tables), never as a superuser (which bypasses all permission checks) and never with `GRANT ALL` broadly. Auto-invokes when writing or editing `GRANT`/`REVOKE`/`CREATE ROLE`/`CREATE USER`, designing database user/role setup, deciding which credentials an application connects with, or on "least privilege" / "who can access this" / "set up a database user" requests.
    0
    installs
  25. SQL Explain And Set Based Thinking · ctoth bundle
    Guides the two performance habits that matter most — think in sets, not rows, and measure the plan instead of guessing. Replaces the N+1 / RBAR ("row-by-agonizing-row") antipattern — application code looping to issue one query per row, or a correlated per-row subquery — with a single set-based query (`JOIN`/`IN`/`VALUES`/`LATERAL`). Auto-invokes when writing or editing per-row query loops in application code, a correlated per-row subquery, `EXPLAIN`/`EXPLAIN QUERY PLAN` output, or on "why is this slow" / "optimize this query" / "N+1" requests. Routes plan reading and set-thinking for the whole plugin.
    0
    installs
  26. SQL Expressions Case And Functions · ctoth bundle
    Guides portable scalar expressions in SQL — use standard `CASE`, `COALESCE`, `NULLIF`, `||` concatenation, and the keyword string functions (`SUBSTRING(... FROM ... FOR ...)`, `TRIM([LEADING|TRAILING|BOTH] c FROM s)`, `POSITION(sub IN s)`, `OVERLAY`, `CHAR_LENGTH`, `UPPER`/`LOWER`), plus `CAST(x AS type)` for conversion, instead of vendor spellings (`IFNULL`/`ISNULL`/`NVL`/`IIF`, `SUBSTR`/`INSTR`/`LEFT`/`RIGHT`/`LENGTH`, `+` for concat, `::`/`CONVERT`). Warns that `||` and arithmetic return NULL if any operand is NULL (the silent-blank concat trap; Oracle deviates by treating NULL as `''`), that a `CASE` with no `ELSE` defaults to NULL and short-circuits with no fall-through, that `NULLIF(a,b)` yields NULL when equal (the `x / NULLIF(y,0)` divide-by-zero guard), and that `GREATEST`/`LEAST` (standardized in SQL:2023) disagree across engines on NULL. Auto-invokes when writing or editing `CASE`, `COALESCE`/`NULLIF`/`GREATEST`/`LEAST`, string functions, string concatenation, or type conversions/`CAST`.
    0
    installs
  27. SQL Generated And Identity Columns · ctoth bundle
    Guides the two standard SQL ways to let the database derive a column value for you — `GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY` for surrogate keys instead of vendor `SERIAL`/`AUTO_INCREMENT`/`IDENTITY(1,1)`, and `GENERATED ALWAYS AS (expr) STORED|VIRTUAL` computed columns instead of recomputing a derived value in every query or maintaining it by hand in application code. Auto-invokes when writing or editing auto-increment / surrogate-key columns, `SERIAL`/`AUTO_INCREMENT`/`IDENTITY(1,1)`, computed/derived columns, `GENERATED` clauses in `CREATE TABLE`, or on "auto-incrementing id" / "computed column" / "store a total/full-name/age" requests. Builds on the foundation `sql-relational-and-null-discipline`.
    0
    installs
  28. SQL Injection And Parameterization · ctoth bundle
    Guides the one non-negotiable rule for combining SQL with data — pass every value through a bind parameter / prepared statement, and never build SQL by string interpolation, concatenation, f-strings, or `format`. Explains why this beats hand-escaping (OWASP ranks escaping last and "STRONGLY DISCOURAGED," and "CANNOT guarantee" it works), why identifiers (table/column names, ASC/DESC) cannot be parameterized and must be allow-listed against a fixed set, and that placeholder syntax (`?`, `$1`. Auto-invokes when writing or editing any query that embeds a variable or user input, string-building of SQL, dynamic `WHERE`/`ORDER BY`/table or column names, ORM raw-query escape hatches, or on "build this query from input" / "is this safe from injection" / "escape this value" requests.
    0
    installs
  29. SQL Lateral And Correlated Derived · ctoth bundle
    Guides LATERAL — a derived table in FROM that may reference columns of preceding FROM items, which a plain subquery cannot. It is the clean, standard answer to top-N-per-group ("latest 3 orders per customer"), per-row set-returning-function expansion, and pulling several correlated values in one pass instead of N correlated scalar subqueries in the SELECT list. Covers the LEFT JOIN LATERAL (...) ON true recipe with ORDER BY + FETCH FIRST n ROWS, implicit LATERAL for table functions, the left-to-right visibility rule, and the SQL Server/Oracle CROSS APPLY / OUTER APPLY spelling of (CROSS/LEFT) JOIN LATERAL. Teaches when a window function top-N is the better tool instead. Auto-invokes when writing or editing LATERAL / CROSS APPLY / OUTER APPLY, top-N-per-group or "newest N per group" queries, per-row table-function expansion (unnest/json_table/string functions in FROM), or a query carrying one correlated scalar subquery per output column. Builds on the foundation sql-relational-and-null-discipline.
    0
    installs
  30. SQL Pattern Matching And Collation · ctoth bundle
    Guides correct, portable text matching in SQL — LIKE with its `%` (any sequence) and `_` (any single character) wildcards, the ESCAPE clause for literal `%`/`_`, and the central trap that LIKE's case sensitivity is decided by the active COLLATION and therefore silently differs across engines (case-SENSITIVE in standard SQL and PostgreSQL, case-INSENSITIVE under the common MySQL/SQL Server default collations, case-insensitive for ASCII only in SQLite) so the identical query returns different. Auto-invokes when writing or editing a LIKE/ILIKE/SIMILAR TO/REGEXP/`~`/GLOB predicate, a COLLATE clause, case-insensitive or accent-insensitive search, or on "case-insensitive search", "find regardless of accents", "LIKE doesn't match" / "matched different rows on MySQL vs Postgres" requests.
    0
    installs
  31. SQL Relational And Null Discipline · ctoth bundle
    Guides the core correctness floor of SQL — query results are unordered sets with no defined order unless you write ORDER BY, NULL means "unknown" and propagates UNKNOWN through every comparison and arithmetic expression, and WHERE/HAVING/ON keep only rows that evaluate to TRUE while CHECK rejects only rows that evaluate to FALSE (so UNKNOWN passes). Auto-invokes when writing or editing any WHERE/HAVING/ON/CHECK predicate, comparisons against possibly-null columns, NOT IN/`not equal to`/`!=`, COUNT/SUM/AVG over nullable columns, GROUP BY/ORDER BY/UNIQUE on nullable columns, or on "why does my query return no rows" / "why is my average wrong" / "handle NULL" requests. The policy root every other SQL skill routes back to.
    0
    installs
  32. SQL Schema Design And Normalization · ctoth bundle
    Guides portable relational schema design — normalize to remove the insertion, update, and deletion anomalies (the 1NF→BCNF ladder), choose natural vs surrogate keys deliberately, model many-to-many with a junction table, and denormalize only with a stated reason. Bans the structural antipatterns that no constraint can later rescue — comma-separated value lists ("Jaywalking", a First Normal Form violation), Entity-Attribute-Value (EAV) key-value rows instead of columns, adjacency-only "Naive Trees" that cannot query a subtree, and polymorphic/promiscuous foreign keys that carry no referential integrity. Auto-invokes when designing tables or schemas, writing CREATE TABLE for a new model, modeling a hierarchy/tree or a many-to-many relationship, storing a list or "flexible attributes" in a column, choosing a primary key, or on "is this schema/data model good", "review my schema", or "how should I store X" requests. Pure design theory — engine-independent and fully portable.
    0
    installs
  33. Go JSON · ctoth bundle
    Guides encoding/json correctly — only exported fields marshal (a lowercase field is silently dropped), struct tags (`json:"name,omitempty"`, `json:"-"`, `,string`), the omitempty-vs-omitzero (Go 1.24) trap where omitempty does NOT drop a zero struct or time.Time, decoding into interface{} yielding map[string]any with every number a float64 (precision loss → json.Number / UseNumber), Decoder/Encoder for streams, DisallowUnknownFields, custom MarshalJSON, json.RawMessage, and always checking the Marshal/Unmarshal error. Auto-invokes when writing or editing struct json tags, json.Marshal/Unmarshal, encoding/json, Decoder/Encoder, omitempty/omitzero, or on "why is this field missing in the JSON" / "why is my number a float64" requests. The struct tag is a contract; the surprises are all in the defaults.
    0
    installs
  34. Go Time · ctoth bundle
    Guides the time package correctly — never compare time.Time with == (it compares the wall instant AND the monotonic reading AND the Location, so two values for the same instant can be unequal); use t.Equal/t.Before/t.After. Reference-layout formatting where the magic constant is the date "Mon Jan 2 15:04:05 MST 2006" (so "2006-01-02", not strftime %Y-%m-%d). time.Duration is an int64 of nanoseconds, so a bare integer is nanoseconds (time.Sleep(1) sleeps 1ns) — write typed literals like 5*time.Second. Stop tickers and don't leak time.After in hot loops; measure elapsed with time.Since (monotonic), not wall-clock subtraction; check the time.Parse error. Auto-invokes when writing or editing time.Time comparisons, time formatting/parsing layouts, time.Duration literals, timers/tickers, measuring elapsed time, or on "why does this time format look wrong" / "why is == on times false" requests. The layout is a date, not a format string; the surprises are all in the defaults.
    0
    installs
  35. Go Context · ctoth bundle
    Guides Go context.Context discipline — pass it as the first parameter named ctx and never store it in a struct, derive children with WithCancel/WithTimeout/WithDeadline and ALWAYS defer cancel() (go vet's lostcancel flags a missing one), check ctx.Done()/ctx.Err() in loops and before expensive work, start from context.Background() at entry points and context.TODO() when you don't have one yet, attach reasons with WithCancelCause/Cause and decouple with WithoutCancel/AfterFunc (1.20/1.21), and carry only request-scoped values behind an unexported key type. Auto-invokes when writing or editing functions taking context.Context, WithCancel/WithTimeout/WithValue, ctx.Done()/Err(), or on "where should ctx go" / "is this context leaking" requests. The propagation-and-cancellation depth behind the policy root's "never start a goroutine you can't stop."
    0
    installs
  36. Go Generics · ctoth bundle
    Guides Go generics restraint and constraint design — reach for a type parameter only when you would otherwise write the exact same code for multiple types (a container, or an algorithm over a slice/map/channel element type like map/filter/reduce), never when you only call a method on the value (that is an interface), and prefer the stdlib slices/maps/cmp helpers over hand-rolled generics. Covers constraints (any, comparable, cmp.Ordered, the ~T underlying-type element, unions like int | int64), type inference, generic type aliases (1.24), and self-referential constraints (1.26). Auto-invokes when writing or editing type parameters ([T any]), type constraints, generic functions or types, and on "should this be generic", "generic or interface here", or "make this generic". A type parameter earns its place only on real duplication; clarity first.
    0
    installs
  37. Go Interfaces · ctoth bundle
    Guides Go interface design and the typed-nil-error gotcha — accept interfaces and return concrete structs, keep interfaces small (1–3 methods, `-er` names), define them on the consumer side not the producer, avoid `any`/`interface{}` as a parameter type, compose with embedding, and never return a concrete `*MyError`/pointer type where the value can be nil. Auto-invokes when writing or editing interface definitions, function signatures that take or return interfaces, `any`/`interface{}` parameters, interface embedding, or functions returning concrete error/pointer types — and on "why is this nil check failing", "is this always non-nil", or "should this be an interface". An interface holds a (type, value) pair, so a nil pointer inside one is not a nil interface.
    0
    installs
  38. Go Performance · ctoth bundle
    Guides Go performance work as a measure-first discipline — never optimize from intuition; profile or benchmark first, then optimize only what the data proves is hot, without sacrificing clarity for unmeasured speed. Covers benchmarking with go test -bench -benchmem and comparing runs with benchstat (not eyeballing one noisy run); profiling with pprof (CPU -cpuprofile, heap -memprofile, net/http/pprof for live servers; top/list/web); escape analysis via go build -gcflags=-m (stack vs heap). Auto-invokes when optimizing Go performance, reducing allocations, profiling with pprof, reading escape analysis, or enabling PGO, and on "make this faster" / "why is this allocating" / "profile this" requests. Routes benchmark mechanics to go-testing-advanced, sync.Pool to go-sync-primitives.
    0
    installs
  39. Go Slog Logging · ctoth bundle
    Guides Go logging with log/slog (Go 1.21+) — the stdlib STRUCTURED logger — over fmt.Println / log.Printf debugging and ad-hoc string logs. Prefer typed attrs (slog.String/Int) or LogAttrs to the key-value variadic form, which silently emits !BADKEY on an odd argument count; set a minimum level and a TextHandler/JSONHandler at the edges via SetDefault; attach context with With/Group and InfoContext; don't log-and-return the same error, don't log secrets/PII, and don't log.Fatal in a library (it skips defers). Auto-invokes when writing or editing logging, log/slog, slog.Info/Error, log.Printf/Println, or structured log attrs, and on "how should this log" / "add logging here" / replacing fmt.Println debugging. Logs are read by the on-call engineer at 3am.
    0
    installs
  40. Go Error Handling · ctoth bundle
    Guides Go error handling as values — wrap with fmt.Errorf and %w to preserve the chain, inspect with errors.Is (sentinel) and errors.As / errors.AsType (typed) instead of string-matching, choose sentinel vs custom error types and when they become API, combine with errors.Join, write lowercase un-punctuated messages, handle each error exactly once, and decorate or close-with-error via named returns and defer. Auto-invokes when writing or editing error returns, fmt.Errorf, errors.Is/As, custom error types, or on "handle this error" / "why is this error not matching" requests. The depth behind the policy root's "errors are values, never silently discarded."
    0
    installs
  41. Go Project Layout · ctoth bundle
    Guides how a Go module is organized into directories and packages — start flat (a single package at the module root is fine; don't build a deep tree prematurely), put each binary behind cmd/name/main.go and keep main thin (parse flags, wire dependencies, delegate to importable packages so the logic is testable), use internal/ for compiler-enforced privacy to keep an API surface small, package by responsibility/capability not by MVC layer (no models//controllers//services/), never create a util/common/helpers/shared grab-bag named for what it holds instead of what it does, don't treat the community golang-standards/project-layout repo as official, and don't reach for pkg/ by reflex. Auto-invokes when creating a new Go project/module structure, adding packages or directories, cmd/ or internal/ dirs, or on "how should I structure this", "where does this code go", or "do I need a pkg/ folder". The official guidance is go.dev/doc/modules/layout, and it is minimal.
    0
    installs
  42. Go Channels Select · ctoth bundle
    Guides Go channel mechanics — declare directionality in signatures (chan less than - send-only, less than -chan receive-only), let only the sender close and only when sends are done (closing is a broadcast, not cleanup), read the comma-ok / range-ends-on-close idiom so a closed channel's zero value is not mistaken for data, choose unbuffered (synchronization) vs buffered (decoupling) deliberately, use chan struct{} for pure signals, and drive select with default for non-blocking and the nil-channel trick to disable a case. Auto-invokes when writing or editing channels, chan declarations, close(), select statements, or buffered channels, and on "send on closed channel panic" / "why does this select block" / "why does my range over a channel never end" requests. The depth behind the policy root's "don't fight Go" for the communication primitive.
    0
    installs
  43. Go Slices And Maps · ctoth bundle
    Guides Go slice and map data operations and the slices/maps stdlib packages — a slice is a view (pointer, len, cap) over a backing array, so subslices alias and append conditionally mutates a caller's shared array (the
    0
    installs
  44. Go Sync Primitives · ctoth bundle
    Guides Go's shared-memory synchronization toolkit — a zero-value sync.Mutex/RWMutex is ready with no constructor and must NEVER be copied after first use (passing a struct-with-Mutex by value copies the lock; go vet's copylocks catches it), keep critical sections small with defer Unlock right after Lock, don't embed a Mutex in an exported struct, reach for RWMutex only when reads vastly dominate, use sync.Once/OnceFunc/OnceValue (1.21) for one-time init, prefer typed sync/atomic (atomic.Int64/Bool/Pointer — 1.19) over the old free functions and over a Mutex for a single word, use sync.Map ONLY for its two documented cases, and treat sync.Pool items as transient. Auto-invokes when writing or editing sync.Mutex/RWMutex, sync.Once, sync/atomic, sync.Map, sync.Pool, or a WaitGroup, and on "is this lock copied" / "mutex or channel here" / "why did copylocks fire" requests. The lock-based half of "share memory by communicating."
    0
    installs
  45. Go Naming And Style · ctoth bundle
    Guides how Go reads to a human across two themes — identifier and structural naming (MixedCaps/mixedCaps never under_scores, initialisms kept as one case unit like URL/ID/HTTP, no Get prefix on getters, single-method interfaces get -er names, short scope-proportional variable and 1–2-letter receiver names that are never this/self, package names that are short lowercase nouns with no util/common grab-bags and no stutter, and the early-return line-of-sight shape) and exported doc comments (a full sentence beginning with the name being declared, one package comment, the Deprecated: convention, gofmt owns mechanical formatting). Auto-invokes when writing or editing identifier names, package names, receiver names, getters, initialisms like URL/ID, or exported doc comments — and on "is this named idiomatically", "rename this", or "clean up the naming". The name and its doc comment are the API a reader meets first.
    0
    installs
  46. Go Testing Advanced · ctoth bundle
    Guides Go's advanced testing techniques — native fuzzing (FuzzXxx, f.Add seed corpus, f.Fuzz property body, the testdata/fuzz corpus, go test -fuzz); benchmarks with the Go 1.24 `for b.Loop()` loop that replaces the error-prone `for i := 0; i less than b.N; i++`, plus b.ReportAllocs, b.ResetTimer, b.RunParallel, and keeping the result alive so the optimizer can't delete the body; testing/synctest (Go 1.25) for deterministic, instant time-based concurrency tests instead of flaky time.Sleep; go test -cover as a guide not a target; and the stdlib-over-testify stance. Auto-invokes when writing or editing benchmarks, fuzz tests, FuzzXxx, b.Loop/b.N, testing/synctest, coverage, or deciding stdlib testing vs testify, or on "benchmark this" / "fuzz this" / "why is this concurrency test flaky" requests. Routes table tests, subtests, helpers, and golden files to go-testing-tabledriven.
    0
    installs
  47. Go Defer Panic Recover · ctoth bundle
    Guides Go's defer, panic, and recover — the LIFO ordering and arguments-evaluated-at-the-defer-statement semantics, why defer is near-free since open-coded defers (so don't avoid it except in tight loops), the loop-defer handle-leak pitfall, panic only for programmer bugs and unrecoverable states (not ordinary failure), and recover only inside a deferred function at a boundary to convert a panic into an error. Auto-invokes when writing or editing defer, panic, recover, or deferred cleanup, and on "why does this defer run in the wrong order", "should this panic", or "how do I stop a panic from crashing the process". Routes ordinary error-as-value handling to go-error-handling.
    0
    installs
  48. Go Iterators Rangefunc · ctoth bundle
    Guides writing and consuming Go push iterators (range-over-func, Go 1.23) — an iter.Seq[V] is func(yield func(V) bool), the iterator calls yield per element and MUST stop calling it the moment yield returns false (the central bug is ignoring that bool — the runtime panics on a yield call after it returned false), range translates break/continue/return through yield, iter.Pull converts push→pull and you MUST call its stop, and the restraint rule is don't wrap a slice you already have in an iterator — return the slice. Covers iter.Seq/Seq2, slices.All/Values/Backward/Collect/Sorted, maps.Keys/Values/Collect, and Seq2 with a trailing error. Auto-invokes when writing or editing iterator functions, iter.Seq/Seq2, range-over-func, yield callbacks, iter.Pull, or on "how do I make this rangeable" / "should this return an iterator or a slice". Honor yield's bool; don't iteratorize a slice for fashion.
    0
    installs
  49. Go Strings Bytes Runes · ctoth bundle
    Guides Go string handling as what a string actually is — an immutable, read-only slice of UTF-8 bytes where indexing yields a byte (not a character), len is a byte count (not a rune count), for range decodes runes while an indexed for walks bytes, []byte/[]rune conversions copy, string(intValue) is the code-point trap go vet flags, strings.Builder (not += in a loop) builds strings without O(n²) reallocation, and strconv beats fmt.Sprintf in hot paths. Auto-invokes when writing or editing string indexing/iteration, []byte/[]rune conversions, string concatenation in loops, strconv vs fmt, string(int), or on "why is len wrong for this unicode string" requests. The depth behind the policy root's "use the most standard tools" for text.
    0
    installs
  50. Go Testing Tabledriven · ctoth bundle
    Guides Go test structure — a slice of named struct cases looped through t.Run so every case is an isolated, individually-runnable subtest; t.Helper in assertion helpers so failures point at the caller; t.Cleanup (LIFO) over defer for teardown; t.Parallel for concurrency (and the Go 1.22 loop-var change that removes the old `tc := tc` copy); t.Errorf to continue vs t.Fatalf to stop this test's goroutine; got-before-want messages that identify the input; cmp.Diff over reflect.DeepEqual; golden files under testdata/ with a -update flag; t.TempDir and TestMain. Auto-invokes when writing or editing _test.go files, table-driven tests, t.Run subtests, t.Helper, t.Cleanup, t.Parallel, golden files, or on "write tests for this" / "add a test case" requests. Routes fuzzing, benchmarks, and synctest to go-testing-advanced.
    0
    installs
  51. Go Version Feature Map · ctoth bundle
    The consolidated Go 1.21→1.26 feature reference and modernization rule — which idiom is available given the module's `go` directive, and prefer the modern builtin/stdlib form over the stale hand-rolled one. The `go` line gates which language features compile (range-over-func needs `go 1.23`, per-iteration loop variables need `go 1.22`), so "idiomatic" means *current* idiomatic for the declared version. Catches the pre-modern Go that older training data emits: the `tc := tc` loop copy (unneeded since 1.22), `for i := 0; i less than b.N; i++` benchmarks (use `b.Loop`, 1.24), hand-rolled `min`/`max`/`Contains` (builtins/`slices`, 1.21), `omitempty` on `time.Time` (use `omitzero`, 1.24), the `errors.As` out-param dance (use `errors.AsType[T]`, 1.26), and the `tools.go` hack (use `tool` directives, 1.24). Auto-invokes when choosing a Go idiom that depends on version, setting or raising the `go` directive, modernizing old Go, or on "what version is this from" / "is there a newer way" questions.
    0
    installs
  52. Go Perf Pgo · ctoth bundle
    Guides Go Profile-Guided Optimization at depth — a representative production CPU profile (not a microbenchmark) committed as default.pgo, auto-detected by go build (GA Go 1.21), for reproducible builds; what PGO buys (hot-call inlining + interface devirtualization); the 2-14% payoff; refreshing as code drifts; merging profiles. Fires on "set up PGO", "profile-guided optimization", "default.pgo", "make the compiler optimize hot paths", "is PGO worth it". Routes inlining→go-perf-inlining, devirtualization→go-perf-compiler-intrinsics, collection→go-perf-pprof-profiling.
    0
    installs
  53. Go Idiomatic Discipline · ctoth bundle
    Guides core Go authoring discipline along two axes — handle errors honestly and stop fighting the language on the floor (no discarded errors, no panic for ordinary failure, no Java/Python-in-Go), and don't over-abstract or out-clever it on the ceiling (no interface-per-struct, no premature generics, no framework scaffolding for a small tool). The judgment target is "clear AND correct." Auto-invokes when writing or editing .go files, and on "make it idiomatic", "is this idiomatic Go", or "clean this up" requests. The dual-axis policy root every other Go skill routes back to.
    0
    installs
  54. Go Perf Maps · ctoth bundle
    Guides high-performance Go maps — the Swiss Tables map (default since Go 1.24; GOEXPERIMENT=noswissmap to A/B), preallocating make(map[K]V, n), key-type hashing cost (int beats large string/array/struct keys), maps never shrinking after delete (recreate to reclaim), clear() vs realloc, map[K]struct{} sets, and when a slice beats a map for small N. Fires on "preallocate this map", "map memory not freed", "faster map keys", "map is slow". Routes correctness to go-slices-and-maps, concurrent maps to go-perf-contention-and-sharding.
    0
    installs
  55. Go Perf Simd · ctoth bundle
    Guides SIMD / vectorization in Go. The compiler barely autovectorizes, so SIMD means hand-written Plan 9 assembly (//go:noescape stubs, GOARCH .s files, or Avo) as stdlib does for bytes.IndexByte, or the experimental simd/archsimd package (Go 1.26, GOEXPERIMENT=simd, amd64, unstable API). Covers when it pays off — data-parallel hot loops, after algorithm/BCE/SoA — and its costs: assembly bypasses bounds checks and the race detector. Fires on "use SIMD in Go", "vectorize this loop", "AVX in Go", "the simd package". Routes to go-perf-compiler-intrinsics and go-perf-data-oriented-layout.
    0
    installs
  56. Go Race And Memory Model · ctoth bundle
    Guides what a data race actually is in Go and how to detect it — a data race (two goroutines touch the same memory concurrently, at least one writing, with no happens-before edge) is undefined behavior, not a stale read; happens-before comes only from channels, mutexes, Once, WaitGroup, and atomics, never from a plain shared variable or a time.Sleep; "it passed once" is not proof; the race detector (go test/build/run -race) has no false positives but only catches races that actually execute, so run it in CI; and testing/synctest (1.25) gives deterministic concurrency tests with a fake clock. Auto-invokes when writing or editing concurrent access to shared variables, maps, or slices, reviewing goroutines for safety, or on "is this a data race" / "why does this only fail sometimes" / "concurrent map writes" / "set up -race in CI" requests. Owns the race concept and -race; routes fixes to go-sync-primitives, go-channels-select, and go-context.
    0
    installs
  57. Go Concurrency Goroutines · ctoth bundle
    Guides goroutine lifetime and ownership — never start a goroutine you can't stop, give every goroutine a defined exit (context cancellation, a closed channel, or bounded work), avoid the blocked-forever leak, use sync.WaitGroup correctly (Add before the go, or wg.Go in 1.25) and golang.org/x/sync/errgroup for fallible fan-out and SetLimit worker pools, and keep library functions synchronous so the caller owns concurrency. Auto-invokes when writing or editing `go` statements, goroutines, sync.WaitGroup, errgroup, worker pools, or on "is this goroutine leaking" / "how do I wait for these" requests. The depth behind the policy root's "never start a goroutine you can't stop."
    0
    installs
  58. Go Modules And Versioning · ctoth bundle
    Guides Go module mechanics and versioning — author and edit go.mod/go.sum through the go command (never by hand), understand that MVS selects the minimum version that satisfies all requirements (not the latest), put /v2 in both the module path and the import path for v2+ (semantic import versioning), keep go.sum committed, run go mod tidy before committing, treat the go directive as a gate on language features and the toolchain line as a request, use replace/exclude/retract correctly, declare build tools with tool directives (1.24) instead of the tools.go hack, and develop multiple local modules together with go.work workspaces. Auto-invokes when writing or editing go.mod/go.sum, adding dependencies, running go get / go mod tidy, doing a major-version /v2 import, using replace/retract/tool directives or go.work, or on "how do I add this dependency" / "why won't this v2 import resolve" requests. The module-lifecycle depth behind the policy root's "work with the toolchain, don't fight it."
    0
    installs
  59. Go Perf Slices · ctoth bundle
    Guides Go slice performance beyond correctness — the real growslice factors (2x while cap less than 256, then newcap += (newcap+768) greater than greater than 2 ≈ 1.25x), preallocating via make([]T, 0, n) and slices.Grow to avoid repeated grow-and-copy, reusing buffers with b = b[:0], copy vs append, the GC-scan cost of []*T, slices.Clip, and a subslice pinning a huge backing array. Fires on "preallocate this slice", "why is append slow", "reduce slice allocations", "reuse this buffer". Routes aliasing to go-slices-and-maps, layout to go-perf-data-oriented-layout.
    0
    installs
  60. Go Perf Inlining · ctoth bundle
    Guides Go inlining as a performance lever — the ~80-node cost budget, mid-stack inlining of non-leaf functions, what blocks it (over budget, defer, go, recover, non-devirtualized interface calls), reading "can inline"/"inlining call" from -gcflags=-m and -m=2, //go:noinline, and how inlining unlocks escape analysis and bounds-check elimination. Fires on "why isn't this inlined", "make this inline", "reduce call overhead", "is this function inlined". Routes PGO to go-perf-pgo, escape to go-perf-escape-analysis.
    0
    installs
  61. Go Perf Gc Tuning · ctoth bundle
    Guides Go GC tuning — GOGC (ratio, default 100) vs GOMEMLIMIT (1.19 soft memory limit), the GOGC=off+limit pattern and thrashing risk when too tight, reading GODEBUG=gctrace, SetGCPercent/SetMemoryLimit, ballast-is-obsolete, Green Tea GC (1.25 experiment, 1.26 default), and the primary lever — lower the allocation rate first. Fires on "tune the GC", "set GOMEMLIMIT", "reduce GC overhead", "GOGC", "too much time in GC". Routes which-allocs to go-perf-pprof-profiling, tail latency to go-perf-tail-latency.
    0
    installs
  62. Go Perf Sync Pool · ctoth bundle
    Guides sync.Pool as a GC-pressure reliever — per-P local pools with a lock-free fast path, the victim cache (a pooled item survives one GC), why items may vanish anytime so a Pool holds only fungible scratch, the Reset discipline, the grown-buffer retention leak (cap-check before Put), and putting a pointer not a value to avoid boxing into any. Auto-invokes on "use a sync.Pool", "pool these buffers", "reduce allocations with pooling", "is sync.Pool worth it". Routes Pool copylock to go-sync-primitives, allocator cost to go-perf-allocator-internals.
    0
    installs
  63. Go Perf Os Tooling · ctoth bundle
    OS-level performance tooling for Go — Linux perf stat (IPC/cache/branch counters) and perf record/report, flame graphs (Gregg's + pprof -http), perf c2c for false-sharing/HITM, strace -c/bpftrace for syscall counts, and perflock for benchmark stability. For off-CPU kernel/hardware cost pprof and the tracer can't see. Fires on "use perf on Go", "cache misses", "flame graph", "perf c2c", "count syscalls". Routes pprof to go-perf-pprof-profiling, false sharing to go-perf-false-sharing, the USE method to go-perf-methodology.
    0
    installs
  64. Go Tooling And Static Analysis · ctoth bundle
    Guides the Go detection layer — the CI gate that catches the rules the authoring skills teach. gofmt/gofumpt for canonical formatting; go vet for built-in correctness analyzers (printf, copylocks, lostcancel, loopclosure, stringintconv, waitgroup); staticcheck for deeper bug/simplification/style checks; golangci-lint as the curated aggregator (do NOT enable-all); govulncheck for reachable known vulnerabilities; go test -race; //go:build constraints; go generate; and the Go 1.26 go fix modernizers. Auto-invokes when setting up CI/linting, configuring golangci-lint/.golangci.yml, running go vet/staticcheck/govulncheck/gofmt, build tags, go generate, or on "add linting" / "why is CI failing on format" / "how do I catch this class of bug". A discarded error or a copied lock is found by the toolchain, not by reading one file.
    0
    installs
  65. Go Perf Buffered Io · ctoth bundle
    Guides buffered I/O in Go — wrapping os.File/net.Conn in bufio so small reads/writes batch into few large syscalls, the mandatory Flush+error check, bufio.Scanner's 64KB token limit and Scanner.Buffer, io.Copy's ReaderFrom/WriterTo fast paths and io.CopyBuffer, and streaming vs loading whole files. Fires on "buffer this I/O", "too many syscalls", "bufio", "scanner token too long", "copy a file efficiently", "slow file writing". Routes sendfile/splice to go-perf-zerocopy-and-syscalls, bytes to go-perf-strings-bytes-zerocopy.
    0
    installs
  66. Go Perf Code Review · ctoth bundle
    Guides reviewing Go for performance — flagging premature pessimization (free wins: prealloc a sized slice, strings.Builder over += in a loop, bounded fan-out) while NOT demanding premature optimization on cold paths (unmeasured pools, unsafe for unproven speed), routing each flag to its deep skill, and wording feedback as a request for evidence not a change. Fires on "review this for performance", "should I flag this in review", "is this premature optimization". Routes the policy root to go-idiomatic-discipline, should-I to go-perf-methodology.
    0
    installs
  67. Go Perf Methodology · ctoth bundle
    Guides Go performance work as a measure-first discipline AT DEPTH — the deep peer of go-performance. Owns the tool-selection matrix (which question a benchmark answers vs a CPU profile vs a heap profile's inuse/alloc vs the execution tracer vs block/mutex profiles vs GODEBUG=gctrace), Brendan Gregg's USE method mapped to Go resources, statistical rigor (why one run lies, benchstat ≥10 runs / p-value / geomean), micro-vs-macro benchmark design, the order of operations and Amdahl's law. Auto-invokes when planning a Go optimization, choosing a diagnostic, setting a perf budget, or judging whether a change is worth it, and on "is this worth optimizing", "which profiler should I use", "how do I know my optimization worked", "why does my benchmark say X but prod says Y". Routes the high-level loop to go-performance, benchmark mechanics to go-testing-advanced, benchstat details to go-perf-benchmarking-statistics.
    0
    installs
  68. Go Zero Values And Construction · ctoth bundle
    Guides how a Go value comes into existence honestly — design types whose zero value is already useful (a zero sync.Mutex, bytes.Buffer, or nil slice just works) so you don't write a New that only zeroes fields; use keyed composite literals over positional ones; pick new vs &T{} vs make correctly; reach for functional options only when a type has many optional params; never stash mutable state in package globals; and model enums as typed iota constants that start at one (or reserve zero as an explicit Unknown) with a String() method. Auto-invokes when writing or editing struct construction, New constructors, composite literals, functional options, iota enums/typed constants, Stringer, or on "do I need a constructor", "how should this enum work", or "is this zero value safe". The zero value is part of your API; the compiler does not check enum exhaustiveness.
    0
    installs
  69. Go Perf Tail Latency · ctoth bundle
    Guides tail-latency for Go services — optimizing p99/p999 not the mean; coordinated omission (Gil Tene) and open-loop/constant-rate fix (wrk2, Vegeta); the Go tail levers in order — lower allocation rate → fewer GCs → less mark-assist tax, GC headroom, scheduler latency, contention, large GC-scan allocs; histograms + flight recorder. Fires on "reduce p99", "tail latency spikes", "GC pause latency", "my latency is bimodal", "measure latency correctly". Routes GC knobs to go-perf-gc-tuning, tracer to go-perf-execution-tracer.
    0
    installs
  70. Go Perf Encoding JSON · ctoth bundle
    Guides fast JSON in Go — encoding/json's reflection and per-call allocation cost, reusing a pooled Encoder/Decoder over per-call Marshal, decoding into typed structs not map[string]any, json.RawMessage to skip subtrees, streaming with Decoder.Token, the json/v2 + jsontext Go 1.25 GOEXPERIMENT=jsonv2 experiment, and codegen libraries (easyjson, jsoniter). Fires on "json is slow", "speed up json marshaling", "reduce json allocations", "stream large json", "json/v2". Routes correctness to go-json, pooling to go-perf-sync-pool.
    0
    installs
  71. Go Perf False Sharing · ctoth bundle
    Guides eliminating false sharing in Go — when goroutines on different cores mutate distinct variables sharing one 64-byte cache line, the coherence protocol ping-pongs the line and serializes them with no lock. Owns the symptom (a sharded counter that scales worse as cores grow), the fix (pad hot per-core fields with cpu.CacheLinePad), and measuring. Fires on "false sharing", "sharded counter doesn't scale", "per-core array slow". Routes packing to go-perf-struct-layout, sharding to go-perf-contention-and-sharding.
    0
    installs
  72. Go Perf Struct Layout · ctoth bundle
    Guides Go struct layout for performance — field alignment and padding, how field ORDER changes its size, ordering fields largest-to-smallest to shrink it (measured unsafe.Sizeof deltas), the fieldalignment analyzer and -fix, unsafe.Sizeof/Alignof/Offsetof, and why pointer-free structs scan faster under GC. Fires on "shrink this struct", "struct padding", "fieldalignment", "why is this struct so big", "align struct fields". Routes GC-scan to go-perf-allocator-internals, false sharing to go-perf-false-sharing.
    0
    installs
  73. Go Perf Escape Analysis · ctoth bundle
    Guides reading Go escape analysis via go build -gcflags=-m to know what heap-allocates and how to keep it on the stack — interpreting moved to heap / escapes to heap / does not escape and the triggers that force the heap (returned pointers, interface/fmt boxing, escaping closures, escaping slices/maps, []byte(string), channel pointers), with the refactor for each. Fires on why is this allocating, does this escape, keep this on the stack, reduce heap allocations. Routes inlining to go-perf-inlining, allocator cost to go-perf-allocator-internals.
    0
    installs
  74. Go Perf Pprof Profiling · ctoth bundle
    Guides the full pprof workflow at depth — collecting CPU and heap profiles from benchmarks and net/http/pprof, go tool pprof top/list/peek/disasm/web (flat vs -cum), the heap inuse-vs-alloc split, -diff_base/-base differential profiling, slicing by request type with pprof.Labels/pprof.Do, and safe production net/http/pprof plus continuous profiling (Pyroscope/Parca). Auto-invokes on "profile this", "what's allocating", "read this pprof", "where's the CPU going", "set up production profiling". Routes contention (block/mutex/goroutine) profiles to go-perf-block-mutex-profiles and the execution tracer to go-perf-execution-tracer.
    0
    installs
  75. Go Perf Atomics Vs Locks · ctoth bundle
    Guides the atomics-vs-locks performance tradeoff in Go — typed sync/atomic ops (atomic.Int64/Pointer/Bool, 1.19) are a single CAS-style instruction, cheaper than a mutex uncontended but still cache-line-bouncing when contended; sync.Mutex's fast path is itself a CAS that only parks the goroutine when contended; RWMutex wins only for long read sections and is slower (scales worse) than a plain Mutex for short ones; the atomic.Pointer copy-on-write config swap; when lock-free isn't worth the correctness risk. Fires on "atomic vs mutex", "is RWMutex faster", "lock-free counter", "reduce locking overhead", "atomic.Pointer config". Routes copylock/atomic-API correctness to go-sync-primitives, memory ordering to go-race-and-memory-model, measuring to go-perf-block-mutex-profiles.
    0
    installs
  76. Go Perf Execution Tracer · ctoth bundle
    Owns the Go execution tracer AT DEPTH — runtime/trace (Start/Stop, WithRegion, NewTask, Log), collecting via go test -trace, the net/http/pprof /debug/pprof/trace?seconds=N endpoint, and reading go tool trace (the timeline, goroutine analysis, scheduler-latency / syscall / network / synchronization blocking profiles, GC events, minimum mutator utilization). Covers user regions/tasks/logs for app-level latency, the post-1.21 low-overhead (1–2%) tracer, and the Go 1.25 trace.FlightRecorder ring buffer for capturing the seconds BEFORE a spike. Auto-invokes on "why is this slow sometimes", "trace this", "poor parallelism", "scheduler latency", "goroutines blocked on a channel", "capture a trace before the spike", "what is the runtime doing". The tracer is for latency / parallelism / scheduling / GC, NOT hot-spot hunting — route CPU/heap hot spots to go-perf-pprof-profiling.
    0
    installs
  77. Go Perf Allocator Internals · ctoth bundle
    What a Go heap allocation costs — the ~70 size classes and rounding waste (unsafe.Sizeof vs real slot), the tiny allocator packing sub-16B pointer-free objects, the lock-free per-P mcache → mcentral → mheap hierarchy, and scannable vs noscan spans (pointer-free objects cut GC cost; "1 alloc/op" hides different costs). Fires on "still slow after removing allocs", "reduce GC pressure", "size class", "how does Go allocate". Routes to go-perf-escape-analysis, go-perf-sync-pool, go-perf-gc-tuning, go-perf-struct-layout.
    0
    installs
  78. Go Perf Compiler Intrinsics · ctoth bundle
    Guides Go compiler intrinsics and microarchitecture tuning — the math/bits functions (OnesCount/popcount, LeadingZeros, TrailingZeros, RotateLeft, Mul64) the compiler lowers to single CPU instructions like POPCNT, the GOAMD64 v1-v4 and GOARM64 levels, the Go 1.17+ register calling convention, atomic intrinsics, and interface devirtualization. Fires on "popcount in Go", "use hardware instructions", "GOAMD64 levels", "reduce call overhead". Routes SIMD to go-perf-simd, PGO devirtualization to go-perf-pgo.
    0
    installs
  79. Go Perf Godebug And Metrics · ctoth bundle
    Guides Go runtime observability — the GODEBUG trace knobs (gctrace, schedtrace/scheddetail, inittrace, allocfreetrace, madvdontneed) and reading a gctrace line, the low-overhead runtime/metrics package and its histogram metrics, preferred over runtime.ReadMemStats which stops the world, and exposing metrics via expvar/Prometheus. Fires on "GODEBUG", "gctrace", "read runtime metrics", "monitor GC in production", "ReadMemStats vs runtime/metrics". Routes GC to go-perf-gc-tuning, scheduler to go-perf-goroutines-scheduler.
    0
    installs
  80. Go Perf Block Mutex Profiles · ctoth bundle
    Guides Go contention diagnosis at depth — the block, mutex, and goroutine profiles, why block/mutex are OFF by default and read empty until runtime.SetBlockProfileRate (nanoseconds, 1=everything) / runtime.SetMutexProfileFraction (1/n sampled) are set, the overhead tradeoff, reading delay-vs-contention in pprof, and the goroutine profile for leak and pile-up detection. Auto-invokes on "why is this contended", "diagnose lock contention", "goroutine leak", "my mutex is slow", "profile blocking", "goroutines are piling up". Routes the fix to go-perf-contention-and-sharding / go-perf-atomics-vs-locks, sync correctness to go-sync-primitives, CPU/heap to go-perf-pprof-profiling.
    0
    installs
  81. Go Perf Data Oriented Layout · ctoth bundle
    Guides data-oriented memory layout in Go — Struct-of-Arrays vs Array-of-Structs and when SoA wins (scan one field over many records, fewer cache lines), why []T beats []*T (a pointer slice scatters objects and adds GC scan work; []T is contiguous and noscan), replacing pointer-chasing lists/trees with int32 indices. Fires on cache-friendly layout, struct of arrays, slice of pointers is slow, data-oriented design. Routes field packing to go-perf-struct-layout, GC-scan to go-perf-allocator-internals, SIMD to go-perf-simd.
    0
    installs
  82. Go Perf Goroutines Scheduler · ctoth bundle
    Guides goroutine and scheduler performance — stack cost (~2KB; cheap, but unbounded spawning isn't), the G-M-P model and work-stealing, GOMAXPROCS as the parallelism limit, container-aware GOMAXPROCS (Go 1.25; cgroup CPU limit, GODEBUG containermaxprocs/updatemaxprocs, SetDefaultGOMAXPROCS), schedtrace, syscall/M handoff. Fires on "how many goroutines is too many", "set GOMAXPROCS", "goroutines not parallel", "container CPU limit Go". Routes leaks to go-concurrency-goroutines, pool sizing to go-perf-worker-pools-throughput.
    0
    installs
  83. Go Perf Production Incidents · ctoth bundle
    Guides diagnosing a LIVE Go performance incident under on-call pressure — OOMKill / RSS climb, GC death-spiral / CPU pegged in GC, p99 latency cliff, goroutine leak / pile-up, CPU saturation — with the capture-evidence-before-restart discipline, safe prod pprof / flight-recorder / heap-profile runbooks, and GOMEMLIMIT triage. Auto-invokes on "my service is OOMing", "production latency spiked", "pod keeps getting OOMKilled", "diagnose this incident", "goroutines climbing in prod", "CPU pegged in GC". Routes GC knobs to go-perf-gc-tuning, tail latency to go-perf-tail-latency, the tracer/flight recorder to go-perf-execution-tracer.
    0
    installs
  84. Go Perf Budgets And Lifecycle · ctoth bundle
    Guides where Go performance work belongs in the dev lifecycle and how a team keeps perf from rotting — budgets at design, don't pessimize while building, profile in staging, gate regressions in CI, monitor in prod, re-baseline after Go upgrades. Turns "fast enough?" into executable allocs/op and p99 budgets. Auto-invokes on "set a performance budget", "when should I optimize", "stop perf regressions in CI", "performance SLO", "keep our service fast". Routes benchstat mechanics to go-perf-benchmarking-statistics, incidents to go-perf-production-incidents.
    0
    installs
  85. Go Perf Zerocopy And Syscalls · ctoth bundle
    Guides Go zero-copy I/O and syscall reduction: how io.Copy already lowers to sendfile/splice/copy_file_range on Linux via the ReaderFrom/WriterTo fast path on net.TCPConn and os.File, the concrete-type conditions that keep it (bufio wrapping defeats it), net.Buffers batching writes into one writev(2), and mmap caveats for read-mostly files. Fires on "zero copy in Go", "sendfile", "writev", "mmap a file", "reduce syscalls". Routes buffering to go-perf-buffered-io, unsafe conversion to go-perf-strings-bytes-zerocopy.
    0
    installs
  86. Go Perf Audience And Tradeoffs · ctoth bundle
    Guides framing a Go performance decision by audience — the same change is right for one and wrong for another: the library author who can't profile callers and must not pessimize the common case (offer AppendXxx/[]byte forms, no unsafe in the API), the app developer who can profile and optimizes the proven hot path, the SRE who needs the code diagnosable (pprof labels, metrics, GOMEMLIMIT), the next reader who pays for clever micro-opts; the clarity-vs-speed through-line. Fires on "should a library do this", "is this worth optimizing for my users", "make this diagnosable", "premature optimization vs pessimization", "who am I optimizing for". Routes the policy root to go-idiomatic-discipline, measure-first to go-perf-methodology.
    0
    installs
  87. Go Perf Strings Bytes Zerocopy · ctoth bundle
    Guides zero-copy string and []byte work in Go — strings.Builder (one Grow) vs += in a loop (quadratic), strconv.Append* vs allocating fmt.Sprintf, a pooled bytes.Buffer+Reset, []byte less than - greater than string conversion cost plus compiler no-copy cases (m[string(b)], comparison, range), and unsafe.String/unsafe.Slice (1.20) zero-copy with safety rules. Auto-invokes on "avoid string allocation", "[]byte to string without copy", "strconv vs fmt", "unsafe.String". Routes rune correctness to go-strings-bytes-runes, pooling to go-perf-sync-pool.
    0
    installs
  88. Go Perf Benchmarking Statistics · ctoth bundle
    Guides trustworthy Go benchmark measurement at the command level — running each side with -count≥10 into old.txt/new.txt and feeding both to benchstat, reading its ± confidence interval, p-value (Mann–Whitney U), geomean, and the "~" no-significant-difference result, choosing the right unit (b.SetBytes for MB/s, b.ReportMetric for custom throughput), grouping a matrix with -col/-row/-filter, building a reproducible environment (perflock's 90% governor + serialization, frequency scaling. Auto-invokes when comparing benchmark runs, running benchstat, writing a perf A/B, or stabilizing a bench machine, and on "is this benchmark result real", "compare these benchmarks", "did this actually get faster", "my benchmark is noisy", "set up a perf regression test". Routes benchmark loop mechanics (for b.Loop, the sink/DCE trap, ResetTimer, RunParallel) to go-testing-advanced and the why-one-run-lies concept to go-perf-methodology.
    0
    installs
  89. Go Perf Contention And Sharding · ctoth bundle
    Reduces Go lock contention by sharding state into N lock-striped shards keyed by hash; shard-count and padding guidance; sync.Map's two optimized use cases vs a sharded map[K]V+Mutex for the general case; per-P counters summed on read; batching to amortize a lock; singleflight to collapse duplicate work. Fires on "reduce lock contention", "shard this map", "sync.Map vs mutex map", "hot mutex", "lock striping". Routes sync.Map API to go-sync-primitives, padding to go-perf-false-sharing, measuring to go-perf-block-mutex-profiles.
    0
    installs
  90. Go Perf Worker Pools Throughput · ctoth bundle
    Guides throughput-oriented Go concurrency at depth — bounded fan-out vs an unbounded goroutine-per-item, pool sizing (CPU-bound near GOMAXPROCS, I/O-bound higher, tuned by measuring), errgroup.SetLimit and semaphore.Weighted for bounding, channel send/recv cost and batching to amortize it, and backpressure via bounded queues. Auto-invokes on "worker pool", "limit concurrency", "how many workers", "bounded parallelism", "errgroup limit". Routes channel correctness to go-channels-select, scheduler/GOMAXPROCS to go-perf-goroutines-scheduler.
    0
    installs
  91. Go Perf Bounds Check Elimination · ctoth bundle
    Guides bounds-check elimination (BCE) in Go — the compiler checks every slice/array index and the SSA pass removes the ones it proves redundant. Covers seeing surviving checks with go build -gcflags="-d=ssa/check_bce/debug=1", prover-friendly idioms (the _ = b[n-1] / b = b[:n] hint, range loops, constant vs variable offsets), the inlining link, and why -B is a footgun not a fix. Fires on "eliminate bounds checks", "why is this loop slow", "bounds check in hot loop", "optimize this numeric loop". Routes should-I to go-perf-methodology, slices to go-perf-slices.
    0
    installs