mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-01 01:44:11 +03:00
## Description
`generateFractionalIndexingKeyBetween(a, b)` can return a key that sorts
after `b`.
When the subkeys of `a` and `b` share a prefix, the key is built as
`generateKeyBetween(a, b) + '0' + postfix()`. If `b` itself starts with
`generateKeyBetween(a, b) + '0'`, the order against `b` is decided by
the random postfix. For example, with `a =
Zz0KDAn9nhfbtFAOnyTqT45wXkV4SGW7XBh` and `b =
Zz10c5IY1TbnCK75NE22mfQEp2rpu6q1n6Z7`, `generateKeyBetween(a, b)` is
`Zz1` and the returned key was `Zz10UESACG9CHEXJNxgEDqhyCILR7N91EmcV`,
which is greater than `b`.
This is easy to reach from the UI helpers: `FolderNode.indexAt('after',
firstId)`, the favorites list, pinned collections, workspace properties
and table rows/columns all call it with their neighbours and sort with a
plain string compare. Starting from an empty list, adding one item
before the first and then repeatedly inserting right after the first
item breaks the order in 1000 out of 1000 runs within 20 inserts; the
inserted item ends up after its intended next neighbour.
The fix keeps stepping towards `b` with `generateKeyBetween(key, b)`
while `b` still starts with `key + '0'`, so the appended postfix can no
longer push the key past `b`. Each step lengthens the shared prefix with
`b`, so the loop ends. Both copies of the helper (`@toeverything/infra`
and `@blocksuite/affine-shared`) get the same change.
Proof: the added tests in `fractional-indexing.spec.ts` and
`fractional-indexing.unit.spec.ts` insert right after the first key 50
times, 100 rounds each. Before the fix both fail (`key < b` is false);
after, both pass across 5 reruns. I also fuzzed 1500 sequences of 200
inserts with mixed insertion strategies: 677 ordering violations before,
0 after, no throws.