Grants that outlive what they name, and a rule you can read

sharing.forget_principal has existed since shares did, documented as the thing
that stops a recycled id inheriting somebody's grant, and was called by nobody.
Deleting a group left every grant naming it; deleting an account left both the
grants to it and the grants of its own work -- that second half is the one
nothing else could catch, since their rows cascade and the shares of those rows
have nothing to cascade from. Both now run before the delete, while the rows are
still findable, and a deleted resource forgets its own.

library.share defaulted to False, which meant sharing shipped documented as done
and unreachable: the panel only renders for somebody holding it, so out of the
box nobody could share anything and nothing said why. It is on.

The panel itself was checkboxes inside the resource's *save form*, listing every
group and every account on the instance, unpaginated, on every detail page -- and
a tick only took effect if you also saved the resource. It is its own routes now:
search, one grant per POST, the panel re-rendered from what is stored. Anything
already shared stays listed whatever the search says, or removing a grant would
mean searching for the name it was given to.

Reports join the shareable set and memories still do not: a finished piece of
work is the thing somebody most wants to hand over, and a record about a person
is not content to pass round. reports.visible became sharing.visible_to, which is
the one line its own docstring predicted. Two things fell out: `owned` beside
`get`, because sharing grants reading and deleting is the owner's alone; and
reading somebody else's report no longer clears their unread dot.

Permissions gained the answer to "what can this person actually do?" --
explain() is resolve()'s working shown rather than thrown away, naming admin, the
baseline, or the groups that granted each one. That is the simulation the union
rule exists to make unnecessary, and until now the only way to get it was to open
every group and read the grids by eye. Users and groups are list-plus-detail, and
membership is edited from one side: it was on both, and a full-form POST from
either overwrote what the other had shown.

Read and write are split for notes, memory and skills -- checked on the tool's
declared risk, after the gate so it can only narrow, and defaulting on.

Quotas are the union rule applied to numbers, with the corner that makes it
interesting: zero means "no limit" and wins outright, or a group saying unlimited
would count for less than one saying a million. Absent means "no opinion".
_narrower folds a group's ceiling with the instance's and is deliberately not
min, for the same reason. Five axes, enforced where each is knowable -- before a
reply is built, before a second one starts, on an agent reply's clock, before a
minute of GPU, and beside the helper cap -- and usage is recorded even for a
reply that was stopped or errored, because an endpoint charges either way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-06 16:48:14 +02:00
parent 20bb569b00
commit 1b8c9f948c
31 changed files with 2226 additions and 377 deletions
+4
View File
@@ -48,6 +48,7 @@ from lembas.db.models.library import (
PRINCIPAL_USER,
RESOURCE_BASE,
RESOURCE_NOTE,
RESOURCE_REPORT,
RESOURCE_SKILL,
SOURCE_LINK,
SOURCE_UPLOAD,
@@ -101,6 +102,7 @@ from lembas.db.models.user import (
Group,
PushSubscription,
Session,
Usage,
User,
user_groups,
)
@@ -108,6 +110,7 @@ from lembas.db.models.user import (
__all__ = [
"AUTHOR_MODEL",
"PushSubscription",
"Usage",
"AUTH_KEY",
"AUTH_METHODS",
"AUTH_PASSWORD",
@@ -126,6 +129,7 @@ __all__ = [
"PRINCIPAL_USER",
"RESOURCE_BASE",
"RESOURCE_NOTE",
"RESOURCE_REPORT",
"RESOURCE_SKILL",
"RESPONSE_JSON",
"RESPONSE_MODES",
+7
View File
@@ -53,6 +53,13 @@ SOURCE_LINK = "link"
RESOURCE_BASE = "base"
RESOURCE_NOTE = "note"
RESOURCE_SKILL = "skill"
# A report is shareable and a memory is not, and the line between them is the
# one already drawn elsewhere: a finished piece of work is exactly the thing
# somebody wants to hand over, and a record *about a person* is not content to
# pass round. The constant lives here beside the other three even though Report
# is not a library model, because `Share.resource_type` is one column and its
# vocabulary belongs in one place.
RESOURCE_REPORT = "report"
PRINCIPAL_USER = "user"
PRINCIPAL_GROUP = "group"
+62 -1
View File
@@ -5,7 +5,18 @@ from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Index, String, Table, Text
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Index,
Integer,
String,
Table,
Text,
UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from lembas.db.base import Base, Timestamps, UUIDPrimaryKey
@@ -69,6 +80,16 @@ class Group(UUIDPrimaryKey, Timestamps, Base):
# lembas.security.permissions.
permissions_json: Mapped[dict[str, Any]] = mapped_column(JSONDict, default=dict)
# What members of this group may spend. Resolved across a user's groups by
# **maximum**, which is the union rule applied to numbers: being in a second
# group can only ever grant more. Zero means "no limit" and therefore wins
# outright, because a group that says "unlimited" saying less than one that
# says "a million" would be the union rule inverted for one value.
#
# Absent keys mean the group has no opinion and contribute nothing. See
# security/permissions.py:limits_for.
limits_json: Mapped[dict[str, Any]] = mapped_column(JSONDict, default=dict)
users: Mapped[list[User]] = relationship(secondary=user_groups, back_populates="groups")
models: Mapped[list[Model]] = relationship(
"Model", secondary="model_groups", back_populates="groups"
@@ -149,3 +170,43 @@ class PushSubscription(UUIDPrimaryKey, Timestamps, Base):
Index("ix_push_subscriptions_user_id", PushSubscription.user_id)
class Usage(UUIDPrimaryKey, Timestamps, Base):
"""What one account spent in one period.
A row per user per period rather than a row per reply. A per-reply ledger is
what somebody eventually wants for a bill; this exists to answer one
question on the request path -- "has this account used its month?" -- and
that question wants one indexed lookup, not a sum over ten thousand rows.
`period` is a plain "YYYY-MM" string in **UTC**. Not the reader's timezone:
a quota that resets at a different instant for each member of a group is a
quota nobody can reason about, and the month boundary is not something
anybody experiences to the hour.
Written by `generation._persist`, which is the single writer for everything
a reply produced, so a reply that is stopped or errors still records what it
spent -- an endpoint charges for tokens it generated whether or not the
reply was wanted.
"""
__tablename__ = "usage"
__table_args__ = (UniqueConstraint("user_id", "period", name="uq_usage_user_period"),)
user_id: Mapped[str] = mapped_column(
String(32), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
)
period: Mapped[str] = mapped_column(String(7), nullable=False)
prompt_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
completion_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
replies: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# Counted separately because it is its own quota: one picture is a minute of
# somebody's GPU and no tokens at all, so a token budget says nothing about
# it. `images_today` on the resolved limits is the daily half; this is the
# month's running total, for the admin screen.
images: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
def __repr__(self) -> str:
return f"<Usage {self.user_id} {self.period}>"