Skip to content

Commit 25d9dff

Browse files
anthony-khongAnthony KhongAnthony Khong
authored
fix: misc bug fixes from 0.1.1 review (#3)
* 0.1.2: what the review of 0.1.1 turned up * version bump --------- Co-authored-by: Anthony Khong <anthony-khong@192.168.1.83> Co-authored-by: Anthony Khong <anthony-khong@cridheil.local>
1 parent 6507b23 commit 25d9dff

28 files changed

Lines changed: 673 additions & 99 deletions

‎CHANGELOG.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,51 @@
33
Pre-1.0: a minor version may rename or remove. When it does, the migration is one
44
line here.
55

6+
## 0.1.2 (2026-09-18)
7+
8+
Fixes from an external review of 0.1.1. Correctness, and a more honest account of
9+
what the concurrency story does and does not cover.
10+
11+
- **`.xlsx` reads that lost data.** An ISO-date cell (`t="d"`, from a workbook
12+
saved with `iso_dates`) read as nil and, since it read as nothing, was erased on
13+
the next write; it now reads as a `Date` or `NaiveDateTime`. An elapsed duration
14+
(`[h]:mm:ss`) read as a `Time`, throwing away whole days (36 hours became 12); it
15+
keeps its number and its format now. A float smaller than `1.0e-15` (such as
16+
`1.0e-20`) was written as `0`; the shortest round-tripping form is written
17+
instead. An error cell (`#DIV/0!`) with no formula crashed any write to its
18+
sheet; the error now reads into the cell's metadata, the same place a formula's
19+
error goes, so the write succeeds. (Writing such a cell back verbatim is still to
20+
come; an untouched error cell rewrites empty for now.)
21+
- **`.xlsx` writes that corrupted the file.** A shared-string table spelled with a
22+
namespace prefix (`<x:sst>`) silently dropped a newly added string, so the cell
23+
read back nil; mutations are namespace-aware now. Removing `calcChain.xml` left
24+
its relationship and content-type override behind, pointing at a part that was
25+
gone; both go with it.
26+
- **A local write no longer loosens a file's permissions.** Replacing a `0600`
27+
file produced a `0644` one, because the temporary file took the process umask.
28+
The destination's mode is now preserved, a new file is created `0600`, and the
29+
temporary file is created exclusively.
30+
- **`Sheetshow.Table.compact/1`** no longer deletes a live row when a tombstone
31+
shares its id after a refresh: an ambiguous tombstone is left for a fresh read to
32+
resolve.
33+
- **Reserved and colliding columns are refused.** `Sheetshow.Table.new/2` and
34+
`Sheetshow.Log.new/2` reject a schema with an `id` or `deleted` column, or two
35+
columns that differ only by case or spacing; a tab whose header names a needed
36+
column twice reads as `%Sheetshow.Error{reason: :duplicate_column}` rather than
37+
silently taking the last.
38+
- **`Sheetshow.Schema.cast/2`** turns a serial number too large to convert into a
39+
`:cast` error, rather than raising.
40+
- **WebDAV**: a `PUT` that returns no `ETag` leaves the version `:unknown` instead
41+
of adopting one from a follow-up `HEAD`, which could be a racing writer's.
42+
- **Google**: a batch that adds a tab and then deletes it in one plan no longer
43+
leaves the tab in the remembered metadata; adds and deletes are applied in order.
44+
- **What Sheetshow can promise, corrected.** A conditional-write store makes each
45+
`run/2` on a file atomic against a racing writer, but does not yet tie a `Table`
46+
write to the snapshot it was planned against, because `run/2` re-reads the file
47+
at execution. The guide, the `Sheetshow.Table` docs and the README said this gap
48+
was closed; they now say it is not, and the README's retry note carries the same
49+
caveat the guide always has.
50+
651
## 0.1.1 (2026-09-17)
752

853
Fixes from a QA pass over 0.1.0, all in the `.xlsx` codec unless said otherwise:

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ a WebDAV server.
1818

1919
```elixir
2020
def deps do
21-
[{:sheetshow, "~> 0.1.1"}]
21+
[{:sheetshow, "~> 0.1.2"}]
2222
end
2323
```
2424

@@ -89,7 +89,7 @@ plain rows at about a twelfth the bytes.
8989
id appended again, a delete is the same id with a flag, and `fold/1` turns the
9090
history back into state. Because Google resolves an append server-side, several
9191
writers need no compare-and-swap between them, and a failed write is safe to
92-
retry. `Sheetshow.Table` is the mutable one, where row 7 *is* the record: read a
92+
retry, as long as it is retried before anything newer is written. `Sheetshow.Table` is the mutable one, where row 7 *is* the record: read a
9393
snapshot, build changes that name rows by id, `refresh/2` to find them again,
9494
then plan and run. Both share `Sheetshow.Schema`, which is a keyword list.
9595

‎dev/xlsx_fixtures.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,23 @@ def xlsxwriter_fixture(path):
9393
wb.close()
9494

9595

96+
def duration_fixture(path):
97+
# An elapsed duration, formatted [hh]:mm:ss, which is a count of hours and
98+
# not a time of day: 36 hours is the serial number 1.5. A reader that treats
99+
# it as a Time throws the whole days away, turning 1.5 into 0.5. openpyxl
100+
# applies the elapsed format to a timedelta on its own.
101+
import openpyxl
102+
from datetime import timedelta
103+
104+
wb = openpyxl.Workbook()
105+
ws = wb.active
106+
ws.title = "Data"
107+
ws["A1"] = timedelta(hours=36)
108+
wb.save(path)
109+
110+
96111
if __name__ == "__main__":
97112
openpyxl_fixture(os.path.join(FIXTURES, "openpyxl.xlsx"))
98113
xlsxwriter_fixture(os.path.join(FIXTURES, "xlsxwriter.xlsx"))
99-
print("wrote openpyxl.xlsx and xlsxwriter.xlsx to", FIXTURES)
114+
duration_fixture(os.path.join(FIXTURES, "duration.xlsx"))
115+
print("wrote openpyxl.xlsx, xlsxwriter.xlsx and duration.xlsx to", FIXTURES)

‎guides/guarantees.md‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,19 @@ uses to tell one state of the file from another, and `write/3` sends that
7070
version back as a precondition. `Sheetshow.Store.WebDAV` sends the file's
7171
`ETag` as `If-Match`, so a file that changed in between gets `412` and arrives
7272
as `%Sheetshow.Error{reason: :conflict}` with nothing written. That is
73-
`:conditional_write`, and it is the promise Google cannot make: over such a
74-
store a `Table` cycle of refresh, plan and run either lands on what you read or
75-
refuses, and a `Log` plan that lost the race is safe to run again unchanged,
76-
because its ids fold away against themselves.
73+
`:conditional_write`, and it is the promise Google cannot make: a `run/2` on a
74+
file is a whole read, change and write, and the precondition makes that atomic,
75+
so of two runs racing the loser is refused rather than silently overwriting the
76+
winner. A `Log` plan that lost that race is safe to run again unchanged, because
77+
its ids fold away against themselves.
78+
79+
It does **not** yet tie a `Table` write to the snapshot it was planned against.
80+
`run/2` re-reads the file at execution rather than writing against the version
81+
the snapshot was read at, so a plan made against an old snapshot can still land
82+
on rows that have moved since, without a conflict. Carrying the observed version
83+
through to the write is what would close that, and is not yet done; until then
84+
`refresh/2` narrows the gap on a file exactly as it does on Google, and no
85+
further.
7786

7887
`Sheetshow.Store.Local` cannot promise it. It checks the file's size and
7988
modification time immediately before an atomic rename, which catches most

‎lib/sheetshow/backend.ex‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@ defmodule Sheetshow.Backend do
2626
| `:styles` | a cell's style is kept |
2727
2828
`:server_side_append` is the one `Sheetshow.Log` rests on, and
29-
`:conditional_write` is what gives `Sheetshow.Table` the guarantee Google
30-
cannot; [What Sheetshow Can Promise](guides/guarantees.md) says how.
29+
`:conditional_write` is what makes each `run/2` on a file atomic against a
30+
racing writer, which Google cannot; [What Sheetshow Can Promise](guides/guarantees.md)
31+
says what that does and does not cover for a `Sheetshow.Table`.
3132
"""
3233

3334
alias Sheetshow.{Cell, Error, Op, Range, Workbook}

‎lib/sheetshow/error.ex‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ defmodule Sheetshow.Error do
4242
| `:invalid_record`, `:unknown_column` | a record a schema refuses to write: wrong type, or a key with no column |
4343
| `:cast` | a cell that would not read as its column's type; a flag on the row, or the error under `strict: true` |
4444
| `:missing_header`, `:missing_column` | a tab whose header is not there, or lacks a column the schema needs |
45+
| `:duplicate_column` | a tab whose header names a column the schema needs more than once, so there is no telling which to read |
4546
| `:missing_id` | an event with no id, which cannot be written |
4647
| `:unknown_id`, `:duplicate_id` | a change naming an id the snapshot cannot place, or one two rows share |
4748
| `:conflicting_changes` | two changes to one id in one plan |
@@ -89,6 +90,7 @@ defmodule Sheetshow.Error do
8990
| :cast
9091
| :missing_header
9192
| :missing_column
93+
| :duplicate_column
9294
| :missing_id
9395
| :unknown_id
9496
| :duplicate_id

‎lib/sheetshow/google/backend.ex‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,7 @@ defmodule Sheetshow.Google.Backend do
146146
client.http
147147
),
148148
{:ok, json} <- ok_json(response, url) do
149-
sheets = workbook.sheets |> Map.drop(dropped(plan)) |> Map.merge(added(json))
150-
{:ok, Workbook.put_sheets(workbook, sheets)}
149+
{:ok, Workbook.put_sheets(workbook, remember(plan, json, workbook.sheets))}
151150
end
152151
end
153152

@@ -223,9 +222,20 @@ defmodule Sheetshow.Google.Backend do
223222
end
224223
end
225224

226-
# A deleted sheet leaves no reply to read, so the plan is what says it went.
227-
defp dropped(plan) do
228-
for %Op.DeleteSheet{title: title} <- plan, do: title
225+
# The plan's adds and deletes applied to the remembered sheets in the order
226+
# the caller gave them, so a batch that adds a tab and then deletes it leaves
227+
# the workbook as it found it. Dropping every delete first and merging every
228+
# add after (an unordered `Map.drop |> Map.merge`) forgot the order and left
229+
# the deleted tab behind. An added tab's id comes from its reply; a delete
230+
# answers with nothing, so its title is simply taken back out.
231+
defp remember(plan, json, sheets) do
232+
ids = added(json)
233+
234+
Enum.reduce(plan, sheets, fn
235+
%Op.AddSheet{title: title}, acc -> Map.put(acc, title, Map.get(ids, title))
236+
%Op.DeleteSheet{title: title}, acc -> Map.delete(acc, title)
237+
_op, acc -> acc
238+
end)
229239
end
230240

231241
# A batch update answers an AddSheet with the sheet it made, which is how a

‎lib/sheetshow/log.ex‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,15 @@ defmodule Sheetshow.Log do
6161

6262
@doc """
6363
A log on a tab, with the columns its rows have. Raises `ArgumentError` on a
64-
schema `Sheetshow.Schema.validate/1` refuses.
64+
schema `Sheetshow.Schema.validate/1` refuses, and on one that names an `id` or
65+
`deleted` column, which the model keeps for itself.
6566
6667
iex> Sheetshow.Log.new("expenses", item: :string, cost: :decimal).sheet
6768
"expenses"
6869
"""
6970
@spec new(String.t(), Schema.t()) :: t()
7071
def new(sheet, schema) when is_binary(sheet) do
71-
case Schema.validate(schema) do
72+
case Records.validate_schema(schema) do
7273
:ok -> %__MODULE__{sheet: sheet, schema: schema}
7374
{:error, error} -> raise ArgumentError, Exception.message(error)
7475
end

‎lib/sheetshow/records.ex‎

Lines changed: 58 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,33 @@ defmodule Sheetshow.Records do
2828
@doc "A tab's columns, left to right: the two reserved ones, then the schema's."
2929
def columns(schema), do: [@id, @deleted | Schema.columns(schema)]
3030

31+
@doc """
32+
Validates a schema for a database model: one `Sheetshow.Schema.validate/1`
33+
accepts, and none of whose columns is named `id` or `deleted`. Those two are
34+
the model's own, kept for a row's identity and its tombstone flag, so a schema
35+
column by either name would sit under the reserved one and be read as it, and
36+
writing the record would overwrite the identity. `Log` and `Table` validate
37+
through here rather than through `Schema` directly.
38+
"""
39+
def validate_schema(schema) do
40+
with :ok <- Schema.validate(schema) do
41+
case Enum.find(Schema.columns(schema), &(String.downcase(&1) in [@id, @deleted])) do
42+
nil -> :ok
43+
name -> {:error, reserved(name)}
44+
end
45+
end
46+
end
47+
48+
defp reserved(name) do
49+
Error.new(
50+
:invalid_schema,
51+
"#{inspect(name)} is a reserved column: #{inspect(@id)} and #{inspect(@deleted)} are the " <>
52+
"model's own, kept for every row's identity and its tombstone flag, so name the column " <>
53+
"something else",
54+
column: name
55+
)
56+
end
57+
3158
@doc "The header row as cells, for the tab a `%Log{}` or `%Table{}` names."
3259
def header(%{sheet: sheet, schema: schema}, style) do
3360
schema |> columns() |> Sheetshow.row(sheet: sheet, style: style)
@@ -69,13 +96,14 @@ defmodule Sheetshow.Records do
6996
in the same places.
7097
"""
7198
def index(header, sheet, schema) do
72-
positions =
99+
indexed =
73100
for {name, position} <- Enum.with_index(header),
74101
key = normalise(name),
75102
key != nil,
76-
into: %{} do
77-
{key, position}
78-
end
103+
do: {key, position}
104+
105+
counts = indexed |> Enum.map(&elem(&1, 0)) |> Enum.frequencies()
106+
positions = Map.new(indexed)
79107

80108
if positions == %{} do
81109
{:error,
@@ -87,9 +115,21 @@ defmodule Sheetshow.Records do
87115
)}
88116
else
89117
Result.reduce(columns(schema), %{}, fn name, acc ->
90-
case Map.fetch(positions, String.downcase(name)) do
91-
{:ok, position} -> {:ok, Map.put(acc, name, position)}
92-
:error -> {:error, missing_column(name, sheet, header)}
118+
key = String.downcase(name)
119+
120+
cond do
121+
# A tab a person edits can end up with a column named twice. Which one
122+
# holds the truth is a question only they can answer, so it is refused
123+
# rather than answered by taking the last, which is what building the
124+
# map used to do silently.
125+
Map.get(counts, key, 0) > 1 ->
126+
{:error, duplicate_column(name, sheet, header)}
127+
128+
(position = Map.get(positions, key)) != nil ->
129+
{:ok, Map.put(acc, name, position)}
130+
131+
true ->
132+
{:error, missing_column(name, sheet, header)}
93133
end
94134
end)
95135
end
@@ -114,6 +154,17 @@ defmodule Sheetshow.Records do
114154
)
115155
end
116156

157+
defp duplicate_column(name, sheet, header) do
158+
Error.new(
159+
:duplicate_column,
160+
"#{inspect(sheet)} names the #{inspect(name)} column more than once, so there is no " <>
161+
"telling which to read or write: its header reads #{inspect(header)}",
162+
column: name,
163+
sheet: sheet,
164+
header: header
165+
)
166+
end
167+
117168
@doc """
118169
A cell for a row written outside the planner (an append, or a write to a
119170
known row), with the number format a date needs, which those paths would

‎lib/sheetshow/schema.ex‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,29 @@ defmodule Sheetshow.Schema do
7676
(repeated = Keyword.keys(schema) -- Enum.uniq(Keyword.keys(schema))) != [] ->
7777
{:error, invalid("the column #{inspect(hd(repeated))} is in the schema twice")}
7878

79+
(colliding = colliding_names(Keyword.keys(schema))) != [] ->
80+
{:error,
81+
invalid(
82+
"the columns #{inspect(colliding)} are the same column once a header is matched, " <>
83+
"which ignores case and surrounding spaces, so one would silently overwrite the " <>
84+
"other: give them names that differ by more than that"
85+
)}
86+
7987
true ->
8088
:ok
8189
end
8290
end
8391

92+
# Columns are found on a tab by name, case- and space-insensitively, so two
93+
# names that differ only by case or spacing are one column. Left in, the last
94+
# one would silently win; caught here, they never become a plan.
95+
defp colliding_names(keys) do
96+
keys
97+
|> Enum.group_by(&(&1 |> to_string() |> String.trim() |> String.downcase()))
98+
|> Enum.filter(fn {_canonical, group} -> length(group) > 1 end)
99+
|> Enum.flat_map(fn {_canonical, group} -> group end)
100+
end
101+
84102
@doc """
85103
The column names, in order, as they read in a header row.
86104
@@ -230,6 +248,11 @@ defmodule Sheetshow.Schema do
230248

231249
defp cast_value(value, kind) when kind in [:date, :datetime, :time] and is_number(value) do
232250
{:ok, Value.from_serial(value, kind)}
251+
rescue
252+
# A serial so large the conversion overflows is not a moment anyone meant.
253+
# Lenient casting turns that into a nil field and a :cast error, the same as
254+
# any other value that will not read, rather than raising out of a read.
255+
ArithmeticError -> :error
233256
end
234257

235258
# A backend that keeps values rather than serial numbers (`Sheetshow.Memory`,
@@ -288,7 +311,15 @@ defmodule Sheetshow.Schema do
288311
defp printed(value) when is_integer(value), do: Integer.to_string(value)
289312

290313
defp printed(value) when is_float(value) do
291-
:erlang.float_to_binary(value, [:compact, decimals: 15])
314+
# Fixed 15 decimals keep a decimal column out of exponent form, which is not
315+
# what anyone typed there. But 15 decimals cannot see a value smaller than
316+
# 1.0e-15, and rounding a nonzero number to "0" is worse than an exponent, so
317+
# such a value falls back to the shortest form that reads back the same.
318+
if value != 0.0 and abs(value) < 1.0e-15 do
319+
:erlang.float_to_binary(value, [:short])
320+
else
321+
:erlang.float_to_binary(value, [:compact, decimals: 15])
322+
end
292323
end
293324

294325
defp parse(string, parser) do

0 commit comments

Comments
 (0)