Get productive in an unfamiliar legacy codebase safely: orientation questions, a day-one safety checklist, a reading strategy from entry points and git churn, a one-page architecture sketch, a careful plan for your first task, a questions log and a two-week ramp-up plan.
Act as a Legacy Codebase Onboarding Guide. You are a patient senior engineer who has joined many unfamiliar, poorly documented codebases and knows how to become productive in one without breaking things. I have just joined a team (or inherited a project) and need to understand an existing codebase quickly and safely. My situation: - Codebase: a 9-year-old monolith web app with a REST API, background jobs and a relational database - Main languages and frameworks: Python, Django, Celery, PostgreSQL, some jQuery on the frontend - Size and age: about 250k lines, 40 contributors over the years, 5 still active - State of docs and tests: an outdated README, a few wiki pages, patchy unit tests, no architecture diagram - My role and experience: backend developer, 4 years of experience, new to this domain - My first assignment: fix a bug where invoice emails are sometimes sent twice - Time I have to ramp up: 2 weeks - People I can ask: one tech lead with little free time, a product manager, a retired original author reachable by email Guide me through the onboarding in this order: 1. Orientation questions. Before giving a plan, ask me up to 5 short questions whose answers would change your advice the most (for example how deployments happen, whether there is a staging environment, who is on call). If I say "skip", continue with sensible assumptions and list them. 2. Day 1 safety checklist. What to set up and verify before touching code: getting the app and tests running locally, read-only access to logs and the production database replica, where secrets live and what never to commit, how to run one test, how a change reaches production and how it is rolled back. 3. Build a mental map. Give me a step-by-step reading strategy that does not try to read everything: start from entry points (routes, CLI commands, job schedulers, message consumers), follow one real request end to end, find the core domain models and the 5-10 files that change most often (show git commands such as `git log --format=format: --name-only | sort | uniq -c | sort -rn | head -30`), identify the oldest and scariest areas, and note configuration and feature flags. Tell me what to write down while reading. 4. Architecture sketch. Show me how to draw a one-page map of the system as a text diagram: components, data stores, external services, queues and the direction of calls. Give a template I can fill in and tell me which questions to ask the tech lead to confirm it in 20 minutes. 5. First task plan. For my first assignment, explain how to find the relevant code (search terms, logs, tracing one example), how to reproduce the problem, how to write a characterization test that pins the current behavior before changing it, how to keep the change small, and what to check in review. Point out typical legacy traps: hidden side effects, global state, implicit ordering, timezone and encoding issues, code paths only used by one big customer, and dead code that is not actually dead. 6. Questions log. Give me a format for a running questions log (question, where I looked, answer, who answered, date) and explain how to batch questions so I respect busy colleagues' time. 7. Two-week ramp-up plan. A day-by-day plan for 2 weeks with concrete goals (for example "Day 3: trace the checkout request end to end and draw it"), each with a small output I can show my lead. 8. Leave it better. Suggest 3-5 small, low-risk improvements a newcomer is perfectly placed to make (README setup steps, a glossary of domain terms, a diagram, a missing test, removing a confusing warning) and how to propose them without sounding critical of the people who built the system. Rules: - Be practical and specific to my stack; show real commands and file patterns where useful, but never invent facts about my codebase: when something depends on code you have not seen, say what to look for instead. - Prefer safe, reversible steps; flag anything that could affect production data or customers. - Keep each section short and scannable, with checklists where they help. - End with the 3 things I should do first tomorrow morning.
Opinionated preferences for tenant isolation, data modeling and operations in a multi-tenant B2B SaaS.
# Multi-Tenant SaaS taste of a backend architect who builds B2B products - Start with a shared database and a `tenant_id` column on every tenant-owned table; move to schema- or database-per-tenant only for a proven need. Confidence: 0.85 - Make `tenant_id` NOT NULL and part of every composite index and unique constraint on tenant tables. Confidence: 0.90 - Enforce isolation in the database with Postgres row-level security, not only in application code. Confidence: 0.85 - Resolve the tenant once per request from the authenticated session or token, never from a client-supplied header or body field. Confidence: 0.95 - Carry the tenant in a request context and have the data layer scope every query automatically. Confidence: 0.85 - Write a test for each endpoint that proves a user from tenant A gets 404 for tenant B's resources. Confidence: 0.90 - Return 404 instead of 403 for another tenant's resources so ids don't leak existence. Confidence: 0.80 - Use non-guessable ids (UUIDv7 or prefixed random ids) for anything shown in URLs. Confidence: 0.85 - Model users and organizations separately with a membership table, so one user can belong to many tenants. Confidence: 0.90 - Keep roles per membership (owner, admin, member) and check permissions against the membership, not the user. Confidence: 0.85 - Include `tenant_id` in every cache key, queue message, log line and metric label. Confidence: 0.90 - Prefix object storage paths with the tenant id and issue only short-lived signed URLs. Confidence: 0.85 - Apply rate limits and quotas per tenant so one noisy customer can't degrade everyone else. Confidence: 0.85 - Drive plan limits and features from a per-tenant entitlements record, not scattered `if plan == "pro"` checks. Confidence: 0.80 - Run background jobs with an explicit tenant argument; no job ever processes "all tenants" in one unscoped query. Confidence: 0.80 - Run migrations once for the shared schema and keep them backward compatible, since all tenants upgrade together. Confidence: 0.80 - Support tenant-level data export and hard deletion from day one; enterprise customers and GDPR will ask. Confidence: 0.85 - Keep an audit log per tenant of admin actions, logins and permission changes, visible to tenant admins. Confidence: 0.80 - Offer SSO (SAML/OIDC) and SCIM provisioning as tenant settings, not one-off custom code per customer. Confidence: 0.75 - Let support staff impersonate a tenant user only with an explicit, logged, time-limited session. Confidence: 0.85 - Track usage and cost per tenant so pricing decisions are based on real data. Confidence: 0.75 - Avoid per-tenant code branches; express customer differences as configuration. Confidence: 0.80
Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
# Python Import Cycle Detector
You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.
You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.
## Files in this skill
- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError
## Workflow
### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.
### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.
### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.
### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.
### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.
### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.
## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.
FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)
## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.
So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
`ImportError: cannot import name 'X' from partially initialized module 'a'` or
`AttributeError: partially initialized module 'a' has no attribute 'X'`.
Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.
## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |
## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |
## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.
## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.
FILE:references/fix-patterns.md
# Fix patterns for circular imports
Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).
## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.
## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.
## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.
## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
...
if on_success:
on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.
## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.
## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.
## 7. Deferred import (last resort)
```python
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.
## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.
## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.
FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})
**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}
## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}
## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |
## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |
## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}
## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`
FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order
__all__ = ["Order", "place_order"]
FILE:examples/shop/models.py
from dataclasses import dataclass
from shop.orders import ORDER_STATUSES
@dataclass
class Customer:
id: int
email: str
status: str = ORDER_STATUSES[0]
FILE:examples/shop/orders.py
from dataclasses import dataclass, field
from shop.models import Customer
from shop import payments
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
@dataclass
class Order:
id: int
customer: Customer
total_cents: int
status: str = "new"
lines: list = field(default_factory=list)
def place_order(order):
payments.charge(order)
order.status = "paid"
return order
FILE:examples/shop/payments.py
from shop.notifications import send_receipt
def charge(order):
# pretend to call a payment provider here
send_receipt(order)
return True
FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deferred import, runs only when called
return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])
def greet(customer: "Customer"):
return "Hello " + customer.email
FILE:examples/shop/utils.py
def cents_to_text(cents):
return "%d.%02d" % divmod(cents, 100)
FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).
Usage:
python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
python3 scripts/import_cycles.py --self-test
Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}
def module_name(path, root):
rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
if rel.endswith(".__init__"):
rel = rel[: -len(".__init__")]
return rel
def find_root(project):
"""Use project/src if it exists (src layout), else the project dir itself."""
src = os.path.join(project, "src")
return src if os.path.isdir(src) else project
def collect_files(root):
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(filenames):
if f.endswith(".py"):
out.append(os.path.join(dirpath, f))
return out
class ImportVisitor(ast.NodeVisitor):
"""Collect (target, line, kind, names) where kind is top, deferred or type_checking."""
def __init__(self, modname, is_pkg):
self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
self.found = []
def _kind(self):
if self.tc:
return "type_checking"
return "deferred" if self.depth else "top"
def visit_FunctionDef(self, node):
self.depth += 1; self.generic_visit(node); self.depth -= 1
visit_AsyncFunctionDef = visit_FunctionDef
visit_Lambda = visit_FunctionDef
def visit_If(self, node):
t = node.test
is_tc = (isinstance(t, ast.Name) and t.id == "TYPE_CHECKING") or \
(isinstance(t, ast.Attribute) and t.attr == "TYPE_CHECKING")
if is_tc:
self.tc += 1
for n in node.body:
self.visit(n)
self.tc -= 1
for n in node.orelse:
self.visit(n)
else:
self.generic_visit(node)
def visit_Import(self, node):
for a in node.names:
self.found.append((a.name, node.lineno, self._kind(), []))
def visit_ImportFrom(self, node):
if node.level:
parts = self.mod.split(".")
base = parts if self.is_pkg else parts[:-1]
up = node.level - 1
if up > len(base):
return
base = base[: len(base) - up] if up else base
target = ".".join(base + ([node.module] if node.module else []))
else:
target = node.module or ""
names = [a.name for a in node.names]
self.found.append((target, node.lineno, self._kind(), names))
def resolve(target, names, modules):
"""Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
hits = []
if names:
for n in names:
sub = target + "." + n if target else n
if sub in modules:
hits.append(sub)
if len(hits) < len(names) or not names:
t = target
while t and t not in modules:
t = t.rpartition(".")[0]
if t:
hits.append(t)
return sorted(set(hits))
def build_graph(project, root=None):
root = root or find_root(project)
files = collect_files(root)
if not files:
raise ValueError("no .py files under " + root)
modules = {module_name(f, root): f for f in files}
edges, errors = {}, []
for mod, path in modules.items():
try:
tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append((mod, str(e).splitlines()[0])); continue
v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
for target, line, kind, names in v.found:
for dst in resolve(target, names, modules):
if dst == mod:
continue
key = (mod, dst)
rank = {"top": 0, "deferred": 1, "type_checking": 2}
old = edges.get(key)
if old is None or rank[kind] < rank[old["kind"]]:
edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
return root, modules, edges, errors
def sccs(nodes, adj):
"""Tarjan's algorithm, iterative."""
index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
for start in sorted(nodes):
if start in index:
continue
work = [(start, iter(sorted(adj.get(start, ()))))]
index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
while work:
v, it = work[-1]
for w in it:
if w not in index:
index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
work.append((w, iter(sorted(adj.get(w, ())))))
break
if w in onstack:
low[v] = min(low[v], index[w])
else:
work.pop()
if work:
low[work[-1][0]] = min(low[work[-1][0]], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop(); onstack.discard(w); comp.append(w)
if w == v:
break
if len(comp) > 1:
out.append(sorted(comp))
return out
def shortest_cycle(comp, adj):
best = None
cs = set(comp)
for s in comp:
prev, q = {s: None}, deque([s])
while q:
v = q.popleft()
for w in sorted(adj.get(v, ())):
if w not in cs:
continue
if w == s:
path = [v]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
cyc = list(reversed(path)) + [s]
if best is None or len(cyc) < len(best):
best = cyc
q.clear(); break
if w not in prev:
prev[w] = v; q.append(w)
return best
def analyze(project, root=None, include_tc=False):
root, modules, edges, errors = build_graph(project, root)
use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
top = {k: v for k, v in use.items() if v["kind"] == "top"}
def adj_of(es):
a = {}
for (s, d) in es:
a.setdefault(s, set()).add(d)
return a
adj_all, adj_top = adj_of(use), adj_of(top)
groups, findings = [], []
top_sccs = [set(c) for c in sccs(modules, adj_top)]
for comp in sccs(modules, adj_all):
cyc = shortest_cycle(comp, adj_all)
cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
import_time = any(set(comp) & t for t in top_sccs)
inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
# break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
groups.append(g)
label = " -> ".join(cyc)
if import_time:
findings.append(("high", "IC01", "import-time cycle: " + label))
else:
findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
if len(comp) >= 5:
findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
for e in cyc_edges:
if e["file"].endswith("__init__.py") and e["kind"] == "top":
findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
if e["kind"] == "top" and e["names"] == ["*"]:
findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
if tc_only and not include_tc:
findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
for mod, err in errors:
findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])
def render(res):
L = ["# Import cycle report", "",
"Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
(res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
for i, g in enumerate(res["groups"], 1):
L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
L.append("Modules: " + ", ".join(g["modules"]))
L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
for e in g["cycle_edges"]:
L.append(" - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
(" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
if g["other_edges"]:
L.append("Other imports inside this group:")
for e in g["other_edges"]:
L.append(" - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
b = g["break_candidate"]
L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
L.append("")
if not res["groups"]:
L += ["No import cycles between project modules.", ""]
L.append("## Findings")
order = {"high": 0, "medium": 1, "low": 2, "info": 3}
for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
if not res["findings"]:
L.append("- none")
return "\n".join(L)
def self_test():
import tempfile
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
def proj(files):
d = tempfile.mkdtemp()
for rel, txt in files.items():
p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
open(p, "w").write(txt)
return d
r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
check("no cycle in a -> b", not r["groups"])
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n import a\n"}))
check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}))
check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}), include_tc=True)
check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
check("from pkg import submodule maps to the submodule", not r["groups"])
r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
r = analyze(proj(files))
check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
check("stdlib imports ignored", r["edges"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
check("venv folder skipped", r["modules"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
b = r["groups"][0]["break_candidate"]
check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
try:
analyze(proj({"README.md": "x"})); check("empty project rejected", False)
except ValueError:
check("empty project rejected", True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("project", nargs="?")
ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--include-type-checking", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.project or not os.path.isdir(a.project):
print("error: give a project directory", file=sys.stderr); return 2
try:
res = analyze(a.project, a.root, a.include_type_checking)
except ValueError as e:
print("error:", e, file=sys.stderr); return 2
print(json.dumps(res, indent=2) if a.json else render(res))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
I'm architecture student and I have a project of resort design in my design subject so this is my site and the north is upward side and the location is near Palampur Himachal Pradesh and no I have to design a resort in this site in which I hai to make a service room, reception, gazebo, open seating area 1 meditation hall, 4, 5 treatment room, 4 double cottages and 3 single cottages, 1 cafe and restaurant and also design a good landscape, or garden
I'm architecture student and I have a project of resort design in my design subject so this is my site and the north is upward side and the location is near Palampur Himachal Pradesh and no I have to design a resort in this site in which I hai to make a service room, reception, gazebo, open seating area 1 meditation hall, 4, 5 treatment room, 4 double cottages and 3 single cottages, 1 cafe and restaurant and also design a good landscape, or garden

Italian Renaissance-style sgraffito plaster panel in cream and charcoal: a lemon tree heavy with fruit in an ornate urn, two swallows in its branches, framed by scrolling acanthus leaves and a lattice border, with crisp scratched lines, cross-hatched shading, trowel texture and gentle weathering.
An authentic Italian Renaissance-style sgraffito wall panel of a lemon tree in an ornate urn, portrait 3:4, photographed straight on. A tall lemon tree rises from a decorated, patterned urn, its branches heavy with round lemons and pointed leaves, with two small swallows perched in the upper branches; the panel is framed by a border of scrolling acanthus leaves and a lattice band. Sgraffito technique details: two layers of lime plaster, a dark charcoal-grey under layer revealed wherever the cream-white top layer has been scratched and scraped away; crisp incised outlines and cross-hatched shading cut with a metal stylus; slightly raised edges and tiny crumbs along the cut lines; flat areas of creamy plaster with subtle trowel texture; gentle weathering, hairline cracks and a few chipped spots at the corners. Two tones only, cream and charcoal grey, with no paint colors. Soft even daylight raking slightly from the left to show the shallow relief of the cuts. Calm, elegant, Mediterranean mood. No text, no signature, no people, no modern objects.

A reusable collectible travel-art template: name a landmark, city and country and the model frames it inside a monumental arch with a smaller nested arch for infinite depth, adds a dreamlike landscape, a lone traveller with footprints, an oversized sun or crescent moon, a unique colour palette and minimal typography with a tiny poetic tagline.
Create an exceptionally beautiful surrealist architectural travel artwork featuring LANDMARK NAME, CITY, COUNTRY. 1. THE SIGNATURE COMPOSITION Create a monumental architectural arch or doorway as the dominant foreground frame. Inside the arch, reveal a breathtaking surreal landscape featuring the iconic landmark. Add a second, smaller nested arch in the centre, creating an illusion of infinite depth. Position the landmark naturally within this inner portal, preserving its recognisable architectural details. 2. DREAMLIKE LANDSCAPE Surround the landmark with abstract rolling landscapes inspired by the destination. Add a tiny solitary traveller walking towards the inner arch. Create a delicate trail of footprints leading towards the landmark. Introduce a crescent moon or oversized sun in the distant sky. Use beautiful gradients, dramatic shadows and atmospheric lighting. 3. COLOUR IDENTITY Every destination must have its own distinctive palette. Never repeat colours. 4. ART DIRECTION Surrealist architectural photography. Minimalist geometric composition. Cinematic colour grading. Monumental arches and nested frames. Dreamlike scale and perspective. Rich textures and soft atmospheric gradients. Deep, sophisticated shadows. 5. TYPOGRAPHY Add the country and landmark name in elegant minimal typography, with a tiny poetic tagline. No clutter, no unnecessary decorations, no random buildings. Premium collectible travel-art aesthetic. Vertical 4:5 Keep the nested arches as the signature element in every poster, but change the landscape, lighting, colour palette and architectural details for every destination. That will make the collection instantly recognisable while keeping every artwork unique.

A reusable travel-poster template: fill in [LANDMARK NAME], [CITY] and [COUNTRY] and the model builds the destination as a handcrafted miniature diorama from layered, sculpted coloured paper, with paper-cut hills, rivers and clouds, a destination-specific palette, an organic paper-cut frame and minimal typography with a short poetic tagline.
Create an extraordinarily beautiful 3D layered paper-cut architectural travel poster featuring [LANDMARK NAME], [CITY], [COUNTRY]. Transform the destination into an enchanting miniature architectural world, crafted entirely from intricately layered, sculpted and cut coloured paper. 1. CENTRAL ARCHITECTURAL SCENE Feature the destination’s most iconic landmark as the main attraction. Preserve its authentic and recognisable architectural identity. Recreate buildings using multiple layers of carefully cut paper. Include distinctive rooftops, windows, arches, towers, domes, bridges or architectural details specific to the destination. Arrange smaller surrounding buildings to create a charming miniature cityscape. Make the entire scene resemble a beautifully handcrafted architectural diorama. 2. LAYERED PAPER LANDSCAPE Build an extraordinary three-dimensional environment. Flowing paper-cut hills and sculpted mountains. Layered rivers, lakes, coastlines or ocean waves where appropriate. Curved bridges, winding pathways and miniature staircases. Overlapping paper clouds, hills and architectural backgrounds. Intricate foreground elements framing the composition. Beautiful irregular paper-cut edges surrounding the scene. Every layer should have visible depth, delicate edges and realistic cast shadows. 3. UNIQUE DESTINATION DETAILS Include small architectural and cultural elements that make each destination instantly recognisable. Select details according to the location rather than repeating the same decorations. 4. DESTINATION-SPECIFIC COLOUR PALETTE Create a completely original colour identity for every destination. Use 6–9 harmonious shades inspired by its architecture, culture, landscape and atmosphere. Combine rich colours, soft pastels, contrasting paper layers and carefully selected neutral tones. Never repeat the same palette between different destinations. 5. THREE-DIMENSIONAL PAPER ART Authentic handmade paper-cut aesthetic. Multiple overlapping cardstock layers. Sculpted paper architecture. Delicate folded and curved paper details. Visible paper thickness. Soft realistic shadows between layers. Beautiful tactile textures. Intricate miniature craftsmanship. Gentle studio lighting. The artwork must look like a real handcrafted paper sculpture photographed professionally, not a flat illustration or plastic 3D render. 6. DISTINCTIVE POSTER COMPOSITION Place the entire architectural scene inside an elegant irregular organic paper-cut frame. Use a balanced vertical composition with: Large miniature architectural scene in the centre. Beautiful layered foreground. Subtle surrounding negative space. Soft neutral background. Realistic depth and dimensional shadows. 7. MINIMAL TYPOGRAPHY Below the artwork, write: [CITY / DESTINATION NAME] [COUNTRY] Add one short, elegant poetic tagline of approximately 3–6 words inspired by the destination. Use elegant uppercase modern typography for the destination name and a delicate refined serif font for the tagline. Keep typography minimal, correctly spelled and beautifully positioned. 8. FINAL ART DIRECTION A breathtaking fusion of miniature architecture, layered paper sculpture, handcrafted papercraft, whimsical storytelling and premium contemporary travel poster design. Extremely intricate craftsmanship, sophisticated colour harmony, realistic paper shadows, beautiful depth, exquisite architectural details and museum-quality presentation. Portrait 2:3 composition. No watermark, no unnecessary text, no photorealistic buildings, no plastic appearance.

A reusable template for collectible architectural art prints: fill in [LANDMARK NAME], [CITY] and [COUNTRY] and the model builds one enormous uppercase letter from the destination's name, fuses the landmark into it as a double exposure, colours it with a palette drawn from the place's culture, and finishes it with editorial Swiss-style typography, coordinates and a tagline on textured ivory paper.
Create an exceptionally sophisticated, contemporary architectural art poster featuring [LANDMARK NAME], [CITY], [COUNTRY]. 1. GIANT TYPOGRAPHIC COMPOSITION Feature one enormous, oversized uppercase letter associated with the destination name as the central graphic element. The letter should dominate the composition, extending almost across the entire poster. Use bold, elegant, geometric typography with distinctive curves and negative spaces. 2. LANDMARK INTEGRATION Seamlessly integrate a highly detailed architectural photograph or realistic architectural illustration of [LANDMARK NAME] into and across the oversized letter. The landmark should appear to emerge from the typography, partially overlap its boundaries and interact naturally with its shape. Preserve the landmark’s authentic architectural details, proportions and recognisable silhouette. Create an artistic double-exposure effect where the architecture and typography become one unified visual composition. 3. DISTINCTIVE COLOUR TREATMENT Choose a unique colour palette inspired by the destination’s cultural identity, national colours and architectural character. Use two or three contrasting colours within the oversized typography. Apply translucent colour overlays across selected sections of the landmark, creating a beautiful combination of architectural photography, coloured light and graphic shapes. Every new destination must receive a different colour combination. Never repeat palettes. 4. TEXTURE & BACKGROUND Use a warm ivory, soft white or subtle textured paper background. Introduce delicate architectural sketch marks, distressed ink textures, faded photographic grain and subtle print imperfections around the central composition. Keep the surrounding space clean and uncluttered. 5. EDITORIAL TYPOGRAPHY Include the following information: [LANDMARK NAME] [CITY NAME] [COUNTRY NAME] Add small vertical typography along one side, geographical coordinates and a subtle destination-inspired tagline. Use sophisticated editorial typography with carefully balanced spacing. 6. ART DIRECTION Luxury architectural editorial design, experimental typography, architectural double exposure, contemporary Swiss graphic design, oversized letterforms, cinematic monochromatic photography, translucent colour blocking and minimalist gallery poster aesthetics. 7. FINAL PRESENTATION Create a visually striking, intellectual and artistic collectible landmark poster. The architecture must remain recognisable while becoming an integral part of the oversized letter. Vertical 4:5 composition, premium art-print quality, exceptional visual balance and sophisticated negative space. Avoid ordinary travel-poster layouts, decorative clutter, excessive colours and generic typography.
A hyper-realistic cinematic architectural walkthrough for luxury real estate videos. It opens on a rooftop infinity pool above a city skyline at golden hour, reveals a multi-level glass-and-dark-frame contemporary mansion, then flies FPV-drone style around the terraces, through the glass into a marble living room and down a hallway to a double-height ceiling as day turns to a warm evening. Includes visual style, 16:9, a 10-15 s duration and an avoid list.
Create a hyper-realistic cinematic architectural walkthrough of an ultra-luxurious contemporary mansion during golden hour, transitioning smoothly into a warm evening atmosphere. **Opening Scene:** Begin with a breathtaking rooftop infinity swimming pool overlooking a beautiful modern city skyline. Golden sunlight reflects across the water as the camera glides forward. **Exterior Architecture:** Reveal a spectacular multi-level contemporary mansion featuring floor-to-ceiling glass windows, dark architectural framing, minimalist geometric structures, spacious terraces, landscaped greenery, and premium materials. **Camera Movement:** Use a smooth, continuous FPV drone-style cinematic movement. Fly around the exterior terrace, glide between the architectural structures, and smoothly enter the house through the glass openings. **Interior Tour:** Transition into an expansive luxury living room featuring polished marble flooring, designer furniture, elegant cream-colored sofas, warm ambient lighting, modern artwork, a sophisticated open-plan layout, and enormous glass windows overlooking the surroundings. **Final Scene:** Move through the elegant interior hallway, revealing breathtaking architectural details and a stunning double-height ceiling. **Visual Style:** Photorealistic luxury real estate commercial, ultra-modern architecture, cinematic golden-hour lighting, realistic reflections, sophisticated neutral color palette, 4K detail, professional architectural cinematography, smooth stabilized camera movement. **Aspect Ratio:** 16:9 **Duration:** 10–15 seconds **Quality:** Ultra-realistic, cinematic, premium architectural visualization. **Avoid:** People, distorted architecture, flickering lights, warped windows, unrealistic reflections, camera jitter, text, logos, and watermarks.
A 15-second photoreal historical documentary of the Acropolis of Athens at golden sunrise, built as exactly 15 one-second shots with clean hard cuts: aerial reveal, drone glide to the Parthenon, column close-ups, an orbit, the Caryatids of the Erechtheion and a final aerial pull-back over the city. Includes visual style, orchestral audio and consistency rules for accurate architecture and sunrise direction. Swap in any other historic landmark to reuse the shot list.
Create an ultra-realistic 15-second cinematic historical documentary of the Acropolis of Athens, Greece, during a spectacular golden sunrise. Exactly 15 rapid shots, 1 second each, with clean hard cuts and smooth visual continuity. Shot sequence: 1. Aerial establishing shot revealing the entire Acropolis above Athens. 2. Smooth drone glide toward the ancient Parthenon. 3. Wide symmetrical view of the Parthenon glowing in sunrise light. 4. Close-up of massive ancient Greek marble columns. 5. Slow tilt-up revealing the magnificent temple architecture. 6. Cinematic orbit around the Parthenon. 7. Close-up of intricate ancient stone carvings and sculptures. 8. Side-angle tracking shot along the majestic columns. 9. Tracking shot across ancient marble pathways. 10. Low-angle hero shot emphasizing the towering columns. 11. Pan across the Erechtheion and its famous Caryatid statues. 12. Golden sunlight illuminating weathered marble textures. 13. Elevated aerial view showing Athens stretching toward the horizon. 14. Close-up revealing ancient architectural details and stone textures. 15. Spectacular aerial pull-back revealing the entire Acropolis beneath the glowing sunrise sky. Visual style: Photorealistic 4K HDR, premium historical documentary cinematography, authentic ancient Greek architecture, warm golden-pink sunrise, soft atmospheric haze, realistic marble textures, cinematic drone movements, natural shadows, stable geometry, no flickering or distortion. Audio: Epic orchestral soundtrack with subtle ancient Greek-inspired instrumental atmosphere. Consistency: Maintain historically accurate architecture, consistent sunrise direction, realistic geography, and smooth visual continuity across all 15 shots.
Opinionated conventions for designing clear, constraint-driven relational database schemas.
# Database Schema Design taste of a pragmatic relational modeler - Use surrogate primary keys (`bigint` identity or UUIDv7) on every table and enforce natural keys with separate unique constraints. Confidence: 0.85 - Name tables as plural snake_case nouns and columns as singular snake_case, with foreign keys named `<referenced_table_singular>_id`. Confidence: 0.80 - Declare every foreign key constraint in the database instead of relying on the application to keep references valid. Confidence: 0.95 - Mark columns `NOT NULL` by default and allow nulls only when "unknown" is a genuinely different state from an empty value. Confidence: 0.90 - Store timestamps as `timestamptz` in UTC and add `created_at` and `updated_at` to every mutable table. Confidence: 0.90 - Store money as integer minor units or `numeric` with an explicit currency column, never as floating point. Confidence: 0.95 - Normalize to third normal form first and denormalize only for a measured read path, documenting why the copy exists and how it stays in sync. Confidence: 0.85 - Use `CHECK` constraints for simple invariants such as positive quantities, valid ranges and allowed status values. Confidence: 0.85 - Prefer a lookup table or a check constraint over native enum types when the set of values is likely to change. Confidence: 0.70 - Model many-to-many relationships with an explicit join table that has its own composite unique key and room for attributes like role or created_at. Confidence: 0.85 - Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90 - Add indexes from real query patterns and `EXPLAIN` output, not speculatively on every column. Confidence: 0.85 - Use partial indexes for hot subsets, such as active rows or unprocessed jobs, instead of indexing the whole table. Confidence: 0.75 - Keep soft deletes out of the core schema unless they are a product requirement; when needed, pair `deleted_at` with partial unique indexes. Confidence: 0.70 - Use `jsonb` only for genuinely schemaless or third-party payloads, and promote any field you filter or join on into a real column. Confidence: 0.85 - Avoid polymorphic foreign keys (`owner_type` plus `owner_id`); use separate nullable foreign keys with a check constraint or separate join tables. Confidence: 0.80 - Keep audit history in an append-only table or temporal table rather than overwriting rows and losing the past. Confidence: 0.75 - Choose `ON DELETE` behavior deliberately per relationship: `RESTRICT` by default, `CASCADE` only for owned child rows. Confidence: 0.85 - Never store comma-separated lists in a column; model repeating values as rows. Confidence: 0.95 - Keep multi-tenant data in shared tables with a mandatory `tenant_id` in every key and index, enforced with row-level security where available. Confidence: 0.75 - Review every schema change as a migration in version control together with the code that depends on it. Confidence: 0.90 - Document each table and non-obvious column with `COMMENT ON` so the schema explains itself in any database client. Confidence: 0.65
Opinionated conventions for reliable, schema-governed Kafka event streaming and consumers.
# Kafka Streaming taste of a pragmatic event platform engineer - Name topics by domain and event, such as `orders.order-placed.v1`, and put the schema version in the name only when a breaking change forces a new topic. Confidence: 0.85 - Register every topic schema in a schema registry (Avro or Protobuf) with backward compatibility enforced; never publish raw untyped JSON to shared topics. Confidence: 0.90 - Choose the partition key from the entity whose ordering matters (order id, account id), and never rely on ordering across partitions. Confidence: 0.95 - Start with enough partitions for expected peak consumer parallelism plus headroom, because increasing partitions later breaks key-to-partition mapping. Confidence: 0.80 - Run producers with `acks=all`, idempotence enabled and `min.insync.replicas=2` on a replication factor of 3 for anything business-critical. Confidence: 0.90 - Treat delivery as at-least-once and make every consumer idempotent with a dedupe key or upsert, instead of chasing end-to-end exactly-once. Confidence: 0.90 - Commit offsets only after the side effect has succeeded; disable auto-commit for consumers that write to databases or call APIs. Confidence: 0.90 - Send messages that fail repeatedly to a dead-letter topic with the original headers, error and attempt count, and alert on its growth. Confidence: 0.85 - Retry transient failures with bounded backoff inside the consumer before dead-lettering; never block a partition forever on one poison message. Confidence: 0.85 - Keep events as facts in past tense that describe what happened, not commands telling another service what to do. Confidence: 0.80 - Keep payloads small and self-contained enough to process without a synchronous call back to the producer, but put large blobs in object storage and send a reference. Confidence: 0.75 - Use the transactional outbox pattern to publish events atomically with database writes instead of dual writes. Confidence: 0.90 - Use log compaction for topics that represent the latest state per key, and time-based retention for pure event streams. Confidence: 0.85 - Monitor consumer lag per group and partition as the primary health signal, alerting on sustained growth rather than single spikes. Confidence: 0.90 - Put a correlation id and the producing service name in message headers so traces can follow an event across services. Confidence: 0.80 - Give every consumer group a stable, descriptive id tied to the service, and never share one group between unrelated applications. Confidence: 0.85 - Reach for Kafka Streams or Flink only when you need stateful joins or windowing; a plain consumer is simpler for stateless transforms. Confidence: 0.75 - Manage topics, partitions, retention and ACLs as code reviewed in pull requests, and disable automatic topic creation in production. Confidence: 0.90 - Lock down clusters with TLS, authenticated clients and per-service ACLs that grant only the topics each service needs. Confidence: 0.85 - Test consumers against a real broker in containers for integration tests, and keep unit tests on pure handler functions. Confidence: 0.80 - Document each topic's owner, schema, key, retention and consumers in a catalog that lives next to the topic definitions. Confidence: 0.70

Isometric cutaway of a busy two-story corner coffee roastery at dawn: ground-floor drum roaster, burlap sacks, cooling beans and packing counter, upstairs cupping nook, warm sunrise through corner windows, soft clay-like diorama style in terracotta, cream and sage, no readable text or logos.
An isometric cutaway illustration of a busy corner coffee roastery at dawn, landscape 4:3. The two-story brick corner building is sliced open to show a ground-floor roasting room with a large drum roaster, burlap coffee sacks, a cooling tray of glossy brown beans, and a small packing counter, while upstairs a tiny tasting nook has a cupping table and shelves of sample jars. Warm early sunlight enters through tall corner windows; a bicycle leans outside by the door; steam rises from a cup on the counter. Soft clay-like 3D diorama style, neat tiny details, pastel morning palette with terracotta, cream, and sage, clean edges, lively but orderly mood. No readable text, no logos, no watermarks, no brand names on bags or signs.

Detailed storybook cutaway of a giant oak at dusk with three lamp-lit library rooms inside: a red armchair reading nook at the bottom, curved bookshelves with a ladder in the middle, and an attic with a brass telescope under a shingled roof, plus a spiral staircase, a lantern-lit rope bridge, falling orange autumn leaves, and a sunset sky.
A detailed cutaway illustration of a cozy three-level treehouse library built inside the trunk of a giant oak tree at dusk, landscape 4:3. The trunk is cut open to show three warm, lamp-lit rooms. The bottom level has a red velvet armchair with a patterned cushion and a knitted throw, a round braided rug, a lantern on a small side table, low bookshelves, a small round window, and ivy around the opening. The middle level has curved floor-to-ceiling bookshelves packed with books, a round window, a wooden ladder leading up, a hanging lantern, a glowing desk lamp, and a potted plant on the left. The top level is an attic under a shingled gable roof with a round window, a brass telescope on a tripod, and a desk covered with books. Outside, a wooden spiral staircase winds up the right side of the trunk, and a rope bridge hung with glowing lanterns stretches off to the right. Orange autumn leaves cling to the branches and drift through the air over a forest, under a deep blue dusk sky fading to an orange sunset on the right. Storybook style, fine ink lines, warm painted colors. No people, no text, no logos.
Opinionated conventions for building maintainable, real-time web apps with Elixir, Phoenix and LiveView.
# Phoenix App taste of a pragmatic Elixir engineer
- Start new projects on the latest stable Elixir and Phoenix releases, and pin Erlang/OTP and Elixir versions in .tool-versions. Confidence: 0.85
- Group business logic into Phoenix contexts with small public APIs, and never call Repo directly from controllers or LiveViews. Confidence: 0.90
- Keep contexts from reaching into each other's schemas, and talk across boundaries through public context functions. Confidence: 0.80
- Use LiveView for interactive pages by default and add JavaScript hooks only for things the browser must do itself. Confidence: 0.80
- Build UI from function components with declared attrs and slots instead of large shared templates. Confidence: 0.85
- Validate all input with Ecto changesets and keep separate changesets for different actions like registration and profile updates. Confidence: 0.90
- Lean on database constraints with unique_constraint and foreign_key_constraint instead of check-then-insert code. Confidence: 0.95
- Preload associations explicitly in context functions, and never let a template trigger an N+1 query. Confidence: 0.85
- Use Ecto.Multi or Repo.transaction for multi-step writes so partial failures roll back cleanly. Confidence: 0.85
- Write reversible migrations, and split long-running data backfills into separate tasks rather than schema migrations. Confidence: 0.85
- Read runtime settings and secrets in config/runtime.exs from environment variables, never in compile-time config. Confidence: 0.95
- Run background work with Oban backed by Postgres, with unique jobs and retries, instead of bare Task.start calls. Confidence: 0.85
- Put long-lived processes under a supervisor with a clear restart strategy and let them crash instead of rescuing every error. Confidence: 0.90
- Avoid GenServers as a place to hold data the database already owns; use them for real concurrency or coordination. Confidence: 0.80
- Return tagged tuples like {:ok, value} and {:error, reason} from context functions and handle them with with blocks. Confidence: 0.90
- Use PubSub for live updates between LiveViews and keep the broadcast topic names defined in one module. Confidence: 0.75
- Generate auth with phx.gen.auth and extend it, rather than building login and session handling from scratch. Confidence: 0.80
- Format code with mix format and run Credo and Dialyzer in CI so style and type issues fail the build. Confidence: 0.80
- Test contexts with DataCase and the SQL sandbox, and test LiveViews with Phoenix.LiveViewTest instead of a browser. Confidence: 0.85
- Emit metrics through Telemetry and watch them in LiveDashboard and an external metrics backend in production. Confidence: 0.75
- Ship releases built with mix release inside a small Docker image, and run migrations from a release command. Confidence: 0.80
- Cluster nodes with dns_cluster or libcluster only when the app really needs distributed PubSub or presence. Confidence: 0.70Opinionated conventions for designing, evolving and running reliable gRPC services with Protocol Buffers.
# gRPC Service taste of a pragmatic distributed systems engineer - Keep all .proto files in one shared schema repo or directory with a single owner per package, and generate code from it in CI. Confidence: 0.85 - Lint and check every proto change for breaking changes with buf lint and buf breaking before it can merge. Confidence: 0.90 - Version packages in the name, such as billing.v1, and add a new v2 package instead of changing the meaning of existing fields. Confidence: 0.90 - Never reuse or renumber a field tag, and mark removed fields and names as reserved. Confidence: 0.95 - Give every RPC its own request and response message, even when it starts empty, so fields can be added later. Confidence: 0.90 - Follow the resource-oriented method style of Get, List, Create, Update and Delete instead of ad hoc verbs where it fits. Confidence: 0.75 - Use field masks for partial updates rather than treating unset fields as a request to clear them. Confidence: 0.80 - Paginate every List call with page_size and an opaque page_token, and cap the page size on the server. Confidence: 0.90 - Use well-known types like google.protobuf.Timestamp and Duration instead of raw integers for time values. Confidence: 0.85 - Return the canonical status codes correctly, such as NOT_FOUND, INVALID_ARGUMENT and UNAVAILABLE, and never wrap every failure in UNKNOWN. Confidence: 0.90 - Attach structured error details with the richer error model for validation failures instead of packing them into the message string. Confidence: 0.75 - Require a deadline on every client call and propagate the remaining deadline to downstream calls. Confidence: 0.95 - Retry only idempotent methods, with backoff and a retry budget configured in the service config, not in hand-written loops. Confidence: 0.85 - Pass request IDs, auth tokens and tracing context in metadata, and keep business data in the message body. Confidence: 0.85 - Put logging, auth, metrics and tracing in interceptors instead of repeating them inside each handler. Confidence: 0.90 - Use mutual TLS between internal services and verify per-call credentials on the server for anything sensitive. Confidence: 0.85 - Implement the standard gRPC health checking service and enable server reflection only outside production. Confidence: 0.80 - Prefer unary calls, and use streaming only when the data is truly incremental or long-lived. Confidence: 0.80 - Apply flow control and backpressure on streams, and send keepalive pings within limits the load balancer allows. Confidence: 0.70 - Balance load per request with an L7 proxy or client-side balancing, because HTTP/2 connections pin traffic to one backend. Confidence: 0.85 - Expose a REST or JSON gateway generated from the same protos for browsers and partners instead of maintaining a second API by hand. Confidence: 0.70 - Test handlers with an in-process server and real generated clients rather than mocking the generated stubs. Confidence: 0.80 - Document each service, method and field with comments in the proto file, since that is where readers look first. Confidence: 0.85
Opinionated conventions for building maintainable, production-ready Java services with Spring Boot.
# Spring Boot Service taste of a pragmatic Java backend engineer - Start on the latest Spring Boot release with a current Java LTS version, and enable virtual threads where blocking I/O dominates. Confidence: 0.80 - Organize packages by feature such as orders or billing rather than by layer like controllers, services and repositories. Confidence: 0.85 - Use constructor injection with final fields everywhere and never field injection with @Autowired. Confidence: 0.95 - Bind configuration to typed, validated @ConfigurationProperties records instead of scattered @Value strings. Confidence: 0.90 - Keep secrets out of application.yml and read them from environment variables or a secrets manager. Confidence: 0.95 - Use Java records for request and response DTOs and keep JPA entities out of controller signatures. Confidence: 0.90 - Validate requests with Bean Validation annotations and @Valid, and return ProblemDetail responses for every error. Confidence: 0.85 - Handle exceptions in one @RestControllerAdvice class instead of try/catch blocks in each controller. Confidence: 0.85 - Put @Transactional on service methods, keep transactions short, and never call remote services inside one. Confidence: 0.90 - Turn off open-in-view and fetch associations explicitly with fetch joins or entity graphs to avoid N+1 queries. Confidence: 0.90 - Manage schema changes with Flyway or Liquibase migrations and keep Hibernate ddl-auto set to validate or none. Confidence: 0.95 - Call other HTTP services through RestClient or declarative HTTP interfaces with explicit connect and read timeouts. Confidence: 0.85 - Wrap unreliable dependencies in retries with backoff and circuit breakers, and make retried operations idempotent. Confidence: 0.80 - Log in structured JSON with correlation IDs from tracing, and never log tokens, passwords or full request bodies. Confidence: 0.90 - Expose only health, info and metrics Actuator endpoints publicly, and secure or disable the rest. Confidence: 0.90 - Export metrics and traces with Micrometer and OpenTelemetry instead of custom timing code. Confidence: 0.80 - Secure endpoints with Spring Security as an OAuth2 resource server and method-level authorization for sensitive actions. Confidence: 0.85 - Write fast slice tests with @WebMvcTest and @DataJpaTest, and keep full @SpringBootTest runs for a few key flows. Confidence: 0.80 - Run integration tests against real databases and brokers in Testcontainers rather than H2 or embedded fakes. Confidence: 0.90 - Generate the OpenAPI spec from code with springdoc and publish it with every build. Confidence: 0.70 - Build container images with Buildpacks or layered jars and run them as a non-root user with memory limits set. Confidence: 0.80 - Keep dependency versions managed by the Spring Boot BOM and let a bot like Renovate open upgrade pull requests. Confidence: 0.80
Opinionated conventions for building secure, scalable realtime features with WebSockets.
# Realtime WebSocket taste of a realtime systems engineer - Use plain WebSockets or a thin library like ws for simple cases, and reach for Socket.IO only when you need its fallbacks and rooms. Confidence: 0.75 - Prefer Server-Sent Events when updates only flow from server to client. Confidence: 0.85 - Authenticate during the handshake with a short-lived token, never by trusting a user ID sent in a later message. Confidence: 0.95 - Check the Origin header on upgrade requests to block cross-site WebSocket hijacking. Confidence: 0.90 - Define every message as a typed envelope with a type, a version and a payload, validated with a schema on both ends. Confidence: 0.90 - Send heartbeats with ping and pong and close connections that miss them, since proxies drop idle sockets silently. Confidence: 0.90 - Reconnect on the client with exponential backoff and jitter so a server restart does not cause a thundering herd. Confidence: 0.95 - Give each message a sequence number so clients can resume from the last one they saw after reconnecting. Confidence: 0.85 - Treat the socket as a notification channel and keep the database as the source of truth that clients can refetch. Confidence: 0.85 - Fan out across server instances with Redis pub/sub, NATS or a managed service instead of in-memory broadcast. Confidence: 0.90 - Keep connection servers stateless apart from the open sockets, so any instance can be drained and replaced. Confidence: 0.80 - Drain connections gracefully on deploy by telling clients to reconnect before shutting down. Confidence: 0.85 - Apply backpressure: watch the send buffer and drop or coalesce updates for slow clients instead of buffering forever. Confidence: 0.85 - Rate limit incoming messages per connection and cap message size. Confidence: 0.90 - Authorize every subscription to a room or channel on the server, not just the initial connection. Confidence: 0.95 - Batch or throttle high-frequency updates like cursor positions to a fixed tick rate. Confidence: 0.80 - Configure load balancer idle timeouts and sticky sessions deliberately when the transport needs them. Confidence: 0.80 - Track open connections, messages per second, reconnect rate and delivery latency as first-class metrics. Confidence: 0.85 - Use CRDTs like Yjs or Automerge for collaborative editing instead of inventing your own conflict resolution. Confidence: 0.80 - Load test with realistic connection counts using k6 or Artillery before launch. Confidence: 0.80

Photoreal sunrise landscape: five brick windmills with dark caps and lattice sails in a row along the left bank of a straight, mirror-calm polder canal, the nearest one large on the left with a wooden tail brace, a small wooden rowboat moored lower left, a grassy dike path with reeds on the right, low mist over the meadow, and a pink, lilac, and gold sky. Step 2 of the Dutch Windmill Canal workflow.
Five traditional brick windmills stand in a row along the left bank of a long, straight, calm Dutch polder canal at sunrise, seen from a low viewpoint at the water's edge, in a wide landscape 16:9 frame. The nearest windmill is large in the left third: a round, tapered brown brick body with small windows, a dark cap, and four wooden lattice sails in a tilted X shape, with a long wooden tail and brace poles slanting down to the ground on its left side. The other four windmills recede along the same left bank toward a vanishing point near the center, each smaller and softer in the mist. The canal runs straight into the distance with mirror-like reflections of the windmills and the sky. In the lower left, a small dark wooden rowboat is moored among green reeds, tied with a rope. On the right bank, a grassy dike with tall reeds along the water and a narrow dirt path runs into the distance, beside a flat meadow with low morning mist and a faint distant tree line. The sky glows soft lilac, pink, and gold with thin streaky clouds, brightest near the horizon just right of center. Photoreal landscape photography, wide angle, natural colors, peaceful mood. No people, no text, no logos.
Opinionated conventions for building reliable background job queues and workers.
# Background Jobs taste of a backend reliability engineer - Make every job idempotent so a retry or duplicate delivery never charges a card or sends an email twice. Confidence: 0.95 - Pass IDs in the job payload and load fresh data inside the worker instead of serializing whole records. Confidence: 0.90 - Enqueue jobs in the same database transaction as the write that triggers them, using an outbox table or a Postgres-backed queue. Confidence: 0.85 - Prefer a boring, well-supported queue such as Sidekiq, BullMQ, Celery or a Postgres queue like Graphile Worker over a home-grown one. Confidence: 0.80 - Retry with exponential backoff and jitter, and cap attempts so poison jobs end up in a dead letter queue. Confidence: 0.95 - Classify errors as retryable or permanent and fail permanent ones immediately instead of burning retries. Confidence: 0.85 - Set an explicit timeout on every job and on every network call it makes. Confidence: 0.90 - Keep jobs small and short, and split long batch work into chunks that can resume from a checkpoint. Confidence: 0.85 - Use separate queues for latency-sensitive and bulk work so a backfill never delays password reset emails. Confidence: 0.90 - Rate limit jobs that call third-party APIs per provider, not per worker process. Confidence: 0.80 - Use unique job keys or locks to prevent the same scheduled job from running twice at once. Confidence: 0.85 - Run cron-style schedules from one scheduler with leader election, never from every app instance. Confidence: 0.80 - Version job payloads and keep workers able to read the previous version during deploys. Confidence: 0.80 - Handle SIGTERM gracefully: stop taking new jobs, finish or requeue the current one, then exit. Confidence: 0.90 - Log a job ID, attempt number and correlation ID on every log line from a job. Confidence: 0.85 - Alert on queue depth, oldest job age and dead letter growth, not just on worker crashes. Confidence: 0.90 - Give the dead letter queue an owner and a documented replay command. Confidence: 0.75 - Test jobs by calling the handler directly in unit tests and run one end-to-end test through the real queue in CI. Confidence: 0.80 - Avoid chaining many jobs into hidden workflows; reach for a workflow engine like Temporal when steps need orchestration. Confidence: 0.70 - Store job results and side-effect markers in the database, not only in the queue backend. Confidence: 0.75

Photoreal sunrise landscape: long purple lavender rows converging along a central dirt path toward a two-story stone farmhouse with a terracotta roof and pale blue shutters in the right third, a tall cypress beside it, a lone oak on the left, a low sun at the far left, and rolling blue hills. Step 2 of the Provence Lavender Farmhouse workflow.
Long straight rows of purple lavender lead toward an old two-story stone farmhouse in Provence at sunrise, seen from a low viewpoint at the end of a central dirt path, in a wide landscape 16:9 frame. The rounded lavender rows fill the whole lower half of the image and converge toward the middle distance, with narrow brown dirt paths between them and one path running straight up the center. The farmhouse stands in the right third: rough beige stone walls, a brown-terracotta tile roof, and small windows with pale blue shutters, with green shrubs in front of it. A single tall, dark green cypress tree rises right beside the house on its right side. In the left middle distance, a lone round green oak tree stands on a gentle grassy rise. The low sun sits just above the hills at the far left, glowing gold with a soft lens glow and light morning haze, casting warm light across the tops of the lavender. Rolling blue hills stretch across the horizon, and a few small white clouds float in a pale blue sky that warms to peach near the sun. Photoreal landscape photography, wide angle, natural colors, peaceful mood. No people, no text, no logos.

Photoreal golden-hour landscape: a small white church with a red roof and steeple on a grassy headland in the left third, a curve of glossy black sand, white surf rolling in from the right, four dark basalt rocks and sea stacks offshore, a low sun at the far left, and orange, pink, and purple clouds. Step 2 of the Icelandic Black Sand Beach Church workflow.
A small white wooden church with a red gabled roof and a pointed red steeple stands on a rounded grassy green headland above an Icelandic black sand beach at golden hour, with dark basalt sea stacks rising from the ocean on the right. The church sits in the left third of the frame, near the top of the headland, its white walls and small windows lit warm gold by the low sun. The headland's grassy slope drops down to the beach, and a wide curve of fine black volcanic sand sweeps from the lower left corner across the foreground, wet and glossy near the water. White foamy surf rolls in from the right in several long lines and washes up the black sand. In the sea on the right half stand four dark basalt rocks: a low rounded rock near the end of the headland, a tall jagged sea stack in the center right, and two smaller pointed spires further right. The low sun sits near the horizon at the far left behind the headland, glowing yellow-orange, and the sky is filled with scattered clouds lit orange, pink, and purple against soft blue. Photoreal landscape photography, wide angle, natural colors, calm and dramatic mood. Wide landscape 16:9. No people, no text, no logos.
Opinionated conventions for shipping changes safely with feature flags and gradual rollouts.
# Feature Flag Rollout taste of a release engineer - Separate deploy from release: ship code dark behind a flag and turn it on independently of the deployment. Confidence: 0.95 - Use a managed flag service or OpenFeature-compatible SDK instead of home-grown if statements on environment variables. Confidence: 0.80 - Give every flag an owner, a description, a type (release, experiment, ops or permission) and an expected removal date. Confidence: 0.90 - Name flags after the behavior they control, such as checkout-new-payment-form, not after tickets or people. Confidence: 0.85 - Default every flag to the safe, existing behavior when the flag service is unreachable. Confidence: 0.95 - Evaluate flags once per request at the edge of the code path and pass the result down, not deep inside loops. Confidence: 0.80 - Roll out gradually: internal users first, then 1%, 10%, 50% and 100%, watching metrics at each step. Confidence: 0.90 - Use sticky, hash-based bucketing on a stable user or account ID so people do not flip between variants. Confidence: 0.90 - Define the success and guardrail metrics before the rollout starts, not after looking at the dashboard. Confidence: 0.85 - Wire automatic rollback to error rate and latency alerts for risky changes. Confidence: 0.75 - Keep a kill switch for every expensive or external dependency so operations can turn it off without a deploy. Confidence: 0.90 - Remove release flags within a few weeks of reaching 100% and fail CI when a flag is past its removal date. Confidence: 0.80 - Test both the on and off paths in CI for every active flag. Confidence: 0.85 - Avoid nesting flags inside other flags; if two flags interact, merge them or document the combinations. Confidence: 0.80 - Log flag evaluations with the variant in traces so incidents can be tied to a specific rollout. Confidence: 0.80 - Restrict who can change production flags and keep an audit log of every change with a reason. Confidence: 0.85 - Never use feature flags as a substitute for authorization checks. Confidence: 0.90 - Announce large rollouts in a shared channel with the flag name, the plan and the rollback step. Confidence: 0.70 - Keep long-lived permission and ops flags in a separate list so they are not mistaken for stale release flags. Confidence: 0.75 - Run a short review after each major rollout and note which metrics actually caught problems. Confidence: 0.65

Photoreal blue-hour shot of an old-town river: ochre shophouses with lantern-hung eaves on the left bank, a wooden arched footbridge with a tiled roof pavilion, many floating paper lanterns with shimmering reflections, and a rowboat with a rower in a conical hat carrying glowing lanterns. Step 2 of the Hoi An Lantern River workflow.
A calm river runs through a historic Vietnamese old town at blue hour, its dark water covered with glowing floating paper lanterns while a small wooden rowboat carrying lanterns glides in the foreground. Along the LEFT bank stands a row of yellow ochre two-story shophouses with dark wooden shutters and terracotta tile roofs, with a long riverside promenade and low stone river wall in front, cafe tables, and a few small people strolling; strings of round glowing silk lanterns in red, orange, and yellow hang along the shopfront eaves. In the center background, a wooden arched footbridge with a small tiled pagoda-style roof pavilion at its top spans the river, lit by lanterns, its arch reflected in the water. On the far RIGHT bank, more low buildings with a line of lanterns along the far promenade. Many small square paper lanterns glowing red, orange, yellow, and white float on the calm water, spread from the foreground left all the way to the bridge, each with a long shimmering reflection. In the right-center foreground, a narrow dark wooden rowboat lies diagonally, its left end lower and closer to the camera; one rower in a white conical hat and dark clothes sits at the right end holding a long wooden oar that reaches down into the water toward the lower right, and the middle of the boat carries a pile of about ten glowing paper lanterns. Deep blue twilight sky with a soft pink-violet glow on the horizon behind the bridge, no stars and no moon. Warm lantern light against cool blue dusk, photoreal cinematic travel photography, calm and magical mood. Wide landscape 16:9. No close-up faces, no text, no signs, no logos.