staquia 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. staquia-0.1.0/.gitignore +9 -0
  2. staquia-0.1.0/CHANGELOG.md +19 -0
  3. staquia-0.1.0/LICENCE +21 -0
  4. staquia-0.1.0/PKG-INFO +367 -0
  5. staquia-0.1.0/README.md +340 -0
  6. staquia-0.1.0/pyproject.toml +81 -0
  7. staquia-0.1.0/src/staquia/__init__.py +50 -0
  8. staquia-0.1.0/src/staquia/aggregates/__init__.py +1 -0
  9. staquia-0.1.0/src/staquia/aggregates/algorithms/__init__.py +32 -0
  10. staquia-0.1.0/src/staquia/aggregates/algorithms/add.py +27 -0
  11. staquia-0.1.0/src/staquia/aggregates/algorithms/after.py +20 -0
  12. staquia-0.1.0/src/staquia/aggregates/algorithms/before.py +24 -0
  13. staquia-0.1.0/src/staquia/aggregates/algorithms/between.py +17 -0
  14. staquia-0.1.0/src/staquia/aggregates/algorithms/clean.py +41 -0
  15. staquia-0.1.0/src/staquia/aggregates/algorithms/compact_numbers.py +36 -0
  16. staquia-0.1.0/src/staquia/aggregates/algorithms/diverge.py +18 -0
  17. staquia-0.1.0/src/staquia/aggregates/algorithms/divide.py +18 -0
  18. staquia-0.1.0/src/staquia/aggregates/algorithms/half.py +39 -0
  19. staquia-0.1.0/src/staquia/aggregates/algorithms/resolve_overflow.py +17 -0
  20. staquia-0.1.0/src/staquia/aggregates/algorithms/substract.py +36 -0
  21. staquia-0.1.0/src/staquia/aggregates/composer.py +49 -0
  22. staquia-0.1.0/src/staquia/aggregates/definition.py +70 -0
  23. staquia-0.1.0/src/staquia/aggregates/forger.py +139 -0
  24. staquia-0.1.0/src/staquia/aggregates/lexicon.py +65 -0
  25. staquia-0.1.0/src/staquia/aggregates/noise/__init__.py +6 -0
  26. staquia-0.1.0/src/staquia/aggregates/noise/jitter.py +113 -0
  27. staquia-0.1.0/src/staquia/aggregates/noise/random.py +54 -0
  28. staquia-0.1.0/src/staquia/aggregates/number/__init__.py +6 -0
  29. staquia-0.1.0/src/staquia/aggregates/number/compare.py +35 -0
  30. staquia-0.1.0/src/staquia/aggregates/number/shape.py +82 -0
  31. staquia-0.1.0/src/staquia/aggregates/ordinal.py +43 -0
  32. staquia-0.1.0/src/staquia/aggregates/presets.py +47 -0
  33. staquia-0.1.0/src/staquia/aggregates/spacer.py +65 -0
  34. staquia-0.1.0/src/staquia/aggregates/verifier.py +21 -0
  35. staquia-0.1.0/src/staquia/constants.py +6 -0
  36. staquia-0.1.0/src/staquia/entities/__init__.py +7 -0
  37. staquia-0.1.0/src/staquia/entities/deterministic_forger.py +20 -0
  38. staquia-0.1.0/src/staquia/entities/digits.py +120 -0
  39. staquia-0.1.0/src/staquia/entities/noisy_forger.py +46 -0
  40. staquia-0.1.0/src/staquia/entities/number_system.py +137 -0
  41. staquia-0.1.0/src/staquia/entities/position.py +89 -0
  42. staquia-0.1.0/src/staquia/entities/signature.py +38 -0
  43. staquia-0.1.0/src/staquia/entities/staquia.py +272 -0
  44. staquia-0.1.0/src/staquia/enums/__init__.py +6 -0
  45. staquia-0.1.0/src/staquia/enums/direction.py +19 -0
  46. staquia-0.1.0/src/staquia/enums/half_mode.py +14 -0
  47. staquia-0.1.0/src/staquia/enums/noise.py +45 -0
  48. staquia-0.1.0/src/staquia/errors/__init__.py +20 -0
  49. staquia-0.1.0/src/staquia/errors/base.py +26 -0
  50. staquia-0.1.0/src/staquia/errors/create.py +72 -0
  51. staquia-0.1.0/src/staquia/errors/lexical.py +126 -0
  52. staquia-0.1.0/src/staquia/errors/position.py +112 -0
  53. staquia-0.1.0/src/staquia/errors/warning.py +55 -0
  54. staquia-0.1.0/src/staquia/lists/__init__.py +1 -0
  55. staquia-0.1.0/src/staquia/lists/item.py +77 -0
  56. staquia-0.1.0/src/staquia/lists/lexical_list.py +142 -0
  57. staquia-0.1.0/src/staquia/lists/links.py +87 -0
  58. staquia-0.1.0/src/staquia/lists/relocate.py +92 -0
  59. staquia-0.1.0/src/staquia/lists/repair.py +96 -0
  60. staquia-0.1.0/src/staquia/lists/replace.py +125 -0
  61. staquia-0.1.0/src/staquia/lists/sort.py +59 -0
  62. staquia-0.1.0/src/staquia/lists/spacing.py +87 -0
  63. staquia-0.1.0/src/staquia/protocols/__init__.py +6 -0
  64. staquia-0.1.0/src/staquia/protocols/digits.py +43 -0
  65. staquia-0.1.0/src/staquia/protocols/forger.py +22 -0
  66. staquia-0.1.0/src/staquia/protocols/position.py +16 -0
  67. staquia-0.1.0/src/staquia/protocols/system.py +53 -0
  68. staquia-0.1.0/src/staquia/py.typed +0 -0
  69. staquia-0.1.0/src/staquia/result.py +92 -0
  70. staquia-0.1.0/tests/__init__.py +0 -0
  71. staquia-0.1.0/tests/conftest.py +13 -0
  72. staquia-0.1.0/tests/cross_language/__init__.py +0 -0
  73. staquia-0.1.0/tests/cross_language/support.py +42 -0
  74. staquia-0.1.0/tests/cross_language/test_lists.py +51 -0
  75. staquia-0.1.0/tests/cross_language/test_noise.py +109 -0
  76. staquia-0.1.0/tests/cross_language/test_positions.py +110 -0
  77. staquia-0.1.0/tests/fixtures/list.tsv +12712 -0
  78. staquia-0.1.0/tests/fixtures/noise.tsv +7334 -0
  79. staquia-0.1.0/tests/fixtures/positions.tsv +33229 -0
  80. staquia-0.1.0/tests/lists/__init__.py +0 -0
  81. staquia-0.1.0/tests/lists/test_access.py +109 -0
  82. staquia-0.1.0/tests/lists/test_add.py +142 -0
  83. staquia-0.1.0/tests/lists/test_edge_cases.py +169 -0
  84. staquia-0.1.0/tests/lists/test_ends.py +98 -0
  85. staquia-0.1.0/tests/lists/test_integrity.py +98 -0
  86. staquia-0.1.0/tests/lists/test_move.py +169 -0
  87. staquia-0.1.0/tests/lists/test_python_lists.py +67 -0
  88. staquia-0.1.0/tests/lists/test_repair.py +90 -0
  89. staquia-0.1.0/tests/lists/test_set.py +196 -0
  90. staquia-0.1.0/tests/lists/test_sort.py +130 -0
  91. staquia-0.1.0/tests/noise/__init__.py +0 -0
  92. staquia-0.1.0/tests/noise/test_lists.py +156 -0
  93. staquia-0.1.0/tests/noise/test_positions.py +135 -0
  94. staquia-0.1.0/tests/noise/test_python_noise.py +66 -0
  95. staquia-0.1.0/tests/staquia/__init__.py +0 -0
  96. staquia-0.1.0/tests/staquia/test_core.py +60 -0
  97. staquia-0.1.0/tests/staquia/test_forge.py +72 -0
  98. staquia-0.1.0/tests/staquia/test_presets.py +100 -0
  99. staquia-0.1.0/tests/staquia/test_stacking.py +88 -0
  100. staquia-0.1.0/tests/staquia/test_systems.py +115 -0
  101. staquia-0.1.0/tests/support/__init__.py +0 -0
  102. staquia-0.1.0/tests/support/alphabet.py +67 -0
  103. staquia-0.1.0/tests/support/lists.py +154 -0
  104. staquia-0.1.0/tests/support/staquia.py +52 -0
  105. staquia-0.1.0/tests/test_package.py +16 -0
  106. staquia-0.1.0/tests/test_python_algorithms.py +58 -0
  107. staquia-0.1.0/tests/test_python_digits.py +63 -0
  108. staquia-0.1.0/tests/test_python_errors.py +152 -0
  109. staquia-0.1.0/tests/test_python_noise.py +28 -0
  110. staquia-0.1.0/tests/test_python_number_system.py +99 -0
  111. staquia-0.1.0/tests/test_python_position.py +77 -0
  112. staquia-0.1.0/tests/test_python_result.py +54 -0
  113. staquia-0.1.0/tests/unit/__init__.py +0 -0
  114. staquia-0.1.0/tests/unit/number/__init__.py +0 -0
  115. staquia-0.1.0/tests/unit/number/test_compare.py +86 -0
  116. staquia-0.1.0/tests/unit/number/test_shape.py +73 -0
  117. staquia-0.1.0/tests/unit/test_algorithms.py +98 -0
  118. staquia-0.1.0/tests/unit/test_composer.py +46 -0
  119. staquia-0.1.0/tests/unit/test_forger.py +89 -0
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
@@ -0,0 +1,19 @@
1
+ # Staquia (Python) Changelog
2
+
3
+ Select a version below to view the changelog history:
4
+
5
+ - [Unreleased](#unreleased)
6
+ - [Staquia 0.1.0](#v010) **Current**
7
+
8
+ ## Unreleased
9
+
10
+ ## V0.1.0
11
+
12
+ The first version: the same positions as the JavaScript library 0.7.0 and the Rust crate 0.3.0.
13
+
14
+ - **Systems:** `Staquia.create(zero, first, last, ln, lz, threshold, *, noise)`, `Staquia.from_characters(...)` and the presets `default`, `alphabet`, `ascii`, `url_safe` and `base36` (`ln = 5`, `lz = 20`, threshold `0.15`, low noise), each one with keyword overrides. An invalid configuration raises `CreateError`, a `ValueError`.
15
+ - **Positions:** `start`, `next`, `previous`, `core`, `forge`, `from_digits`, `spread` and `stack_room`, returning `Ok` / `Err` results that work with `match`; `unwrap()` raises the error. `Position` is an immutable value that compares, hashes and pickles like its string.
16
+ - **Errors:** `StaquiaError` and its subclasses, returned in an `Err` and picklable: `InvalidCharacterError`, `SystemOverflowError` (JavaScript's `OverflowError`, with the edges of `N` as a `direction`), `ThresholdReachedError`, `CollisionRiskError`, `SystemMismatchError`, `LexicalError` (with `kind`, `id` and the position error as `__cause__`) and `CreateError`.
17
+ - **Noise:** `Noise.OFF`, `LOW` and `HIGH` (also the strings `"off"`, `"low"`, `"high"`), SplitMix64 with `noise_seed`, one state per thread, and a new seed in every forked process (gunicorn, Celery, multiprocessing).
18
+ - **LexicalList:** `append`, `appendleft`, `remove`, `move(id, after=, before=)`, `set(rows, untrusted=)`, `sort(key=, reverse=)`, `rebalance` and `repair(id, reach=8)`, for any object with an `id` and a `position` attribute; it reads like a Python sequence (`len`, iteration, `reversed`, indexes, `in`, `get`).
19
+ - **Tests:** the JavaScript specs ported with the same names, the cross-language fixtures (33,229 positions, 12,712 list operations, 7,334 seeded noisy operations) replayed identically, and the README and docstring examples as doctests. CI on Python 3.10 to 3.14 with ruff and strict mypy.
staquia-0.1.0/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 Carlos Andres Briones Montellano
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
staquia-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,367 @@
1
+ Metadata-Version: 2.5
2
+ Name: staquia
3
+ Version: 0.1.0
4
+ Summary: Lexicographic positions for lists users reorder: move an item, save one row.
5
+ Project-URL: Documentation, https://nona9614.github.io/staquia-js/#view=get-started&lang=python
6
+ Project-URL: Repository, https://github.com/Nona9614/staquia-python
7
+ Project-URL: Changelog, https://github.com/Nona9614/staquia-python/blob/master/CHANGELOG.md
8
+ Author: Carlos Andres Briones Montellano
9
+ License-Expression: MIT
10
+ License-File: LICENCE
11
+ Keywords: database,drag-and-drop,fractional-indexing,lexicographic,order,position,reorder,sort
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Database
23
+ Classifier: Topic :: Software Development :: Libraries
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+
28
+ # staquia
29
+
30
+ [![PyPI](https://img.shields.io/pypi/v/staquia.svg)](https://pypi.org/project/staquia/)
31
+ [![CI](https://github.com/Nona9614/staquia-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Nona9614/staquia-python/actions/workflows/ci.yml)
32
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](#install)
33
+ ![dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)
34
+ ![typed](https://img.shields.io/badge/types-included-blue.svg)
35
+ [![license](https://img.shields.io/badge/license-MIT-blue.svg)](#license)
36
+
37
+ Short lexicographic positions for ordered lists: moving an item writes one row.
38
+
39
+ - Zero dependencies, pure Python, fully typed (`py.typed`, checked with strict mypy).
40
+ - Nothing raises: every operation returns an `Ok` or an `Err` you can `match`.
41
+ - The same positions as the JavaScript and Rust libraries, checked with more than 50,000 recorded operations.
42
+
43
+ Staquia is a configurable, zero dependency, lexicographic **position** algorithm. It solves the reinsertion and sorting problem of long lists: every item stores a short string position, and sorting those strings gives the order of the list.
44
+
45
+ When an item is moved, only **its own** position changes, the surrounding items never need to be updated. This makes it ideal for lists and tables stored in a database, where reordering one row should mean writing one row.
46
+
47
+ To have a full detailed explanation you can go to the [documentation site](https://nona9614.github.io/staquia-js/#view=get-started&lang=python) (how positions work, using them in a database, error handling).
48
+
49
+ This package is the Python version of the [staquia](https://github.com/Nona9614/staquia-js) JavaScript library (0.7.0) and the [staquia](https://github.com/Nona9614/staquia-rust) Rust crate (0.3.0). For the same system and operations all of them create **the same positions**, so a Python server can read and write the positions stored by a JavaScript app. The tests of the repository replay more than 50,000 operations recorded with the JavaScript library and assert the same strings.
50
+
51
+ - [Install](#install)
52
+ - [Quick start](#quick-start)
53
+ - [How positions work](#how-positions-work)
54
+ - [Creating a system](#creating-a-system) (and [presets](#presets))
55
+ - [Positions](#positions)
56
+ - [Results and errors](#results-and-errors)
57
+ - [Lexical list](#lexical-list)
58
+ - [Storing positions in a database](#storing-positions-in-a-database)
59
+ - [Concurrent edits (noise)](#concurrent-edits-noise)
60
+ - [Differences with JavaScript](#differences-with-javascript)
61
+ - [Running the tests](#running-the-tests)
62
+ - [License](#license)
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install staquia
68
+ ```
69
+
70
+ Or `uv add staquia`, `poetry add staquia`... The package has no dependencies and needs Python 3.10 or later.
71
+
72
+ ## Quick start
73
+
74
+ Any object with an `id` and a `position` attribute works: a Django or SQLAlchemy model, a dataclass, a pydantic model.
75
+
76
+ ```pycon
77
+ >>> from dataclasses import dataclass
78
+ >>> from staquia import LexicalList, Staquia
79
+
80
+ >>> @dataclass
81
+ ... class Task:
82
+ ... id: int
83
+ ... title: str
84
+ ... position: str = ""
85
+
86
+ >>> tasks = LexicalList(Staquia.alphabet())
87
+
88
+ >>> # Every new position ends with one random digit (the low noise of the presets)
89
+ >>> write = tasks.append(Task(1, "Write")).unwrap().value # "mmmmm" and a random digit
90
+ >>> review = tasks.append(Task(2, "Review")).unwrap().value # "mmmmn" and a random digit
91
+ >>> publish = tasks.append(Task(3, "Publish")).unwrap().value # "mmmmo" and a random digit
92
+
93
+ >>> # Moves "Publish" between "Write" and "Review": only its position changes, save this one row
94
+ >>> moved = tasks.move(3, after=1, before=2).unwrap()
95
+ >>> write.position < publish.position < review.position
96
+ True
97
+ >>> [task.value.title for task in tasks]
98
+ ['Write', 'Publish', 'Review']
99
+
100
+ ```
101
+
102
+ ## How positions work
103
+
104
+ A system has a zero character and a range of characters from `first` to `last`: they are the digits of a number system of base `(last - first) + 2`. A position is a number written with those digits, split in two sections:
105
+
106
+ - `N`, of a fixed length `ln`: stacking an item before or after the list adds or subtracts `1` here, so positions never get longer.
107
+ - `Z`, of up to `lz` digits: moving an item between two adjacent positions takes the middle value here, one digit longer.
108
+
109
+ Positions compare exactly as their strings, so a database sorts them with a plain `ORDER BY position`. Moving items again and again into the same gap makes positions grow: the system warns at the **threshold** length and fails at the **overflow** length, and the list can then be repaired around that item (`repair`, only the positions near it spaced again) or rebalanced (every position spaced again).
110
+
111
+ ## Creating a system
112
+
113
+ ```pycon
114
+ >>> from staquia import Staquia
115
+
116
+ >>> # The alphabet: "!" is 0, "a" is 1 and "z" is 26, a base 27 system
117
+ >>> alphabet = Staquia.create("!", "a", "z", 5, 15, 0.15)
118
+ >>> alphabet.base, alphabet.max_length, alphabet.threshold_length
119
+ (27, 20, 17)
120
+
121
+ >>> # The default system: "!", from "°" (U+00B0) to "ұ" (U+04B1), base 1027,
122
+ >>> # ln = 5, lz = 20, threshold 0.15, low noise
123
+ >>> system = Staquia.default()
124
+
125
+ >>> # Every preset takes keyword overrides
126
+ >>> longer = Staquia.default(ln=6, noise="off")
127
+
128
+ ```
129
+
130
+ `create(zero, first, last, ln, lz, threshold, *, noise="off")` checks the configuration once and raises `CreateError` (a `ValueError`) when:
131
+
132
+ - the characters are not `zero < first <= last`, or are not single characters,
133
+ - a character is above `U+FFFF`, or the range includes the surrogates (`U+D800` to `U+DFFF`), so Python, JavaScript, Rust, UTF-8 and UTF-16 compare them in the same order,
134
+ - `ln` or `lz` is `0`, or `ln + lz` is above 32,
135
+ - the threshold factor is not from `0` to `1`,
136
+ - the noise doesn't leave 2 digits of `lz` for the order.
137
+
138
+ The presets never raise it.
139
+
140
+ ### Presets
141
+
142
+ Ready to use systems, no parameters to choose. Change any of them with keyword arguments: `Staquia.url_safe(ln=6, noise="high")`.
143
+
144
+ | Preset | Characters | Base | Start | Pick it when |
145
+ | --- | --- | --- | --- | --- |
146
+ | `Staquia.ascii()` | `!` + printable ASCII from `#` to `~` without `'`, `\` and `` ` `` | 90 | `PPPPP!` | you want plain ASCII: the most compact per byte, nothing to escape in JSON, SQL or logs |
147
+ | `Staquia.url_safe()` | `-`, `0`-`9`, `A`-`Z`, `_`, `a`-`z` | 64 | `VVVVV-` | positions go in URLs, file names or HTML ids |
148
+ | `Staquia.base36()` | `0`-`9`, `a`-`z` | 36 | `iiiii0` | the column is case insensitive (MySQL's default) or keys must be alphanumeric |
149
+ | `Staquia.alphabet()` | `!` + `a`-`z` | 27 | `mmmmm!` | you want to read them in logs and docs (every example here uses it) |
150
+ | `Staquia.default()` | `!` + `°` to `ұ` | 1027 | `ʰʰʰʰʰ!` | the shortest in characters (PostgreSQL `varchar(n)` counts characters) |
151
+
152
+ Every preset has `ln = 5`, `lz = 20` (positions up to 25 characters, a `varchar(25)` column), a threshold of `0.15` and low noise. The characters of `url_safe` are the ones of URL safe base64, but sorted by their code instead of the base64 order: positions are sort keys, not encoded data, so they keep the order a database compares them in.
153
+
154
+ Any other set of characters works too, not only a range: `Staquia.from_characters(characters, ln, lz, threshold)` takes the zero followed by every digit, sorted by their code.
155
+
156
+ ```pycon
157
+ >>> # The digits without the vowels: "0" is the zero, base 22
158
+ >>> system = Staquia.from_characters("0bcdfghjklmnpqrstvwxyz", 5, 15, 0.15)
159
+ >>> print(system.start().unwrap())
160
+ nnnnn0
161
+
162
+ ```
163
+
164
+ ## Positions
165
+
166
+ ```pycon
167
+ >>> system = Staquia.create("!", "a", "z", 5, 15, 0.15)
168
+
169
+ >>> start = system.start().unwrap() # the middle digit, as much room before as after
170
+ >>> after = system.next(start).unwrap()
171
+ >>> before = system.previous(start).unwrap()
172
+ >>> core = system.core(start, after).unwrap() # between both, in either order
173
+ >>> print(start, after, before, core)
174
+ mmmmm! mmmmn! mmmml! mmmmmn
175
+
176
+ >>> # From a stored string; shorter strings are completed with zeroes to the right
177
+ >>> print(system.forge("xy").unwrap())
178
+ xy!!!!
179
+
180
+ >>> # Positions compare, sort and hash with the same order as their strings
181
+ >>> before < start < core < after
182
+ True
183
+
184
+ ```
185
+
186
+ A `Position` is an immutable value: its digits and the signature of the system that created it (its characters and `ln`), with no reference to the system, so it can be compared, hashed, copied and pickled freely. `str(position)` is the value to store and `len(position)` its length. `position.n`, `position.z` and `position.digits` give its digits, and `system.from_digits(digits)` creates a position back from them.
187
+
188
+ ## Results and errors
189
+
190
+ Every operation that can fail returns a `Result`: an `Ok` with its `value`, or an `Err` with its `error`. Check `result.ok`, `match` it, or call `unwrap()`, which returns the value or raises the error.
191
+
192
+ ```pycon
193
+ >>> from staquia import Err, InvalidCharacterError, Ok, ThresholdReachedError
194
+
195
+ >>> match system.forge("abC"):
196
+ ... case Ok(position):
197
+ ... print("valid", position)
198
+ ... case Err(InvalidCharacterError(string, index)):
199
+ ... print("not a digit at", index)
200
+ not a digit at 2
201
+
202
+ >>> # A threshold warning still has a valid position: use it, and repair the list soon
203
+ >>> match system.forge("m" * 17):
204
+ ... case Ok(position) | Err(ThresholdReachedError(position)):
205
+ ... print(position)
206
+ mmmmmmmmmmmmmmmmm
207
+
208
+ ```
209
+
210
+ Errors are returned, not raised, because some of them are warnings with a valid position inside. They are still exceptions (`StaquiaError` is the base of them all), so `unwrap()` raises them and they can be pickled across processes (Celery, multiprocessing).
211
+
212
+ | Error | When |
213
+ | --- | --- |
214
+ | `InvalidCharacterError` | `forge` found a character that is not a digit of the system (`index`, `character`) |
215
+ | `SystemOverflowError` | the position would be longer than `ln + lz` (`length`, `limit`), or `next` of the last value of `N` / `previous` of the first one (`direction`) |
216
+ | `ThresholdReachedError` | the position reached the threshold: it is still valid (`position`) but the list should be repaired |
217
+ | `CollisionRiskError` | the random digits of the noise didn't fit whole: the position is valid (`position`) but more likely to collide |
218
+ | `SystemMismatchError` | the position was created by a system with another configuration |
219
+ | `LexicalError` | an operation of a list failed: its `kind` tells why, `id` is the item and `__cause__` the position error behind it |
220
+ | `CreateError` | raised by `create` and `from_characters` for an invalid configuration |
221
+
222
+ The position errors share the base `PositionError`, with the `position` they are about.
223
+
224
+ ## Lexical list
225
+
226
+ `LexicalList` keeps the order of your values and their positions in sync, as a doubly linked list of ids. It reads the `id` of your objects and writes every new position string into their `position` attribute.
227
+
228
+ | Method | |
229
+ | --- | --- |
230
+ | `append(value)` / `appendleft(value)` | adds at the end / start |
231
+ | `move(id, after=, before=)` | moves between two neighbors (only `after` for the end, only `before` for the start), only the moved item changes |
232
+ | `remove(id)` | removes the item and gives its value back |
233
+ | `set(values)` | loads rows already sorted by position (any iterable, like a QuerySet), verified and not changed |
234
+ | `set(values, untrusted=True)` | loads rows and repairs them: sorted, duplicates and invalid positions given new ones |
235
+ | `sort(key=, reverse=)` | sorts like `list.sort` and spaces every position again from the start |
236
+ | `rebalance()` | spaces every position again keeping the order |
237
+ | `repair(id, reach=8)` | spaces again only the positions around an item, to retry after its gap is full |
238
+ | `head()` / `tail()` | the position a new item would get at the start / end |
239
+ | `len(items)`, `for item in items`, `reversed(items)`, `items[i]`, `id in items`, `items.get(id)`, `items.first`, `items.last` | reading, like a Python sequence |
240
+ | `items.selected = id` | the selected item, cleared when it is removed |
241
+
242
+ When an operation fails, neither the list nor your values are changed. The operations return the items to save: `append`, `appendleft` and `move` the item, `set` the affected items and the list, `sort` and `rebalance` the affected items and every item, and `repair` the affected items.
243
+
244
+ `rebalance` changes almost every position of the list. When a `move` fails because its gap is full, `repair` is enough: the item and `reach` items on each side of it get new positions spread evenly between the two items around them, which don't change.
245
+
246
+ ```pycon
247
+ >>> tasks = LexicalList(Staquia.create("!", "a", "z", 5, 15, 0.15))
248
+ >>> for task_id in range(1, 41):
249
+ ... _ = tasks.append(Task(task_id, f"Task {task_id}"))
250
+
251
+ >>> # Moves new tasks again and again into the same gap, until it is full
252
+ >>> after = 10
253
+ >>> for task_id in range(41, 300):
254
+ ... _ = tasks.append(Task(task_id, "New"))
255
+ ... moved = tasks.move(task_id, after=after, before=11)
256
+ ... if not moved.ok:
257
+ ... break
258
+ ... after = task_id
259
+
260
+ >>> moved.error.kind
261
+ <LexicalErrorKind.POSITION: 'position'>
262
+ >>> repaired = tasks.repair(after).unwrap() # the rows to save, in one transaction
263
+ >>> len(repaired) <= 17
264
+ True
265
+ >>> tasks.move(task_id, after=after, before=11).ok
266
+ True
267
+
268
+ ```
269
+
270
+ The new positions are as short as possible, at most two digits longer than `N`. When the items don't fit in that length the reach is doubled and it tries again; a window that reaches an end of the list stacks its positions from the other side, and one that covers the whole list is a `rebalance`.
271
+
272
+ ## Storing positions in a database
273
+
274
+ Store the position in a text column of the preset's `max_length` (25), with a binary collation so the database compares it byte by byte, and a unique constraint per list, checked at the end of the transaction:
275
+
276
+ ```sql
277
+ -- PostgreSQL
278
+ CREATE TABLE tasks (
279
+ id serial PRIMARY KEY,
280
+ list_id integer NOT NULL,
281
+ title text NOT NULL,
282
+ position varchar(25) COLLATE "C" NOT NULL,
283
+ CONSTRAINT tasks_position UNIQUE (list_id, position) DEFERRABLE INITIALLY DEFERRED
284
+ );
285
+ ```
286
+
287
+ Read the rows `ORDER BY position` into a list with `set(rows)`, and save only the rows each operation returns. The [Database chapter](https://nona9614.github.io/staquia-js/#view=database&lang=python) has the collations of every database and how to migrate an integer order column.
288
+
289
+ ## Concurrent edits (noise)
290
+
291
+ When two clients move an item into the same gap at the same time, both get the **same** position and the unique constraint of the database rejects one of the writes. With `noise` every new position ends with random digits, so both writes succeed. The default system and the presets have **low** noise; `create` and `from_characters` have none unless you pass it:
292
+
293
+ ```pycon
294
+ >>> from staquia import Noise
295
+
296
+ >>> system = Staquia.default(noise=Noise.HIGH) # or noise="high"
297
+ >>> len(system.start().unwrap()) # N and two random digits
298
+ 7
299
+
300
+ ```
301
+
302
+ | Noise | Random digits | Collision odds of two clients (default system) | Moves into one gap (default system) |
303
+ | --- | --- | --- | --- |
304
+ | `Noise.OFF` (`create`) | 0 | always the same position | 160 to 176 |
305
+ | `Noise.LOW` (presets) | 1 | 1 in 1,026 | about 100 to 158 |
306
+ | `Noise.HIGH` | 2 | 1 in about a million | about 98 to 150 |
307
+
308
+ - The two items keep an arbitrary but **stable** order: the strings never change, so every client and every `ORDER BY` sees the same one.
309
+ - Positions still sort as **plain strings**: the random digits never make a position pass its neighbor, and a position never ends with the zero.
310
+ - When the random digits don't fit whole a `CollisionRiskError` is returned with the valid position: `repair` the list.
311
+ - Only `start`, `next`, `previous` and `core` (and so `append`, `appendleft` and `move`) are noisy. `rebalance`, `sort`, `set` and `repair` stay deterministic.
312
+ - `system.deterministic()` turns the noise off until `system.noisy()`.
313
+
314
+ ### The randomizer
315
+
316
+ The random digits come from **SplitMix64**, the same generator as the JavaScript and Rust libraries. It is not a cryptographic generator and doesn't need to be: positions are not secrets, the noise only has to make two clients draw different digits.
317
+
318
+ - **One state per thread**, seeded from the operating system (`secrets`), so you never need to seed it.
319
+ - **Forked workers take a new seed.** gunicorn, Celery and multiprocessing workers are forks of one process: each child reseeds itself, otherwise every worker would draw the same digits.
320
+ - **The same in every language:** `noise_seed(42)` seeds the current thread and gives the same digits on every run, and the same positions as JavaScript's `noiseSeed(42)` and Rust's `noise_seed(42)`, for tests. `noise_seed()` takes a new seed.
321
+
322
+ ```pycon
323
+ >>> from staquia import noise_seed
324
+
325
+ >>> noise_seed(42)
326
+ >>> print(Staquia.alphabet().start().unwrap())
327
+ mmmmmt
328
+
329
+ ```
330
+
331
+ Never give every client the same seed (a constant or the clock), or they all draw the same digits and collide again.
332
+
333
+ ## Differences with JavaScript
334
+
335
+ The logic and the positions are the same; the API follows Python conventions:
336
+
337
+ - Snake case and the names of Python's containers: `append` / `appendleft` instead of `push` / `unshift`, `remove(id)` instead of `delete`, `move(id, after=, before=)`, `sort(key=, reverse=)` instead of a comparator, `items.get(id)` instead of `find`, `items[i]` instead of `at`, iteration instead of `toArray()`, `items.selected = id` instead of `select`.
338
+ - Keyword arguments instead of option objects: `Staquia.ascii(noise="high")`, `set(rows, untrusted=True)`, `repair(id, reach=16)`.
339
+ - `create` and `from_characters` raise a `CreateError` for an invalid configuration (JavaScript doesn't validate it).
340
+ - `OverflowError` is `SystemOverflowError` (`OverflowError` is a Python built-in), and an edge of `N` is the same error with a `direction`.
341
+ - `LexicalError.kind` instead of `type` (a Python built-in), as a string enum: `error.kind == "not-found"` works.
342
+ - `Noise` is a string enum: `Noise.HIGH` or `"high"`.
343
+ - `len(position)` is the length of the stored string (`"mmmmm!"` is 6); JavaScript's `position.length` is the length measured when the position was created, which doesn't count the zeroes that complete it (5, `position.measured` in Python). The checks use that measured length in every language.
344
+ - Ids can be any hashable value but `None`, and the list can't contain a cycle, so there is no map overflow error.
345
+
346
+ ## Running the tests
347
+
348
+ ```bash
349
+ uv sync --locked
350
+ uv run pytest
351
+ uv run ruff check
352
+ uv run mypy
353
+ ```
354
+
355
+ The tests of the JavaScript library are ported with the same names (`tests/unit/`, `tests/staquia/`, `tests/lists/`, `tests/noise/`), the Python-only behavior is in `tests/test_python_*.py`, and the examples of this README and of the docstrings run as doctests.
356
+
357
+ `tests/cross_language/` replays the operations recorded in `tests/fixtures/*.tsv` with the JavaScript library: 33,229 positions, 12,712 list operations and 7,334 seeded noisy operations, all identical. To record them again, from the `javascript/` folder of the staquia repository:
358
+
359
+ ```bash
360
+ node_modules/.bin/tsx ../rust/tests/fixtures/generate.ts
361
+ ```
362
+
363
+ and copy `rust/tests/fixtures/*.tsv` to `python/tests/fixtures/`.
364
+
365
+ ## License
366
+
367
+ MIT (see `LICENCE`), the same as the JavaScript and Rust libraries.