Facet

One problem. Many right answers.

“Is this good code?” is the wrong question, and here is why, in code you can read. Below are two small problems, each solved several ways. Each solution is written for a different purpose, and Facet profiles each across the same 14 dimensions. Watch two things: no solution is best on every axis, and a dimension only scores when the problem gives it surface. Security separates the careful from the careless on both problems, but the pure aggregator (no database, shell, or auth to harden) gives it far less to prove than the auth boundary, whose full attack surface lets the careful solution show everything it does right, and dimensions a one-off script gives no surface at all read an honest N/A.

Each dimension is a diverging two-pole bar: ✓ capabilities present grow right, ✕ harmful patterns present grow left, never netted. N/A means no surface to measure, not a low score.

The problem: Total amount per account

Given a stream of transactions - each a (account_id, amount, timestamp) - return the total amount for each account_id. A pure arithmetic problem: it has no database, shell, or authorisation surface, so the security-hardened version tops out at D6 4/5 (it cannot harden attack classes that do not exist here) while the careless versions sit at 1/5. Security still separates the careful from the careless - but watch the genuine N/A on dimensions a one-off script gives no surface at all, like concurrency and API ergonomics. A dimension only scores when the problem gives its indicators something to bite on.

P2 Quick script

python

Get a one-off job done fast: five lines, no ceremony, no guards.

import csv, sys

t = {}
for r in csv.reader(open(sys.argv[1])):
    t[r[0]] = t.get(r[0], 0) + float(r[1])
print(t)

Written for P2 Quick script.

Facet’s closest auto-match: P2 QUICK SCRIPT · runner-up P5 TEACHING EXAMPLE heuristic

2 N/A (no surface)

D1 Runtime performance✕ 0%✓ 58%
D2 Memory efficiency✕ 0%✓ 18%
D3 Readability and comprehensibility✓ 67%
D4 Maintainability and extensibility✓ 67%
D5 Robustness and defensive correctness✓ 7%
D6 Security✕ 0%✓ 25%
D7 Portability and dependency minimalism✕ 0%✓ 83%
D8 Development speed and prototype economy✕ 0%✓ 100%
D9 Testability✕ 0%✓ 29%
D10 Observability and debuggability✕ 0%✓ 0%
D11 Auditability and compliance✕ 25%✓ 80%
D12 Concurrency safety and scalabilityno surface · N/A
D13 API ergonomics and interface stabilityno surface · N/A

P1 Hot path

python

Throughput first: single pass, integer cents, no per-row allocation or validation.

"""Single-pass aggregation in integer cents, built for throughput on a hot path.

No per-row objects, no Decimal, no validation overhead: split, parse to int cents, accumulate.
Money stays exact because it never touches float.
"""
from collections import defaultdict


def total_cents_per_account(rows):
    totals = defaultdict(int)
    for acct, amount, _ts in rows:
        neg = amount[:1] == "-"
        whole, _, frac = (amount[1:] if neg else amount).partition(".")
        cents = int(whole) * 100 + int((frac + "00")[:2])
        totals[acct] += -cents if neg else cents
    return totals

Written for P1 Hot path.

Facet’s closest auto-match: P5 TEACHING EXAMPLE · runner-up P1 HOT PATH heuristic

D1 Runtime performance✕ 0%✓ 89%
D2 Memory efficiency✕ 0%✓ 55%
D3 Readability and comprehensibility✓ 79%
D4 Maintainability and extensibility✓ 55%
D5 Robustness and defensive correctness✓ 9%
D6 Security✕ 0%✓ 33%
D8 Development speed and prototype economy✕ 0%✓ 83%
D9 Testability✕ 0%✓ 67%
D10 Observability and debuggability✕ 0%✓ 0%
D11 Auditability and compliance✕ 0%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 75%
D13 API ergonomics and interface stability✓ 20%
D14 Resource cost and energy efficiency✕ 0%✓ 33%

P4 Regulated core

python

Correctness and traceability: exact decimals, validation, audit logging, a reconciliation invariant.

"""Decimal-exact ledger aggregation with schema validation, audit logging, and a reconciliation
invariant. Built for a regulated core where correctness and traceability outrank speed."""
from __future__ import annotations

import logging
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import Iterable

logger = logging.getLogger("ledger.aggregate")


@dataclass(frozen=True)
class Transaction:
    account_id: str
    amount: Decimal
    timestamp: str


class TransactionError(ValueError):
    """A row failed validation; carries enough context for the audit trail."""


def parse_row(row: list[str]) -> Transaction:
    if len(row) != 3:
        raise TransactionError(f"expected 3 fields, got {len(row)}")
    account_id, raw_amount, timestamp = (field.strip() for field in row)
    if not account_id:
        raise TransactionError("missing account id")
    try:
        amount = Decimal(raw_amount)
    except InvalidOperation as exc:
        raise TransactionError(f"invalid amount {raw_amount!r}") from exc
    return Transaction(account_id, amount, timestamp)


def totals_per_account(rows: Iterable[list[str]]) -> dict[str, Decimal]:
    """Sum amounts per account using exact decimal arithmetic. Invalid rows are rejected and
    logged, never silently dropped, and the result is reconciled against a running grand total."""
    totals: dict[str, Decimal] = {}
    grand = Decimal("0")
    rejected = 0
    for row in rows:
        try:
            tx = parse_row(row)
        except TransactionError:
            rejected += 1
            logger.warning("rejected transaction row", exc_info=True)
            continue
        totals[tx.account_id] = totals.get(tx.account_id, Decimal("0")) + tx.amount
        grand += tx.amount
    if sum(totals.values(), Decimal("0")) != grand:
        raise AssertionError("reconciliation failed: per-account totals do not sum to grand total")
    logger.info("aggregated %d accounts (%d rows rejected)", len(totals), rejected)
    return totals

Written for P4 Regulated core.

Facet’s closest auto-match: P5 TEACHING EXAMPLE · runner-up P4 REGULATED CORE heuristic

D1 Runtime performance✕ 0%✓ 50%
D2 Memory efficiency✕ 0%✓ 44%
D3 Readability and comprehensibility✓ 75%
D4 Maintainability and extensibility✓ 55%
D5 Robustness and defensive correctness✓ 67%
D6 Security✕ 0%✓ 100%
D8 Development speed and prototype economy✕ 0%✓ 86%
D9 Testability✕ 0%✓ 29%
D10 Observability and debuggability✕ 0%✓ 36%
D11 Auditability and compliance✕ 0%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 75%
D13 API ergonomics and interface stability✓ 30%

P9 Security-critical boundary

python

Assume hostile input: bounded resources, strict allow-list parsing, reject the malformed.

"""Aggregation that treats its input as hostile: every resource is bounded and every field is
strictly validated before use. Built for a security-critical boundary facing untrusted data."""
from decimal import Decimal, InvalidOperation

MAX_ROWS = 1_000_000        # refuse unbounded input (DoS bound)
MAX_FIELD_LEN = 64          # bound per-field length (memory + log-injection guard)
MAX_ACCOUNTS = 100_000      # bound distinct-account cardinality


def aggregate(rows):
    totals: dict[str, Decimal] = {}
    for i, row in enumerate(rows):
        if i >= MAX_ROWS:
            raise ValueError("row limit exceeded")
        if len(row) != 3:
            raise ValueError("malformed row: wrong field count")
        account_id, raw_amount, _timestamp = row
        if len(account_id) > MAX_FIELD_LEN or len(raw_amount) > MAX_FIELD_LEN:
            raise ValueError("field exceeds maximum length")
        if not account_id.isalnum():            # strict allow-list, never a blocklist
            raise ValueError("account id is not alphanumeric")
        try:
            amount = Decimal(raw_amount)
        except InvalidOperation:
            raise ValueError("amount is not a valid decimal")
        if not amount.is_finite():
            raise ValueError("amount is not finite")
        if account_id not in totals and len(totals) >= MAX_ACCOUNTS:
            raise ValueError("account cardinality limit exceeded")
        totals[account_id] = totals.get(account_id, Decimal("0")) + amount
    return totals

Written for P9 Security-critical boundary.

Facet’s closest auto-match: P2 QUICK SCRIPT · runner-up P5 TEACHING EXAMPLE heuristic

D1 Runtime performance✕ 50%✓ 50%
D2 Memory efficiency✕ 0%✓ 73%
D3 Readability and comprehensibility✓ 79%
D4 Maintainability and extensibility✓ 55%
D5 Robustness and defensive correctness✓ 47%
D6 Security✕ 0%✓ 100%
D8 Development speed and prototype economy✕ 0%✓ 100%
D9 Testability✕ 0%✓ 67%
D10 Observability and debuggability✕ 0%✓ 0%
D11 Auditability and compliance✕ 0%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 100%
D13 API ergonomics and interface stability✓ 18%

P5 Teaching example

python

Optimised for a learner: documented, simple structures, explained step by step.

"""
Summing transactions, explained.

Goal: given a list of transactions, find the total amount for each account.
A transaction is a pair (account_id, amount). We keep a running total for each
account in a dictionary, adding each amount to the matching account as we go.
"""
from collections import defaultdict


def total_per_account(transactions):
    """Return the total amount for each account.

    Args:
        transactions: an iterable of (account_id, amount) pairs, for example
            [("alice", 10.0), ("bob", 12.5), ("alice", 20.0)]

    Returns:
        A dictionary mapping each account id to the sum of its amounts, for example
            {"alice": 30.0, "bob": 12.5}
    """
    totals = defaultdict(float)
    for account_id, amount in transactions:
        # defaultdict(float) starts each new account at 0.0, so we can just add.
        totals[account_id] += amount
    return dict(totals)

Written for P5 Teaching example.

Facet’s closest auto-match: P5 TEACHING EXAMPLE · runner-up P3 PUBLIC LIBRARY heuristic

D1 Runtime performance✕ 0%✓ 90%
D2 Memory efficiency✕ 0%✓ 64%
D3 Readability and comprehensibility✓ 77%
D4 Maintainability and extensibility✓ 60%
D5 Robustness and defensive correctness✓ 8%
D6 Security✕ 0%✓ 33%
D8 Development speed and prototype economy✕ 0%✓ 83%
D9 Testability✕ 0%✓ 67%
D10 Observability and debuggability✕ 0%✓ 0%
D11 Auditability and compliance✕ 0%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 75%
D13 API ergonomics and interface stability✓ 44%

The problem: Authenticated record lookup

Given an API key and a user id, verify the key and return that user's record. The same boundary written five ways. Now Security has real surface - secret handling, constant-time comparison, path-traversal, default-deny, input validation - so it separates cleanly: the careless version is genuinely exposed, the hardened one genuinely is not.

P2 Quick script

python

Make it work: a hardcoded key and a direct, unchecked file read.

import json, sys

KEY = "s3cr3t"

def lookup(api_key, user_id):
    if api_key == KEY:
        return json.load(open(f"data/{user_id}.json"))
    return None

print(lookup(sys.argv[1], sys.argv[2]))

Written for P2 Quick script.

Facet’s closest auto-match: P2 QUICK SCRIPT · runner-up P8 RESEARCH PROTOTYPE heuristic

D1 Runtime performance✕ 0%✓ 18%
D2 Memory efficiency✕ 0%✓ 50%
D5 Robustness and defensive correctness✓ 0%
D6 Security✕ 0%✓ 25%
D8 Development speed and prototype economy✕ 0%✓ 100%
D10 Observability and debuggability✕ 100%✓ 0%
D11 Auditability and compliance✕ 25%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 100%
D13 API ergonomics and interface stability✓ 18%

P5 Teaching example

python

Optimised for a learner: documented and explained step by step.

"""
Verify an API key and return a user's record - explained step by step.

We compare the caller's key to the key we expect. If it matches, we read that
user's record from a JSON file and return it; otherwise we return None.
"""
import json

EXPECTED_KEY = "example-key"  # in a real system this comes from a secret store, not the source


def lookup_user(api_key, user_id):
    """Return the user's record if the api_key is valid, otherwise None.

    Args:
        api_key: the caller-supplied key to check.
        user_id: which user's record to load.
    """
    # Step 1: check the key matches the one we expect.
    if api_key != EXPECTED_KEY:
        return None
    # Step 2: load and return that user's record.
    with open(f"data/{user_id}.json") as f:
        return json.load(f)

Written for P5 Teaching example.

Facet’s closest auto-match: P1 HOT PATH · runner-up P3 PUBLIC LIBRARY heuristic

D1 Runtime performance✕ 0%✓ 64%
D2 Memory efficiency✕ 0%✓ 38%
D4 Maintainability and extensibility✓ 69%
D5 Robustness and defensive correctness✓ 33%
D6 Security✕ 0%✓ 25%
D7 Portability and dependency minimalism✕ 0%✓ 57%
D8 Development speed and prototype economy✕ 0%✓ 86%
D9 Testability✕ 100%✓ 33%
D10 Observability and debuggability✕ 100%✓ 0%
D11 Auditability and compliance✕ 25%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 80%
D13 API ergonomics and interface stability✓ 33%

P3 Public library

python

A reusable, misuse-resistant interface: injected secret, constant-time compare.

"""Reusable API-key authenticator with a documented, misuse-resistant interface."""
from __future__ import annotations

import hmac
from typing import Callable, Mapping


class Authenticator:
    """Verify API keys and fetch records from an injected store.

    Example:
        >>> auth = Authenticator(secret_provider=lambda: os.environ["API_KEY"],
        ...                      records={"alice": {"plan": "pro"}})
        >>> auth.lookup(api_key=incoming, user_id="alice")
        {"plan": "pro"}

    The secret is supplied by a provider callable (there is deliberately no default), so the key is
    never baked into the call site, and comparison is constant-time.
    """

    def __init__(self, secret_provider: Callable[[], str], records: Mapping[str, dict]) -> None:
        self._secret_provider = secret_provider
        self._records = records

    def lookup(self, *, api_key: str, user_id: str) -> dict | None:
        """Return the record for `user_id` if `api_key` is valid, else None."""
        expected = self._secret_provider()
        if not hmac.compare_digest(api_key, expected):
            return None
        return self._records.get(user_id)

Written for P3 Public library.

Facet’s closest auto-match: P1 HOT PATH · runner-up P4 REGULATED CORE heuristic

D1 Runtime performance✕ 0%✓ 90%
D2 Memory efficiency✕ 0%✓ 75%
D5 Robustness and defensive correctness✓ 50%
D6 Security✕ 0%✓ 67%
D8 Development speed and prototype economy✕ 0%✓ 57%
D10 Observability and debuggability✕ 100%✓ 0%
D11 Auditability and compliance✕ 0%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 100%
D13 API ergonomics and interface stability✓ 70%

P7 High-concurrency service

python

Safe under parallel load: lock-guarded rate limit, never logs the key.

"""Concurrent request handler: authenticate, rate-limit, and serve, safe under parallel load."""
import hmac
import logging
import os
import threading

logger = logging.getLogger("auth.service")

_LOCK = threading.Lock()
_counts: dict[str, int] = {}
RATE_LIMIT = 100


def handle(api_key: str, user_id: str, client_id: str, records: dict) -> dict | None:
    # Rate-limit per client with no check-then-act race: increment under the lock, then test the result.
    with _LOCK:
        seen = _counts.get(client_id, 0) + 1
        _counts[client_id] = seen
    if seen > RATE_LIMIT:
        logger.warning("rate limit exceeded", extra={"client_id": client_id})
        return None
    if not hmac.compare_digest(api_key, os.environ.get("API_KEY", "")):
        logger.warning("auth failed", extra={"client_id": client_id})  # never log the key itself
        return None
    return records.get(user_id)  # stateless handler over a shared, read-only record store

Written for P7 High-concurrency service.

Facet’s closest auto-match: P5 TEACHING EXAMPLE · runner-up P3 PUBLIC LIBRARY heuristic

D1 Runtime performance✕ 0%✓ 70%
D2 Memory efficiency✕ 0%✓ 33%
D3 Readability and comprehensibility✓ 100%
D4 Maintainability and extensibility✓ 91%
D5 Robustness and defensive correctness✓ 60%
D6 Security✕ 0%✓ 78%
D7 Portability and dependency minimalism✕ 0%✓ 100%
D8 Development speed and prototype economy✕ 0%✓ 86%
D9 Testability✕ 100%✓ 14%
D10 Observability and debuggability✕ 0%✓ 70%
D11 Auditability and compliance✕ 25%✓ 60%
D12 Concurrency safety and scalability✕ 0%✓ 75%
D13 API ergonomics and interface stability✓ 40%
D14 Resource cost and energy efficiency✕ 0%✓ 33%

P9 Security-critical boundary

python

Fail-closed, constant-time, bounded, path-traversal guarded, audited.

"""Security-critical authenticated lookup: fail-closed, constant-time, bounded, audited.

Dependencies are pinned in requirements.txt (integrity-checked); this module imports stdlib only.
"""
from __future__ import annotations

import hmac
import json
import logging
import os
import re
from pathlib import Path

logger = logging.getLogger("auth.secure")

_USER_ID = re.compile(r"^[a-z0-9_]{1,32}$")            # strict allow-list + length bound
_DATA_ROOT = Path(os.environ["DATA_ROOT"]).resolve()   # no hardcoded paths


class AuthError(Exception):
    """Generic auth failure. Carries no detail to the caller, so errors never leak internals."""


def _expected_key() -> str:
    key = os.environ.get("API_KEY")                    # secret from the environment, never from source
    if not key:
        raise RuntimeError("API_KEY not configured")   # fail closed (server-side only)
    return key


def lookup(api_key: str, user_id: str) -> dict:
    # Default-deny: every path raises AuthError unless explicitly authorised.
    if not hmac.compare_digest(api_key, _expected_key()):   # constant-time comparison
        logger.warning("auth failure")                      # security event, no key or payload logged
        raise AuthError()
    if not _USER_ID.match(user_id):                         # validate before use
        logger.warning("rejected user_id format")
        raise AuthError()
    target = (_DATA_ROOT / f"{user_id}.json").resolve()
    if _DATA_ROOT not in target.parents:                    # path traversal guarded: stay within root
        logger.warning("path traversal blocked")
        raise AuthError()
    try:
        with target.open(encoding="utf-8") as fh:
            return json.load(fh)
    except FileNotFoundError:
        raise AuthError() from None                         # no enumeration: same generic failure

Written for P9 Security-critical boundary.

Facet’s closest auto-match: P4 REGULATED CORE · runner-up P9 SECURITY-CRITICAL BOUNDARY heuristic

D1 Runtime performance✕ 0%✓ 88%
D2 Memory efficiency✕ 0%✓ 33%
D5 Robustness and defensive correctness✓ 79%
D6 Security✕ 0%✓ 100%
D8 Development speed and prototype economy✕ 25%✓ 71%
D10 Observability and debuggability✕ 0%✓ 36%
D11 Auditability and compliance✕ 0%✓ 80%
D12 Concurrency safety and scalability✕ 0%✓ 100%
D13 API ergonomics and interface stability✓ 64%

So which one is “best”?

None of them, and all of them. The throwaway is passing as a throwaway; the hardened boundary would be over-engineered as one. Judge any of these against the wrong profile and it looks broken. And notice the honesty of the N/A: where a dimension has no surface at all (a one-off script has no concurrency to get wrong and no public API to stabilise), Facet declines to score it rather than inventing a low number. The auto-matched profile is a heuristic shown for orientation: what each solution is written for is what the fingerprint is read against. That is the whole idea: code quality is a profile, not a score.

Profile your own codeHow the dimensions work