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
pythonGet 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)
P1 Hot path
pythonThroughput 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
P4 Regulated core
pythonCorrectness 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
P9 Security-critical boundary
pythonAssume 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
P5 Teaching example
pythonOptimised 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
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
pythonMake 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
P5 Teaching example
pythonOptimised 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
P3 Public library
pythonA 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
P7 High-concurrency service
pythonSafe 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
P9 Security-critical boundary
pythonFail-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
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.