@terpjs/spec 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.23.0
1
+ 0.25.0
@@ -0,0 +1,22 @@
1
+ {
2
+ "id": "backend/no_manual_lease_columns",
3
+ "surface": "backend",
4
+ "title": "Application tables do not re-derive leases; expiring custody of work is a platform primitive",
5
+ "intent": "Exclusive, time-bounded custody of a unit of work belongs to the platform, not to each table that needs it. An application table must not declare its own lease bookkeeping \u2014 a holder column paired with an expiry, a heartbeat stamp, or an equivalent claim deadline \u2014 because the hand-rolled form reliably omits the part that makes a lease safe. Expiry alone establishes that a holder may have died; it does not prevent that holder, if it merely paused, from waking after its deadline and completing work a successor has already taken over. A conformant platform supplies custody that is fenced (a monotonic grant token every write is matched against, so a superseded holder is refused rather than trusted), taken atomically with the state change it guards, renewable by a heartbeat that fails closed when the grant is lost, and recoverable \u2014 an expired grant must trigger the owning domain's declared recovery, so work a crashed holder abandoned returns to a retryable state instead of requiring manual repair. Platform-owned delivery infrastructure that claims batches of its own rows, and needs no domain recovery, is a reviewed exception rather than an application pattern.",
6
+ "layer": "static-portable",
7
+ "enforcement": [
8
+ {
9
+ "kind": "build-time",
10
+ "tool": "terp.arch",
11
+ "ref": "check_no_manual_lease_columns"
12
+ }
13
+ ],
14
+ "reference": "LeaseResource names the leased row or domain mutex; hold_lease / acquire_lease take it through the configured LeaseStore, LeaseGuard.heartbeat renews it and raises when the grant was lost, and register_lease_reaper declares the per-kind recovery an expiry triggers. terp-cap-leases keeps the grants in the app's own database so a claim commits with the row change it protects.",
15
+ "opt_out": "# arch-allow-no-manual-lease-columns: <reason>",
16
+ "runtime": {
17
+ "applicability": "not-applicable",
18
+ "rationale": "Column presence is observable at runtime but not attributable. Composition shares one model-metadata registry across every installed distribution, and the platform's own durable-delivery table legitimately declares exactly these columns for its batch claim \u2014 so a running app cannot tell an application's hand-rolled lease from the framework's sanctioned one (the same non-attribution as the import-form egress and background-runtime rules). Nor can a module manifest close the gap: it carries routers and jobs, never a model reference to attribute a column through. The lease seam's own fail-closed controls \u2014 the fence that refuses a superseded holder's write, the heartbeat that raises rather than returning a flag, and the boot guard that refuses a store whose grants die with their holder \u2014 protect the sanctioned path; they cannot see a table that never joined it. The paired protection is therefore constructive rather than preventive: a maintained primitive that is strictly better than the hand-rolled shape, offered where the hand-rolled shape used to be the only option."
19
+ },
20
+ "guide_topic": "leases",
21
+ "corpus": true
22
+ }
@@ -2,7 +2,7 @@
2
2
  "id": "backend/schemas_avoid_positional_tuples",
3
3
  "surface": "backend",
4
4
  "title": "A schema field never crosses the wire as a positional tuple",
5
- "intent": "A fixed-length tuple annotation (tuple[str, str], list[tuple[str, int]], tuple[str, ...]) on a schema a client can see or send serialises into the contract as an array whose element types are positional (prefixItems, or the list form of items). Client generators do not agree on that shape: one emits the positional form and another the widened element array, so the two descriptions of the same field are structurally unrelated and the app cannot type its own calls against its own API — the failure surfaces at the call site as an opaque generic-instantiation mismatch, far from the field that caused it, and only with error truncation disabled. A tuple is also a poor contract in its own right: the positions carry meaning that no name records. Name the shape instead — a nested model with named fields when the positions differ in meaning, or a homogeneous sequence (list[str]) when they do not.",
5
+ "intent": "A fixed-length tuple annotation (tuple[str, str], list[tuple[str, int]]) on a schema a client can see or send serialises into the contract as an array whose element types are positional (prefixItems, or the list form of items). Client generators do not agree on that shape: one emits the positional form and another the widened element array, so the two descriptions of the same field are structurally unrelated and the app cannot type its own calls against its own API — the failure surfaces at the call site as an opaque generic-instantiation mismatch, far from the field that caused it, and only with error truncation disabled. A fixed tuple is also a poor contract in its own right: the positions carry meaning that no name records. Name the shape instead — a nested model with named fields when the positions differ in meaning, or a homogeneous sequence when they do not. Scope is the positional shape only: a variadic tuple[X, ...] serialises byte-identically to list[X] — it is the immutable spelling of a homogeneous sequence, the natural annotation for a frozen value object — so it is compliant, and refusing it would force a source rewrite with zero wire effect. A fixed tuple nested inside one (tuple[tuple[str, int], ...]) is still refused.",
6
6
  "layer": "static-bespoke",
7
7
  "enforcement": [
8
8
  {
@@ -18,9 +18,9 @@
18
18
  ],
19
19
  "runtime": {
20
20
  "applicability": "required",
21
- "rationale": "The invariant survives into the running app: the generated OpenAPI document is the artifact the client is built from, so the boot-time contract validation walks every component schema and refuses a positional array shape (prefixItems, or items as a list) fail-closed. This catches the vector the source check cannot see a tuple reaching the contract through a type alias, a generic parameter, or a custom __get_pydantic_core_schema__ — and both halves name the same fix."
21
+ "rationale": "The invariant survives into the running app: the generated OpenAPI document is the artifact the client is built from, so the boot-time contract validation walks the generated document and refuses a positional array shape (prefixItems, or items as a list) fail-closed, reporting every offending location in one pass rather than raising on the first. Judging the document rather than the annotations is what makes the scope exact in both directions: a variadic tuple emits nothing positional and passes, while a tuple reaching the contract through a discriminated-union member, a type alias, a generic parameter, or a custom __get_pydantic_core_schema__ is in the document no matter what the annotation walk could see — and both halves name the same fix."
22
22
  },
23
- "reference": "Schema fields annotated with a nested BaseSchema model or a homogeneous list[...]; tuple[...] annotations on BaseSchema subclasses and on any class used as a route body or response_model are refused.",
23
+ "reference": "Schema fields annotated with a nested BaseSchema model or a homogeneous sequence (list[...], or the variadic tuple[X, ...] which serialises identically); fixed-length tuple[...] annotations on BaseSchema subclasses and on any class used as a route body or response_model are refused.",
24
24
  "opt_out": "# arch-allow-schemas-avoid-positional-tuples: <reason>",
25
25
  "guide_topic": "module",
26
26
  "corpus": true
@@ -0,0 +1,13 @@
1
+ import uuid
2
+
3
+ from sqlmodel import Field
4
+ from terp.core import BaseTable
5
+
6
+
7
+ class RunRequest(BaseTable, table=True):
8
+ """The row records its own lifecycle; custody is the platform's, keyed on the row."""
9
+
10
+ __tablename__ = "run_request"
11
+
12
+ connection_id: uuid.UUID = Field(index=True)
13
+ status: str = Field(max_length=16, index=True)
@@ -0,0 +1,44 @@
1
+ from terp.core import (
2
+ AuditAction,
3
+ BaseService,
4
+ LeaseResource,
5
+ hold_lease,
6
+ register_lease_reaper,
7
+ )
8
+
9
+ from app.modules.requests.models import RunRequest
10
+ from app.modules.requests.schemas import RunRequestCreate, RunRequestUpdate
11
+
12
+ CLAIMED = "claimed"
13
+ QUEUED = "queued"
14
+
15
+
16
+ class RunRequestService(BaseService[RunRequest, RunRequestCreate, RunRequestUpdate]):
17
+ model = RunRequest
18
+
19
+ def __init__(self, holder: str) -> None:
20
+ self._holder = holder
21
+
22
+ def _after_write(self, session, entity, action):
23
+ """Take the lease inside the write that claims the row, so the two agree.
24
+
25
+ A resource somebody else holds raises here, before the write commits, so the row
26
+ never reaches ``claimed`` at all — there is no compensating update to forget.
27
+ """
28
+ if entity.status == CLAIMED:
29
+ hold_lease(
30
+ session,
31
+ LeaseResource.for_row(entity),
32
+ holder=self._holder,
33
+ ttl_seconds=60,
34
+ )
35
+
36
+
37
+ def requeue_stale_request(session, lease) -> None:
38
+ """The recovery an expired lease triggers: put the abandoned row back in the queue."""
39
+ service = RunRequestService(holder="reaper")
40
+ row = service.get(session, lease.resource.key)
41
+ service.update(session, row.id, RunRequestUpdate(status=QUEUED, version=row.version))
42
+
43
+
44
+ register_lease_reaper("run_request", requeue_stale_request)
@@ -0,0 +1,15 @@
1
+ from datetime import datetime
2
+
3
+ from terp.core import BaseSchema
4
+
5
+
6
+ class LeaseRead(BaseSchema):
7
+ """A read DTO may surface who holds a lease and until when — it declares no column.
8
+
9
+ Only a persisted column on a table model is refused; showing an operator what is
10
+ stuck is exactly what the primitive is for.
11
+ """
12
+
13
+ holder: str | None
14
+ locked_until: datetime | None
15
+ heartbeat_at: datetime | None
@@ -0,0 +1,19 @@
1
+ from datetime import datetime
2
+
3
+ from sqlmodel import Field
4
+ from terp.core import BaseTable
5
+
6
+
7
+ class RunRequest(BaseTable, table=True):
8
+ """A queue row that re-derives custody on itself: a holder plus a deadline.
9
+
10
+ Nothing here can refuse a holder that merely paused: it wakes past its deadline,
11
+ finds its own name still in ``locked_by``, and finishes over the successor that
12
+ already took the work.
13
+ """
14
+
15
+ __tablename__ = "run_request"
16
+
17
+ status: str = Field(max_length=16, index=True)
18
+ locked_by: str | None = Field(default=None, max_length=128)
19
+ locked_until: datetime | None = None
@@ -0,0 +1,17 @@
1
+ from datetime import datetime
2
+
3
+ from sqlmodel import Field
4
+ from terp.core import BaseTable
5
+
6
+
7
+ class PipelineRun(BaseTable, table=True):
8
+ """The same defect in its other common spelling: a heartbeat stamp on the row.
9
+
10
+ A reader still cannot tell "working" from "died", because nothing declares how long
11
+ a gap in the heartbeat is allowed to be, and nothing walks the run back when it is.
12
+ """
13
+
14
+ __tablename__ = "pipeline_run"
15
+
16
+ status: str = Field(max_length=16, index=True)
17
+ heartbeat_at: datetime | None = None
@@ -0,0 +1,2 @@
1
+ class NoteRead(BaseSchema):
2
+ fingerprint: tuple[str, ...]
@@ -0,0 +1,2 @@
1
+ class NoteRead(BaseSchema):
2
+ spans: tuple[tuple[int, int], ...]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terpjs/spec",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "The Terp Standard — stack-neutral rule catalog, violation corpus, finding format, and refused-surface declaration (ADRs 0080/0081; packaged per ADR 0082, published per ADR 0086). Data only: consumers resolve the spec root via require.resolve('@terpjs/spec/package.json').",
5
5
  "files": [
6
6
  "VERSION",