Reading the actual browser journal led me to rebuild its file-ownership question as independent synthetic code. Complete implementation, actual local records and tests are shared without connecting the original browser or customer records.
Constrain the accepted record
Save receives an explicit existing trusted directory, a bounded key and an exact synthetic record containing phase and sample. Keys cannot supply arbitrary separators or extensions; state and text are limited. Invalid input fails before a stage is created.
This schema does not copy the product receipt. It contains no account, tab, manuscript or result destination. A new standard-library Python contract isolates file-cleanup decisions. Adding operational fields requires another review of their necessity, validation and information scope.
Use creation evidence as cleanup authority
The stage is opened exclusively. A name collision fails while created remains false; ownership is claimed only after actual creation. Error cleanup removes that one owned stage, leaving other temporary files and the old destination alone. Filename similarity is not used as an ownership test.
Tests separately cover collision and an unrelated stage. This is not a folder-cleaning utility and save contains no directory deletion. The caller must control the root and its ancestors; the module makes no hostile-directory security claim.
Recheck context after writing
After writing serialized bytes, flushing, syncing and closing, save calls the context check again. Only an accepted context proceeds to same-directory replacement. Tests confirm that a post-write rejection preserves prior destination bytes.
Check is a cooperative callback, not a login or authorization server. There is no multi-writer revision or lock protocol. The single-file failure boundary should remain distinct from the responsibilities of existing database and permission modules.
Explore the implementation
Complete independent synthetic implementation
"""Synthetic single-file replacement in an explicitly trusted private directory."""
from pathlib import Path
from uuid import uuid4
import json,re,os,hashlib
def save(root,key,record,check=lambda:None):
if not isinstance(key,str) or re.fullmatch(r'[a-z][a-z0-9-]{0,39}',key) is None:
raise ValueError('invalid key')
if not isinstance(record,dict) or set(record)!={'phase','sample'}:
raise ValueError('exact synthetic record fields required')
if record['phase'] not in ('prepared','confirmed') or not isinstance(record['sample'],str) or not 1<=len(record['sample'])<=200:
raise ValueError('bounded synthetic record required')
data=json.dumps(record,ensure_ascii=False,sort_keys=True).encode('utf-8')
root=Path(root)
if not root.is_absolute() or not root.is_dir() or root.is_symlink():
raise ValueError('explicit existing trusted directory required')
target=root/(key+'.json');stage=root/('.'+key+'-'+uuid4().hex+'.tmp')
created=False
check()
try:
with stage.open('xb') as stream:
created=True
stream.write(data);stream.flush();os.fsync(stream.fileno())
check()
os.replace(stage,target);created=False
except Exception as error:
if created:
try:stage.unlink(missing_ok=True)
except Exception as cleanup:
raise ExceptionGroup('save and owned-stage cleanup failed',[error,cleanup]) from None
raise
return {'key':key,'payload_sha256':hashlib.sha256(data).hexdigest(),'bytes':len(data),'state':'stored'}Inspect failures using actual local files
A real destination directory triggers replacement failure, after which the peer file and destination are inspected. Tests cover invalid keys and records plus cancellation before and after writing. Cleanup denial is injected to verify retention of both the original exception and PermissionError.
Twelve tests pass in source and extracted ZIP. Files are created only in owned subdirectories beside the package, and cleanup first checks containment under the designated test root. Operating-system default temporary locations and actual user downloads are not used as test material.
The selector only reads saved records
The selector displays actual local records for success, post-write cancellation, destination conflict and invalid key. It shows preservation flags and remaining synthetic stage names without executing Python or accessing a visitor’s disk. Only the selected displayed record changes.
Actual inline selection code is executed for every scenario in both languages against DOM stubs and compared with records. That is not rendered-browser or keyboard-usability verification. The original application and customer accounts remain disconnected, keeping record display separate from file writing.
Download the limits alongside the implementation
The ZIP includes the complete core, twelve tests, runner, saved records and guidance for Python 3.11 or newer, with modification and reuse permitted. It promises no automatic recovery after process kill or power loss, universal filesystem durability or directory synchronization. Concurrency, authentication and backup remain separate.
This is not a replacement for the existing SQLite workflow module. Different storage and failure boundaries require different verification. A reusable guide should expose both what works here and what the next maker must decide, rather than imply that one save function resolves every operational problem.