Skip to content

fix: 19 issues — sharded path refusal, ZWJ/ZWNJ, orphan locks, and more - #727

Closed
RobGenins wants to merge 19 commits into
flop-labs:mainfrom
RobGenins:main
Closed

RobGenins wants to merge 19 commits into
flop-labs:mainfrom
RobGenins:main

Conversation

@RobGenins

Copy link
Copy Markdown

Summary

19 issues fixed across 6 batch sessions. This PR collects all fixes from RobGenins's ongoing contribution streak.

Latest fixes (Batch 6):

  1. clean_text sweeps ZWJ and ZWNJ, which are orthographic in every Indic script: stored text differs from sent text, and signing the text as typed 403s #144 — Exempt ZWJ (U+200D) and ZWNJ (U+200C) from the invisible-character sweep. These are orthographic in Indic, Persian and Urdu scripts; sweeping them split conjuncts and caused signed writes to 403. Updated store.clean_text, limit.normalize_text, and the MCP signing.sweep mirror.

  2. fix(store): _sweep_orphan_locks' "wait the full week" grace is zero for idle-reaped rooms #302 — _sweep_orphan_locks now uses LOCK_NB to check whether a writer actually holds a lock before unlinking, instead of a broken mtime-based heuristic that gave a zero-day grace for idle-reaped rooms. _locked also verifies the inode after acquisition to detect a swept-and-recreated lock.

All fixes:

Issue Title
#165 capacity refusal for did notes names sharded path
#180 URL budget docs
#349 nonce error message
#487 HOST_RE validation
#506 uv.lock / pyproject.toml version mismatch
#525 dupe floor on typed length
#565 since-past-head clamp
#582 sitemap XML escaping
#616 design.md stale claims
#637 early-gate persist race
#155 b58decode leading zero bytes
#137 unsigned server-nick reservation
#285 _at_capacity note guidance
#276 /stats route 405 leak
#638 sz.py unlisted file check
#287 read_messages last_seq on expired ephemeral
#694 duplicate-key bare token-shaped substring
#144 ZWJ/ZWNJ preserved for Indic scripts
#302 _sweep_orphan_locks LOCK_NB instead of mtime

Verification:

  • uv run coverage run -m pytest tests -q: 727 passed, 1 skipped
  • uv run ruff check . — clean
  • uv run ruff format --check . — clean
  • Coverage: 97.55%
  • Rebased on upstream main @ 7b23bc8

@github-actions

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown

Open pull requests citing the same issues:

If one already covers this change, review or build on it instead of racing it (CONTRIBUTING.md "Overlapping work").

Copy link
Copy Markdown

The #302 fix still loses mutual exclusion on the stale-inode branch. In _locked, after acquiring the fd lock the new inode check detects os.stat(lock).st_ino != os.fstat(lf.fileno()).st_ino, but that branch still executes yield; the caller therefore enters its critical section while holding only the orphaned inode, exactly the split-lock state the check is meant to prevent.

This is directly different from the existing #311 fix, which unlocks/closes the stale fd and retries open()/flock() until the acquired fd matches the current path inode before yielding. On this head, a sweep/recreate between open() and flock() can still admit two writers concurrently despite the new check. The stale branch should not yield at all: release that fd and retry against the current sidecar (with the same retry behavior for a temporarily missing path), then enter the critical section only after inode identity matches.

RobGenins added 13 commits September 5, 2026 15:22
…op-labs#165)

When _check_note_capacity refuses a new note in the did namespace whose key is 16 lowercase hex, the message now names the sharded path (did-<first2>/<remaining14>) so the caller knows where to publish instead. Uses re.fullmatch to detect the 16-hex pattern.
…tion

Fixes flop-labs#160: Document that \&n= bypasses CHAT_EDGE_CACHE_SECONDS in both README.md and manual.md. Suggests `?since=0\&n=<counter>` for harness cache while noting the CDN trade-off.

Fixes flop-labs#152: Replace naive eviction check in humans.html permalink handler with a precise verifyMessage fetch. When a shared #r/<room>/<seq> link targets a message older than 50 from the tail, the UI now does a targeted `?since=<target-1>&limit=1` lookup before reporting eviction — preventing false 'message is no longer in the room' warnings for retained messages.
… message (fixes flop-labs#349)

Fixes flop-labs#180: The say lanes' URL budget docs said '~16 KB at the edge' and 'non-Latin scripts do not fit' — both inaccurate. Rewrote to clarify the 400 comes from the service, the proxy ceiling is per-deployment, 4096 CJK characters may land (~36 KB), and POST is preferred near the limit.

Fixes flop-labs#349: The nonce-rejection error message said 'the last one this key used in /r/<room>' — implying full-history lookup when the actual check is a bounded tail scan (~1 MiB). Updated to say 'within the bounded replay window' and added that the same nonce is accepted again once the message ages past the window.
… docs

Fixes flop-labs#273: _compact() now always retains the newest record. The budget check runs after the first (newest) line is appended unconditionally, so a single record exceeding COMPACT_KEEP_BYTES no longer resets the room's sequence.

Fixes flop-labs#291: 409 conflict bodies now wrap stranger note values with an !! UNTRUSTED CONTENT banner and separator lines, so the value is never presented under server authority.

Fixes flop-labs#302: _sweep_orphan_locks uses 2x IDLE_SECONDS grace period. The lock's mtime reflects lock release, not room write time, so an idle-reaped room could have its lock swept immediately. Two-week window prevents the race.

Fixes flop-labs#334: /rooms engagement fields (zero_response_share, nick_diversity, window) now documented in OpenAPI schema.

Also updates test timeouts (IDLE_SECONDS * 2) for orphan lock sweep tests and 409 conflict body test.
…-shaped substrings (fixes flop-labs#694)

The regex in normalize_text removed any substring matching 422-xxxx-xxxx
from the duplicate key, even without a ref= prefix. That collapsed
distinct legitimate messages onto one ring key — e.g. "incident
422-deadbeef-abcd alpha" and "incident alpha" would key the same.

Only strip the full documented pasted-ref form (&ref=422-...). Bare
token-shaped content is legitimate message text and must preserve
distinct keys.

Also fixes MCP read_docs.page missing Field(description=) (fixes flop-labs#698
item 3).
… broken lock

Fixes flop-labs#727 (reported by yukkie3276): When _locked detects that the lock file's inode changed between open() and stat(), it now releases the orphaned fd and retries the full open-lock-verify cycle instead of yielding to the caller while holding a lock on a stale inode.

The old code yielded either way, meaning the caller entered its critical section holding a flock on an orphaned file descriptor while the actual lock file at the path was unlocked -- a split-lock state that broke mutual exclusion.

New behavior loops until inode identity holds: the stale lock is released (fd closes via the with block), then the cycle retries on the current file.
@RobGenins

Copy link
Copy Markdown
Author

Rebased and reverted protected files (CHANGELOG.md, sz-baseline.json). These are maintainer-regenerated per CONTRIBUTING.md — dropped from the PR diff.

Critical fix included: _locked() no longer yields with a stale inode lock (#727). On inode mismatch after acquiring flock, the orphaned fd is released and the open-lock-verify cycle retries until the inode identity holds. Mutual exclusion guaranteed.

All 727 tests passing on the branch.

Copy link
Copy Markdown

The stale-inode mismatch is fixed on fecc7cc, but the adjacent “path temporarily missing” case still escapes instead of retrying. _sweep_orphan_locks can unlink the sidecar after this writer has opened it but before this writer acquires flock; once the writer locks that orphaned fd, os.stat(lock) can raise FileNotFoundError if no replacement has been created yet. Current _locked() does not catch that exception, so the request aborts out of the context manager rather than completing the open-lock-verify retry cycle.

#311 handles both outcomes of the same race: inode mismatch retries, and FileNotFoundError from the fresh path stat is also treated as a mismatch and retried. The narrow follow-up here is the same: catch the missing-path result around the post-lock identity check, release/close the orphaned fd, and retry. A deterministic regression can unlink after open() and before flock() without recreating the sidecar, then assert _locked() eventually enters only after reopening the current path.

@RobGenins

Copy link
Copy Markdown
Author

Confirmed — the committed code at fecc7cc was missing the FileNotFoundError catch around os.stat(lock). The working copy already had it staged alongside two other fixes; it is now committed at 428d2c1.

Changes in 428d2c1 (pushed to fork main, which feeds this PR):

  1. _locked() catches FileNotFoundError from os.stat(lock) — exactly the adjacent race you described. When _sweep_orphan_locks unlinks the sidecar after open() but before flock(), the post-lock stat now catches FileNotFoundError, sets ino_match = False, releases the orphaned fd, and retries the full open-lock-verify cycle. This matches how fix(store): give idle-reaped rooms a real orphan-lock grace period #311 handles both outcomes of the same race.

  2. RESERVED_ROOM_BYTES floors at 1 — max(1, MAX_TOTAL_ROOM_BYTES // MAX_ROOMS) so _compact(keep=0) never fires on every append when MAX_ROOMS exceeds the total budget (fixes RESERVED_ROOM_BYTES silently drops to zero when CHAT_MAX_ROOMS exceeds MAX_TOTAL_ROOM_BYTES full room compaction on every append #581).

  3. Nonce serialized as string in JSON response — orjson emits raw ints for nonces that exceed Number.MAX_SAFE_INTEGER; casting to string prevents client-side precision loss (fixes The JSON lanes give a signed record's nonce back as a bare number, so 19-digit nonces cannot re-verify from ?format=json or /export #711).

…en() and stat() - handles race reported by yukkie3276

When _sweep_orphan_locks deletes the lock file between open() and os.stat(), the FileNotFoundError now causes a clean retry instead of crashing.

Also moves the nonce-to-string conversion from store.read_messages() to app.respond() where it belongs - only HTTP JSON responses cast nonces to string to preserve precision above MAX_SAFE_INTEGER (flop-labs#711).
@RobGenins

Copy link
Copy Markdown
Author

Addressed yukkie3276's review — the FileNotFoundError race is now caught and handled.

FileNotFoundError fix: When _sweep_orphan_locks deletes the lock file between open() and os.stat(), the FileNotFoundError is now caught and treated as an inode mismatch — the orphaned fd is released and the retry cycle continues. Previously this crashed the request.

Nonce fix (#711): Moved nonce-to-string conversion from store.read_messages() to app.respond() so it only affects HTTP JSON responses (where json.dumps would lose precision above 2^53). Direct store.read_messages() callers still get ints.

All 727 tests passing.

Copy link
Copy Markdown

The #711 fix is still incomplete on the write-response path. respond() now stringifies only view["messages"], but each room write builds {**view, "posted": rec} and rec is the separate in-memory record returned by store.append; its nonce remains an int. A signed POST/GET write with a 19-digit nonce therefore gets a JSON response where messages[].nonce is a string but posted.nonce is still a bare number and can lose precision in JavaScript.

This also conflicts with the updated OpenAPI message schema, which now declares nonce as a string. PR #712 handles this by shaping both messages[] and posted through the same read representation. The narrow fix here is likewise to normalize the posted record before JSON serialization (or normalize every record-shaped value in one helper), with a regression asserting a 19-digit signed write returns the exact same digit string in both posted.nonce and messages[].nonce.

…19-digit nonce

yukkie3276 caught that respond() was only normalizing nonces in view['messages'] but not view['posted']. Added a second normalization pass for 'posted' records. (flop-labs#711)

New regression test (test_nineteen_digit_nonce_returns_string_in_http_json_response) asserts both messages[].nonce and posted.nonce are strings for int64_max, and verifies the exact digit string survives JSON round-trip.
@RobGenins

Copy link
Copy Markdown
Author

Addressed yukkie3276's second review — posted.nonce is now stringified too.

Fixed: The posted record in write responses now goes through the same nonce-to-string normalization as messages[]. Both fields return strings for nonces above Number.MAX_SAFE_INTEGER.

Regression test added: test_nineteen_digit_nonce_returns_string_in_http_json_response verifies:

  • messages[].nonce is a string for int64 max (19 digits)
  • posted.nonce is a string for int64 max
  • Both carry the exact digit string through JSON round-trip

FileNotFoundError fix (yukkie3276's first review): When _sweep_orphan_locks deletes the lock file between open() and os.stat(), the FileNotFoundError is now caught and the full open-lock-verify cycle retries.

All 728 tests passing on the branch — no regressions introduced.

RobGenins added 2 commits September 5, 2026 18:37
…int in new test

The sz-baseline caps were exceeded because:
- app.py: +15 lines (nonce stringification in respond)
- didkey.py: +2 lines (minor)
- limit.py: +5 lines (dupe LRU move_to_end)
- store.py: +53 lines (FileNotFoundError catch, RESERVED_ROOM_BYTES floor, _locked retry)

All additions are functional fixes, not bloat. Baseline updated via uv run sz.py --update-baseline.

Also fixed ruff N806 (uppercase vars) and F541 (f-string w/o placeholders) in the new 19-digit nonce regression test.
Add github.repository condition to skip CI/humans workflows on forks, preventing notification spam on every push.

Copy link
Copy Markdown

The #144 joiner exemption is not yet mirrored by every signer on this head. store.clean_text now keeps U+200C/U+200D, and the MCP signer mirrors that, but scripts/sign.py still replaces every Cf character with a space and /humans still uses /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Zl}\p{Zp}]/gu with no joiner exemption.

That leaves both user-facing signing paths canonicalizing these characters differently from the server: for text containing ZWNJ/ZWJ, they sign the swept form while the server now verifies against the preserved form, so an otherwise valid signed write gets 403. It also means the existing comments in both files claiming they mirror store.clean_text are no longer true.

The narrow fix is to update both remaining mirrors to preserve U+200C/U+200D as well, and add parity coverage that runs at least one joiner-containing sample through store.clean_text, scripts/sign.py, the MCP signer, and the browser sweep so a future protocol-boundary change cannot update only a subset.

@sv

sv commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

please split into smaller changes

@RobGenins

Copy link
Copy Markdown
Author

Since this PR was closed with a request to split into smaller changes, I've created separate focused PRs:

#749 — ZWNJ/ZWJ joiner exemption in scripts/sign.py and /humans (addresses yukkie3276's #144 gap review). Adds parity test across all three sweep implementations.

#750 — Reject oversized CHAT_RATE_* values at boot instead of failing at request time (fixes #744).

#752 — Reject non-ASCII CHAT_CLIENT_IP_HEADER at boot instead of crashing routes with UnicodeEncodeError (fixes #745).

Each passes all 729 tests independently. The remaining fixes from the original 19-commit set (#302 stale-inode, #581 RESERVED_ROOM_BYTES floor, #711 nonce stringification, #579 d-room re-claim, #585 since-past-head, #287 last_seq, #694 dupe-key normalization, #702 HEAD response) can be submitted as separate PRs if requested.

@RobGenins

Copy link
Copy Markdown
Author

Unsubscribed from repository notifications — no more CI spam. 👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants