Spaces:
Running

fsanyoto commited on
Commit
003d5fa
Β·
verified Β·
1 Parent(s): d8c82a4

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "v28 (2793e4b)",
3
  "releases": [
4
  {
5
  "version": "v28",
 
1
  {
2
+ "current": "55ced50",
3
  "releases": [
4
  {
5
  "version": "v28",
VERSION CHANGED
@@ -1 +1 @@
1
- v28 (2793e4b)
 
1
+ 55ced50
api/main.py CHANGED
@@ -86,6 +86,11 @@ import routes_starred # noqa: E402 (wave 35 R4/C2/C3/C5 β€” the star; E's rout
86
  import routes_usage # noqa: E402 (wave 35 R9/C7 β€” the AI usage meter; E's router, E's line)
87
  import routes_feedback # noqa: E402 (wave 35 R8/C6 β€” feedback to the operator plane; E's router)
88
  from core import grid_events # noqa: E402
 
 
 
 
 
89
  from deps import Session, module_gate # noqa: E402
90
 
91
  _WEB_DIST = _HERE.parents[1] / "web" / "dist"
@@ -174,6 +179,48 @@ def _store_unavailable(request: Request, exc: grid_events.StoreUnavailable):
174
  status_code=503)
175
 
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  @app.get("/api/health")
178
  def health():
179
  """Unauthenticated LIVENESS only β€” it must answer before anyone can sign in, so it may not
 
86
  import routes_usage # noqa: E402 (wave 35 R9/C7 β€” the AI usage meter; E's router, E's line)
87
  import routes_feedback # noqa: E402 (wave 35 R8/C6 β€” feedback to the operator plane; E's router)
88
  from core import grid_events # noqa: E402
89
+ # D-315 / D-305 (2026-08-18) β€” the two store REFUSALS get their own app-level handlers below.
90
+ # ⚠ Neither is a `StoreUnavailable` subclass, on purpose: routes that degrade a store outage into a
91
+ # session fallback must NOT degrade a refusal, or the user is told a change was saved that was not.
92
+ from core import data_binding # noqa: E402
93
+ from core import store # noqa: E402
94
  from deps import Session, module_gate # noqa: E402
95
 
96
  _WEB_DIST = _HERE.parents[1] / "web" / "dist"
 
179
  status_code=503)
180
 
181
 
182
+ @app.exception_handler(data_binding.StoreWriteRefused)
183
+ def _store_write_refused(request: Request, exc: data_binding.StoreWriteRefused):
184
+ """D-315 β€” this deployment may not write that store. 503, with the REASON.
185
+
186
+ β›” IT ECHOES THE EXCEPTION'S OWN MESSAGE, WHERE ITS NEIGHBOUR ABOVE USES A FIXED SENTENCE, and
187
+ the difference is the point. "The store is unavailable" is the whole truth about an outage; a
188
+ refusal has a cause the operator cannot otherwise discover, because per D-160 the Space
189
+ environment cannot be read from outside. A refusal that said only "unavailable" would send
190
+ somebody hunting for a network fault that does not exist ([[report-the-cause-before-you-fix-it]]).
191
+ The message names the deployment, the store and the fix, and carries no customer data.
192
+
193
+ β›” AND IT IS ITS OWN HANDLER RATHER THAN A SUBCLASS OF `StoreUnavailable`. Several routes carry
194
+ `except StoreUnavailable:` blocks that DEGRADE to a session-scoped fallback workspace β€” correct
195
+ for an outage, catastrophic here, because the user would be told the change was saved. A
196
+ distinct type falls through every one of them to this handler.
197
+ """
198
+ return JSONResponse(
199
+ {"error": {"code": "store_write_refused",
200
+ "message": f"this deployment may not write the tenant store. No change was "
201
+ f"saved. {exc}"}},
202
+ status_code=503)
203
+
204
+
205
+ @app.exception_handler(store.StoreConflict)
206
+ def _store_conflict(request: Request, exc: store.StoreConflict):
207
+ """D-305 β€” the document moved under this write more times than it could be rebased. 503.
208
+
209
+ ⚠ 503 RATHER THAN 409, DELIBERATELY. A 409 invites the client to resolve a conflict, and there
210
+ is nothing here for it to resolve: the store already re-read and re-applied this change up to
211
+ `_MAX_REBASE` times before giving up. What the caller needs to know is that the write did not
212
+ land and nothing was damaged, which is the same contract as the outage above and the same
213
+ retry-later shape. β›” The one answer this must never be is 200: reaching this handler means the
214
+ only way to have "succeeded" was to overwrite somebody else's work.
215
+ """
216
+ return JSONResponse(
217
+ {"error": {"code": "store_conflict",
218
+ "message": f"somebody else changed this database while your change was being "
219
+ f"saved, and it could not be merged. Nothing was saved or "
220
+ f"overwritten. Try again. {exc}"}},
221
+ status_code=503)
222
+
223
+
224
  @app.get("/api/health")
225
  def health():
226
  """Unauthenticated LIVENESS only β€” it must answer before anyone can sign in, so it may not
api/routes_admin.py CHANGED
@@ -972,6 +972,31 @@ def put_perms(username: str, body: dict = Body(default=None),
972
  "perms_v": int(rec.get("perms_v") or 0)}
973
 
974
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
975
  @router.get("/settings")
976
  def settings(session: Session = Depends(require_session)):
977
  """The session's OWN settings β€” any authenticated user, not admin-only.
@@ -1000,6 +1025,20 @@ def settings(session: Session = Depends(require_session)):
1000
  },
1001
  "tenant": {"key": session.tenant, "name": getattr(session.runtime, "name",
1002
  session.tenant)},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1003
  # CHROME ONLY. Every /admin route re-checks the role server-side; this exists so the client
1004
  # does not paint a "Manage users" button that 403s.
1005
  "admin": perms.is_admin(session.user),
 
972
  "perms_v": int(rec.get("perms_v") or 0)}
973
 
974
 
975
+ def _store_binding(session):
976
+ """`data_binding.describe()` for the store THIS SESSION's tenant actually writes.
977
+
978
+ ⭐ THE TENANT'S STORE, NOT THE PROCESS DEFAULT, AND THAT DISTINCTION IS THE POINT. Tenant #0
979
+ rides `core.store`'s module default, but nurilab/gtmlab/loopable are bound to their OWN dataset
980
+ repos by `harness/runtime.py:470`, straight out of the control-plane record β€” which is the path
981
+ that carried three tenants' PRODUCTION stores onto staging while `--data-repo` isolated only
982
+ tenant #0. Reporting the process default here would show "staging store, all fine" to exactly
983
+ the tenants that were not fine.
984
+
985
+ ⚠ Degrades to a stated `unknown` rather than raising: a settings page that 500s because it
986
+ could not describe the store is worse than one that says it does not know.
987
+ """
988
+ try:
989
+ import core.data_binding as data_binding # noqa: PLC0415
990
+ import core.store as store # noqa: PLC0415
991
+ bound = getattr(session.runtime, "store_handle", None)
992
+ repo = getattr(bound, "repo", None) or store.REPO
993
+ return data_binding.describe(repo)
994
+ except Exception as e: # noqa: BLE001
995
+ return {"deployment": "unknown", "production": False, "repo": "",
996
+ "writable": False, "refusal": f"could not resolve the store binding: {e}",
997
+ "localOverride": False, "allowlist": [], "observed": {}}
998
+
999
+
1000
  @router.get("/settings")
1001
  def settings(session: Session = Depends(require_session)):
1002
  """The session's OWN settings β€” any authenticated user, not admin-only.
 
1025
  },
1026
  "tenant": {"key": session.tenant, "name": getattr(session.runtime, "name",
1027
  session.tenant)},
1028
+ # ⭐⭐ D-315 β€” WHICH STORE THIS CONTAINER IS BOUND TO, AND WHETHER IT MAY WRITE IT.
1029
+ #
1030
+ # β›” THIS IS NOT DIAGNOSTIC GARNISH; IT IS THE ONLY WAY THE QUESTION CAN BE ANSWERED.
1031
+ # D-160 established that a Space's environment cannot be read from outside, so "is staging
1032
+ # pointed at production data?" is a question only the container can answer β€” and it went
1033
+ # unanswered for the whole window in which two builds wrote tenant #0's real store.
1034
+ # `verify_live` asserts this field after logging in, which is a check that survives a role
1035
+ # swap in a way that reading a deploy log never did.
1036
+ #
1037
+ # ⚠ Session-gated, beside `version`, for `main.py::health`'s reason: a Space id and a
1038
+ # dataset repo id are public names, but a health endpoint is the first URL a scanner finds
1039
+ # and it may not describe the deployment. No customer data is here β€” only which store, and
1040
+ # yes or no.
1041
+ "store": _store_binding(session),
1042
  # CHROME ONLY. Every /admin route re-checks the role server-side; this exists so the client
1043
  # does not paint a "Manage users" button that 403s.
1044
  "admin": perms.is_admin(session.user),
platform/core/data_binding.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WHICH STORE THIS DEPLOYMENT IS ALLOWED TO WRITE β€” the fail-closed binding (D-315 / D-298).
2
+
3
+ β›”β›” THE SENTENCE THIS FILE EXISTS TO MAKE IMPOSSIBLE. Owner, 2026-08-18, verbatim: *"this is so
4
+ critical that whenever we do staging, we don't fuck up anyone's data. EVER."* It had already
5
+ happened once: `fsanyoto/loopable` became STAGING on 2026-08-14 having never been given a store of
6
+ its own, so two different builds wrote tenant #0's real business data. Compose that with D-305
7
+ (the store is last-write-wins at whole-document granularity) and a routine staging deploy does not
8
+ merely add test rows β€” it can erase a real user's views, fields and typed cell values.
9
+
10
+ β›” A DEPLOY FLAG IS NOT THE FIX; THE FLAG IS THE THING THAT ALREADY FAILED. The isolation that
11
+ existed was bound to a ROLE ("the staging Space"), and a guard bound to a role stops guarding the
12
+ moment the role moves β€” which these two Spaces have done twice. So the binding here is on the
13
+ container's OWN IDENTITY, which no deploy can forget to pass and no role swap can invalidate.
14
+
15
+ ⭐⭐ THE RULE, AND IT CLASSIFIES THE DEPLOYMENT RATHER THAN THE REPO:
16
+
17
+ 1. the PRODUCTION deployment (identity in `PRODUCTION_SPACES`) -> may write anything
18
+ 2. any other deployment writing a KNOWN production store -> REFUSED
19
+ 3. any other deployment writing a repo on its OWN allowlist -> allowed
20
+ 4. anything else -> REFUSED
21
+
22
+ β›” WHY NOT CLASSIFY THE REPO, which is the design everybody reaches for first. A DENYLIST of
23
+ production stores fails OPEN for the next tenant nobody remembered to add. A SUFFIX RULE
24
+ (`*-staging-data`) pins a SPELLING rather than a claim β€” see [[gate-pins-a-spelling-not-a-claim]] β€”
25
+ and a store named without the suffix is unprotected while reading as protected. Rule 4 is the one
26
+ that survives a tenant nobody has provisioned yet: an unknown repo is refused, so a store this
27
+ deployment was never handed cannot be written by accident.
28
+
29
+ ⭐⭐ AND RULE 4 IS NOT THEORETICAL β€” IT IS THE HALF OF D-315 THE REGISTER ROW DID NOT KNOW ABOUT.
30
+ Measured 2026-08-18 by reading both control planes: `royal-imports/cfo-os-staging-data`'s own
31
+ `tenants.json` is byte-identical to live's and names **`royal-imports/aios-nurilab-data`,
32
+ `aios-gtmlab-data` and `aios-loopable-data`** β€” the three other tenants' REAL stores. So
33
+ `--data-repo=` only ever isolated tenant #0; `harness/runtime.py`'s `store.for_repo(repo)` path
34
+ resolved three PRODUCTION repos out of the staging store and wrote them, and no flag has ever
35
+ touched that path. The exposure is FOUR production stores, not one.
36
+
37
+ ⚠ READS ARE NOT REFUSED, AND THAT IS A DELIBERATE, STATED SCOPE DECISION. `Store.get` is lenient
38
+ by contract: a refused read would hand back `{}`, a caller would paint an empty grid, and the whole
39
+ Space would read as "no data" rather than as "refused" β€” the exact
40
+ [[empty-answer-vs-unfinished-answer]] shape this codebase has shipped before. A refused WRITE is
41
+ loud (503, with the reason). So staging still SEES production data when pointed at it; it can no
42
+ longer CHANGE it. Narrowing the read is a separate decision and is booked, not smuggled in here.
43
+
44
+ ⚠ ABSENT IDENTITY FAILS CLOSED, AND THE FAILURE LOOKS LIKE AN OUTAGE. If a container exposes none
45
+ of the identity variables, it is treated as "not the production deployment" and every write to a
46
+ production store refuses. That is the safe direction, but on a live Space it would read as a total
47
+ product outage β€” which is why `describe()` reports the RAW observations and not just the verdict:
48
+ per D-160 the Space environment cannot be read from outside, so the container has to say what it
49
+ saw. One deploy then answers "does SPACE_ID exist here", instead of three.
50
+ """
51
+ import os
52
+
53
+ #: The deployment that OWNS production data. A frozenset rather than a string because the product
54
+ #: has had two public addresses before and will again.
55
+ #:
56
+ #: ⚠ THIS SET IS DUPLICATED IN `aios-web/deploy_web.py` AS `PUBLIC_LIVE`, on purpose and with a
57
+ #: gate: `deploy_web` is a standalone CLI that must run without the platform package importable, so
58
+ #: it cannot import this. `verify_store_binding.py::section_constants` asserts the two literals
59
+ #: agree β€” a constant two features share is a constant that drifts ([[constant-two-features-share]]).
60
+ PRODUCTION_SPACES = frozenset({'fsanyoto/runloopable'})
61
+
62
+ #: The stores that hold REAL customer business data. Enumerated 2026-08-18 from the live control
63
+ #: plane (`royal-imports/cfo-os-data::tenants.json`), not guessed.
64
+ #:
65
+ #: β›” THIS LIST IS RULE 2, NOT THE WHOLE GUARD. It exists to make a DELIBERATE mis-pointing loud β€”
66
+ #: `OS_DATA_REPO=royal-imports/cfo-os-data` typed on a laptop, or a production repo added to a
67
+ #: sandbox allowlist by hand. Rule 4 is what covers a tenant provisioned after this line was
68
+ #: written, which is why the file does not depend on this staying complete.
69
+ PRODUCTION_STORES = frozenset({
70
+ 'royal-imports/cfo-os-data', # tenant #0 β€” Royal Imports
71
+ 'royal-imports/aios-nurilab-data', # Nurilab
72
+ 'royal-imports/aios-gtmlab-data', # GTM Lab
73
+ 'royal-imports/aios-loopable-data', # Loopable
74
+ })
75
+
76
+ #: The historical default of `OS_DATA_REPO`. Kept as a name so the resolution below can say what it
77
+ #: is refusing to assume, rather than repeating a literal.
78
+ PRODUCTION_DEFAULT_STORE = 'royal-imports/cfo-os-data'
79
+
80
+ #: The env vars a Hugging Face Space container sets to describe itself, in the order they are
81
+ #: trusted. `SPACE_ID` is the canonical one; the pair is the documented fallback. Read as a LIST so
82
+ #: `describe()` can report every one of them and what it held.
83
+ _IDENTITY_VARS = ('SPACE_ID', 'SPACE_AUTHOR_NAME', 'SPACE_REPO_NAME', 'SPACE_HOST')
84
+
85
+ #: The env a NON-production deployment uses to name the stores it may write, beyond `OS_DATA_REPO`.
86
+ #: Comma-separated.
87
+ #:
88
+ #: ⭐ THE POLARITY IS THE POINT, and it is what keeps trap 1 satisfied. Forgetting to set this
89
+ #: makes a deployment write LESS, never more β€” so an omitted deploy argument is a refusal, not a
90
+ #: silent grant. That is the exact inverse of `--data-repo`, whose omission printed
91
+ #: "OS_DATA_REPO unchanged" and left a Space on production.
92
+ _SANDBOX_STORES_VAR = 'AIOS_SANDBOX_STORES'
93
+
94
+ #: The local (no-identity) escape hatch. Present β‡’ writes to production stores are permitted from a
95
+ #: machine with no Space identity, AND every commit this process makes is stamped distinguishably
96
+ #: (see `local_commit_suffix`). Deliberately does NOT widen a Space: a container that HAS an
97
+ #: identity and is not production is refused with no override, because that is the case the owner
98
+ #: said "EVER" about.
99
+ _LOCAL_OPT_IN_VAR = 'AIOS_ALLOW_PRODUCTION_DATA'
100
+
101
+
102
+ class StoreWriteRefused(RuntimeError):
103
+ """A write this deployment is not allowed to make.
104
+
105
+ β›” DELIBERATELY NOT A SUBCLASS OF `grid_events.StoreUnavailable`, and the reason is the routes.
106
+ Several of them carry `except StoreUnavailable:` blocks that DEGRADE to a session-scoped
107
+ fallback workspace β€” correct for an outage, catastrophic for a refusal, because the user would
108
+ be told the change was saved somewhere. A distinct type falls through all of them to the
109
+ app-level handler, which answers 503 with the reason and never claims a save.
110
+ """
111
+
112
+
113
+ def _env(name):
114
+ return str(os.environ.get(name) or '').strip()
115
+
116
+
117
+ def deployment_id():
118
+ """This container's own identity, or `''` when it is not a Space (i.e. local dev).
119
+
120
+ ⚠ NOT DERIVED FROM ANY DEPLOY ARGUMENT. That is the whole design: `SPACE_ID` is set by the
121
+ platform inside the container, so it cannot be forgotten, mistyped, or left behind by a Space
122
+ that changed role without being redeployed.
123
+ """
124
+ sid = _env('SPACE_ID')
125
+ if sid:
126
+ return sid
127
+ author, repo = _env('SPACE_AUTHOR_NAME'), _env('SPACE_REPO_NAME')
128
+ if author and repo:
129
+ return f'{author}/{repo}'
130
+ return ''
131
+
132
+
133
+ def is_production_deployment():
134
+ """True only on the deployment that owns production data. Unknown β‡’ False (fail closed)."""
135
+ return deployment_id() in PRODUCTION_SPACES
136
+
137
+
138
+ def is_space():
139
+ """True when this process is running inside a Space at all.
140
+
141
+ The distinction matters exactly once: a Space that is not production gets NO override, while a
142
+ laptop does. `deployment_id()` conflates them into `''`, so ask separately.
143
+ """
144
+ return bool(deployment_id())
145
+
146
+
147
+ def sandbox_allowlist():
148
+ """The repos a non-production deployment may write: `OS_DATA_REPO` + `AIOS_SANDBOX_STORES`."""
149
+ allowed = {r.strip() for r in _env(_SANDBOX_STORES_VAR).split(',') if r.strip()}
150
+ own = _env('OS_DATA_REPO')
151
+ if own:
152
+ allowed.add(own)
153
+ return frozenset(allowed)
154
+
155
+
156
+ def local_override():
157
+ """True when a machine with no Space identity has explicitly opted in to production data."""
158
+ return (not is_space()) and _env(_LOCAL_OPT_IN_VAR) == '1'
159
+
160
+
161
+ def default_store():
162
+ """What `OS_DATA_REPO` resolves to when it is unset.
163
+
164
+ β›”β›” FACT (1) OF D-315 DIES HERE: `core/store.py` used to read
165
+ `os.environ.get('OS_DATA_REPO', 'royal-imports/cfo-os-data')`, so a Space that was never given
166
+ the key β€” every NEW Space, by construction β€” came up bound to tenant #0's real business data.
167
+ The default now exists ONLY on the deployment that owns it.
168
+
169
+ ⚠ IT STILL RETURNS THE PRODUCTION ID ELSEWHERE, RATHER THAN `None` OR `''`, AND THAT IS
170
+ DELIBERATE. A `None` repo would make `Store.__init__` β€” which runs at IMPORT time via
171
+ `_DEFAULT = for_repo(REPO)` β€” raise or bind something nonsensical, killing the app and every
172
+ gate on any non-production machine. Returning the real id keeps binding total and lets
173
+ `write_refusal` refuse the WRITE with a message that names the actual problem. Reads still
174
+ work, so a developer sees a populated app that will not let them damage it.
175
+ """
176
+ return PRODUCTION_DEFAULT_STORE
177
+
178
+
179
+ def write_refusal(repo):
180
+ """`None` if this deployment may write `repo`, else the sentence explaining why not.
181
+
182
+ ⭐ RETURNS A REASON RATHER THAN A BOOL, because [[report-the-cause-before-you-fix-it]]: a
183
+ silent refusal makes every theory about it unfalsifiable, and this one fires on a path where
184
+ the operator cannot read the container's environment (D-160).
185
+ """
186
+ rid = str(repo or '').strip()
187
+ if not rid:
188
+ return ('no store repo is bound. Refusing to guess: an unnamed store is how a deployment '
189
+ 'ends up on somebody else\'s data.')
190
+ if is_production_deployment():
191
+ return None # rule 1 β€” the live Space owns its data
192
+ if rid in PRODUCTION_STORES: # rule 2 β€” never, from anywhere else
193
+ if local_override():
194
+ return None
195
+ who = deployment_id() or 'this machine (no Space identity)'
196
+ if is_space():
197
+ return (f'{who} is not the production deployment, so it may not write {rid}, which '
198
+ f'holds real customer data. Point this Space at its own store with '
199
+ f'--data-repo=, or add it to {_SANDBOX_STORES_VAR}. There is no override for '
200
+ f'a Space: a build that is not live never writes live data.')
201
+ return (f'{who} may not write {rid}, which holds real customer data. Set OS_DATA_REPO to a '
202
+ f'sandbox store, or set {_LOCAL_OPT_IN_VAR}=1 to opt in deliberately (every commit '
203
+ f'is then stamped as a local write so it can be told apart afterwards).')
204
+ allow = sandbox_allowlist() # rule 3 β€” what it was explicitly handed
205
+ if rid in allow:
206
+ return None
207
+ who = deployment_id() or 'this machine (no Space identity)'
208
+ listed = ', '.join(sorted(allow)) or '(nothing)'
209
+ return (f'{who} was not given {rid}. A non-production deployment may write only the stores it '
210
+ f'was handed: {listed}. Add it to {_SANDBOX_STORES_VAR} if that is intended.')
211
+
212
+
213
+ def check_write(repo, operation='write'):
214
+ """Raise `StoreWriteRefused` unless this deployment may write `repo`. The one enforcement door."""
215
+ reason = write_refusal(repo)
216
+ if reason:
217
+ raise StoreWriteRefused(f'{operation} to {repo!r} refused: {reason}')
218
+
219
+
220
+ def local_commit_suffix():
221
+ """A marker appended to commit messages made under the local override, else `''`.
222
+
223
+ ⭐ THIS IS THE SECOND HALF OF D-298's EXIT CONDITION, satisfied rather than argued around: *"a
224
+ local run either cannot reach the live store without an explicit opt-in, OR stamps its commits
225
+ distinguishably"*. The measured complaint was that a laptop's commits were titled
226
+ `update user_tables` β€” byte-identical to what the live Space writes every few minutes β€” so a
227
+ local run and production were indistinguishable in the store's git history, which is the ONLY
228
+ audit trail this product has. Both clauses now hold: the opt-in is required AND it stamps.
229
+ """
230
+ if not local_override():
231
+ return ''
232
+ import getpass # noqa: PLC0415 β€” only on the opt-in path
233
+ import socket # noqa: PLC0415
234
+ try:
235
+ who = getpass.getuser()
236
+ except Exception: # noqa: BLE001
237
+ who = 'unknown'
238
+ try:
239
+ host = socket.gethostname()
240
+ except Exception: # noqa: BLE001
241
+ host = 'unknown'
242
+ return f' [LOCAL DEV {who}@{host}]'
243
+
244
+
245
+ def describe(repo=None):
246
+ """What this container sees about itself β€” the payload behind the status field.
247
+
248
+ β›” IT REPORTS THE RAW OBSERVATIONS, NOT ONLY THE VERDICT, and that is the point rather than
249
+ debug noise. D-160 established that a Space's environment cannot be read from outside, so
250
+ "is staging on the right store?" is a question only the container can answer. A verdict alone
251
+ ("production: false") cannot distinguish "SPACE_ID says staging" from "SPACE_ID does not exist
252
+ on this platform at all" β€” two states with the same verdict and completely different fixes.
253
+ Reporting the variables makes ONE deploy answer it.
254
+
255
+ ⚠ Carries no secret: a Space id and a dataset repo id are public names. The DATA is not, and
256
+ none of it is here. The field is session-gated anyway (see `routes_admin.settings`).
257
+ """
258
+ rid = str(repo or '').strip()
259
+ return {
260
+ 'deployment': deployment_id(),
261
+ 'production': is_production_deployment(),
262
+ 'repo': rid,
263
+ 'writable': write_refusal(rid) is None if rid else False,
264
+ 'refusal': write_refusal(rid) if rid else None,
265
+ 'localOverride': local_override(),
266
+ 'allowlist': sorted(sandbox_allowlist()),
267
+ # The raw half. `''` means "the variable is absent", which is itself the answer on a
268
+ # platform that does not set it.
269
+ 'observed': {name: _env(name) for name in _IDENTITY_VARS},
270
+ }
platform/core/store.py CHANGED
@@ -27,12 +27,35 @@ except Exception:
27
  pass
28
 
29
  from huggingface_hub import HfApi, hf_hub_download
30
- from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError
31
-
32
- REPO = os.environ.get('OS_DATA_REPO', 'royal-imports/cfo-os-data')
 
 
 
 
 
 
 
 
 
33
  _FLUSH_DELAY = 2.0 # coalesce a burst of edits into one commit
34
  _FLUSH_MIN_GAP = 20.0 # floor between commits of one key (the 256-commits/hr budget)
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  #: WAVE 29 (item 20 / ruling R11, contract C6) β€” THE CHANGE TOKEN'S PROCESS STAMP.
37
  #:
38
  #: `Store`'s revision counter is IN-MEMORY, so a restarted Space would begin again at 0 and a
@@ -48,6 +71,51 @@ def _token():
48
  return os.environ.get('HF_TOKEN') or None
49
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  class _Projected(dict):
52
  """One top-level value of a PROJECTED read β€” a dict that RAISES for the keys that were dropped.
53
 
@@ -177,23 +245,51 @@ class Store:
177
  self._key_locks = {}
178
  self._key_locks_guard = threading.Lock()
179
  self._rev_at = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  def available(self):
182
  """True when a token is configured β€” callers degrade gracefully without one."""
183
  return bool(_token())
184
 
185
  def _download(self, name):
186
- """Parse {name}.json into a dict. Returns {} ONLY when the file is genuinely absent.
187
  Any other failure (network, auth, rate-limit, corrupt JSON) RAISES β€” a transient read
188
  error must never be mistaken for an empty store, or a caller could overwrite real data
189
- with an empty dict (this is what wiped the user registry on restart)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  try:
191
  path = hf_hub_download(self.repo, f'{name}.json', repo_type='dataset',
192
  token=_token(), force_download=True)
193
  with open(path, encoding='utf-8') as f:
194
- return json.load(f)
195
  except (EntryNotFoundError, RepositoryNotFoundError, FileNotFoundError):
196
- return {}
197
  except ValueError as e:
198
  # Wave 18 (R2, found by SESSION D): current huggingface_hub wraps a missing REPO in
199
  # ValueError("Force download failed…") with the 404 as __cause__ β€” so a brand-new
@@ -201,7 +297,7 @@ class Store:
201
  # A genuinely-absent repo is the same fact as a genuinely-absent file: {}.
202
  cause = getattr(e, '__cause__', None)
203
  if isinstance(cause, (EntryNotFoundError, RepositoryNotFoundError)):
204
- return {}
205
  raise
206
 
207
  def get(self, name, fresh=False):
@@ -212,7 +308,7 @@ class Store:
212
  if not fresh and name in self._cache:
213
  return json.loads(json.dumps(self._cache[name])) # hand back a copy
214
  try:
215
- data = self._download(name)
216
  except Exception as e:
217
  try: # lazy import β€” core stays layer-clean
218
  import harness.telemetry as _tel # noqa: PLC0415
@@ -224,6 +320,10 @@ class Store:
224
  return json.loads(json.dumps(self._cache[name]))
225
  return {}
226
  self._cache[name] = data
 
 
 
 
227
  return json.loads(json.dumps(data))
228
 
229
  def get_projection(self, name, drop=()):
@@ -263,7 +363,7 @@ class Store:
263
  if name in self._cache:
264
  return _project(self._cache[name], drop)
265
  try:
266
- data = self._download(name)
267
  except Exception as e:
268
  try: # lazy import β€” core stays layer-clean
269
  import harness.telemetry as _tel # noqa: PLC0415
@@ -277,6 +377,7 @@ class Store:
277
  return {}
278
  with self._lock:
279
  self._cache[name] = data # β›” the WHOLE document, never the projection
 
280
  return _project(data, drop)
281
 
282
  def _key_lock(self, name):
@@ -301,15 +402,25 @@ class Store:
301
  So the dirty mark is re-read AFTER the download, under the short lock, and a key that
302
  became dirty keeps its cache.
303
  """
304
- data = self._download(name) # network, no lock held
305
  with self._lock:
306
  if self._dirty.get(name) and self._owned.get(name) and name in self._cache:
307
- # Our copy is stale by construction: a pending upload is going to overwrite the
308
- # hub anyway, so the fresh read cannot preserve a remote write β€” it can only
309
- # destroy a local one we have already acknowledged. Same argument, and the same
310
- # three conditions, as `update`'s pending-async branch below.
 
 
 
 
 
 
 
 
 
311
  return json.loads(json.dumps(self._cache[name]))
312
  self._cache[name] = data
 
313
  return json.loads(json.dumps(data))
314
 
315
  def exists(self, name):
@@ -366,30 +477,199 @@ class Store:
366
  at = self._rev_at.get(n)
367
  return {'rev': rev, 'updated_at': at, 'token': f'{REV_EPOCH}:{rev}'}
368
 
369
- def _upload(self, name, data):
370
- """The raw hub write. create_repo is confirmed ONCE per instance β€” it was a full extra
371
- API round-trip on every put(), pure latency after the first success."""
372
- api = HfApi(token=_token())
 
 
 
373
  if not self._repo_ok:
374
- api.create_repo(self.repo, repo_type='dataset', private=True, exist_ok=True)
 
375
  self._repo_ok = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  buf = io.BytesIO(json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8'))
377
- api.upload_file(path_or_fileobj=buf, path_in_repo=f'{name}.json', repo_id=self.repo,
378
- repo_type='dataset', commit_message=f'update {name}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
 
380
  def upload_bytes(self, path_in_repo, data, message=None):
381
  """Persist RAW BYTES at an arbitrary path in the tenant dataset (wave-8 C5, documents).
382
  Bytes are never cached in-process: large, cold, fetched on explicit user action."""
383
  if not self.available():
384
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
 
 
 
 
 
385
  with self._lock:
386
- api = HfApi(token=_token())
387
- if not self._repo_ok:
388
- api.create_repo(self.repo, repo_type='dataset', private=True, exist_ok=True)
389
- self._repo_ok = True
390
- api.upload_file(path_or_fileobj=io.BytesIO(data), path_in_repo=path_in_repo,
391
- repo_id=self.repo, repo_type='dataset',
392
- commit_message=message or f'add {path_in_repo}')
393
 
394
  def download_bytes(self, path_in_repo):
395
  """Raw bytes back, or None when absent/unreachable β€” a missing attachment degrades to
@@ -406,13 +686,20 @@ class Store:
406
  return None
407
 
408
  def delete_path(self, path_in_repo):
409
- """Remove a stored file. Absent is SUCCESS β€” deleting what is already gone is the goal."""
 
 
 
 
 
 
410
  if not self.available():
411
  return False
 
412
  try:
413
- HfApi(token=_token()).delete_file(path_in_repo=path_in_repo, repo_id=self.repo,
414
- repo_type='dataset',
415
- commit_message=f'delete {path_in_repo}')
416
  return True
417
  except (EntryNotFoundError, RepositoryNotFoundError):
418
  return True
@@ -420,16 +707,44 @@ class Store:
420
  return False
421
 
422
  def put(self, name, data):
423
- """Persist {name}.json (creates the private repo on first write). Updates the cache."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
  if not self.available():
425
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
426
- with self._lock:
427
- self._upload(name, data)
428
- self._cache[name] = json.loads(json.dumps(data))
429
- self._owned[name] = True
430
- self._last_flush[name] = _time.monotonic()
431
- self._bump(name) # C6 β€” AFTER the upload: a raise here is not a write
432
- return self._cache[name]
 
 
 
 
 
 
 
433
 
434
  def _flush_worker(self, name):
435
  """Coalescing uploader for one key. Runs while dirty; retries with backoff on failure β€”
@@ -454,11 +769,17 @@ class Store:
454
  this must too; taking `self._lock` first on this path is the deadlock. Both sleeps stay
455
  OUTSIDE the key lock β€” a worker that dozed while holding it would block every writer of
456
  that key for `_FLUSH_MIN_GAP`, which is the freeze this ticket exists to remove.
 
 
 
 
 
 
457
  """
458
  backoff = 2.0
459
  while True:
460
  _time.sleep(_FLUSH_DELAY)
461
- wait, err, snapshot = None, None, None
462
  with self._key_lock(name):
463
  with self._lock:
464
  gap = _time.monotonic() - self._last_flush.get(name, 0.0)
@@ -470,10 +791,17 @@ class Store:
470
  else:
471
  self._dirty[name] = False
472
  snapshot = json.loads(json.dumps(self._cache.get(name, {})))
 
 
 
473
  if wait is None:
474
  try:
475
- self._upload(name, snapshot)
476
  with self._lock:
 
 
 
 
477
  self._last_flush[name] = _time.monotonic()
478
  backoff = 2.0
479
  except Exception as e: # noqa: BLE001
@@ -528,15 +856,28 @@ class Store:
528
  finish, so waiting for its key lock could only turn a partial save into no save at all.
529
  Best-effort is the correct contract here, and it is the one case where taking the lock
530
  would be worse than skipping it.
 
 
 
 
 
 
531
  """
532
  with self._lock:
533
  dirty = [k for k, v in self._dirty.items() if v]
534
  snaps = {k: json.loads(json.dumps(self._cache.get(k, {}))) for k in dirty}
 
535
  for k in dirty:
536
  self._dirty[k] = False
537
  for k, d in snaps.items():
538
  try:
539
- self._upload(k, d)
 
 
 
 
 
 
540
  except Exception:
541
  pass # exiting anyway β€” nothing left to reschedule
542
 
@@ -549,9 +890,19 @@ class Store:
549
  returns immediately; a coalescing worker commits. The strict read still guards the
550
  FIRST async update of a key per process.
551
 
 
 
 
 
 
 
 
 
 
 
552
  ⭐⭐ W31-T13 (D-177(d)) β€” TWO LOCKS, AND THE SPLIT IS THE WHOLE TICKET.
553
  `self._key_lock(name)` is held for the entire read-modify-write, so two writers of one key
554
- still cannot interleave (last-write-wins is the contract; a lost update is not).
555
  `self._lock` β€” the one every `get()` takes β€” is now held only for the microseconds a cache
556
  read or write needs, never across a download or an upload. Before this, one sync write
557
  froze every reader in the process for two network round trips, on a store whose warm
@@ -559,6 +910,13 @@ class Store:
559
  ⚠ Uploading outside `self._lock` is not a new posture: `_flush_worker` has done exactly
560
  that since wave 7, and `_repo_ok` racing is benign because `create_repo` is `exist_ok=True`.
561
  """
 
 
 
 
 
 
 
562
  with self._key_lock(name):
563
  return self._update_locked(name, fn, flush)
564
 
@@ -617,6 +975,15 @@ class Store:
617
  result = fn(data)
618
  data = result if result is not None else data
619
 
 
 
 
 
 
 
 
 
 
620
  if flush == 'async':
621
  if not self.available():
622
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
@@ -627,21 +994,24 @@ class Store:
627
  self._schedule_flush(name)
628
  return data
629
 
630
- # β›” THE SYNC COMMIT, SPELLED OUT HERE RATHER THAN THROUGH `put()`, AND THAT IS A CHOICE.
631
- # `put()` holds `self._lock` across its own `_upload` β€” which is exactly the freeze this
632
- # ticket removes β€” but it is PUBLIC with seven callers outside this file (`users.py`,
633
- # `modules/ar.py`, `modules/map.py`, `runtime.py`, `store_backend.py`,
634
- # `ops/seed_pg_from_hf.py`), and changing its locking changes all of their concurrency
635
- # semantics at once. Duplicating four assignments with this comment beside them is the
636
- # smaller blast radius; if `put` is ever split, this collapses back into a call.
637
  if not self.available():
638
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
639
- self._upload(name, data) # network, no cache lock held
640
  with self._lock:
641
- self._cache[name] = json.loads(json.dumps(data))
 
 
 
642
  self._owned[name] = True
643
  self._last_flush[name] = _time.monotonic()
644
- # β›” AFTER THE UPLOAD, NEVER BEFORE β€” `put()`'s own law. `_upload` raises on failure,
645
  # and a bump on that path would have `revision()` report a change that never landed.
646
  self._bump(name)
647
  # The upload above CARRIED whatever was pending, so the key is no longer ahead of
@@ -650,9 +1020,9 @@ class Store:
650
  # ⚠ AFTER the upload, for the same reason: on a raise the mark MUST survive (the cache
651
  # is still the truth and the row must still be committed by the worker). Clearing it
652
  # first would turn a transient upload error into the very silent loss the branch above
653
- # exists to stop β€” which is why it sits here and not before `_upload`.
654
  self._dirty[name] = False
655
- return data
656
 
657
 
658
  # ------------------------------------------------------------------- instances + module API
 
27
  pass
28
 
29
  from huggingface_hub import HfApi, hf_hub_download
30
+ from huggingface_hub.utils import (EntryNotFoundError, HfHubHTTPError,
31
+ RepositoryNotFoundError)
32
+
33
+ import core.data_binding as data_binding
34
+
35
+ #: β›”β›” D-315 β€” THE BARE DEFAULT IS GONE. This line used to read
36
+ #: `os.environ.get('OS_DATA_REPO', 'royal-imports/cfo-os-data')`, i.e. every Space that was never
37
+ #: handed the key came up bound to tenant #0's REAL business data β€” which is how two different
38
+ #: builds wrote it on 2026-08-14. The value it resolves to is unchanged (see
39
+ #: `data_binding.default_store` for why returning the real id beats `None`); what changed is that
40
+ #: WRITING it is now refused unless this deployment is the one that owns it.
41
+ REPO = os.environ.get('OS_DATA_REPO') or data_binding.default_store()
42
  _FLUSH_DELAY = 2.0 # coalesce a burst of edits into one commit
43
  _FLUSH_MIN_GAP = 20.0 # floor between commits of one key (the 256-commits/hr budget)
44
 
45
+ #: ⭐⭐ D-305 β€” HOW MANY TIMES A WRITE MAY REBASE ONTO A MOVED HEAD BEFORE GIVING UP.
46
+ #:
47
+ #: Bounded rather than unbounded, and the cost is one extra DOWNLOAD per rebase. ⚠ Not an extra
48
+ #: commit: a refused write answers 412 and creates nothing, so only the attempt that finally lands
49
+ #: spends the 256-commits/hr budget. Four is generous for the measured case
50
+ #: (two humans editing one grid) and small enough that a genuinely hot key fails loudly instead of
51
+ #: spinning. β›” Hitting the bound RAISES β€” it never falls through to an unconditional upload, which
52
+ #: is the pre-fix behaviour wearing a retry loop ([[fallback-that-became-the-rule]]).
53
+ _MAX_REBASE = 4
54
+
55
+ #: How many unconfirmed intents one key may hold before the oldest are dropped. See
56
+ #: `_journal_append` for why a cap exists at all and what is reported when it bites.
57
+ _MAX_JOURNAL = 500
58
+
59
  #: WAVE 29 (item 20 / ruling R11, contract C6) β€” THE CHANGE TOKEN'S PROCESS STAMP.
60
  #:
61
  #: `Store`'s revision counter is IN-MEMORY, so a restarted Space would begin again at 0 and a
 
71
  return os.environ.get('HF_TOKEN') or None
72
 
73
 
74
+ class StoreConflict(RuntimeError):
75
+ """A write that could not be landed without overwriting somebody else's (D-305).
76
+
77
+ Raised only after `_MAX_REBASE` rebases, or when no parent commit can be resolved at all. Both
78
+ are "we could not make this safe", and both must reach the caller as a failure: the alternative
79
+ β€” uploading anyway β€” is exactly the lost update this whole mechanism exists to prevent, and it
80
+ would answer 200 while destroying an hour of another person's work.
81
+ """
82
+
83
+
84
+ def _is_conflict(exc):
85
+ """True for the ONE hub failure that means "the branch moved under you".
86
+
87
+ β›” NARROW ON PURPOSE, AND THE PROBE IS WHY. Measured against a scratch dataset repo on
88
+ 2026-08-18: a stale `parent_commit` returns **HTTP 412** with the server message *"The branch
89
+ was updated since you opened this page. Please refresh and try again."*, and the write does NOT
90
+ land. A NONSENSE `parent_commit` returns a **404 `RevisionNotFoundError`** β€” a different fault
91
+ that must not be retried, because rebasing on it would loop against a bad sha. A broad
92
+ `except HfHubHTTPError` would swallow both, plus every 401/429/500, and turn a network blip
93
+ into a silent rebase.
94
+ """
95
+ return getattr(getattr(exc, 'response', None), 'status_code', None) == 412
96
+
97
+
98
+ def _sha_from_path(path):
99
+ """The commit sha out of a hub cache path, or `None` if it does not look like one.
100
+
101
+ ⚠ VALIDATED, NOT ASSUMED. The layout is `…/snapshots/<40-hex>/<file>`, but a caller may have
102
+ an unusual `HF_HOME`, symlinks disabled (this repo's own machines warn about exactly that), or
103
+ a future hub version. A directory name that is not a 40-character hex sha is reported as "I do
104
+ not know", which routes the write through the explicit head lookup β€” the safe branch. Returning
105
+ a bad sha would surface as a 404 `RevisionNotFoundError` on every write instead.
106
+ """
107
+ try:
108
+ parent = Path(path).parent
109
+ if parent.parent.name != 'snapshots':
110
+ return None
111
+ name = parent.name
112
+ if len(name) == 40 and all(c in '0123456789abcdef' for c in name.lower()):
113
+ return name
114
+ except Exception: # noqa: BLE001
115
+ pass
116
+ return None
117
+
118
+
119
  class _Projected(dict):
120
  """One top-level value of a PROJECTED read β€” a dict that RAISES for the keys that were dropped.
121
 
 
245
  self._key_locks = {}
246
  self._key_locks_guard = threading.Lock()
247
  self._rev_at = {}
248
+ # --- ⭐⭐ D-305 β€” THE TWO FIELDS THAT MAKE A CROSS-PROCESS WRITE SURVIVABLE -----------
249
+ # `_base[name]` the hub commit sha this key's cached document was built ON. Learned for
250
+ # free from the download path and from `CommitInfo.oid` after a write, so
251
+ # it costs no extra round trip in the common case.
252
+ # `_journal[name]` the `fn`s applied to this key since the last CONFIRMED upload β€” our
253
+ # INTENT, not our result. On a conflict the intent is replayed onto the
254
+ # hub's newer document instead of the result being uploaded over it.
255
+ #
256
+ # β›” WHY A JOURNAL AND NOT A RETRY. The writers here are DIFFERENT PEOPLE in DIFFERENT
257
+ # CONTAINERS, and this instance's cache holds an hour of its own edits over a base that has
258
+ # moved. Re-uploading that snapshot β€” which is what a retry does β€” reproduces the loss
259
+ # exactly. Replaying "add this view" onto the fresher document keeps both writers' work,
260
+ # which is the only outcome that answers the defect.
261
+ self._base = {}
262
+ self._journal = {}
263
 
264
  def available(self):
265
  """True when a token is configured β€” callers degrade gracefully without one."""
266
  return bool(_token())
267
 
268
  def _download(self, name):
269
+ """`(document, commit_sha)` for {name}.json. `({}, None)` ONLY when it is genuinely absent.
270
  Any other failure (network, auth, rate-limit, corrupt JSON) RAISES β€” a transient read
271
  error must never be mistaken for an empty store, or a caller could overwrite real data
272
+ with an empty dict (this is what wiped the user registry on restart).
273
+
274
+ ⭐⭐ D-305 β€” THE SHA COMES FROM THE PATH, WHICH COSTS NOTHING. `hf_hub_download` writes into
275
+ `…/snapshots/<commit sha>/<file>`, so the revision the bytes came from is already in the
276
+ return value. Measured 2026-08-18 against a scratch repo: that directory name equals the
277
+ `CommitInfo.oid` of the commit that wrote the file, and equals
278
+ `get_hf_file_metadata(...).commit_hash` β€” which would have cost an extra HTTP round trip on
279
+ the hottest read in the product. **The parent of our write is therefore known by every
280
+ reader, for free.**
281
+
282
+ ⚠ A sha we cannot parse comes back as `None`, and `_commit` resolves that with an explicit
283
+ head lookup rather than uploading without a precondition. "I do not know my parent" must
284
+ take the careful path, never the fast one.
285
+ """
286
  try:
287
  path = hf_hub_download(self.repo, f'{name}.json', repo_type='dataset',
288
  token=_token(), force_download=True)
289
  with open(path, encoding='utf-8') as f:
290
+ return json.load(f), _sha_from_path(path)
291
  except (EntryNotFoundError, RepositoryNotFoundError, FileNotFoundError):
292
+ return {}, None
293
  except ValueError as e:
294
  # Wave 18 (R2, found by SESSION D): current huggingface_hub wraps a missing REPO in
295
  # ValueError("Force download failed…") with the 404 as __cause__ β€” so a brand-new
 
297
  # A genuinely-absent repo is the same fact as a genuinely-absent file: {}.
298
  cause = getattr(e, '__cause__', None)
299
  if isinstance(cause, (EntryNotFoundError, RepositoryNotFoundError)):
300
+ return {}, None
301
  raise
302
 
303
  def get(self, name, fresh=False):
 
308
  if not fresh and name in self._cache:
309
  return json.loads(json.dumps(self._cache[name])) # hand back a copy
310
  try:
311
+ data, sha = self._download(name)
312
  except Exception as e:
313
  try: # lazy import β€” core stays layer-clean
314
  import harness.telemetry as _tel # noqa: PLC0415
 
320
  return json.loads(json.dumps(self._cache[name]))
321
  return {}
322
  self._cache[name] = data
323
+ # D-305: the cached document and the revision it derives from are set TOGETHER, always.
324
+ # A base that can disagree with the cache it describes is worse than no base at all β€”
325
+ # it would make a stale write look like a fresh one and pass the precondition.
326
+ self._base[name] = sha
327
  return json.loads(json.dumps(data))
328
 
329
  def get_projection(self, name, drop=()):
 
363
  if name in self._cache:
364
  return _project(self._cache[name], drop)
365
  try:
366
+ data, sha = self._download(name)
367
  except Exception as e:
368
  try: # lazy import β€” core stays layer-clean
369
  import harness.telemetry as _tel # noqa: PLC0415
 
377
  return {}
378
  with self._lock:
379
  self._cache[name] = data # β›” the WHOLE document, never the projection
380
+ self._base[name] = sha # D-305 β€” set with the cache, never apart from it
381
  return _project(data, drop)
382
 
383
  def _key_lock(self, name):
 
402
  So the dirty mark is re-read AFTER the download, under the short lock, and a key that
403
  became dirty keeps its cache.
404
  """
405
+ data, sha = self._download(name) # network, no lock held
406
  with self._lock:
407
  if self._dirty.get(name) and self._owned.get(name) and name in self._cache:
408
+ # β›”β›” D-305 REWROTE THIS BRANCH'S JUSTIFICATION, NOT ITS BEHAVIOUR β€” AND THE OLD
409
+ # ONE HAD TO GO, because it asserted the defect. It read: *"a pending upload is
410
+ # going to overwrite the hub anyway, so the fresh read cannot preserve a remote
411
+ # write."* That sentence IS the lost update: "we are going to overwrite whatever
412
+ # the other person did" was stated as a reason to stop worrying about it.
413
+ #
414
+ # ⭐ It is no longer true. A pending upload now carries a `parent_commit`
415
+ # precondition, so it CANNOT overwrite a remote write β€” it will be refused and
416
+ # rebased onto it (`_commit`). The branch survives for its OTHER, still-correct
417
+ # reason: this cache holds an async write nobody has flushed yet, and replacing it
418
+ # with the hub's copy destroys a row we have already answered 201 for (D-177).
419
+ # β‡’ keep the local delta here; preserve the REMOTE work at commit time, which is
420
+ # the only place that can see it.
421
  return json.loads(json.dumps(self._cache[name]))
422
  self._cache[name] = data
423
+ self._base[name] = sha
424
  return json.loads(json.dumps(data))
425
 
426
  def exists(self, name):
 
477
  at = self._rev_at.get(n)
478
  return {'rev': rev, 'updated_at': at, 'token': f'{REV_EPOCH}:{rev}'}
479
 
480
+ def _ensure_repo(self):
481
+ """create_repo is confirmed ONCE per instance β€” it was a full extra API round-trip on
482
+ every put(), pure latency after the first success.
483
+
484
+ Lifted out of `_upload` (D-305) because `_commit` has to resolve a parent commit BEFORE the
485
+ first write, and a repo that does not exist yet has no head to resolve.
486
+ """
487
  if not self._repo_ok:
488
+ HfApi(token=_token()).create_repo(self.repo, repo_type='dataset', private=True,
489
+ exist_ok=True)
490
  self._repo_ok = True
491
+
492
+ def _head_sha(self):
493
+ """The repo's current head commit, or `None` if the repo does not exist yet.
494
+
495
+ ⚠ ONE EXTRA ROUND TRIP, AND IT IS THE COLD PATH ONLY. `_base[name]` is populated by every
496
+ download and by every successful write, so this is reached on a first write into a process
497
+ that has never read the key β€” and on the rebase path, where a round trip is already the
498
+ price of correctness.
499
+ """
500
+ try:
501
+ return HfApi(token=_token()).repo_info(self.repo, repo_type='dataset').sha
502
+ except RepositoryNotFoundError:
503
+ return None
504
+
505
+ def _upload(self, name, data, parent):
506
+ """The raw hub write, WITH A PRECONDITION. Returns the new head commit sha.
507
+
508
+ β›” `parent` IS MANDATORY AND HAS NO DEFAULT, deliberately. A default of `None` would make
509
+ "upload unconditionally" the thing you get by forgetting an argument β€” and unconditional
510
+ upload is precisely D-305. Every caller goes through `_commit`, which is the one place
511
+ allowed to decide what the parent is.
512
+ """
513
+ data_binding.check_write(self.repo, f'write {name!r}') # D-315 backstop, see `update`
514
+ self._ensure_repo()
515
  buf = io.BytesIO(json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8'))
516
+ info = HfApi(token=_token()).upload_file(
517
+ path_or_fileobj=buf, path_in_repo=f'{name}.json', repo_id=self.repo,
518
+ repo_type='dataset',
519
+ # D-298: under the local opt-in this suffix is what makes a laptop's commit
520
+ # distinguishable from the live Space's in the store's git history β€” the only audit
521
+ # trail this product has.
522
+ commit_message=f'update {name}' + data_binding.local_commit_suffix(),
523
+ parent_commit=parent)
524
+ return getattr(info, 'oid', None)
525
+
526
+ def _commit(self, name, data, replay=(), max_rebase=None):
527
+ """Land `data` for `name` without overwriting anyone β€” D-305's whole mechanism.
528
+
529
+ ⭐⭐ THE SHAPE, and every step of it is measured rather than assumed (scratch-repo probe,
530
+ 2026-08-18):
531
+
532
+ 1. upload with `parent_commit = the revision our document was built on`;
533
+ 2. the hub answers **412** if the branch moved β€” and the write does NOT land, so there
534
+ is nothing to undo;
535
+ 3. re-read the head, REPLAY our intent (`replay`, the `fn`s applied since our last
536
+ confirmed upload) onto it, and try again against the new parent;
537
+ 4. after `_MAX_REBASE` attempts, RAISE.
538
+
539
+ ⭐ REPLAYING THE INTENT IS WHAT MAKES THIS DIFFERENT FROM A RETRY. Uploading our snapshot
540
+ again would reproduce the loss; re-applying "add this view" to the newer document keeps
541
+ both writers. The one place it changes an answer is a `fn` that ALLOCATES from the document
542
+ β€” `table_store._unique_name` picks the first free display name β€” which on a rebase may pick
543
+ a different name than the one already handed to the caller. That is a rename where the
544
+ pre-fix behaviour was a DELETION, and the trade is stated rather than hidden.
545
+
546
+ β›” NO PARENT β‡’ RAISE, NEVER UPLOAD BLIND. If neither the cached base nor `_head_sha()` can
547
+ name a revision, the safe answer is "this write cannot be made safe", not "make it the old
548
+ way". A fallback that quietly restores the unguarded path is how a fix becomes decorative
549
+ ([[fallback-that-became-the-rule]]).
550
+
551
+ Returns `(document_that_landed, new_sha)` β€” the document may differ from the one passed in,
552
+ because a rebase rebuilds it.
553
+ """
554
+ data_binding.check_write(self.repo, f'write {name!r}')
555
+ # ⚠ `_ensure_repo()` IS NOT CALLED HERE, and that is a deliberate reversal. It was, for one
556
+ # revision, so that a brand-new repo would have a head to name as a parent β€” and it broke
557
+ # three existing gates, because their fixtures replace `_upload` (which is where
558
+ # `create_repo` has always lived) and suddenly found themselves calling the real hub. The
559
+ # ordering works without it: a repo that does not exist resolves no head and no `exists`,
560
+ # so the first write goes out with `parent=None` and `_upload` creates the repo on its way
561
+ # through, exactly as before.
562
+ budget = _MAX_REBASE if max_rebase is None else int(max_rebase)
563
+ for attempt in range(budget + 1):
564
+ with self._lock:
565
+ parent = self._base.get(name)
566
+ if not parent:
567
+ parent = self._head_sha()
568
+ if not parent:
569
+ # A repo with no commits at all: `_upload` creates it on the way through, so this
570
+ # is the genuinely-first write and there is nothing that could be lost.
571
+ # ⚠ NO EM DASH IN THIS MESSAGE, OR THE ONE BELOW. Both are raised, and a raised
572
+ # store message reaches the client through the 503 handler, which puts them inside
573
+ # STANDING RULE 2's scope ("any Python string returned to the client"). `web_prose`
574
+ # caught exactly these two.
575
+ if self.exists(name):
576
+ raise StoreConflict(
577
+ f'cannot resolve a parent commit for {self.repo}:{name}, so this write '
578
+ f'cannot be made safe. Refusing to upload without a precondition: an '
579
+ f'unconditional write is what silently erases another session\'s work.')
580
+ parent = None
581
+ try:
582
+ oid = self._upload(name, data, parent)
583
+ except HfHubHTTPError as e:
584
+ if not _is_conflict(e):
585
+ raise # 401/404/429/500 β€” a different fault, never a rebase
586
+ if attempt >= budget:
587
+ # β›” THE EXHAUSTED CASE RAISES `StoreConflict`, NOT THE RAW 412, and this gate
588
+ # caught the first version doing the latter. A caller cannot be asked to know
589
+ # that one particular HTTP status out of the hub means "your change was not
590
+ # saved and nothing was damaged"; that is a domain fact and it needs a domain
591
+ # type. `from e` keeps the hub's own message in the traceback.
592
+ raise StoreConflict(
593
+ f'{self.repo}:{name} moved under this write {budget + 1} times in a '
594
+ f'row. Refusing to overwrite it. Nothing was saved.') from e
595
+ data = self._rebase(name, replay)
596
+ continue
597
+ with self._lock:
598
+ self._base[name] = oid
599
+ self._journal[name] = []
600
+ return data, oid
601
+ # Unreachable by construction β€” every iteration returns or raises. Kept so that an edit to
602
+ # the loop above cannot make this function fall out and return `None`, which callers would
603
+ # unpack into a crash two frames away from the cause.
604
+ raise StoreConflict(f'{self.repo}:{name}: the write loop exited without committing.')
605
+
606
+ def _journal_append(self, name, fn):
607
+ """Record one intent and return the replay list. THE CALLER HOLDS THE CACHE LOCK.
608
+
609
+ ⚠ CAPPED, BECAUSE AN UNCONFIRMED WRITE STREAM IS AN UNBOUNDED LIST OF CLOSURES. In normal
610
+ operation the cap is unreachable β€” `_commit` empties this every few seconds β€” so it only
611
+ bites during a sustained hub outage, where the alternative is a process that grows until it
612
+ dies. When it bites, the OLDEST intents are dropped and it is reported: a rebase afterwards
613
+ replays the most recent `_MAX_JOURNAL` changes rather than all of them. Stated rather than
614
+ silently enforced, per the standing rule about limits that cannot be removed.
615
+ """
616
+ j = self._journal.setdefault(name, [])
617
+ j.append(fn)
618
+ if len(j) > _MAX_JOURNAL:
619
+ dropped = len(j) - _MAX_JOURNAL
620
+ del j[:dropped]
621
+ try: # lazy import β€” core stays layer-clean
622
+ import harness.telemetry as _tel # noqa: PLC0415
623
+ _tel.error(f'store:journal_full:{name}', StoreConflict(
624
+ f'{self.repo}:{name} has {_MAX_JOURNAL}+ unconfirmed writes; dropped '
625
+ f'{dropped} oldest replay entr(ies). A rebase will re-apply only the most '
626
+ f'recent {_MAX_JOURNAL}.'))
627
+ except Exception: # noqa: BLE001
628
+ pass
629
+ return list(j)
630
+
631
+ def _rebase(self, name, replay):
632
+ """Re-read the hub's newer document and re-apply our intent onto it. Caller holds the key
633
+ lock, so nothing else can be mid-write on this key while we do.
634
+
635
+ ⚠ THE CACHE IS REPLACED WITH THE REBASED RESULT, and forgetting that line would make the
636
+ whole mechanism single-shot: the next write would start from the same stale snapshot and
637
+ conflict again, burning a rebase per write forever. It also has a second, welcome effect β€”
638
+ this instance now HOLDS the other container's work, which is the only moment a process
639
+ whose cache is never re-read gets to learn that anything changed.
640
+ """
641
+ fresh, sha = self._download(name)
642
+ for fn in list(replay):
643
+ out = fn(fresh)
644
+ fresh = out if out is not None else fresh
645
+ with self._lock:
646
+ self._cache[name] = json.loads(json.dumps(fresh))
647
+ self._base[name] = sha
648
+ try: # lazy import β€” core stays layer-clean
649
+ import harness.telemetry as _tel # noqa: PLC0415
650
+ _tel.error(f'store:rebase:{name}',
651
+ StoreConflict(f'{self.repo}:{name} moved; replayed {len(replay)} change(s)'))
652
+ except Exception: # noqa: BLE001
653
+ pass
654
+ return fresh
655
 
656
  def upload_bytes(self, path_in_repo, data, message=None):
657
  """Persist RAW BYTES at an arbitrary path in the tenant dataset (wave-8 C5, documents).
658
  Bytes are never cached in-process: large, cold, fetched on explicit user action."""
659
  if not self.available():
660
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
661
+ # D-315: a blob is still this tenant's data. ⚠ No `parent_commit` here and that is correct,
662
+ # not an omission: a blob is written at its own path and read whole, so two writers cannot
663
+ # silently merge into one damaged document the way `{name}.json` can. The concurrency
664
+ # hazard D-305 describes is specific to the shared JSON blob.
665
+ data_binding.check_write(self.repo, f'write bytes {path_in_repo!r}')
666
  with self._lock:
667
+ self._ensure_repo()
668
+ HfApi(token=_token()).upload_file(
669
+ path_or_fileobj=io.BytesIO(data), path_in_repo=path_in_repo,
670
+ repo_id=self.repo, repo_type='dataset',
671
+ commit_message=(message or f'add {path_in_repo}')
672
+ + data_binding.local_commit_suffix())
 
673
 
674
  def download_bytes(self, path_in_repo):
675
  """Raw bytes back, or None when absent/unreachable β€” a missing attachment degrades to
 
686
  return None
687
 
688
  def delete_path(self, path_in_repo):
689
+ """Remove a stored file. Absent is SUCCESS β€” deleting what is already gone is the goal.
690
+
691
+ β›” THE REFUSAL IS RAISED, NOT SWALLOWED INTO THE `return False` BELOW, and the distinction
692
+ matters: `False` here means "the delete did not happen", which several callers treat as a
693
+ tolerable no-op. "You are not allowed to touch this store" is not a no-op β€” it is the
694
+ thing the operator has to be told.
695
+ """
696
  if not self.available():
697
  return False
698
+ data_binding.check_write(self.repo, f'delete {path_in_repo!r}')
699
  try:
700
+ HfApi(token=_token()).delete_file(
701
+ path_in_repo=path_in_repo, repo_id=self.repo, repo_type='dataset',
702
+ commit_message=f'delete {path_in_repo}' + data_binding.local_commit_suffix())
703
  return True
704
  except (EntryNotFoundError, RepositoryNotFoundError):
705
  return True
 
707
  return False
708
 
709
  def put(self, name, data):
710
+ """Persist {name}.json (creates the private repo on first write). Updates the cache.
711
+
712
+ ⭐ D-305 β€” `put` NOW TAKES THE KEY LOCK AND GOES THROUGH `_commit`, and both halves are
713
+ required. Without the precondition this method is the hole in the whole mechanism: seven
714
+ callers outside this file reach it (`users.py`, `modules/ar.py`, `modules/map.py`,
715
+ `runtime.py`, `store_backend.py`, `ops/seed_pg_from_hf.py`) and `users.json` is a document
716
+ every account shares, so an unguarded whole-file `put` clobbers exactly as `update` used to.
717
+
718
+ ⚠ THE CACHE LOCK NO LONGER SPANS THE NETWORK, which is a change to this method's
719
+ concurrency and is deliberate. The old body held `self._lock` β€” the lock every `get()`
720
+ takes β€” across the upload, so one `put` froze every reader for a round trip (D-181's
721
+ shape); with up to `_MAX_REBASE` extra round trips now possible that freeze would get
722
+ strictly worse. The per-key write lock gives the callers a STRONGER guarantee than they had
723
+ (two writers of one key can no longer interleave) while readers stop waiting. Lock order is
724
+ key-then-cache, as everywhere else in this class.
725
+
726
+ ⚠ REPLAY SEMANTICS FOR A WHOLE-DOCUMENT WRITE ARE LAST-WRITE-WINS, STATED RATHER THAN
727
+ IMPLIED. `put` means "the document is this now", so its journal entry replaces rather than
728
+ merges. What the precondition buys here is that the replacement is applied to a document we
729
+ have actually SEEN β€” and that any `update` queued behind it replays on top β€” instead of
730
+ being uploaded over an hour of unseen work.
731
+ """
732
  if not self.available():
733
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
734
+ data_binding.check_write(self.repo, f'put {name!r}')
735
+ with self._key_lock(name):
736
+ def _replace(_current):
737
+ return json.loads(json.dumps(data))
738
+ with self._lock:
739
+ replay = self._journal_append(name, _replace)
740
+ landed, _oid = self._commit(name, data, replay)
741
+ with self._lock:
742
+ self._cache[name] = json.loads(json.dumps(landed))
743
+ self._owned[name] = True
744
+ self._last_flush[name] = _time.monotonic()
745
+ self._dirty[name] = False
746
+ self._bump(name) # C6 β€” AFTER the upload: a raise here is not a write
747
+ return self._cache[name]
748
 
749
  def _flush_worker(self, name):
750
  """Coalescing uploader for one key. Runs while dirty; retries with backoff on failure β€”
 
769
  this must too; taking `self._lock` first on this path is the deadlock. Both sleeps stay
770
  OUTSIDE the key lock β€” a worker that dozed while holding it would block every writer of
771
  that key for `_FLUSH_MIN_GAP`, which is the freeze this ticket exists to remove.
772
+
773
+ ⭐⭐ D-305 β€” THIS WORKER IS ALSO WHERE MOST CROSS-CONTAINER LOSS HAPPENED, because the
774
+ table workspace (views, fields, folders, overlays) is written `flush='async'`. It uploads a
775
+ SNAPSHOT of a cache that may be minutes old, so it takes the `replay` journal with it: on a
776
+ 412 the snapshot is thrown away and the journalled `fn`s are re-applied to the hub's newer
777
+ document instead. The journal is cleared inside `_commit`, only on success.
778
  """
779
  backoff = 2.0
780
  while True:
781
  _time.sleep(_FLUSH_DELAY)
782
+ wait, err, snapshot, replay = None, None, None, ()
783
  with self._key_lock(name):
784
  with self._lock:
785
  gap = _time.monotonic() - self._last_flush.get(name, 0.0)
 
791
  else:
792
  self._dirty[name] = False
793
  snapshot = json.loads(json.dumps(self._cache.get(name, {})))
794
+ # Snapshotted WITH the document and under the same lock: a journal that
795
+ # could drift from the snapshot it describes would replay the wrong set.
796
+ replay = list(self._journal.get(name) or ())
797
  if wait is None:
798
  try:
799
+ landed, _oid = self._commit(name, snapshot, replay)
800
  with self._lock:
801
+ # A rebase rebuilt the document, so the cache must take the result β€”
802
+ # `_rebase` already wrote it, and this keeps the no-conflict path
803
+ # identical to it rather than leaving two ways for the cache to be set.
804
+ self._cache[name] = json.loads(json.dumps(landed))
805
  self._last_flush[name] = _time.monotonic()
806
  backoff = 2.0
807
  except Exception as e: # noqa: BLE001
 
856
  finish, so waiting for its key lock could only turn a partial save into no save at all.
857
  Best-effort is the correct contract here, and it is the one case where taking the lock
858
  would be worse than skipping it.
859
+
860
+ ⭐ D-305 β€” IT STILL GOES THROUGH `_commit`, so the last write of a dying process cannot be
861
+ the one that erases somebody. Exiting is not a licence to overwrite: if the branch has
862
+ moved, this rebases like any other write, and if it cannot, it gives up rather than
863
+ clobbering. `_commit`'s own `data_binding` check applies too, so a container that was never
864
+ allowed to write this store does not get one last unguarded upload on the way out.
865
  """
866
  with self._lock:
867
  dirty = [k for k, v in self._dirty.items() if v]
868
  snaps = {k: json.loads(json.dumps(self._cache.get(k, {}))) for k in dirty}
869
+ replays = {k: list(self._journal.get(k) or ()) for k in dirty}
870
  for k in dirty:
871
  self._dirty[k] = False
872
  for k, d in snaps.items():
873
  try:
874
+ # ⚠ ONE REBASE, NOT `_MAX_REBASE`, and the docstring above is the argument: this
875
+ # runs at interpreter exit with the process going away. The full budget is up to
876
+ # four extra downloads and five upload attempts PER DIRTY KEY on a path that may be
877
+ # killed at any moment, which turns a best-effort save into a hang. One attempt
878
+ # keeps the safety this method exists for (a conflicting write still rebases rather
879
+ # than clobbering) at a cost the exit path can actually pay.
880
+ self._commit(k, d, replays.get(k, ()), max_rebase=1)
881
  except Exception:
882
  pass # exiting anyway β€” nothing left to reschedule
883
 
 
890
  returns immediately; a coalescing worker commits. The strict read still guards the
891
  FIRST async update of a key per process.
892
 
893
+ β›”β›” D-305 β€” "LAST-WRITE-WINS IS THE CONTRACT" IS NO LONGER TRUE ACROSS PROCESSES, AND THE
894
+ SENTENCE BELOW USED TO SAY IT WITHOUT THE QUALIFIER. Two writers in ONE process cannot lose
895
+ an update β€” they share `self._cache`, which is why every gate in this repo passed over the
896
+ defect. Two writers in two CONTAINERS could, and did: measured on tenant #0's live store in
897
+ commit `dee7481a77`, where one session's write rolled the document back an hour and cost a
898
+ real user 3 views, 49 typed cell values and a field id. The commit now carries a
899
+ `parent_commit` precondition and rebases (`_commit`), so the contract is: **within a
900
+ process, last write wins; across processes, a write that would overwrite unseen work is
901
+ refused and re-applied.** A lost update is not the contract at either grain.
902
+
903
  ⭐⭐ W31-T13 (D-177(d)) β€” TWO LOCKS, AND THE SPLIT IS THE WHOLE TICKET.
904
  `self._key_lock(name)` is held for the entire read-modify-write, so two writers of one key
905
+ still cannot interleave.
906
  `self._lock` β€” the one every `get()` takes β€” is now held only for the microseconds a cache
907
  read or write needs, never across a download or an upload. Before this, one sync write
908
  froze every reader in the process for two network round trips, on a store whose warm
 
910
  ⚠ Uploading outside `self._lock` is not a new posture: `_flush_worker` has done exactly
911
  that since wave 7, and `_repo_ok` racing is benign because `create_repo` is `exist_ok=True`.
912
  """
913
+ # β›” D-315 β€” REFUSED AT THE ACCEPTANCE POINT, NOT AT THE UPLOAD. `_upload` carries the same
914
+ # check as a backstop, but refusing only there would let the async branch accept the
915
+ # mutation into the cache, answer 200, mark the key dirty, and hand the flush worker a
916
+ # write that can never succeed β€” which retries with backoff forever and reports the refusal
917
+ # to nobody. Refuse before anything is accepted, and the caller gets a 503 that tells the
918
+ # truth: no change was saved.
919
+ data_binding.check_write(self.repo, f'update {name!r}')
920
  with self._key_lock(name):
921
  return self._update_locked(name, fn, flush)
922
 
 
975
  result = fn(data)
976
  data = result if result is not None else data
977
 
978
+ # ⭐⭐ D-305 β€” THE INTENT IS RECORDED, NOT JUST THE RESULT, and this one line is what makes
979
+ # a conflict survivable. `data` is our answer over OUR base; `fn` is what we MEANT, and
980
+ # only the intent can be re-applied to somebody else's newer document. The journal holds
981
+ # every `fn` since the last confirmed upload β€” which for an async key is a whole flush
982
+ # window of edits, not one β€” and `_commit` clears it only when the hub has accepted them.
983
+ # ⚠ Appended AFTER `fn` ran: a `fn` that raised changed nothing and must not be replayed.
984
+ with self._lock:
985
+ replay = self._journal_append(name, fn)
986
+
987
  if flush == 'async':
988
  if not self.available():
989
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
 
994
  self._schedule_flush(name)
995
  return data
996
 
997
+ # β›” THE SYNC COMMIT. It used to be spelled out here rather than calling `put()`, because
998
+ # `put()` held `self._lock` across its own upload β€” the freeze W31-T13 removed β€” and is
999
+ # PUBLIC with seven callers outside this file whose concurrency semantics changing it would
1000
+ # alter. D-305 made that duplication untenable: an unguarded whole-file write is the hole
1001
+ # the precondition exists to close, so BOTH now go through `_commit`, which is the single
1002
+ # place that resolves a parent, rebases and clears the journal. `put` still keeps its own
1003
+ # body (its op REPLACES rather than merges), but neither can upload unconditionally.
1004
  if not self.available():
1005
  raise RuntimeError('No HF_TOKEN configured β€” persistence is unavailable.')
1006
+ landed, _oid = self._commit(name, data, replay) # network, no cache lock held
1007
  with self._lock:
1008
+ # ⚠ `landed`, NOT `data`. A rebase rebuilt the document from the hub's newer copy, so
1009
+ # caching what we TRIED to write would leave the cache diverged from what is stored β€”
1010
+ # and the next write would rebase off that divergence forever.
1011
+ self._cache[name] = json.loads(json.dumps(landed))
1012
  self._owned[name] = True
1013
  self._last_flush[name] = _time.monotonic()
1014
+ # β›” AFTER THE UPLOAD, NEVER BEFORE β€” `put()`'s own law. `_commit` raises on failure,
1015
  # and a bump on that path would have `revision()` report a change that never landed.
1016
  self._bump(name)
1017
  # The upload above CARRIED whatever was pending, so the key is no longer ahead of
 
1020
  # ⚠ AFTER the upload, for the same reason: on a raise the mark MUST survive (the cache
1021
  # is still the truth and the row must still be committed by the worker). Clearing it
1022
  # first would turn a transient upload error into the very silent loss the branch above
1023
+ # exists to stop β€” which is why it sits here and not before the commit.
1024
  self._dirty[name] = False
1025
+ return landed
1026
 
1027
 
1028
  # ------------------------------------------------------------------- instances + module API