From f0c318dd48f2666fad755dbfec5282f809b96e77 Mon Sep 17 00:00:00 2001 From: Paul Tristan Wagner Date: Fri, 16 Oct 2026 11:24:44 +0200 Subject: [PATCH 1/3] Add update_food_entry tool to edit or move a logged entry The app changes a serving's amount with /api/v2/edit_serving, re-sending the whole serving. The meal group lives in the high bits of `order`, and edit_serving accepts a new order too, so one call changes the amount, the measure and the meal. Claude-Session: https://claude.ai/code/session_01MCJFDo71qoSqTRtcGfkpXJ --- README.md | 1 + src/cronometer_api_mcp/client.py | 69 +++++++++++++++++++++ src/cronometer_api_mcp/server.py | 58 ++++++++++++++--- tests/test_diary_edit.py | 103 +++++++++++++++++++++++++++++++ tests/test_server_import.py | 1 + 5 files changed, 223 insertions(+), 9 deletions(-) create mode 100644 tests/test_diary_edit.py diff --git a/README.md b/README.md index 1f73d5e..0e9056d 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ cached session, so it also overrides a stale cached timezone. | Tool | Description | |------|-------------| | `add_food_entry` | Log a food serving to the diary | +| `update_food_entry` | Change a logged entry's amount or measure, or move it to another meal | | `remove_food_entry` | Remove one or more diary entries | | `add_custom_food` | Create a custom food with specified nutrition and optional barcodes | | `update_custom_food` | Edit a custom food in place: name, nutrition, serving size, or barcodes | diff --git a/src/cronometer_api_mcp/client.py b/src/cronometer_api_mcp/client.py index 89e4575..f0fe70a 100644 --- a/src/cronometer_api_mcp/client.py +++ b/src/cronometer_api_mcp/client.py @@ -1427,6 +1427,75 @@ def add_serving( ) return data + def update_serving( + self, + serving_id: str | int, + day: date | None = None, + *, + grams: float | None = None, + measure_id: int | None = None, + diary_group: int | None = None, + ) -> dict: + """Change the amount, measure or meal group of a logged serving. + + Fetches the day's diary, takes the serving as stored and sends it back + to /api/v2/edit_serving with the changed fields. The server keeps the + serving id. The meal group lives in the high bits of `order` (see + add_serving); a moved serving goes to the end of its new group. The + app moves entries with /api/v2/update_order, but edit_serving accepts + a new `order` as well (verified against the live API), so one call + covers both. + + Args: + serving_id: The servingId from get_diary. + day: The day the serving is logged on. Defaults to today. + grams: New weight in grams. + measure_id: New display measure (grams stays the amount). + diary_group: New meal group, 1 = Breakfast, 2 = Lunch, + 3 = Dinner, 4 = Snacks. + + Returns the updated serving as sent. + """ + if grams is None and measure_id is None and diary_group is None: + raise ValueError("update_serving needs grams, measure_id or diary_group") + if grams is not None and grams <= 0: + raise ValueError(f"grams must be positive, got {grams}") + if diary_group is not None and diary_group not in (1, 2, 3, 4): + raise ValueError(f"diary_group must be 1-4, got {diary_group}") + + entries = self.get_diary(day).get("diary", []) + serving = next( + (e for e in entries if str(e.get("servingId")) == str(serving_id)), + None, + ) + if serving is None: + raise CronometerError( + f"No serving {serving_id} in the diary for {self._format_day(day)}" + ) + + serving = dict(serving) + if grams is not None: + serving["grams"] = grams + if measure_id is not None: + serving["measureId"] = measure_id + if diary_group is not None and serving.get("order", 0) >> 16 != diary_group: + last = max( + ( + e.get("order", 0) & 0xFFFF + for e in entries + if e.get("order", 0) >> 16 == diary_group + ), + default=0, + ) + serving["order"] = (diary_group << 16) | (last + 1) + + payload = {"serving": serving, "config": {"call_version": 2}} + data = self._request("/api/v2/edit_serving", payload) + if str(data.get("id")) != str(serving["servingId"]): + raise CronometerError(f"Failed to update serving {serving_id}: {data}") + logger.info("Updated serving %s on %s", serving_id, serving.get("day")) + return serving + # ------------------------------------------------------------------ # Diary: get diary entries # ------------------------------------------------------------------ diff --git a/src/cronometer_api_mcp/server.py b/src/cronometer_api_mcp/server.py index af0b74f..876e66a 100644 --- a/src/cronometer_api_mcp/server.py +++ b/src/cronometer_api_mcp/server.py @@ -258,6 +258,9 @@ def _food_log_for_day(client: CronometerClient, day: date) -> dict: # ------------------------------------------------------------------ +_DIARY_GROUPS = {"auto": 0, "breakfast": 1, "lunch": 2, "dinner": 3, "snacks": 4} + + @mcp.tool(annotations=_WRITE) def add_food_entry( food_id: int, @@ -282,15 +285,7 @@ def add_food_entry( "dinner", "snacks" (case-insensitive, default "auto"). """ try: - group_map = { - "auto": 0, - "breakfast": 1, - "lunch": 2, - "dinner": 3, - "snacks": 4, - } - group_key = diary_group.strip().lower() - group_int = group_map.get(group_key) + group_int = _DIARY_GROUPS.get(diary_group.strip().lower()) if group_int is None: return _err( ValueError( @@ -319,6 +314,51 @@ def add_food_entry( return _err(e) +@mcp.tool(annotations=_WRITE_IDEMPOTENT) +def update_food_entry( + entry_id: str, + date: str | None = None, + grams: float | None = None, + measure_id: int | None = None, + diary_group: str | None = None, +) -> str: + """Change a logged food entry: its amount, its measure, or its meal. + + Use get_food_log to find the entry ID. Pass only what should change. + + Args: + entry_id: Serving/entry ID from get_food_log. + date: Date the entry is logged on as YYYY-MM-DD (defaults to today). + grams: New weight of the serving in grams. + measure_id: New measure/unit ID from get_food_details (the amount is + still given in grams). + diary_group: Move to another meal -- one of "breakfast", "lunch", + "dinner", "snacks" (case-insensitive). + """ + try: + group_int = None + if diary_group is not None: + group_int = _DIARY_GROUPS.get(diary_group.strip().lower()) + if not group_int: + return _err( + ValueError( + f"Invalid diary_group '{diary_group}'. " + "Must be one of: breakfast, lunch, dinner, snacks." + ) + ) + client = _get_client() + entry = client.update_serving( + entry_id, + _parse_date(date), + grams=grams, + measure_id=measure_id, + diary_group=group_int, + ) + return _ok({"entry": entry}) + except Exception as e: + return _err(e) + + @mcp.tool(annotations=_DESTRUCTIVE) def remove_food_entry( entry_ids: list[str], diff --git a/tests/test_diary_edit.py b/tests/test_diary_edit.py new file mode 100644 index 0000000..6203417 --- /dev/null +++ b/tests/test_diary_edit.py @@ -0,0 +1,103 @@ +"""update_serving: change a logged serving's amount, measure or meal group. + +The serving is read back from get_diary and re-sent whole to +/api/v2/edit_serving. The meal group is the high 16 bits of `order`. +""" + +from __future__ import annotations + +from datetime import date + +import pytest +from test_client import make_cold_client + +from cronometer_api_mcp.client import CronometerError + +DAY = date(1900, 1, 2) +SERVING_ID = 5312202908 + + +def serving(**overrides) -> dict: + """A get_diary entry shaped like the real one.""" + entry = { + "servingId": SERVING_ID, + "type": "Serving", + "foodId": 5442, + "measureId": 14990, + "translationId": 0, + "grams": 100, + "day": "1900-01-02", + "time": "11:23:50", + "offset": 0, + "userId": 42, + "order": (1 << 16) | 1, # breakfast, first + } + entry.update(overrides) + return entry + + +def diary(*entries) -> dict: + return {"diary": list(entries), "summary": {}, "messages": []} + + +EDITED = {"messages": [], "id": SERVING_ID} + + +def test_update_serving_changes_grams_and_keeps_the_rest(tmp_path): + client, state = make_cold_client(tmp_path, [diary(serving()), EDITED]) + + result = client.update_serving(SERVING_ID, DAY, grams=150) + + sent = state["payloads"][1] + assert sent["config"] == {"call_version": 2} + assert sent["serving"] == serving(grams=150) + assert result == serving(grams=150) + + +def test_update_serving_moves_to_end_of_new_group(tmp_path): + lunch = [ + serving(servingId=1, order=(2 << 16) | 1), + serving(servingId=2, order=(2 << 16) | 4), + ] + client, state = make_cold_client(tmp_path, [diary(serving(), *lunch), EDITED]) + + client.update_serving(str(SERVING_ID), DAY, diary_group=2) + + assert state["payloads"][1]["serving"]["order"] == (2 << 16) | 5 + + +def test_update_serving_same_group_keeps_position(tmp_path): + entry = serving(order=(1 << 16) | 3) + client, state = make_cold_client(tmp_path, [diary(entry), EDITED]) + + client.update_serving(SERVING_ID, DAY, diary_group=1, measure_id=7) + + sent = state["payloads"][1]["serving"] + assert sent["order"] == (1 << 16) | 3 + assert sent["measureId"] == 7 + + +def test_update_serving_unknown_id_raises_without_editing(tmp_path): + client, state = make_cold_client(tmp_path, [diary(serving()), EDITED]) + + with pytest.raises(CronometerError, match="No serving 999"): + client.update_serving(999, DAY, grams=10) + + assert len(state["payloads"]) == 1 + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({}, "needs grams"), + ({"grams": 0}, "positive"), + ({"diary_group": 5}, "1-4"), + ], +) +def test_update_serving_validates_before_any_request(tmp_path, kwargs, message): + client, state = make_cold_client(tmp_path, [diary(serving()), EDITED]) + + with pytest.raises(ValueError, match=message): + client.update_serving(SERVING_ID, DAY, **kwargs) + + assert state["payloads"] == [] diff --git a/tests/test_server_import.py b/tests/test_server_import.py index 917f190..53d9ec9 100644 --- a/tests/test_server_import.py +++ b/tests/test_server_import.py @@ -31,6 +31,7 @@ "remove_food_entry", "search_foods", "update_custom_food", + "update_food_entry", } From 2319dd30cbca00ac81043b08c1cc843a9892a9ae Mon Sep 17 00:00:00 2001 From: jorgebaptista <38887971+jorgebaptista@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:41:21 +0000 Subject: [PATCH 2/3] fix: accept any account diary group in update_serving update_serving limited diary_group to 1-4, the old default layout. Groups now come from resolve_diary_group, so any enabled group is valid (for example a custom group 5). Add server-level tests for moving to a named custom group and for rejecting "auto". --- src/cronometer_api_mcp/client.py | 10 ++++---- tests/test_diary_edit.py | 3 ++- tests/test_diary_groups.py | 41 ++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/cronometer_api_mcp/client.py b/src/cronometer_api_mcp/client.py index 7d802f7..87d0a67 100644 --- a/src/cronometer_api_mcp/client.py +++ b/src/cronometer_api_mcp/client.py @@ -1694,8 +1694,8 @@ def update_serving( day: The day the serving is logged on. Defaults to today. grams: New weight in grams. measure_id: New display measure (grams stays the amount). - diary_group: New meal group, 1 = Breakfast, 2 = Lunch, - 3 = Dinner, 4 = Snacks. + diary_group: New meal group number, as resolve_diary_group + returns it for one of the account's enabled groups. Returns the updated serving as sent. """ @@ -1703,8 +1703,10 @@ def update_serving( raise ValueError("update_serving needs grams, measure_id or diary_group") if grams is not None and grams <= 0: raise ValueError(f"grams must be positive, got {grams}") - if diary_group is not None and diary_group not in (1, 2, 3, 4): - raise ValueError(f"diary_group must be 1-4, got {diary_group}") + # Group numbers come from the account's layout (resolve_diary_group); + # they occupy the high 16 bits of `order`. + if diary_group is not None and not 0 <= diary_group <= 0xFFFF: + raise ValueError(f"diary_group must be 0-65535, got {diary_group}") entries = self.get_diary(day).get("diary", []) serving = next( diff --git a/tests/test_diary_edit.py b/tests/test_diary_edit.py index 6203417..fa5370c 100644 --- a/tests/test_diary_edit.py +++ b/tests/test_diary_edit.py @@ -91,7 +91,8 @@ def test_update_serving_unknown_id_raises_without_editing(tmp_path): [ ({}, "needs grams"), ({"grams": 0}, "positive"), - ({"diary_group": 5}, "1-4"), + ({"diary_group": -1}, "0-65535"), + ({"diary_group": 1 << 16}, "0-65535"), ], ) def test_update_serving_validates_before_any_request(tmp_path, kwargs, message): diff --git a/tests/test_diary_groups.py b/tests/test_diary_groups.py index ed5d084..e7375f6 100644 --- a/tests/test_diary_groups.py +++ b/tests/test_diary_groups.py @@ -731,3 +731,44 @@ def test_label_diary_groups_reuses_groups_cached_by_a_write(tmp_path): assert state["post"] == 1 assert diary["diary"][0]["diary_group"]["name"] == "Dinner" + + +# ------------------------------------------------------------------ +# update_food_entry resolves the target group from the account layout +# ------------------------------------------------------------------ + + +def test_update_food_entry_moves_to_a_named_custom_group(tmp_path, monkeypatch): + from test_diary_edit import EDITED, diary, serving + + from cronometer_api_mcp import server + + client, state = make_cold_client( + tmp_path, [profile(**CUSTOM_GROUPS), diary(serving()), EDITED] + ) + monkeypatch.setattr(server, "_client", client) + + result = json.loads( + server.update_food_entry( + entry_id=str(serving()["servingId"]), + date="1900-01-02", + diary_group="Pre-bedtime", + ) + ) + + assert result["status"] == "success" + assert result["diary_group"] == {"group": 5, "name": "Pre-bedtime"} + assert state["payloads"][-1]["serving"]["order"] >> 16 == 5 + + +def test_update_food_entry_refuses_auto_without_editing(tmp_path, monkeypatch): + from cronometer_api_mcp import server + + client, state = make_cold_client(tmp_path, []) + monkeypatch.setattr(server, "_client", client) + + result = json.loads(server.update_food_entry(entry_id="1", diary_group="auto")) + + assert result["status"] == "error" + assert '"auto" cannot move an entry' in result["message"] + assert state["payloads"] == [] From 151164793bb1f978e4819f8318fd1e4d9e7c3fd9 Mon Sep 17 00:00:00 2001 From: Randy Westergren Date: Wed, 25 Nov 2026 07:08:36 -0500 Subject: [PATCH 3/3] Fix recipe amount validation and concurrent diary edits Reject gram-weight edits for serving-based recipes, whose API amounts are reference-serving counts. Keep measure and group edits available and document the restriction. Lock each serving's full fetch-modify-save cycle so concurrent partial edits preserve each other's changes. Cover both fixes with regression tests. --- src/cronometer_api_mcp/client.py | 85 ++++++++++++------- src/cronometer_api_mcp/server.py | 3 +- tests/test_diary_edit.py | 138 ++++++++++++++++++++++++++++++- 3 files changed, 190 insertions(+), 36 deletions(-) diff --git a/src/cronometer_api_mcp/client.py b/src/cronometer_api_mcp/client.py index 87d0a67..9d3bf7a 100644 --- a/src/cronometer_api_mcp/client.py +++ b/src/cronometer_api_mcp/client.py @@ -197,7 +197,8 @@ class CronometerClient: dispatches on worker threads. Auth state transitions are serialized (see `_auth_lock`), edits to a given custom food are serialized per food id (see `_food_lock`), and macro split reads/writes share `_macro_split_lock`. - Macro target updates share `_macro_targets_lock`. + Macro target updates share `_macro_targets_lock`, and diary serving edits + are serialized per serving id (see `_serving_lock`). """ def __init__(self, *, session_path: Path | None = None) -> None: @@ -216,6 +217,8 @@ def __init__(self, *, session_path: Path | None = None) -> None: # entire object. `_food_locks_guard` protects the lock registry. self._food_locks: dict[int, threading.Lock] = {} self._food_locks_guard = threading.Lock() + self._serving_locks: dict[str, threading.Lock] = {} + self._serving_locks_guard = threading.Lock() self._macro_targets_lock = threading.Lock() self._macro_split_lock = threading.Lock() @@ -1670,6 +1673,15 @@ def add_serving( ) return data + def _serving_lock(self, serving_id: str | int) -> threading.Lock: + """Serialize the fetch-modify-save cycle for one diary serving.""" + key = str(serving_id) + with self._serving_locks_guard: + lock = self._serving_locks.get(key) + if lock is None: + lock = self._serving_locks[key] = threading.Lock() + return lock + def update_serving( self, serving_id: str | int, @@ -1692,7 +1704,8 @@ def update_serving( Args: serving_id: The servingId from get_diary. day: The day the serving is logged on. Defaults to today. - grams: New weight in grams. + grams: New weight in grams. Requires a weight-based food or recipe; + serving-based recipes store reference-serving counts instead. measure_id: New display measure (grams stays the amount). diary_group: New meal group number, as resolve_diary_group returns it for one of the account's enabled groups. @@ -1708,38 +1721,46 @@ def update_serving( if diary_group is not None and not 0 <= diary_group <= 0xFFFF: raise ValueError(f"diary_group must be 0-65535, got {diary_group}") - entries = self.get_diary(day).get("diary", []) - serving = next( - (e for e in entries if str(e.get("servingId")) == str(serving_id)), - None, - ) - if serving is None: - raise CronometerError( - f"No serving {serving_id} in the diary for {self._format_day(day)}" + with self._serving_lock(serving_id): + entries = self.get_diary(day).get("diary", []) + serving = next( + (e for e in entries if str(e.get("servingId")) == str(serving_id)), + None, ) + if serving is None: + raise CronometerError( + f"No serving {serving_id} in the diary for {self._format_day(day)}" + ) - serving = dict(serving) - if grams is not None: - serving["grams"] = grams - if measure_id is not None: - serving["measureId"] = measure_id - if diary_group is not None and serving.get("order", 0) >> 16 != diary_group: - last = max( - ( - e.get("order", 0) & 0xFFFF - for e in entries - if e.get("order", 0) >> 16 == diary_group - ), - default=0, - ) - serving["order"] = (diary_group << 16) | (last + 1) - - payload = {"serving": serving, "config": {"call_version": 2}} - data = self._request("/api/v2/edit_serving", payload) - if str(data.get("id")) != str(serving["servingId"]): - raise CronometerError(f"Failed to update serving {serving_id}: {data}") - logger.info("Updated serving %s on %s", serving_id, serving.get("day")) - return serving + serving = dict(serving) + if grams is not None: + food = self.get_food(serving["foodId"]) + if any(m.get("type") == "Recipe" for m in food.get("measures") or []): + raise CronometerError( + f"Serving {serving_id} is a serving-based recipe; grams updates " + "require a weight-based food or recipe. Change this amount " + "in Cronometer instead." + ) + serving["grams"] = grams + if measure_id is not None: + serving["measureId"] = measure_id + if diary_group is not None and serving.get("order", 0) >> 16 != diary_group: + last = max( + ( + e.get("order", 0) & 0xFFFF + for e in entries + if e.get("order", 0) >> 16 == diary_group + ), + default=0, + ) + serving["order"] = (diary_group << 16) | (last + 1) + + payload = {"serving": serving, "config": {"call_version": 2}} + data = self._request("/api/v2/edit_serving", payload) + if str(data.get("id")) != str(serving["servingId"]): + raise CronometerError(f"Failed to update serving {serving_id}: {data}") + logger.info("Updated serving %s on %s", serving_id, serving.get("day")) + return serving # ------------------------------------------------------------------ # Diary: notes diff --git a/src/cronometer_api_mcp/server.py b/src/cronometer_api_mcp/server.py index 89088ec..06815b0 100644 --- a/src/cronometer_api_mcp/server.py +++ b/src/cronometer_api_mcp/server.py @@ -473,7 +473,8 @@ def update_food_entry( Args: entry_id: Serving/entry ID from get_food_log. date: Date the entry is logged on as YYYY-MM-DD (defaults to today). - grams: New weight of the serving in grams. + grams: New weight of the serving in grams. Only supported for weight-based + foods and recipes; change serving-based recipe amounts in Cronometer. measure_id: New measure/unit ID from get_food_details (the amount is still given in grams). diary_group: Move to another meal: the name of one of the account's diff --git a/tests/test_diary_edit.py b/tests/test_diary_edit.py index fa5370c..d4c3822 100644 --- a/tests/test_diary_edit.py +++ b/tests/test_diary_edit.py @@ -6,10 +6,15 @@ from __future__ import annotations +import copy +import json +import threading +from concurrent.futures import ThreadPoolExecutor from datetime import date import pytest -from test_client import make_cold_client +from test_client import SAMPLE_FOODS, make_cold_client +from test_custom_food_edit import stored_recipe from cronometer_api_mcp.client import CronometerError @@ -41,14 +46,20 @@ def diary(*entries) -> dict: EDITED = {"messages": [], "id": SERVING_ID} +FOOD = { + "id": 5442, + "defaultMeasureId": 14990, + "measures": [{"id": 14990, "name": "g", "type": "Weight", "value": 1}], +} def test_update_serving_changes_grams_and_keeps_the_rest(tmp_path): - client, state = make_cold_client(tmp_path, [diary(serving()), EDITED]) + client, state = make_cold_client(tmp_path, [diary(serving()), FOOD, EDITED]) result = client.update_serving(SERVING_ID, DAY, grams=150) - sent = state["payloads"][1] + assert state["payloads"][1]["id"] == FOOD["id"] + sent = state["payloads"][2] assert sent["config"] == {"call_version": 2} assert sent["serving"] == serving(grams=150) assert result == serving(grams=150) @@ -102,3 +113,124 @@ def test_update_serving_validates_before_any_request(tmp_path, kwargs, message): client.update_serving(SERVING_ID, DAY, **kwargs) assert state["payloads"] == [] + + +@pytest.mark.parametrize( + "kwargs", + [ + {"grams": 100}, + {"grams": 100, "measure_id": 31}, + {"grams": 100, "diary_group": 5}, + ], +) +def test_update_serving_rejects_recipe_weights_without_editing(tmp_path, kwargs): + entry = serving(foodId=300, measureId=30, grams=1.1) + recipe = SAMPLE_FOODS[2] + client, state = make_cold_client(tmp_path, [diary(entry), recipe, EDITED]) + + with pytest.raises(CronometerError, match="serving-based recipe"): + client.update_serving(SERVING_ID, DAY, **kwargs) + + assert len(state["payloads"]) == 2 + assert all("serving" not in p for p in state["payloads"]) + + +def test_update_food_entry_reports_unsupported_recipe_weight(tmp_path, monkeypatch): + from cronometer_api_mcp import server + + entry = serving(foodId=300, measureId=30, grams=1.1) + client, state = make_cold_client(tmp_path, [diary(entry), SAMPLE_FOODS[2]]) + monkeypatch.setattr(server, "_client", client) + + result = json.loads( + server.update_food_entry(str(SERVING_ID), DAY.isoformat(), grams=100) + ) + + assert result["status"] == "error" + assert "serving-based recipe" in result["message"] + assert "in Cronometer instead" in result["message"] + assert len(state["payloads"]) == 2 + + +def test_update_serving_changes_weight_based_recipe_amount(tmp_path): + recipe = stored_recipe() + entry = serving(foodId=recipe["id"], measureId=1) + client, state = make_cold_client(tmp_path, [diary(entry), recipe, EDITED]) + + result = client.update_serving(SERVING_ID, DAY, grams=150) + + assert result == {**entry, "grams": 150} + assert state["payloads"][-1]["serving"] == result + + +@pytest.mark.parametrize( + "kwargs", + [{"measure_id": 31}, {"diary_group": 5}, {"measure_id": 31, "diary_group": 5}], +) +def test_update_serving_preserves_recipe_amount_on_measure_or_group_edit( + tmp_path, kwargs +): + entry = serving(foodId=300, measureId=30, grams=1.1) + client, state = make_cold_client(tmp_path, [diary(entry), EDITED]) + + result = client.update_serving(SERVING_ID, DAY, **kwargs) + + expected = dict(entry) + if "measure_id" in kwargs: + expected["measureId"] = kwargs["measure_id"] + if "diary_group" in kwargs: + expected["order"] = (kwargs["diary_group"] << 16) | 1 + assert result == expected + assert state["payloads"][-1]["serving"] == expected + assert len(state["payloads"]) == 2 + + +def test_concurrent_serving_edits_preserve_both_changes(tmp_path, monkeypatch): + client, _ = make_cold_client(tmp_path, []) + stored = serving() + state_lock = threading.Lock() + first_fetched = threading.Event() + release_first = threading.Event() + second_started = threading.Event() + second_fetched = threading.Event() + reads = 0 + + def request(endpoint, payload): + nonlocal stored, reads + if endpoint == "/api/v2/get_diary": + with state_lock: + snapshot = copy.deepcopy(stored) + reads += 1 + first = reads == 1 + if first: + first_fetched.set() + assert release_first.wait(timeout=5) + else: + second_fetched.set() + return diary(snapshot) + if endpoint == "/api/v2/get_food": + return FOOD + assert endpoint == "/api/v2/edit_serving" + with state_lock: + stored = copy.deepcopy(payload["serving"]) + return EDITED + + def move(): + second_started.set() + return client.update_serving(str(SERVING_ID), DAY, diary_group=5) + + monkeypatch.setattr(client, "_request", request) + with ThreadPoolExecutor(max_workers=2) as pool: + amount = pool.submit(client.update_serving, SERVING_ID, DAY, grams=150) + try: + assert first_fetched.wait(timeout=5) + moved = pool.submit(move) + assert second_started.wait(timeout=5) + fetched_before_save = second_fetched.wait(timeout=0.2) + finally: + release_first.set() + amount.result(timeout=5) + moved.result(timeout=5) + + assert not fetched_before_save + assert stored == serving(grams=150, order=(5 << 16) | 1)