keelmodel 0.1.0__py3-none-any.whl
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.
- keeliam/__init__.py +12 -0
- keeliam/context.py +155 -0
- keeliam/principal.py +58 -0
- keelmodel/__init__.py +1 -0
- keelmodel/adoption/__init__.py +4 -0
- keelmodel/adoption/__main__.py +28 -0
- keelmodel/adoption/decision-guide.md +98 -0
- keelmodel/adoption/quickstart.md +98 -0
- keelmodel/adoption/recovery.md +104 -0
- keelmodel/adoption/reference.md +265 -0
- keelmodel/authz.py +562 -0
- keelmodel/extensions/audit/__init__.py +3 -0
- keelmodel/extensions/audit/audit.py +169 -0
- keelmodel/generation.py +110 -0
- keelmodel/migrations.py +161 -0
- keelmodel/py.typed +0 -0
- keelmodel/registry.py +209 -0
- keelmodel/runtime/base.py +6 -0
- keelmodel/runtime/constraints.py +72 -0
- keelmodel/runtime/context.py +18 -0
- keelmodel/runtime/errors.py +29 -0
- keelmodel/runtime/filtering.py +81 -0
- keelmodel/runtime/models.py +307 -0
- keelmodel/runtime/operations.py +22 -0
- keelmodel/runtime/results.py +13 -0
- keelmodel/runtime/serialization.py +285 -0
- keelmodel/runtime/session.py +2344 -0
- keelmodel/schema.py +779 -0
- keelmodel/ui/__init__.py +17 -0
- keelmodel/ui/introspection.py +289 -0
- keelmodel/ui/loader.py +307 -0
- keelmodel-0.1.0.dist-info/METADATA +292 -0
- keelmodel-0.1.0.dist-info/RECORD +39 -0
- keelmodel-0.1.0.dist-info/WHEEL +4 -0
- keelmodel-0.1.0.dist-info/licenses/LICENSE +21 -0
- keelpolicy/__init__.py +1 -0
- keelpolicy/evaluator.py +117 -0
- keelpolicy/parser.py +133 -0
- keelpolicy/types.py +26 -0
keeliam/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""KeelIAM — provider-neutral identity/access-context contracts.
|
|
2
|
+
|
|
3
|
+
KeelIAM is not an identity provider. It does not authenticate users,
|
|
4
|
+
parse or validate tokens, manage sessions, or store user directories.
|
|
5
|
+
The host application authenticates with its own middleware/IdP first and
|
|
6
|
+
only then constructs these contracts from the verified result.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .context import AccessContext
|
|
10
|
+
from .principal import VerifiedIdentity
|
|
11
|
+
|
|
12
|
+
__all__ = ["AccessContext", "VerifiedIdentity"]
|
keeliam/context.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""AccessContext — the application-scoped identity for one request or job.
|
|
2
|
+
|
|
3
|
+
A :class:`~keeliam.principal.VerifiedIdentity` proves *who* the caller
|
|
4
|
+
is. AccessContext adds what the *application* knows about them for this
|
|
5
|
+
call: tenant, roles, permissions, and attributes. Roles and permissions
|
|
6
|
+
are application-owned strings — KeelIAM normalizes their shape but never
|
|
7
|
+
invents their meaning.
|
|
8
|
+
|
|
9
|
+
The context does not authenticate anything. Build it only at the trusted
|
|
10
|
+
application boundary, after authentication and after the application has
|
|
11
|
+
resolved the caller's tenant/roles itself.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from types import MappingProxyType
|
|
19
|
+
from typing import TYPE_CHECKING, Any
|
|
20
|
+
|
|
21
|
+
from .principal import VerifiedIdentity
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from keelflow.sdk import Actor, JobContext
|
|
25
|
+
|
|
26
|
+
from keelmodel.runtime.context import OperationContext
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _clean_strings(values: Any, name: str) -> frozenset[str]:
|
|
30
|
+
if values is None:
|
|
31
|
+
return frozenset()
|
|
32
|
+
if isinstance(values, str):
|
|
33
|
+
values = (values,)
|
|
34
|
+
result = []
|
|
35
|
+
for value in values:
|
|
36
|
+
if not isinstance(value, str) or not value.strip():
|
|
37
|
+
raise ValueError(f"{name} entries must be non-empty strings")
|
|
38
|
+
result.append(value.strip())
|
|
39
|
+
return frozenset(result)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class AccessContext:
|
|
44
|
+
"""Immutable application-scoped access context for one call or job.
|
|
45
|
+
|
|
46
|
+
- ``identity``: the verified external principal.
|
|
47
|
+
- ``tenant``: the application tenant/organization this call acts in,
|
|
48
|
+
or None when the application is single-tenant. KeelIAM does not
|
|
49
|
+
validate tenant membership — that is the application's
|
|
50
|
+
responsibility.
|
|
51
|
+
- ``roles``: application-owned role names (their meaning is decided
|
|
52
|
+
by the application and by each framework's policy layer).
|
|
53
|
+
- ``permissions``: fine-grained permission strings, matching
|
|
54
|
+
KeelFlow's ``JobContext.permissions`` contract.
|
|
55
|
+
- ``attributes``: additional application-owned request attributes
|
|
56
|
+
(correlation ids, IP, feature flags) exposed to policy evaluation.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
identity: VerifiedIdentity
|
|
60
|
+
tenant: str | None = None
|
|
61
|
+
roles: frozenset[str] = field(default_factory=frozenset)
|
|
62
|
+
permissions: frozenset[str] = field(default_factory=frozenset)
|
|
63
|
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
if not isinstance(self.identity, VerifiedIdentity):
|
|
67
|
+
raise TypeError(
|
|
68
|
+
"identity must be a VerifiedIdentity — construct it only "
|
|
69
|
+
"after the host has authenticated the caller"
|
|
70
|
+
)
|
|
71
|
+
if self.tenant is not None:
|
|
72
|
+
if not isinstance(self.tenant, str) or not self.tenant.strip():
|
|
73
|
+
raise ValueError("tenant must be a non-empty string or None")
|
|
74
|
+
object.__setattr__(self, "tenant", self.tenant.strip())
|
|
75
|
+
object.__setattr__(self, "roles", _clean_strings(self.roles, "roles"))
|
|
76
|
+
object.__setattr__(
|
|
77
|
+
self, "permissions", _clean_strings(self.permissions, "permissions")
|
|
78
|
+
)
|
|
79
|
+
object.__setattr__(
|
|
80
|
+
self, "attributes", MappingProxyType(dict(self.attributes))
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# --- KeelModel mapping -------------------------------------------------
|
|
84
|
+
|
|
85
|
+
def subject_dict(self) -> dict[str, Any]:
|
|
86
|
+
"""Subject mapping for KeelModel/KeelPolicy evaluation.
|
|
87
|
+
|
|
88
|
+
Roles are always present (possibly empty) so policy rules can
|
|
89
|
+
rely on the key existing. ``id`` is the issuer-qualified
|
|
90
|
+
principal id — unqualified ids must never cross issuers.
|
|
91
|
+
"""
|
|
92
|
+
subject: dict[str, Any] = {
|
|
93
|
+
"id": self.identity.principal_id,
|
|
94
|
+
"issuer": self.identity.issuer,
|
|
95
|
+
"subject": self.identity.subject,
|
|
96
|
+
"roles": sorted(self.roles),
|
|
97
|
+
}
|
|
98
|
+
if self.tenant is not None:
|
|
99
|
+
subject["tenant"] = self.tenant
|
|
100
|
+
return subject
|
|
101
|
+
|
|
102
|
+
def attributes_dict(self) -> dict[str, Any]:
|
|
103
|
+
"""Attributes mapping for KeelModel/KeelPolicy evaluation."""
|
|
104
|
+
return dict(self.attributes)
|
|
105
|
+
|
|
106
|
+
def to_operation_context(self) -> OperationContext:
|
|
107
|
+
"""Build a KeelModel ``OperationContext`` for one SDK call.
|
|
108
|
+
|
|
109
|
+
KeelModel is an optional integration target: it is imported
|
|
110
|
+
lazily so KeelIAM itself has no framework dependency.
|
|
111
|
+
"""
|
|
112
|
+
from keelmodel.runtime.context import OperationContext
|
|
113
|
+
|
|
114
|
+
return OperationContext(
|
|
115
|
+
subject=self.subject_dict(),
|
|
116
|
+
attributes=self.attributes_dict(),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# --- KeelFlow mapping ---------------------------------------------------
|
|
120
|
+
|
|
121
|
+
def to_actor(self) -> Actor:
|
|
122
|
+
"""Build a KeelFlow human ``Actor`` from the principal.
|
|
123
|
+
|
|
124
|
+
KeelFlow is an optional integration target (imported lazily).
|
|
125
|
+
Service/system actors are application decisions, not identity
|
|
126
|
+
facts — construct those directly with ``Actor.service()`` /
|
|
127
|
+
``Actor.system()`` instead of through this mapping.
|
|
128
|
+
"""
|
|
129
|
+
from keelflow.sdk import Actor
|
|
130
|
+
|
|
131
|
+
return Actor.user(self.identity.principal_id)
|
|
132
|
+
|
|
133
|
+
def to_job_context(self, **overrides: Any) -> JobContext:
|
|
134
|
+
"""Build a KeelFlow ``JobContext`` carrying this access context.
|
|
135
|
+
|
|
136
|
+
Permissions map one-to-one. Tenant maps to ``tenant_id``.
|
|
137
|
+
KeelFlow-specific fields (``correlation_id``, ``request_id``,
|
|
138
|
+
``extra``) can be passed as keyword overrides — KeelIAM does not
|
|
139
|
+
own their semantics.
|
|
140
|
+
"""
|
|
141
|
+
from keelflow.sdk import JobContext
|
|
142
|
+
|
|
143
|
+
fields: dict[str, Any] = {
|
|
144
|
+
"actor": self.to_actor(),
|
|
145
|
+
"tenant_id": self.tenant,
|
|
146
|
+
"permissions": self.permissions,
|
|
147
|
+
}
|
|
148
|
+
unknown = set(overrides) - {"correlation_id", "request_id", "extra"}
|
|
149
|
+
if unknown:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"unknown JobContext override(s): {sorted(unknown)} — "
|
|
152
|
+
"KeelIAM only maps correlation_id, request_id, extra"
|
|
153
|
+
)
|
|
154
|
+
fields.update(overrides)
|
|
155
|
+
return JobContext(**fields)
|
keeliam/principal.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Principal contracts — identity already verified by the host application.
|
|
2
|
+
|
|
3
|
+
Trust boundary: constructing :class:`VerifiedIdentity` asserts that the
|
|
4
|
+
host has completed authentication (OIDC, SAML, session middleware, mTLS
|
|
5
|
+
— whichever mechanism it uses). KeelIAM does not and cannot verify that
|
|
6
|
+
claim itself; the contract exists so the boundary is explicit in one
|
|
7
|
+
place instead of re-invented per application.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from types import MappingProxyType
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class VerifiedIdentity:
|
|
20
|
+
"""An external identity whose authentication is already proven.
|
|
21
|
+
|
|
22
|
+
``issuer`` identifies the identity system that authenticated the
|
|
23
|
+
user (an IdP issuer URI, or an internal scheme name such as
|
|
24
|
+
``"local-ad"`` for a corporate directory integration). ``subject``
|
|
25
|
+
is the stable identifier of the person or service within that
|
|
26
|
+
issuer. The pair ``(issuer, subject)`` is the principal's identity —
|
|
27
|
+
never use ``subject`` alone across issuers, because two different
|
|
28
|
+
issuers may issue the same string for different people.
|
|
29
|
+
|
|
30
|
+
``claims`` carries additional verified attributes exposed by the
|
|
31
|
+
issuer (email, name, groups). They are treated as read-only; copy
|
|
32
|
+
them if the application needs to transform them.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
issuer: str
|
|
36
|
+
subject: str
|
|
37
|
+
claims: Mapping[str, Any] = field(default_factory=dict)
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
if not isinstance(self.issuer, str) or not self.issuer.strip():
|
|
41
|
+
raise ValueError("issuer must be a non-empty string")
|
|
42
|
+
if not isinstance(self.subject, str) or not self.subject.strip():
|
|
43
|
+
raise ValueError("subject must be a non-empty string")
|
|
44
|
+
if len(self.subject) > 255:
|
|
45
|
+
raise ValueError("subject must be at most 255 characters")
|
|
46
|
+
if "|" in self.issuer or "|" in self.subject:
|
|
47
|
+
raise ValueError(
|
|
48
|
+
"issuer and subject must not contain '|' — it is the "
|
|
49
|
+
"principal_id separator; OIDC issuer URLs never do"
|
|
50
|
+
)
|
|
51
|
+
object.__setattr__(self, "issuer", self.issuer.strip())
|
|
52
|
+
object.__setattr__(self, "subject", self.subject.strip())
|
|
53
|
+
object.__setattr__(self, "claims", MappingProxyType(dict(self.claims)))
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def principal_id(self) -> str:
|
|
57
|
+
"""Issuer-qualified principal identifier, unique across issuers."""
|
|
58
|
+
return f"{self.issuer}|{self.subject}"
|
keelmodel/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Synchronous, PostgreSQL-first data SDK for business applications."""
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from importlib import resources
|
|
5
|
+
|
|
6
|
+
_DOCS = ("quickstart", "decision-guide", "reference", "recovery")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main() -> None:
|
|
10
|
+
args = sys.argv[1:]
|
|
11
|
+
base = resources.files("keelmodel.adoption")
|
|
12
|
+
if not args:
|
|
13
|
+
print("keelmodel adoption docs — shipped with the installed version")
|
|
14
|
+
print()
|
|
15
|
+
for name in _DOCS:
|
|
16
|
+
print(f" python -m keelmodel.adoption {name}")
|
|
17
|
+
print()
|
|
18
|
+
print("Start with quickstart; use decision-guide to map use cases.")
|
|
19
|
+
return
|
|
20
|
+
name = args[0].removesuffix(".md")
|
|
21
|
+
if name not in _DOCS:
|
|
22
|
+
print(f"unknown doc {args[0]!r}; choose one of: {', '.join(_DOCS)}")
|
|
23
|
+
raise SystemExit(2)
|
|
24
|
+
print((base / f"{name}.md").read_text(encoding="utf-8"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
main()
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# keelmodel decision guide
|
|
2
|
+
|
|
3
|
+
Map your use case to the right primitive. Each row lists the valid
|
|
4
|
+
configuration shape and the trade-off.
|
|
5
|
+
|
|
6
|
+
## I want to…
|
|
7
|
+
|
|
8
|
+
### Define a business model
|
|
9
|
+
→ Write one YAML file per model: `version`, `module`, `model`, `fields`,
|
|
10
|
+
optional `relations`/`constraints`/`mixins`. Strict: unknown keys fail.
|
|
11
|
+
Trade-off: schema lives outside Python — reviewable, but you regenerate
|
|
12
|
+
artifacts when it changes.
|
|
13
|
+
|
|
14
|
+
### Load and use models at runtime
|
|
15
|
+
→ `ModuleRegistry` + `registry.register(ModuleDefinition(...), models)`
|
|
16
|
+
then `KeelModel(database_url, registry)`. No auto-discovery, no implicit
|
|
17
|
+
imports: registration is explicit because module boundaries are contracts.
|
|
18
|
+
|
|
19
|
+
### Guard against concurrent overwrites (lost updates)
|
|
20
|
+
→ Add `mixins: [versioned]` or `version: true` on one `integer` field.
|
|
21
|
+
Every `update` then requires `changes["version"]` (what the caller read);
|
|
22
|
+
a stale write is `ConflictError`. Upsert conflict branches need it too.
|
|
23
|
+
Trade-off: callers must round-trip the version — clients that ignore it
|
|
24
|
+
cannot write at all.
|
|
25
|
+
|
|
26
|
+
### Read related rows without N+1
|
|
27
|
+
→ `km.query(..., include=["customer", "lines", "lines.product"])` —
|
|
28
|
+
batched, one query per relation hop, authorization applied per related
|
|
29
|
+
resource. Nested dotted paths work; there is no lazy loading.
|
|
30
|
+
Trade-off: each hop re-checks authorization — deeply nested graphs pay
|
|
31
|
+
one query per hop and wide trees pay one per relation.
|
|
32
|
+
|
|
33
|
+
### Insert-or-update by a natural key
|
|
34
|
+
→ `km.upsert(values, ctx, conflict_target="number", update_fields=[...])`.
|
|
35
|
+
`conflict_target` must be the PK or a declared unique group present in
|
|
36
|
+
`values`; fields outside both lists are insert-only.
|
|
37
|
+
Trade-off: the target must be schema-declared (no ad-hoc arbitrary keys).
|
|
38
|
+
|
|
39
|
+
### Store money or addresses as one logical field
|
|
40
|
+
→ Composite types `money`/`address` — input and output are nested
|
|
41
|
+
mappings (`{"amount": ..., "currency": ...}`). Default `storage: prefix`
|
|
42
|
+
creates one typed column per component (`price__amount`) so you can
|
|
43
|
+
filter/order/index by dotted path (`price.amount`); `storage: json` is
|
|
44
|
+
one document column — no component querying, whole-document updates.
|
|
45
|
+
Trade-off: built-in shapes only; per-component authorization references
|
|
46
|
+
the physical column names.
|
|
47
|
+
|
|
48
|
+
### Derive values like line totals or invoice sums
|
|
49
|
+
→ `computed: {sql: "..."}` for same-row arithmetic (database-generated,
|
|
50
|
+
filterable) or `computed: {python: name}` for cross-row derivations —
|
|
51
|
+
the function runs inside the write transaction; use `km.recompute()`
|
|
52
|
+
after changing dependent rows since automatic triggering is not built yet.
|
|
53
|
+
Trade-off: recompute is explicit, not dependency-triggered.
|
|
54
|
+
|
|
55
|
+
### Keep aggregates current automatically
|
|
56
|
+
→ Add `depends` to the computed field: writes to dependent rows mark the
|
|
57
|
+
owner dirty and a single cascade pass before commit recomputes each owner
|
|
58
|
+
exactly once — bulk imports do not multiply recomputes. Chains follow
|
|
59
|
+
topological order.
|
|
60
|
+
Trade-off: reads inside an open transaction do not see cascade effects
|
|
61
|
+
until commit; hot parent rows serialize concurrent writers (opt-in per
|
|
62
|
+
field is the escape hatch); cascade writes ignore parent-level write
|
|
63
|
+
grants by design.
|
|
64
|
+
|
|
65
|
+
### Carry authenticated identity into Model and Flow
|
|
66
|
+
→ `keeliam.VerifiedIdentity` + `AccessContext` after the host's own
|
|
67
|
+
authentication; map with `to_operation_context()` (KeelModel) or
|
|
68
|
+
`to_actor()` / `to_job_context()` (KeelFlow). keeliam does no token
|
|
69
|
+
validation and is not an IdP — it only normalizes the context contract.
|
|
70
|
+
|
|
71
|
+
### Restrict who sees/edits what
|
|
72
|
+
→ `KeelModel(..., authz=AuthorizationProvider(policy_path))` — opt-in.
|
|
73
|
+
Record conditions compile into SQL; with `enable_field_rules=True` every
|
|
74
|
+
field is default-deny for read/create/update/filter/order.
|
|
75
|
+
Field grants may carry record conditions: on single-row write paths
|
|
76
|
+
(create/update) they evaluate against the post-write record view, so
|
|
77
|
+
data-tiered rules like "managers update status only on manager-tier
|
|
78
|
+
orders" are enforceable. Read projections stay record-agnostic — a
|
|
79
|
+
field granted only conditionally is absent from reads even when the
|
|
80
|
+
row would match (fail closed). The enforcement read selects only
|
|
81
|
+
columns grant conditions reference, so denied columns never appear in
|
|
82
|
+
any SELECT. Bulk paths cannot evaluate per-row grants and fail closed.
|
|
83
|
+
Trade-off: only SDK calls are enforced — raw engine/session access
|
|
84
|
+
bypasses it, and you own subject authentication.
|
|
85
|
+
|
|
86
|
+
### Audit mutations
|
|
87
|
+
→ `KeelModel(..., audit=AuditExtension(redact_fields={...}))` — same
|
|
88
|
+
transaction as the mutation. DB-cascade deletions are not audited.
|
|
89
|
+
Trade-off: audit rows capture full field values unless redacted — list
|
|
90
|
+
sensitive fields deliberately.
|
|
91
|
+
|
|
92
|
+
### Paginate large result sets
|
|
93
|
+
→ `limit`/`offset` on `query` for small result sets — PK tie-breakers
|
|
94
|
+
make pages deterministic. At scale use `cursor=page.next_cursor`:
|
|
95
|
+
keyset pagination stays constant-cost and immune to inserts between
|
|
96
|
+
pages. Sort fields must be non-null and readable; cursor and offset
|
|
97
|
+
cannot be combined.
|
|
98
|
+
Trade-off: cursor pagination has no random page access — forward only.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# keelmodel quickstart (executable)
|
|
2
|
+
|
|
3
|
+
Every snippet below is executed by the keelmodel test suite — if it
|
|
4
|
+
drifts from reality, CI fails. Python blocks are concatenated in order.
|
|
5
|
+
|
|
6
|
+
## 1. Declare a model
|
|
7
|
+
|
|
8
|
+
```yaml
|
|
9
|
+
# ticket.yaml
|
|
10
|
+
version: 1
|
|
11
|
+
module: support
|
|
12
|
+
model: Ticket
|
|
13
|
+
mixins: [uuid_pk, versioned]
|
|
14
|
+
fields:
|
|
15
|
+
subject: {type: text, required: true, length: 200}
|
|
16
|
+
status: {type: enum, values: [open, closed], required: true, default: open}
|
|
17
|
+
priority: {type: integer, required: true, default: 3}
|
|
18
|
+
constraints:
|
|
19
|
+
unique:
|
|
20
|
+
- [subject]
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## 2. Register and connect
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import tempfile, uuid
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from keelmodel.registry import ModuleDefinition, ModuleRegistry
|
|
30
|
+
from keelmodel.runtime.context import OperationContext
|
|
31
|
+
from keelmodel.runtime.session import KeelModel
|
|
32
|
+
from keelmodel.schema import parse_model
|
|
33
|
+
import yaml
|
|
34
|
+
|
|
35
|
+
raw = yaml.safe_load(TICKET_YAML)
|
|
36
|
+
definition = parse_model(raw)
|
|
37
|
+
registry = ModuleRegistry()
|
|
38
|
+
registry.register(
|
|
39
|
+
ModuleDefinition(
|
|
40
|
+
name="support",
|
|
41
|
+
version="1.0.0",
|
|
42
|
+
requires=(),
|
|
43
|
+
exports=("Ticket",),
|
|
44
|
+
models_path="models",
|
|
45
|
+
),
|
|
46
|
+
(definition,),
|
|
47
|
+
)
|
|
48
|
+
db = Path(tempfile.mkdtemp()) / "qs.db"
|
|
49
|
+
km = KeelModel(f"sqlite:///{db}", registry)
|
|
50
|
+
km._all_mapped["support.Ticket"].__table__.create(km.engine)
|
|
51
|
+
ctx = OperationContext(subject={"roles": ["admin"]}, attributes={})
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## 3. Create, read, update with optimistic locking
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
ticket = km.create("support.Ticket", {"subject": "Login broken"}, ctx)
|
|
58
|
+
assert ticket["version"] == 1
|
|
59
|
+
assert ticket["status"] == "open"
|
|
60
|
+
|
|
61
|
+
updated = km.update(
|
|
62
|
+
"support.Ticket", ticket["id"],
|
|
63
|
+
{"version": ticket["version"], "status": "closed"}, ctx,
|
|
64
|
+
)
|
|
65
|
+
assert updated["version"] == 2
|
|
66
|
+
|
|
67
|
+
# A stale write fails instead of overwriting silently:
|
|
68
|
+
from keelmodel.runtime.errors import ConflictError
|
|
69
|
+
try:
|
|
70
|
+
km.update("support.Ticket", ticket["id"],
|
|
71
|
+
{"version": 1, "status": "open"}, ctx)
|
|
72
|
+
raise AssertionError("stale update must fail")
|
|
73
|
+
except ConflictError:
|
|
74
|
+
pass
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## 4. Query with deterministic paging, and upsert
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
page = km.query(
|
|
81
|
+
"support.Ticket", ctx,
|
|
82
|
+
filters={"field": "status", "op": "eq", "value": "closed"},
|
|
83
|
+
order=["-priority"], limit=10,
|
|
84
|
+
)
|
|
85
|
+
assert page.total == 1
|
|
86
|
+
|
|
87
|
+
row = km.upsert(
|
|
88
|
+
"support.Ticket",
|
|
89
|
+
{"subject": "Login broken", "priority": 1, "version": 2},
|
|
90
|
+
ctx, conflict_target="subject", update_fields=["priority"],
|
|
91
|
+
)
|
|
92
|
+
assert row["priority"] == 1
|
|
93
|
+
assert row["version"] == 3
|
|
94
|
+
assert row["id"] == ticket["id"]
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Next: `python -m keelmodel.adoption decision-guide` for feature mapping,
|
|
98
|
+
`reference` for the exact YAML/API grammar.
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# keelmodel recovery guide
|
|
2
|
+
|
|
3
|
+
Symptom → cause → fix. Errors are typed; catch the base classes, not
|
|
4
|
+
message strings.
|
|
5
|
+
|
|
6
|
+
## SchemaError / "unknown key(s)" at parse time
|
|
7
|
+
The YAML uses keys outside the grammar. The validator never invents
|
|
8
|
+
defaults — check `reference.md`; do not guess alternative spellings.
|
|
9
|
+
|
|
10
|
+
## "at least one primary_key field is required"
|
|
11
|
+
Add `mixins: [uuid_pk]` or a field with `primary_key: true`.
|
|
12
|
+
|
|
13
|
+
## ValidationError: "expected version ... is required"
|
|
14
|
+
The model is versioned; `update` must pass `changes["version"]` set to
|
|
15
|
+
the version the caller last read. On upsert conflict branches, put it in
|
|
16
|
+
`values`.
|
|
17
|
+
|
|
18
|
+
## ConflictError: "stale version ..."
|
|
19
|
+
Another writer committed first. Re-read the row, recompute changes,
|
|
20
|
+
retry with the new version. This is the optimistic-locking contract
|
|
21
|
+
working — never catch-and-ignore it.
|
|
22
|
+
|
|
23
|
+
## ConflictError: "failed to create/update/upsert ..."
|
|
24
|
+
A database constraint rejected the write (unique, FK, check). Messages
|
|
25
|
+
deliberately omit driver internals; query the DB or enable SQLAlchemy
|
|
26
|
+
echo for detail. Idempotent retry is safe only after confirming the
|
|
27
|
+
conflicting row is semantically identical.
|
|
28
|
+
|
|
29
|
+
## NotFoundError vs PermissionDenied on get/update/delete
|
|
30
|
+
`NotFoundError` = the row does not exist. `PermissionDenied` = it exists
|
|
31
|
+
but record/field rules deny access. Both are deliberate and correct —
|
|
32
|
+
do not "fix" callers by probing; handle them as separate outcomes.
|
|
33
|
+
|
|
34
|
+
## "conflict_target ... is not the primary key or a declared unique constraint"
|
|
35
|
+
Upsert targets only schema-declared identity. Add the group to
|
|
36
|
+
`constraints.unique` in the YAML and regenerate, or target the PK.
|
|
37
|
+
|
|
38
|
+
## "update_fields member ... must be present in values"
|
|
39
|
+
The allowlist references a field not in the payload. Upsert does not
|
|
40
|
+
synthesize values — supply them.
|
|
41
|
+
|
|
42
|
+
## include raises "unknown relation ... in include path"
|
|
43
|
+
Every hop of a dotted path must name a relation declared in the YAML of
|
|
44
|
+
that hop's model. Check spelling; dotted paths nest (e.g. `"lines.product"`)
|
|
45
|
+
but cannot skip levels.
|
|
46
|
+
|
|
47
|
+
## include raises PermissionDenied about correlation keys
|
|
48
|
+
With field rules enabled, the FK column and both PKs must be readable to
|
|
49
|
+
correlate rows. Grant `read` on those columns or drop the include —
|
|
50
|
+
there is no silent fallback.
|
|
51
|
+
|
|
52
|
+
## "transaction aborted after an authorization denial"
|
|
53
|
+
A caught `PermissionDenied` inside `km.transaction()` still poisons the
|
|
54
|
+
transaction. Treat denials as terminal for that transaction; start a new
|
|
55
|
+
one instead of catching and continuing.
|
|
56
|
+
|
|
57
|
+
## Empty `{}` responses after successful writes
|
|
58
|
+
Write responses are READ-projected: the caller lacks read action/record/
|
|
59
|
+
field grants for the resulting row. The write committed — do not retry
|
|
60
|
+
it. Grant read or treat `{}` as success-without-projection.
|
|
61
|
+
|
|
62
|
+
## Pagination returns overlapping rows or skips rows
|
|
63
|
+
PK tie-breakers make a static dataset deterministic — the usual cause is
|
|
64
|
+
concurrent writes between page fetches, a read-isolation property of
|
|
65
|
+
offset paging. Switch to cursor pagination (`cursor=page.next_cursor`),
|
|
66
|
+
which is immune to inserts before the cursor position.
|
|
67
|
+
|
|
68
|
+
## ValidationError: invalid cursor
|
|
69
|
+
Cursors are opaque and bound to the exact order list they were issued
|
|
70
|
+
with. Do not build them by hand, reuse them across different `order`
|
|
71
|
+
terms, or combine them with `offset`.
|
|
72
|
+
|
|
73
|
+
## ValidationError: nullable sort field / cursor position is null
|
|
74
|
+
Cursor pagination cannot express NULL ordering portably. Order by a
|
|
75
|
+
required field or the primary key, or fall back to offset paging.
|
|
76
|
+
|
|
77
|
+
## composite field errors
|
|
78
|
+
- "expects a mapping of components" — pass nested input:
|
|
79
|
+
`{"amount": "10", "currency": "USD"}`, not a scalar.
|
|
80
|
+
- "missing required component(s)" — create/upsert need every required
|
|
81
|
+
component.
|
|
82
|
+
- "merging the update into the stored document would leave it
|
|
83
|
+
incomplete" — the row never had this composite set (or stored data
|
|
84
|
+
predates the schema); write a complete document once, then partial
|
|
85
|
+
updates merge normally.
|
|
86
|
+
- "violates money format rules" — currency must be uppercase ISO 4217
|
|
87
|
+
(`USD`), country uppercase ISO 3166 alpha-2 (`VN`).
|
|
88
|
+
- "composite field has no single column" / "json-stored composite cannot
|
|
89
|
+
be filtered" — prefix storage queries by dotted path
|
|
90
|
+
(`price.amount`); json storage is not component-queryable. Choose
|
|
91
|
+
prefix at schema time when you need filtering or indexing.
|
|
92
|
+
|
|
93
|
+
## cascade / trigger-graph errors
|
|
94
|
+
- "dependency cycle in computed fields: A.x → B.y → A.x" — the loop is
|
|
95
|
+
named in the error; break it by removing one depends entry or making
|
|
96
|
+
one side manual recompute.
|
|
97
|
+
- "no many-to-one/one-to-one relation toward" / "multiple relations" —
|
|
98
|
+
cross-model depends needs exactly one such relation on the dependent
|
|
99
|
+
model pointing at the owner; v1 rejects ambiguity instead of guessing.
|
|
100
|
+
- "cascade depth limit exceeded" — chains beyond 16 levels are refused;
|
|
101
|
+
split the derivation or use manual recompute for part of the chain.
|
|
102
|
+
- values stale inside a transaction — expected: the cascade runs before
|
|
103
|
+
commit, not per write. Standalone writes are unaffected; batch callers
|
|
104
|
+
read after committing.
|