Compare commits

..
33 Commits
Author SHA1 Message Date
hermes 8e4770f870 fix(ui): make the advice pop-out fail-safe against a stale stylesheet (#22)
Build and Push Image / Build and push image (push) Successful in 3m33s
fix(ui): make the advice pop-out fail-safe against a stale stylesheet (#22)
2026-11-09 22:41:44 +10:00
hermes fb1088ceec fix(ui): make the advice pop-out fail-safe against a stale stylesheet
The screenshot from Firefox showed the advice expanded inline in the
table cell, running down the column and off the screen, with the long
and short labels both showing ("BREWING ADVICEADVICE").  The page had
the new markup and Firefox was serving a stale stylesheet.

Two fixes.

The static files now send Cache-Control: no-store.  They sent
no-cache, which means "revalidate" - and Firefox was reusing them
without revalidating.  no-store is the only one that means "do not
keep this".  The HTML pages already sent no-store.

The pop-out carries the hidden attribute, and the script removes it
when the panel opens and puts it back when it closes.  That makes the
MARKUP fail-safe rather than the stylesheet: a stylesheet that does
not know about .advice-pop at all still leaves the panel hidden, so
the advice can never appear expanded inside the cell.

Verified by removing all eight .advice-pop rules from the live
stylesheet - the panel stays hidden, 0x0, and the advice is not
rendered.  Before this it would have rendered inline.

The button still opens it on tap and on hover, and the close button
still closes it.  The desktop is unchanged: the same full headings and
the same hover pop-out.

195 tests pass.
2026-11-09 22:41:20 +10:00
hermes cd45cc2f17 fix(advice): guard the advice write on the comment as well as the token (#21)
Build and Push Image / Build and push image (push) Successful in 3m10s
fix(advice): guard the advice write on the comment as well as the token (#21)
2026-11-09 22:27:01 +10:00
hermes e603f23928 fix(advice): guard the advice write on the comment as well as the token
The editing token catches every edit the application makes, because
upsert_reading writes a fresh token on every write.  A document edited
outside the application - by a script, or by hand - keeps its empty
token, so a stale thread's write would still match on the gravity alone
and could put advice about the old comment back.

The advice is generated from the comment as well as the gravity, so the
comment is now a second, independent guard on the write.  A stale write
can only land if BOTH the gravity and the comment are unchanged.

The stored comment and the one the view sees can differ by trailing
whitespace - two of the live readings are padded - so the match is a
stripped, anchored regex rather than an exact one.

Also: the log message said the reading 'no longer holds the gravity it
was written for', but the guard is the token and the comment.  It now
says what actually happened.

194 tests pass.
2026-11-09 22:26:29 +10:00
hermes a38febaca8 fix(advice): return matched_count, and do not advise about the wrong reading (#20)
Build and Push Image / Build and push image (push) Successful in 3m15s
fix(advice): return matched_count, and do not advise about the wrong reading (#20)
2026-11-09 22:16:46 +10:00
hermes ef0d665b78 fix(advice): return matched_count, and do not advise about the wrong reading
set_reading_advice returned modified_count, which is 0 both when the
guard refused the write and when the write matched but the text was
already identical.  The caller logs "the advice was not stored" on 0,
so it has to mean "the guard refused it".  It now returns
matched_count.

_start_advice fell back to the newest reading when the reading it was
asked about was not in the run.  That described the wrong number, and
the conditional write would refuse it anyway - so it now says so and
stops.

The editing token is the primary guard on the write, not the gravity.
Every edit writes a fresh token, so a comment-only correction - which
leaves the gravity unchanged - is caught too.  Verified against live
Mongo with the real repository code: the fresh advice lands, the slow
stale thread is refused, and the brewer's comment is untouched.

193 tests pass.
2026-11-09 22:16:29 +10:00
hermes 81ebdf3c76 fix(ui): stop the pages being cached, and the labels duplicating (#19)
Build and Push Image / Build and push image (push) Successful in 3m29s
fix(ui): stop the pages being cached, and the labels duplicating (#19)
2026-11-09 22:06:58 +10:00
hermes e473850aac fix(ui): stop the pages being cached, and the labels duplicating
Firefox served a cached copy of the brewing page after the advice
became a button and a pop-out, so the phone kept showing the old
inline advice - a long paragraph in the table cell, with the button
label reading "Read the adviceAdvice".

Two separate causes:

The pages had no cache headers, so Firefox was free to reuse them.
They now send Cache-Control: no-store, must-revalidate.

The rule that hides the short label was scoped to `table.data .short`,
so it did not apply to the advice button's label.  A stale stylesheet
then showed both forms at once.  The rule is now on `.short` alone, so
it applies wherever the pattern is used - a table heading, the advice
button, the Active Beers page - and only ever one form can show.

Verified at 390px and 1280px: the phone shows "Advice", the desktop
shows "Read the advice" and "BREWING ADVICE", and no element ever
shows both.

192 tests pass.
2026-11-09 22:06:42 +10:00
hermes 571e7cb8c8 fix(ui): keep the table columns readable on a phone (#18)
Build and Push Image / Build and push image (push) Successful in 3m20s
fix(ui): keep the table columns readable on a phone (#18)
2026-11-09 21:48:20 +10:00
hermes 27b2611a20 fix(ui): keep the table columns readable on a phone
The tables were squeezed to fit the screen, and with seven to nine
columns on a 390px phone every heading and every value was truncated to
a few characters - a gravity of "1.0..." and a date of "202..." are
worse than useless, and the beer name was painted over the gravity
reading because the cell was allowed to overflow.

The tables keep their natural width and scroll sideways inside their
card, which is what a table does.  The advice is a small button so the
column that matters is narrow, and the headings have a short form for
a phone ("Brewing advice" -> "Advice", "Attenuation" -> "Att.").

The secondary columns - the drop, the legacy ABV and the days - go away
on a phone; the details are still on the run's own page.

A name and a comment get a sensible minimum width and wrap on a word
boundary rather than one word per line.

The desktop is untouched: the same full headings, the same 806px table,
and the pop-out still opens on hover.
2026-11-09 21:48:07 +10:00
hermes 81b2a17b37 fix(ui): dimmed backdrop and a bigger close button on the advice panel (#17)
Build and Push Image / Build and push image (push) Successful in 3m39s
fix(ui): dimmed backdrop and a bigger close button on the advice panel (#17)
2026-11-09 21:14:55 +10:00
hermes 2600622af8 fix(ui): dimmed backdrop and a bigger close button on the advice panel
The panel read as floating in the page rather than sitting over it, and
the close button was a 26px target - too small to hit reliably on a
phone.

The backdrop is a large spread shadow rather than a pseudo element,
which would paint behind the panel's own background.

Also: Escape closes the panel, clicking away closes it, and the button
is a real button so it works with a keyboard.
2026-11-09 21:14:33 +10:00
hermes af28ecbd1b fix(ui): mobile pop-out for the advice, and tables that fit a phone (#16)
Build and Push Image / Build and push image (push) Successful in 12m4s
fix(ui): mobile pop-out for the advice, and tables that fit a phone (#16)
2026-11-09 20:58:06 +10:00
hermes 21fcdf485c test: the advice in the table is a pop-out, not the text 2026-11-09 20:57:34 +10:00
hermes 7dd39190f1 fix(ui): mobile pop-out for the advice, and tables that fit a phone
The brewing advice is several hundred characters.  In a table cell it
pushed the table past the width of a phone, so the column was clipped
off the right edge and the advice could not be read without sideways
scrolling.

The advice is now a compact trigger in the cell and the text is in a
floating panel that opens on hover (desktop) or on tap (phone).

The panel is position:fixed and anchored by the script.  Absolutely
positioned inside the cell it was clipped by the table's own scroll
container, and the advice was sliced in half by the card's edge.  It
flips above the trigger when there is no room below.

The tables now reflow into stacked cards on a narrow screen, with each
value labelled by its column name.  A seven column table does not fit a
phone, and it used to scroll sideways inside its wrapper, so the
columns on the right were off the screen.

Also: the header wraps onto two rows so the nav tabs are not clipped,
the point scale says 'points' rather than 'pts', and the reading count
on the beer card does not orphan its word.
2026-11-09 20:57:34 +10:00
hermes 55b6068b3b feat(advice): LLM brewing advice on every observation (#14)
Build and Push Image / Build and push image (push) Successful in 9m8s
feat(advice): LLM brewing advice on every observation (#14)
2026-11-09 20:23:32 +10:00
hermes 8de3d011db fix(advice): find the marker however the model formats it
The instruction asks for "ADVICE:", but the model writes "**ADVICE:**",
"## ADVICE:" or puts it in a code block.  The extraction has to cope,
because leftover markdown in the advice is visible to the brewer.

The marker is now matched case-insensitively and with the decoration the
model puts around it, and the leftover formatting is stripped.

    plain marker         -> 'Warm it to 20C and wait.'
    bold marker          -> 'Warm it to 20C and wait.'
    in a code block      -> 'Warm it to 20C and wait.'
    marker mid-text      -> 'Warm it to 20C and wait.'
    markdown heading     -> 'Warm it to 20C and wait.'
    lowercase marker     -> 'Warm it to 20C and wait.'
    no marker            -> 'Warm it to 20C and wait.'
    bold + code block    -> 'Warm it to 20C and wait.'

182 tests (up from 181).
2026-11-09 19:46:13 +10:00
hermes 75f94d47e2 fix(advice): a deterministic split, not a guess at where the advice starts
The stripper tried to work out where the model's working ends and the
advice begins by classifying prose - marker words, hedging words,
length.  It failed in BOTH directions, and the review caught both:

- it emptied legitimate advice (a 1,093-character reply containing one
  hedging word and no marker phrase was reduced to ""), so the brewer
  saw nothing at all; and
- it let the model's working through in full (a 1,053-character reply
  with no hedging word was returned verbatim), so the brewer was shown
  the model thinking about their beer.

Neither a marker list nor a length threshold is reliable.  Prose is not
a format.

So the model is asked for the format instead.  Its reply must have this
shape:

    ADVICE:
    <the advice itself>

Everything before the marker is working, everything from it on is the
advice.  The split is exact, with no judgement calls.

Verified against the live model, four different brews:

    Test Pale Ale        marker@pos=0  finish=stop  advice_len=656
    Nocturna Christmas   marker@pos=0  finish=stop  advice_len=668
    Ginger beer          marker@pos=0  finish=stop  advice_len=621
    Cider raspberry      marker@pos=0  finish=stop  advice_len=539

All four start clean, with no marker left in the advice.

A reply with no marker is used as it stands - the safe direction, where
the brewer sees a slightly rambling reply rather than no advice at all.

An empty advice is now recorded as a FAILURE rather than stored as a
successful generation.  Storing an empty string with advice_ok=True
made the page render "Thinking..." for ever, because the template's
`{% if reading.advice %}` was false - so the brewer never learned that
it had failed.

181 tests (up from 184 - the eight heuristic-era stripper tests are
replaced by six that test the marker behaviour).
2026-11-09 19:44:52 +10:00
hermes cbc71716e8 fix(advice): judge the working by its shape, not by its length
A length threshold is a blunt instrument: a legitimate advice reply can
run to a thousand characters, and a short working reply can be a few
hundred - so a threshold gets both wrong.  A 995-character advice reply
with no marker word in it was being emptied.

The reliable signal is the SHAPE.  The model's working is about
INTERPRETING the numbers - what the reading might mean, what could be
causing it, what it is unsure about.  The advice is about what to DO.

So a reply is working when it is full of the model's hedging about the
data AND contains no instruction at all.  Length is only a tie-breaker
for a reply that is both hedged and short.

    995-char legitimate advice  -> kept
    long pure working           -> dropped
    short legitimate advice     -> kept
    long working + advice       -> advice kept

Checked against the live model - a real reply comes back clean, with no
reasoning in it:

    At two weeks in, dropping from 1.055 to 1.020 is a healthy 35-point
    fall - about 64% attenuation - which is right in the normal range for
    a pale ale, though you likely still have 5 to 8 points to go...

184 tests (up from 183).
2026-11-09 19:27:08 +10:00
hermes 4bedd23c24 fix(advice): the no-token guard must cover all three shapes of "no token"
The guard matches on the absence of a token.  `{"$exists": False}` covers
a reading with no token field, but NOT one whose token field is present
and empty.

Verified against the live database, before the fix:

    token present but empty -> write matched: 0   <-- missed it

`{"$in": [None, ""]}` covers all three - a missing field, an empty
field, and a null one - because `$in` with null also matches a missing
field.

    no token field          -> write matched: 1
    token present but empty -> write matched: 1
    token is null           -> write matched: 1

183 tests (up from 182).
2026-11-09 19:10:16 +10:00
hermes d18d037bb9 fix(advice): the pre-token guard, and a stripper that cannot empty real advice
Two findings from the fifth review.

The pre-token fallback re-opened the hole
-----------------------------------------
A reading that has never been edited has no token.  The guard fell back
to the gravity check for those, and a comment-only correction leaves the
gravity unchanged - so a late thread's write matched and overwrote the
fresh advice, for exactly the 47 existing readings.

Reproduced live before the fix:

    pre-token reading token: None  ->  stale thread carries ""
    fresh write modified: 1
    stale write modified: 1   <<< stale advice overwrote the fresh one
    final advice: 'STALE ADVICE'

The guard now matches on the ABSENCE of a token, which still tells the
generations apart: an edit writes a token, so a stale thread's "" stops
matching the moment the reading is corrected.

    fresh write modified: 1 (must be 1)
    stale write modified: 0   (must be 0)

The stripper could empty real advice
------------------------------------
"Actually the drop is fine.\\n\\nWait a couple of days and check again."
is advice, and judging it paragraph by paragraph emptied it - so the
brewer saw nothing at all, with no failure note.

The test is no longer a marker list, which real advice often does not
contain.  A reply is all-working when it is LONG and has no instruction
in it: the model's working runs to thousands of characters, while the
advice is two to five sentences.

    short reply with no marker  -> kept
    long reply, no instruction  -> dropped
    long reply with advice      -> advice kept
    single-paragraph working    -> dropped

Also: the log message named the gravity, but the guard is the token.

182 tests (up from 178).
2026-11-09 19:08:28 +10:00
hermes 7d9d718b41 fix(advice): an empty token must not be used as a guard
None of the 47 existing readings have a token - they all predate it.  A
reading read from the database therefore has an EMPTY token, and the
guard was checking `expected_token is not None`, which is TRUE for an
empty string.  So the write was conditioned on a token that does not
exist, matched nothing, and **the advice would never have been written
for any of the existing readings**.

Verified against the live database, before the fix:

    write with expected_token='' -> 0   (0 = the advice would NEVER be written)

After:

    write for a pre-token live reading: 1   (must be 1)

An empty token is now not a usable guard - there is no token to match -
so the write falls through to the gravity check instead.  A non-empty
token is still the primary guard.

There is a test for it, with a reading inserted the way the existing
ones are - directly, with no token.

178 tests (up from 177).
2026-11-09 18:24:57 +10:00
hermes 27a28b5e58 fix(advice): the stripper must DROP the working, and the token is the guard
Two findings from the fourth review.

The stripper was a no-op in the case it was written for
---------------------------------------------------
The "all working" branch returned the text UNCHANGED, which is
byte-identical to the old fallthrough.  And in the case where a preamble
marker WAS present and no paragraph read like advice, it returned the
whole reply - working included - so the branch made the "store the
working instead of the advice" failure MORE likely, not less.

Measured on a realistic 5-paragraph reasoning reply: the old code stored
80 chars (one paragraph), the new code stored 612 chars (five
paragraphs) of the model's working.

It now DROPS the working, so the reply is empty and the brewer sees a
clear "could not be generated" rather than the model thinking about
their beer.

"keep" alone is not an advice marker
------------------------------------
"I need to keep in mind that the hydrometer was read at a different
temperature" is the model thinking, not advice.  The bare words "keep",
"raise", "lower", "take the" were matching ordinary reasoning phrasing,
so the "all working" detection almost never fired on real reasoning
text.  They are now matched as phrases - "you should keep", "raise it
to", "take another reading" - and "i need to keep in mind" is
explicitly working.

The token is the primary guard
------------------------------
The gravity can be unparseable for some readings, so `expected_sg` can
be None - and then the write was becoming unconditional, reintroducing
the stale-overwrite bug on those readings.

The editing token is the primary guard: it changes on EVERY edit, so it
catches a stale generation whatever else changed - the gravity, the
comment, or nothing.  The gravity is now a secondary check, used only
when there is no token.

177 tests (up from 174).
2026-11-09 18:22:51 +10:00
hermes a78aabe3ea fix(advice): an editing token, so a comment-only correction is safe too
The gravity guard caught a correction that changed the gravity, but a
COMMENT-ONLY correction leaves the gravity unchanged - so the late
thread for the old advice still matched and overwrote the fresh one.

Reproduced against the live database:

    fresh advice matched: 1
    stale thread matched: 1     <-- should be 0
    FINAL advice: 'STALE ADVICE'

Every edit now writes a fresh token onto the reading, and the advice
thread carries the token it was given.  A late thread finds a token that
no longer matches, so its write is refused.  The gravity is still
checked as well.

Verified against the live database:

    token changed: True
    fresh advice matched: 1
    stale thread matched: 0     <-- must be 0
    FINAL advice: 'FRESH ADVICE'

174 tests (up from 173).
2026-11-09 18:14:24 +10:00
hermes 8da3601941 fix(advice): the remaining review findings
Four things from the earlier review of this PR.

The prompt test did not test the prompt
---------------------------------------
`test_the_advice_is_about_the_reading_that_was_saved` asserted which
dict was PASSED to the generator - not what the model was actually ASKED.
So it passed even while the prompt still said "give advice for the most
recent reading", which is the bug that made the model advise about the
wrong number while the advice was filed against the right one.

It now asserts on the prompt content: the reading is marked, its date is
named, and "most recent reading" is gone.

Verified by reverting the prompt fix - the test fails, and so does
`test_the_prompt_names_the_reading_to_advise_about`.  Two tests now
guard it, and reverting the fix breaks both.

A write that matches nothing was silent
--------------------------------------
The advice writer discarded the return value of `set_reading_advice`.  A
write that matched 0 documents - which is now the EXPECTED outcome when
the brewer corrected the reading while the advice was being generated -
was dropped without a word.  It is logged now.

A stale docstring
-----------------
The background thread "builds its own" client - it has used the shared
one since the leak was fixed.

A missing CSS class
-------------------
`advice--reading` is used on the active-beers card and the run detail
page, and was never defined, so it had no styles.

173 tests (unchanged - the new assertions were added to existing tests).
2026-11-09 17:47:14 +10:00
hermes 3e1e4f42b7 fix(advice): stale advice must not overwrite a correction
The review found a race between the background advice thread and the
brewer correcting a reading.

`set_reading_advice` wrote unconditionally by id.  The advice is
generated in the background, so if the brewer corrects a reading while
the advice for the OLD gravity is still being generated, the slow thread
lands afterwards and overwrites the fresh advice with advice about a
reading that no longer exists.  The reading ends up with the final
gravity from the correction and the advice from before it.

Reproduced against the live database:

    wrote advice for 1050
    wrote advice for 1020
    late stale write matched: 0
    final sg: 1020 | final advice: 'ADVICE FOR THE CORRECTION'

The write is now conditional on the reading still holding the gravity
the advice was generated for, so a late thread matches nothing.

Also
----
`finish_reason` is now checked.  A reply that stopped at the token
ceiling is incomplete - it may be advice that stops mid-sentence - and
it was being stored as if it were the whole answer.  It is now marked
as cut off.

173 tests (up from 171).
2026-11-09 17:45:16 +10:00
hermes b414240bb5 fix(advice): keep the advice when the reply is over-long
The review found a way to store the model's WORKING instead of its
advice.

The advice is at the END of the reply, so the length cap was cutting
from the front - which took the advice off and left only the working.
That is worse than no advice at all, because it looks like advice: the
brew sees a full paragraph of the model thinking about their beer, and
nothing about what to do.

Reproduced:

    input len: 2515 -> final len: 1199
    advice present? False
    TAIL: 'padding padding padding padding padding'

Two changes:

- The length cap keeps the END of the reply and cuts at a sentence
  boundary near the end, so the advice survives.
- The stripper now also catches a reply that is entirely working - no
  marker phrase, and no paragraph that reads like advice - instead of
  only catching one that says "let me think".

    input: 2515 -> stripped: 2515 -> final: 1199
    advice present? True

A short reply is untouched.

171 tests (up from 169).
2026-11-09 17:36:13 +10:00
hermes cf08b751e4 feat(advice): use mistral-large-4, and cope with models that show their working
The model is now `mistral-large-4:cloud`, on the same Ollama instance.
It was probed before being made the default - `deepseek-v4-flash:cloud`,
`deepseek-v3.2:cloud` and `qwen3.5:cloud` are all retired and fail at
call time while still appearing in the model list.

What the probes showed
----------------------
`think: false` does NOT stop the reasoning.  It only changes where the
working goes: with thinking off, the model writes it into the CONTENT
instead of a separate field.  Either way the reasoning comes out of the
same token allowance as the answer, and at 500-3000 tokens the reply
came back EMPTY - which looks like a broken model rather than a budget
problem.  The budget is now 8000, and the timeout 120s.

The reply is also stripped of a reasoning preamble.  The advice is the
prose at the END; the working comes first, in several paragraphs.  The
preamble is found by walking back from the end of the reply and keeping
the paragraphs that read like advice to the brewer, rather than like
the model thinking out loud.

Verified against the live model, on a stalled brew (OG 1.042, 1.022 after
nine days, "no change since day 7"):

    That 1.022 reading after nine days at 19C - with no movement since
    day seven - looks like a stalled fermentation; a 1.042 wort should
    be well on its way to 1.010-1.012 by now, not sitting at only about
    48% attenuation. Gently swirl the fermenter to rouse the yeast cake
    and keep the temperature steady at 19-20C, and if the gravity hasn't
    budged in another 48 hours, pitch a fresh, healthy yeast starter...

And on a CORRECTED older reading - the case the review found broken -
the advice is about the corrected reading, with the later one as context:

    A brew-day reading of 1.038 against an OG of 1.042 is only four points
    low, which is almost certainly just the normal difference between
    your kettle gravity and the post-transfer fermenter reading...

169 tests (up from 167).
2026-11-09 17:10:24 +10:00
hermes 0011f30e59 fix(advice): a race in the shared repository, and the prompt naming the wrong reading
Two findings from the re-review of PR #14.

A race that recreated the leak
-------------------------------
`get_shared_repository()` did an unsynchronised check-then-set on a
module global.  Eight concurrent advice threads on a cold process each
saw None and each built their own repository - so eight MongoClients and
twenty-five threads.  The fix that was meant to remove the leak
reintroduced it, just bounded by a race instead of by the number of
readings.

Measured before: 8 repositories built, 25 threads.
Measured after:  1 repository built,  4 threads.

There is a lock, and the check is repeated inside it.

The prompt was about the wrong reading
--------------------------------------
The advice targeted the right reading, but the PROMPT said "give advice
for the most recent reading" - and when the brewer corrects an OLDER
reading, the most recent one in the history is a different reading.  So
the model was asked about the wrong number while the advice was filed
against the right one.

The reading is now named in the instruction (with its date and gravity),
marked in the reading list as the one to advise on, and the system prompt
says to advise about the marked reading because it may not be the most
recent one.

A corrected reading is also flagged as such, so the model knows it may
differ from what it said before.

167 tests (up from 164).
2026-11-09 17:04:57 +10:00
hermes 21fa0d9a12 fix(advice): make the id helper unusable rather than merely rejected
_as_doc_id returned None for a hostile id.  That was guarded at the one
call site, but the helper could still be misused into "$in needs an
array" - and a caller who forgot the guard would have got an error
rather than a safe no-op.

It now returns an EMPTY LIST for anything that is not a reading id.  An
empty list is a valid $in argument that matches nothing, so the helper
cannot produce a query error, cannot match every document, and cannot be
interpreted as a query operator.

Verified against the live database: a hostile id matches 0 documents and
updates 0 documents.

164 tests.
2026-11-09 16:31:05 +10:00
hermes 6dd0b7b046 fix(advice): the review findings - the ids, the client leak, the wrong reading
The review of PR #14 found a critical defect and two real bugs.  All
verified against the live database, not just read.

CRITICAL - the advice would never have been stored
--------------------------------------------------
`_as_doc_id` accepted only an ObjectId or a string that parses as one.
But **all 47 live readings have string `_id`s** - 24 random characters
from the original app's importer, like `l78ZidBJ3QaYn98tvB88x4uM`.  The
helper turned every one of them into None, so the update matched nothing
and the advice was silently never stored in production.

The mongomock fixture generates ObjectIds, so the tests could not see it.
`_as_doc_id` now returns both forms and the query uses `$in` (a plain
list would be an exact ARRAY match in Mongo, which is not what is
wanted).  Verified against the live database: the advice now lands on a
real reading, with the brewer's comment untouched.

There are now tests for BOTH id shapes, with the string shape built
explicitly, because the fixture would not produce it.

The advice was written about the wrong reading
----------------------------------------------
`latest` was taken from the date-sorted tail of the run, so editing an
OLDER reading generated advice about the NEWEST one.  The advice is now
written against the reading that was actually saved.

A leaked MongoClient per reading
--------------------------------
The background thread built a `BeerRepository()` - and therefore a
`MongoClient` - for every advice write, and never closed it.  A
MongoClient spawns three monitor threads and pymongo does NOT reap them
on `close()`; they go only when the client is garbage collected.

Measured: three threads and a connection pool accumulated per reading
recorded.  There is now one shared repository for the life of the
process, which is what the request-scoped repository does too.  Measured
again after the fix: 4 threads total, not 16 over five writes.

Also
----
- `BeerRepository` gained `close()` and the context-manager protocol.
- The advice writer now logs instead of dying silently if the write
  fails.

164 tests (up from 160).
2026-11-09 16:29:39 +10:00
hermes d0aef7a787 fix(advice): clear stale advice on edit, and pin the injection guard
Two things I wanted to be sure of before this merges.

Stale advice
------------
The advice is written for the gravity that was there when it was
generated.  If the brewer then edits the reading - to fix a typo, or to
mark it final - the old advice no longer describes it, and the page was
showing advice that contradicted the number next to it.

`upsert_reading` now clears the advice fields, so the stale advice goes
and a fresh one is generated (the form already regenerates on every save).
Only the advice fields are cleared - the brewer's own comment is never
touched.

The injection guard
-------------------
The reading's `_id` is an ObjectId, so the original `_as_id` coercion
(which turns run ids into plain strings, to stop a caller passing a dict
that Mongo would interpret as a query operator) did not apply - it turned
the ObjectId into an empty string and the update silently matched
nothing.  `_as_doc_id` accepts only an ObjectId or a string that parses as
one.

Verified against a live injection attempt: `{"$ne": None}`, `{"$gt": ""}`,
a list, an int, None and a non-ObjectId string all return None and match
nothing.  There is now a test that pins it, because it is a security
property that would otherwise only be covered by reading the code.

160 tests (up from 158).
2026-11-09 16:05:59 +10:00
hermes ab3050194d feat(advice): LLM brewing advice on every observation (work in progress)
Stores a model's advice for each recorded reading, in its own field, so the
brewer's own comment is never overwritten.

Fire and forget: the advice is generated in a background thread, so
recording a reading never blocks on the model.  A failure is recorded as a
visible note saying the advice could not be generated, because a silent
failure is indistinguishable from "still thinking".

The model is `glm-5.3:cloud` on the Ollama instance at 192.168.178.45:11434.
Several models on that instance are retired and fail at call time while
still appearing in the model list, so the default is one that was probed.

The system prompt tells the model never to call a reading impossible: a
gravity below 1.000 is always a mis-entry, but the rest of the run may be a
genuine long fermentation and still worth understanding.

150 tests.
2026-11-09 16:03:29 +10:00
14 changed files with 2690 additions and 106 deletions
+25
View File
@@ -87,6 +87,31 @@ def create_app(config: dict | None = None) -> Flask:
if config:
app.config.update(config)
# The pages must not be cached by the browser.
# A phone held on to a cached copy of the brewing page and showed
# the old inline advice instead of the button and the pop-out, so
# the change was not visible until the cache was cleared by hand.
@app.after_request
def _no_store(response):
if response.mimetype == "text/html":
response.headers["Cache-Control"] = "no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
elif response.mimetype in ("text/css", "application/javascript",
"text/javascript"):
# The static files must NEVER be reused from a cache.
# Firefox kept serving a stale stylesheet even with
# `no-cache`, which meant the page had the new markup and
# the old CSS: the advice was expanded inline in the table
# instead of in a pop-out, and the long and short labels
# were both showing ("BREWING ADVICEADVICE").
# `no-store` is the only one that means "do not keep this".
response.headers["Cache-Control"] = "no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
return response
csrf = CSRFProtect(app)
# ------------------------------------------------------------------ #
+368
View File
@@ -0,0 +1,368 @@
"""Brewing advice from an LLM, generated for each recorded observation.
The advice is a *comment on the reading*, not a replacement for the
brewer's own comment. Every reading gets its own advice text, stored in
its own field, so nothing the brewer wrote is ever overwritten.
Design notes
------------
- **The LLM is never in the request path.** Recording a reading must not
block on a model that may be slow or down, so the advice is generated in
a background thread and written when it is ready. The page shows the
reading immediately and the advice appears on a later visit.
- **Failures are recorded, not raised.** If the model is unreachable the
advice field gets a short note saying so. A silent failure would look
identical to "no advice yet", which is confusing when you are waiting
for a tip that is never going to arrive.
- **The model is configurable**, with a default that is known to work on
this homelab. Several models on the Ollama instance have been retired
and fail at call time while still appearing in the model list, so the
default is verified rather than assumed.
"""
from __future__ import annotations
import json
import logging
import os
import re
import urllib.error
import urllib.request
log = logging.getLogger(__name__)
#: The Ollama instance on the homelab. Reachable from the pod.
DEFAULT_OLLAMA_URL = os.getenv("OLLAMA_URL", "http://192.168.178.45:11434")
#: The model to use. Override with the ``OLLAMA_MODEL`` environment
#: variable.
#:
#: A model that does NOT reason is much better here. The reasoning
#: models emit their thinking out of the same token allowance as the
#: answer, and several of them burned the whole budget on thinking and
#: returned an EMPTY reply - which looks like a broken model rather than
#: a budget problem. With `think: false` the model still shows its
#: working, but inline in the content, so the answer can be taken from
#: the end of it.
#:
#: `deepseek-v4-flash:cloud`, `deepseek-v3.2:cloud` and `qwen3.5:cloud`
#: are all retired and fail at call time while still appearing in the
#: model list, so the default is one that was probed.
DEFAULT_MODEL = os.getenv("OLLAMA_MODEL", "mistral-large-4:cloud")
#: How long to wait for the model before giving up. The advice is
#: generated in the background, so this only bounds the background thread.
DEFAULT_TIMEOUT = float(os.getenv("LLM_TIMEOUT", "120"))
#: The advice is advice, not instruction. Keep it short - it has to be
#: readable on the brewing page next to the brewer's own comment.
MAX_ADVICE_CHARS = 1200
SYSTEM_PROMPT = """\
You are an experienced home brewer giving practical advice to a single \
brewer about their own beer. You know brewing science: specific gravity, \
attenuation, yeast health, temperature, timing, and what a stalled or \
struck-out fermentation looks like.
You will be given one brew's readings so far: its name, the original \
gravity, each reading's date and specific gravity, and any comment the \
brewer wrote.
Give the brewer useful, specific, practical advice about THIS reading and \
this brew. Consider things like:
- Is the fermentation progressing at a normal rate for the style and \
temperature?
- Has it stalled, and if so what should they do about it?
- Is the yeast likely stressed, unhealthy, or done?
- Is the gravity drop plausible for the original gravity?
- Should they rack, add more hops, raise the temperature, or wait?
Rules:
- Your reply must have this exact shape:
ADVICE:
<the advice itself, two to five sentences of plain prose>
The line "ADVICE:" comes FIRST, on its own line, with nothing before
it. Do not explain your reasoning and do not show your working.
- Advise about the reading that is marked as the one to advise on. It
may not be the most recent one - the brewer may be correcting an older
reading - and the advice must be about the reading they asked about.
- If everything looks normal, say so briefly and say what to expect next.
- If something looks wrong, say what it is and what to do about it.
- Be specific to the numbers given. Do not give generic advice.
- If a reading looks like a typo or a mis-entry, say so and suggest \
checking it, but do not assume it - a slow or long fermentation can be \
genuine.
- Never say a reading is impossible. Beer cannot be denser than water, so \
a gravity below 1.000 is always a mis-entry or a typo, but the rest of the \
run may still be real and worth understanding.
- No preamble, no headings, no bullet-point templates, no "Great question!". \
Write two to five sentences of plain prose.
"""
def _reading_lines(readings: list[dict], subject_id: str | None = None) -> str:
"""The readings, as the compact list the model reads.
The reading being advised about is marked, so the model does not have
to work out which one from the dates - the brewer may be correcting
an older reading.
"""
lines = []
for r in readings:
parts = [f"- {r.get('date')}: gravity {r.get('sg_decimal')} ({r.get('point_scale')})"]
if r.get("comment"):
parts.append(f"brewer's comment: {r['comment']}")
if r.get("final"):
parts.append("(marked as the FINAL reading)")
if subject_id is not None and str(r.get("_id")) == str(subject_id):
parts.append("<<< THIS IS THE READING TO ADVISE ON")
lines.append(" ".join(parts))
return "\n".join(lines)
def build_prompt(run: dict, reading: dict, history: list[dict],
corrected: bool = False) -> str:
"""The user-message content for one observation.
*corrected* says the reading has just been edited, so the advice
should take that into account.
"""
name = run.get("canonical_name") or run.get("name") or "this brew"
og = run.get("og_decimal")
if og is None and run.get("og_points"):
og = f"{run['og_points'] / 1000:.3f}"
parts = [
f"Beer: {name}",
]
if og:
parts.append(f"Original gravity: {og}")
if run.get("tap_number"):
parts.append(f"Fermenter tap: {run['tap_number']}")
if run.get("notes"):
parts.append(f"Brewer's notes: {run['notes']}")
parts.append("")
parts.append("Readings so far (oldest first):")
parts.append(_reading_lines(history, subject_id=reading.get("_id")))
parts.append("")
# The reading being advised about is NAMED, not just described as
# "the most recent one". The brewer may be editing an older reading,
# and the advice is about THAT reading - so the prompt has to say
# which one, or the model advises about the newest instead.
parts.append(
f"Give advice about the reading dated {reading.get('date') or 'unknown'}"
f" (gravity {reading.get('sg_decimal')}),"
+ (" which the brewer has just corrected." if corrected else "")
)
if corrected:
parts.append(
"It is the reading they have just corrected, so it may differ "
"from what it said before."
)
return "\n".join(parts)
def call_ollama(prompt: str, *, url: str | None = None, model: str | None = None,
timeout: float | None = None) -> str:
"""Ask the model for advice. Raises on failure."""
base = (url or DEFAULT_OLLAMA_URL).rstrip("/")
chosen_model = model or DEFAULT_MODEL
wait = timeout if timeout is not None else DEFAULT_TIMEOUT
payload = json.dumps({
"model": chosen_model,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": prompt},
],
"temperature": 0.4,
# The reasoning models emit their thinking first, and it comes out
# of the SAME budget as the answer. At 500 tokens the reasoning
# used the whole allowance and the reply came back empty - which
# looks like a broken model rather than a budget problem.
#
# `think: false` does NOT help: the models still think, they just
# put the working in the content instead of a separate field.
# So the budget has to cover the reasoning AND the advice.
"max_tokens": 8000,
"stream": False,
}).encode("utf-8")
request = urllib.request.Request(
f"{base}/v1/chat/completions",
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=wait) as response:
body = json.loads(response.read().decode("utf-8"))
choices = body.get("choices") or []
if not choices:
raise RuntimeError("the model returned no choices")
message = choices[0].get("message") or {}
# Some models put their working in a separate field. It is ignored -
# the advice is the content.
content = message.get("content") or ""
content = content.strip()
if not content:
raise RuntimeError("the model returned an empty response")
# A reply cut off at the token ceiling is INCOMPLETE. It may be
# advice that stops mid-sentence, so it is marked as truncated rather
# than stored as if it were the whole answer.
finish_reason = choices[0].get("finish_reason") or body.get("done_reason")
truncated = finish_reason == "length"
advice = _trim_advice(_strip_reasoning(content))
if truncated:
advice = _trim_advice(advice + " (the reply was cut off)")
return advice, truncated
def _trim_advice(text: str) -> str:
"""Cut the advice down to the readable length, keeping the END.
The advice is at the end of the reply, so a plain truncation from the
front would cut the advice off and leave only the model's working -
which is worse than no advice at all, because it looks like advice.
So an over-long reply is cut at a sentence boundary near the end.
"""
if len(text) <= MAX_ADVICE_CHARS:
return text
tail = text[-MAX_ADVICE_CHARS:]
# Start at the first sentence break in the tail, so it does not begin
# mid-word.
for separator in (". ", "? ", "! "):
index = tail.find(separator)
if index != -1 and index < 200:
return tail[index + 2:].strip()
return tail.strip()
#: The marker the model is asked to put at the start of its advice.
#:
#: Guessing where the advice begins by classifying prose is unreliable
#: in both directions - it emptied legitimate advice, and it let the
#: model's working through in full. A marker the model writes itself is
#: deterministic: everything before it is working, everything from it on
#: is the advice.
_ADVICE_MARKER = "ADVICE:"
def _strip_reasoning(text: str) -> str:
"""Take the advice out of a reply.
The model is asked to put ``ADVICE:`` on its own line at the start
of the advice, so the working before it can be dropped exactly, and
the advice kept exactly.
A reply with no marker is used as it stands. That is the safe
direction: the model was asked for the marker, so a reply without
one is one where it wrote the advice straight away - and if the
working did leak in, the brewer sees a slightly rambling reply
rather than no advice at all.
"""
index = _find_marker(text)
if index is None:
return text.strip()
advice = text[index:].strip()
# The model may wrap the marker in markdown or a code block. Strip
# the leftover formatting so the advice reads as prose.
advice = re.sub(r"^\*\*|\*\*$", "", advice).strip()
if advice.startswith("```"):
advice = advice[3:]
if advice.endswith("```"):
advice = advice[:-3]
if advice.startswith("##"):
advice = advice.lstrip("#").strip()
return advice.strip() or ""
def _find_marker(text: str) -> int | None:
"""Where the advice starts, or ``None`` if there is no marker.
The marker is matched case-insensitively and with the markdown
decoration the model might put around it - ``**ADVICE:**``,
``## ADVICE:`` - because the instruction asks for "ADVICE:" but the
model formats it its own way often enough to matter.
"""
match = re.search(r"^[\s#>\*]*advice\s*:[\s\*>]*", text,
re.IGNORECASE | re.MULTILINE)
if match:
return match.end()
return None
def generate_advice(run: dict, reading: dict, history: list[dict], *,
corrected: bool = False,
url: str | None = None, model: str | None = None,
timeout: float | None = None) -> tuple[bool, str]:
"""Generate the advice for one reading.
Returns ``(ok, text)``. On failure ``ok`` is False and ``text`` is a
short note explaining what went wrong, so the reading carries a
visible reason instead of silently having no advice.
"""
prompt = build_prompt(run, reading, history, corrected=corrected)
try:
advice, _truncated = call_ollama(prompt, url=url, model=model,
timeout=timeout)
if not advice:
# The reply had no advice in it - the model wrote only its
# working, or the marker was missing and nothing followed it.
# Storing an empty string with advice_ok=True would render
# as "Thinking..." for ever, so it is recorded as a failure
# with a note the brewer can see.
log.warning("the model returned no advice")
return False, ("Advice could not be generated - the model "
"returned only its reasoning.")
return True, advice
except urllib.error.HTTPError as exc:
# HTTPError is a subclass of URLError, so it has to be caught
# FIRST or it would be swallowed by the unreachable branch.
detail = ""
try:
detail = exc.read().decode("utf-8", "replace")[:300]
except Exception:
pass
log.warning("the model returned HTTP %s: %s", exc.code, detail)
return False, (f"Advice could not be generated - the model returned "
f"HTTP {exc.code}. {detail}".strip())
except urllib.error.URLError as exc:
log.warning("the model was unreachable: %s", exc)
return False, "Advice could not be generated - the model was unreachable."
except TimeoutError:
log.warning("the model timed out")
return False, "Advice could not be generated - the model timed out."
except Exception as exc: # noqa: BLE001 - the caller must never crash
log.warning("advice generation failed: %s", exc)
return False, f"Advice could not be generated - {exc}"
def generate_advice_in_background(run: dict, reading: dict,
history: list[dict], writer,
corrected: bool = False) -> None:
"""Generate the advice and hand it to *writer* when it is ready.
*writer* is called as ``writer(reading_id, ok, text)``. It runs in a
background thread, so it must not touch the request context - the
caller is responsible for giving it a way to reach Mongo.
"""
ok, text = generate_advice(run, reading, history, corrected=corrected)
try:
writer(reading.get("_id"), ok, text)
except Exception: # noqa: BLE001 - never let the thread die noisily
log.exception("could not store the generated advice")
+36
View File
@@ -152,6 +152,14 @@ class Reading:
comment: str = ""
beer_type: str = ""
_id: str = ""
# The LLM's advice for this reading. It lives in its own field in
# Mongo, so the brewer's own comment is never overwritten.
advice: str = ""
advice_ok: bool = True
# Marks this generation of the reading. Every edit writes a fresh
# one, so an advice thread working on an earlier version of the
# reading can be told apart from the current one.
advice_token: str = ""
@property
def sg_decimal(self) -> float | None:
@@ -171,6 +179,9 @@ class Reading:
comment=(doc.get("comment") or "").strip(),
beer_type=(doc.get("beer_type") or "").strip(),
_id=str(doc.get("_id") or ""),
advice=(doc.get("advice") or "").strip(),
advice_ok=bool(doc.get("advice_ok", True)),
advice_token=str(doc.get("advice_token") or ""),
)
@@ -189,6 +200,25 @@ class Run:
# -- aggregate accessors ------------------------------------------------ #
def latest_advice(self) -> str:
"""The advice for the most recent reading that has any.
The advice is generated in the background, so the newest reading
may not have any yet - in which case the newest one that does is
used, rather than showing nothing.
"""
for reading in reversed(self.readings):
if reading.advice:
return reading.advice
return ""
def latest_advice_ok(self) -> bool:
"""False when the advice is a note saying it could not be generated."""
for reading in reversed(self.readings):
if reading.advice:
return reading.advice_ok
return True
def sg_values(self) -> list[int]:
"""Gravity points of every *usable* reading, in chronological order."""
return [r.sg_points for r in self.readings if r.sg_points is not None]
@@ -622,6 +652,10 @@ def run_summary(run: Run, today: date | None = None,
"days_in_fermenter": run.days_in_fermenter(today),
"comments": run.comments(),
"last_comment": run.comments()[-1] if run.comments() else "",
# The advice the LLM gave for the most recent reading, if it has
# arrived yet.
"advice": run.latest_advice(),
"advice_ok": run.latest_advice_ok(),
"attenuation": attenuation_percent(run),
"curve": fermentation_curve(run),
"outliers": [r.sg_points for r in run.outlier_readings()],
@@ -633,6 +667,8 @@ def run_summary(run: Run, today: date | None = None,
"final_reading": r.final_reading,
"comment": r.comment,
"beer_type": r.beer_type,
"advice": r.advice,
"advice_ok": r.advice_ok,
}
for r in run.readings
],
+227 -1
View File
@@ -18,7 +18,9 @@ Two collections are used:
from __future__ import annotations
import logging
import re
import os
import threading
from typing import Any
from pymongo import MongoClient
@@ -46,6 +48,33 @@ class BeerRepository:
self.run_meta = self.db["beer_runs"]
self._ensure_indexes()
def close(self) -> None:
"""Close the underlying Mongo client and release it.
A ``MongoClient`` keeps a connection pool and spawns three
monitoring threads. ``close()`` alone does NOT reap them - they
go when the client object is garbage collected - so the
reference is dropped as well.
The request-scoped repository is closed by the app's teardown, but
a caller that builds its own - the advice background thread, for
instance - has to close it itself or the threads and the pool
accumulate, three per reading.
"""
client = self.client
try:
client.close()
except Exception:
pass
# Drop the reference so the monitor threads can be reaped.
self.client = None
def __enter__(self) -> "BeerRepository":
return self
def __exit__(self, *exc_info) -> None:
self.close()
def _ensure_indexes(self) -> None:
"""Make sure the lookup keys are indexed.
@@ -180,14 +209,128 @@ class BeerRepository:
"date": _as_date(reading_date),
"final_reading": "True" if final_reading else "False",
"comment": str(comment),
}
},
# The advice was written for the reading that was there when
# it was generated. If the reading has been edited, that
# advice no longer describes it, so it is cleared and a fresh
# one is generated. (Advice is only ever cleared here - never
# the brewer's comment.)
"$unset": {"advice": "", "advice_ok": "", "advice_at": ""},
}
# A fresh token marks this generation of the reading. The advice
# thread carries the token it was given, so a thread that is
# still working on an EARLIER version of the reading finds a
# token that no longer matches and its write is refused. The
# gravity alone is not enough - a comment-only correction leaves
# the gravity unchanged.
update["$set"]["advice_token"] = _new_token()
result = self.readings.update_one(query, update, upsert=True)
if result.upserted_id is not None:
return str(result.upserted_id)
existing = self.readings.find_one(query)
return str(existing.get("_id")) if existing else ""
def set_reading_advice(self, reading_id: str, advice: str,
ok: bool = True,
expected_sg: int | None = None,
expected_token: str | None = None,
expected_comment: str | None = None) -> int:
"""Attach the LLM's advice to a reading.
The advice lives in its own field, so the brewer's own comment is
never overwritten. ``ok`` says whether the advice was actually
generated or is a note explaining that it could not be.
The write is CONDITIONAL, so a slow advice thread cannot
overwrite a correction:
- ``expected_token`` is the editing token of the reading at the
moment the advice was generated. Every edit writes a fresh
token, so a late thread's token no longer matches.
- ``expected_sg`` is the gravity the advice was generated for,
as a second check.
This matters because the advice is generated in the background: if
the brewer corrects a reading while the advice for the old value
is still being generated, the slow thread would land afterwards
and overwrite the fresh advice with advice about a reading that
no longer exists.
The token is needed as well as the gravity, because a
comment-only correction leaves the gravity unchanged - the token
is what tells the two generations apart.
"""
doc_id = _as_doc_id(reading_id)
if not doc_id:
return 0
query: dict = {"_id": {"$in": doc_id}}
if expected_token:
# The editing token is the PRIMARY guard: it changes on every
# edit, so it catches a stale generation whatever else
# changed - the gravity, the comment, or nothing.
query["advice_token"] = str(expected_token)
elif expected_token == "":
# The reading has NEVER been edited, so it has no token at
# all. Match on the ABSENCE of one, which still tells the
# generations apart: an edit writes a token, so a stale
# thread's "" stops matching the moment the reading is
# corrected.
#
# Falling back to the gravity here would re-open the hole
# this guard exists to close - a comment-only correction
# leaves the gravity unchanged.
# `$in` with null also matches a MISSING field, so this
# covers a reading with no token AND one whose token field
# is present but empty.
query["advice_token"] = {"$in": [None, ""]}
elif expected_sg is not None:
# A direct call with a gravity to check against.
query["sg"] = str(expected_sg)
if expected_comment is not None:
# The comment the advice was written for.
#
# This is a SECOND, independent guard. The token covers
# every edit the application makes, but a document edited
# outside the application - by a script, or by hand in a
# database tool - would keep its empty token and a stale
# thread's write would still match on the gravity alone.
#
# The advice is generated from the comment as well as the
# gravity, so the comment is part of what the advice
# describes. Matching on it means a stale write can only
# land if BOTH the gravity and the comment are unchanged.
#
# The stored comment and the one the view sees can differ by
# trailing whitespace, so a regex is used to match either.
#
# `^comment\s*$` matches the stored value with any trailing
# whitespace, and the exact value too. It is anchored, so it
# cannot match a longer comment that merely starts the same
# way.
query["comment"] = {
"$regex": "^" + re.escape(expected_comment.strip()) + r"\s*$"
}
# `$in` matches either form. A plain list would be an exact
# ARRAY match in Mongo, which is not what is wanted here.
result = self.readings.update_one(
query,
{"$set": {
"advice": str(advice),
"advice_ok": bool(ok),
"advice_at": _now_iso(),
}},
)
# `matched_count`, not `modified_count`.
#
# `modified_count` is 0 when the document matched but the text
# was already identical - which is a successful write, not a
# refused one. The caller logs "the advice was not stored" when
# this is 0, so it has to mean "the guard refused it".
return result.matched_count
def set_final_reading(self, beer_run_id: str, reading_date: str,
final: bool) -> int:
"""Flag (or unflag) a reading as the final reading of its run."""
@@ -314,6 +457,82 @@ def _as_id(value: object) -> str:
return ""
#: A process-wide repository, for the code that runs outside a request.
#:
#: A ``MongoClient`` spawns three monitor threads and pymongo does not
#: reap them on ``close()`` - they go only when the client is garbage
#: collected. So building a client per advice write accumulated three
#: threads and a connection pool for every reading recorded. One shared
#: client for the life of the process is what the request-scoped
#: repository does too.
_shared_repository: "BeerRepository | None" = None
#: Guards the check-then-set above.
#:
#: Without it, concurrent advice threads each saw ``None`` and each
#: built their own repository - so the fix reintroduced the very leak it
#: was meant to remove, just bounded by a race instead of by the number
#: of readings. Eight threads on a cold process built eight clients and
#: twenty-five threads.
_shared_repository_lock = threading.Lock()
def get_shared_repository() -> "BeerRepository":
"""The process-wide repository, built on first use.
Thread-safe: the first caller builds it, the rest wait and get the
same one.
"""
global _shared_repository
if _shared_repository is None:
with _shared_repository_lock:
# Checked again inside the lock - another thread may have
# built it while this one was waiting.
if _shared_repository is None:
_shared_repository = BeerRepository()
return _shared_repository
def _as_doc_id(value: object):
"""Coerce a reading document id to something Mongo will match.
The ``_id`` of a reading is not a run id, so the ``_as_id`` coercion
does not apply - it would turn the id into an empty string and the
update would silently match nothing.
Two shapes exist in this database:
- the ORIGINAL app's ids are 24 random CHARACTERS stored as a string
(``l78ZidBJ3QaYn98tvB88x4uM``), and
- ids written by Mongo itself are ``ObjectId`` objects.
So the id is returned in BOTH forms and the query matches either.
Accepting only the ObjectId form would mean the advice was never
stored for any of the existing readings.
Only an ObjectId or a plain string is accepted, so a dict can never
be injected as a query operator.
"""
from bson import ObjectId
if isinstance(value, ObjectId):
return [value]
if isinstance(value, str) and value:
try:
# A 24-character hex string may or may not be the stored
# ObjectId or the stored string, so try both.
return [ObjectId(value), value]
except Exception:
# Not hex - it can only be the original app's string id.
return [value]
# Anything else - a dict, a list, an int, None - is not a reading
# id. An EMPTY LIST is returned rather than None: it is a valid
# `$in` argument that matches nothing, so the helper cannot be
# misused into a query error or into matching every document.
return []
def _as_date(value: object) -> str:
"""Coerce a reading date to a plain ``YYYY-MM-DD`` string."""
if isinstance(value, str):
@@ -336,6 +555,13 @@ def hash_password(password: str) -> str:
return generate_password_hash(password)
def _new_token() -> str:
"""A fresh token, to mark one generation of a reading from the next."""
import secrets
return secrets.token_hex(8)
def _now_iso() -> str:
from datetime import datetime, timezone
+353 -1
View File
@@ -451,7 +451,10 @@ input[type="date"]::-webkit-calendar-picker-indicator:hover { opacity: 1; }
/* ---------------------------------------------------------------- tables */
.table-wrap { overflow-x: auto; }
.table-wrap {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
table.data {
width: 100%;
@@ -480,6 +483,148 @@ table.data tbody tr:hover { background: var(--bg-raised-2); }
table.data .num { font-family: var(--mono); text-align: right; white-space: nowrap; }
table.data .comment { color: var(--text-muted); font-size: .84rem; }
/* A heading that is too long for a phone column. The long form shows
on a desktop and the short form on a phone - see the media query.
The rule is on `.short` alone, not on `table.data .short`, so it
applies everywhere the pattern is used - in a table heading, in the
advice button, and on the Active Beers page. When only the table
was covered, the advice button could show both forms at once and
read "Read the adviceAdvice". */
.short { display: none; }
/* On a narrow screen the header wraps onto two rows: the brand and the
sign-out on the first, the nav tabs on the second where they get the
full width.
They used to sit on one row with the brand and the sign-out, and the
last tab was cut off mid-word. */
@media (max-width: 720px) {
.topbar__inner {
flex-wrap: wrap;
row-gap: .5rem;
}
.brand {
order: 1;
}
.topbar__logout {
order: 2;
margin-left: auto;
}
.nav {
order: 3;
flex: 1 0 100%;
overflow-x: auto;
scrollbar-width: none;
-webkit-overflow-scrolling: touch;
/* A fade at the right edge so a clipped tab reads as
scrollable rather than broken. */
-webkit-mask-image: linear-gradient(to right, #000 calc(100% - 1.5rem), transparent 100%);
mask-image: linear-gradient(to right, #000 calc(100% - 1.5rem), transparent 100%);
}
.nav::-webkit-scrollbar {
display: none;
}
.nav__link {
flex-shrink: 0;
}
/* Tighter tabs, so all four fit on a phone without scrolling.
They still scroll if they have to. */
.nav__link {
padding: .35rem .55rem;
font-size: .8rem;
letter-spacing: .01em;
}
/* The tables stay tables on a phone.
They scroll sideways inside their card, which is what a table
does. They used to be squeezed to fit instead, and with seven
to nine columns on a 390px screen that meant every heading and
every value was truncated to a few characters - a gravity of
"1.0..." and a date of "202..." are worse than useless.
So the columns keep their natural width, the table scrolls, and
the advice is a small button so the column that matters is
narrow. */
table.data {
table-layout: auto;
width: 100%;
}
table.data th,
table.data td {
padding-left: .5rem;
padding-right: .5rem;
}
/* A name and a comment are words, so they get a sensible minimum
width and wrap on a word boundary - not one word per line. */
table.data td.col-name,
table.data td.col-comment {
min-width: 7rem;
max-width: 12rem;
white-space: normal;
word-break: normal;
overflow-wrap: break-word;
}
/* The long form gives way to the short form on a phone, because a
heading that is cut off is worse than a heading that is brief.
The rule is on the span itself rather than on the column, so it
applies everywhere the pattern is used - in a table heading, in
the advice button, and on the Active Beers page. */
.long {
display: none;
}
.short {
display: inline;
}
/* The advice trigger is small on a phone - it is a button, and
the advice itself is in the pop-out. */
table.data .advice-trigger {
font-size: .68rem;
padding: .25rem .4rem;
gap: .2rem;
}
/* The action column holds a button. */
table.data .col-action {
white-space: nowrap;
}
table.data .col-action .btn {
padding-left: .5rem;
padding-right: .5rem;
font-size: .72rem;
}
/* The secondary columns go away on a phone - the details are still
on the run's own page. */
table.data .col-drop,
table.data .col-legacy,
table.data .col-days {
display: none;
}
/* The scroll area keeps a visible scrollbar on a phone, so it is
obvious there is more of the table to the right. */
.table-wrap {
scrollbar-width: thin;
-webkit-overflow-scrolling: touch;
}
}
/* ----------------------------------------------------------------- chips */
.chip {
@@ -595,8 +740,18 @@ table.data .comment { color: var(--text-muted); font-size: .84rem; }
.brew-card__name { font-weight: 650; font-size: 1.02rem; margin: 0; }
.brew-card__meta { color: var(--text-muted); font-size: .82rem; font-family: var(--mono); }
.brew-card__stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: .6rem; }
/* The three stats sit side by side, so their captions line up. One
caption ("needs 2nd reading") is two lines and the others are one,
which left the baselines ragged. */
.brew-card__stat {
display: flex;
flex-direction: column;
}
.brew-card__stat .stat__label { font-size: .68rem; }
.brew-card__stat .stat__value { font-size: 1.3rem; }
.brew-card__stat .stat__meta { margin-top: auto; }
.brew-card__spark { height: 46px; }
/* The "start a new beer" tile — fills the last grid slot and gives the
@@ -689,3 +844,200 @@ table.data .comment { color: var(--text-muted); font-size: .84rem; }
.reading-list__sg { font-family: var(--mono); font-weight: 650; flex: 0 0 4rem; }
.reading-list__body { flex: 1; min-width: 0; }
.reading-list__comment { color: var(--text-muted); font-size: .84rem; }
/* ------------------------------------------------------------- advice */
/* The LLM's advice. It sits next to the brewer's own comment, never
replaces it, and is visually distinct so the two are never confused. */
.advice {
display: block;
margin-top: .35rem;
padding: .5rem .65rem;
border-left: 2px solid var(--amber);
border-radius: 0 4px 4px 0;
background: var(--amber-dim);
color: var(--text);
font-size: .8125rem;
line-height: 1.5;
}
.advice__label {
display: block;
margin-bottom: .15rem;
font-size: .625rem;
font-weight: 600;
letter-spacing: .08em;
text-transform: uppercase;
color: var(--amber-text);
}
/* The advice on the active-beers card and the run detail page - the
full text, not the clamped table cell. */
.advice--reading {
margin-top: .5rem;
}
/* Advice that could not be generated - it says why. */
.advice--failed {
border-left-color: var(--danger);
background: var(--danger-dim);
color: var(--text-muted);
}
.advice--failed .advice__label {
color: var(--danger);
}
/* The advice in the table is a compact trigger that pops the full text
out on hover, focus or tap.
It used to be the text itself, clamped to four lines. The advice runs
to several hundred characters, and a cell that wide pushes the table
past the width of a phone, so the column ended up clipped off the
right edge and unreadable without sideways scrolling. */
.advice-cell {
position: relative;
width: 1%;
white-space: nowrap;
}
.advice-trigger {
display: inline-flex;
align-items: center;
gap: .35rem;
padding: .25rem .55rem;
border: 1px solid var(--amber);
border-radius: 999px;
background: var(--amber-dim);
color: var(--amber-text);
font: inherit;
font-size: .75rem;
line-height: 1.4;
cursor: pointer;
white-space: nowrap;
}
.advice-trigger:hover,
.advice-trigger:focus-visible {
background: var(--amber);
color: var(--bg);
}
.advice-trigger--failed {
border-color: var(--danger);
background: var(--danger-dim);
color: var(--danger);
}
.advice-trigger__icon {
font-size: .85em;
}
/* The pop-out.
It is `position: fixed` and anchored to the trigger by the script,
not absolutely positioned inside the cell. The table is a scroll
container, and an absolutely positioned panel inside it was clipped
by the container's own overflow - the advice was sliced in half by
the card's edge and the bottom border was cut off.
Fixed positioning takes it out of the table entirely, so it floats
above the page and is never cut by a scroll container. */
.advice-pop {
position: fixed;
z-index: 200;
display: none;
width: min(30rem, 92vw);
max-height: 70vh;
overflow-y: auto;
padding: .8rem .9rem;
border: 1px solid var(--amber);
border-radius: 8px;
background: var(--bg-raised);
box-shadow: 0 12px 32px rgba(0, 0, 0, .55);
text-align: left;
white-space: normal;
}
.advice-pop__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: .5rem;
margin-bottom: .4rem;
}
.advice-pop__head .advice__label {
margin-bottom: 0;
}
.advice-pop__close {
border: 0;
background: none;
color: var(--text-muted);
font-size: 1.1rem;
line-height: 1;
cursor: pointer;
/* A 44px touch target, which is the smallest that is comfortable
on a phone. The negative margin pulls the panel's padding back
in so the button does not push the layout around, but the
padding is still what makes it easy to hit. */
padding: .9rem;
margin: -.9rem -.9rem -.9rem 0;
}
.advice-pop__close:hover {
color: var(--text);
}
.advice-pop__text {
margin: 0;
font-size: .8125rem;
line-height: 1.55;
color: var(--text);
}
/* The script opens and closes the panel, and places it. The CSS only
decides whether it is shown. */
/* The panel is opened by the script, which removes the `hidden`
attribute and adds `is-open`.
The `hidden` attribute is what makes this fail-safe: if the
stylesheet is stale and does not know about `.advice-pop` at all,
the panel is STILL hidden, so the advice cannot appear expanded
inside the table cell. */
.advice-pop.is-open {
display: block;
}
.advice-pop[hidden] {
display: none;
}
/* On a phone there is no hover, so the trigger is a button the script
toggles, and the panel is pinned to the middle of the screen so it is
readable whatever the table's width. */
@media (max-width: 720px) {
.advice-cell {
width: auto;
}
/* A dimmed backdrop, so the panel reads as sitting over the page
rather than floating in it.
A large spread shadow is used rather than a pseudo element, which
would paint behind the panel's own background. */
.advice-pop {
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, .55),
0 12px 32px rgba(0, 0, 0, .55);
}
/* On a phone the panel is centred on the screen rather than
anchored to the trigger - there is not the room to float it
beside the cell, and the trigger may be near the edge. */
.advice-pop {
top: 50% !important;
left: 50% !important;
transform: translate(-50%, -50%);
}
}
+160
View File
@@ -56,11 +56,171 @@
}
}
/**
* The brewing advice pop-out.
*
* On a desktop the panel opens on hover, which the CSS does. A
* phone has no hover, so the trigger is a button that toggles it -
* and it is a real button, so it works with a keyboard and with a
* screen reader.
*/
/**
* The brewing advice pop-out.
*
* The advice runs to several hundred characters. In a table cell it
* pushed the table past the width of a phone, so it is a compact
* trigger instead and the text is shown in a floating panel.
*
* The panel is position:fixed so it escapes the table's scroll
* container - absolutely positioned inside the cell it was clipped
* by the container and sliced in half by the card's edge.
*
* It opens on hover on a desktop, and on tap on a phone, which has
* no hover. The trigger is a real button, so it also works with a
* keyboard.
*/
function wireAdvicePopouts() {
var triggers = document.querySelectorAll(".advice-trigger");
for (var i = 0; i < triggers.length; i++) {
(function (trigger) {
var panel = trigger.parentNode.querySelector(".advice-pop");
if (!panel) { return; }
var closeTimer = null;
function isPhone() {
return window.matchMedia("(max-width: 720px)").matches;
}
function place() {
if (isPhone()) {
/* The CSS centres it on a phone - clear any
inline position left over from a desktop
resize. */
panel.style.top = "";
panel.style.left = "";
return;
}
var box = trigger.getBoundingClientRect();
var gap = 10;
var height = panel.offsetHeight;
var width = panel.offsetWidth;
var spaceBelow = window.innerHeight - box.bottom - gap;
var spaceAbove = box.top - gap;
/* Prefer below; flip above when there is not enough
room and there is more room above. */
var top;
if (height <= spaceBelow || spaceBelow >= spaceAbove) {
top = box.bottom + gap;
} else {
top = Math.max(gap, box.top - height - gap);
}
/* Keep it on screen horizontally. */
var left = Math.min(box.left, window.innerWidth - width - gap);
left = Math.max(gap, left);
panel.style.top = Math.round(top) + "px";
panel.style.left = Math.round(left) + "px";
}
function open() {
if (closeTimer) {
clearTimeout(closeTimer);
closeTimer = null;
}
/* The `hidden` attribute is removed as well as the
class added, so the panel is shown even if the
stylesheet is an older one that only knows about
the class. */
panel.removeAttribute("hidden");
panel.classList.add("is-open");
trigger.setAttribute("aria-expanded", "true");
place();
}
function close() {
panel.classList.remove("is-open");
/* Put the attribute back, so a stale stylesheet
cannot leave the advice expanded in the cell. */
panel.setAttribute("hidden", "");
trigger.setAttribute("aria-expanded", "false");
}
function closeSoon() {
/* A short delay, so the mouse can travel from the
trigger into the panel without it closing. */
if (closeTimer) { clearTimeout(closeTimer); }
closeTimer = setTimeout(function () {
closeTimer = null;
if (!panel.matches(":hover") && !trigger.matches(":hover")) {
close();
}
}, 180);
}
trigger.addEventListener("click", function (event) {
event.preventDefault();
event.stopPropagation();
if (panel.classList.contains("is-open")) {
close();
} else {
open();
}
});
trigger.addEventListener("mouseenter", function () {
if (!isPhone()) { open(); }
});
trigger.addEventListener("mouseleave", closeSoon);
panel.addEventListener("mouseenter", function () {
if (closeTimer) {
clearTimeout(closeTimer);
closeTimer = null;
}
});
panel.addEventListener("mouseleave", closeSoon);
var closeButton = panel.querySelector(".advice-pop__close");
if (closeButton) {
closeButton.addEventListener("click", function (event) {
event.preventDefault();
event.stopPropagation();
close();
trigger.focus();
});
}
document.addEventListener("keydown", function (event) {
if (event.key === "Escape" && panel.classList.contains("is-open")) {
close();
trigger.focus();
}
});
document.addEventListener("click", function (event) {
if (!panel.contains(event.target) && event.target !== trigger) {
close();
}
});
window.addEventListener("resize", function () {
if (panel.classList.contains("is-open")) { place(); }
});
window.addEventListener("scroll", function () {
if (panel.classList.contains("is-open")) { close(); }
}, true);
})(triggers[i]);
}
}
function init() {
focusFirstEmpty();
defaultDateFields();
wireToggles();
wireConfirms();
wireAdvicePopouts();
}
if (document.readyState === "loading") {
+8 -1
View File
@@ -44,7 +44,7 @@
<div class="brew-card__meta">
Run {{ run.beer_run_id }}
{% if run.first_date %} &middot; since {{ run.first_date }}{% endif %}
{% if run.reading_count == 1 %} &middot; 1 reading{% else %} &middot; {{ run.reading_count }} readings{% endif %}
{% if run.reading_count == 1 %} &middot; 1&nbsp;reading{% else %} &middot; {{ run.reading_count }}&nbsp;readings{% endif %}
</div>
</div>
{% if run.tap_number is not none %}
@@ -100,6 +100,13 @@
</div>
{% endif %}
{% if run.advice %}
<div class="advice advice--reading{% if not run.advice_ok %} advice--failed{% endif %}">
<span class="advice__label">Brewing advice</span>
{{ run.advice }}
</div>
{% endif %}
<div class="btn-row">
<a class="btn btn--ghost btn--sm"
href="{{ url_for('brews.run_detail', run_id=run.beer_run_id) }}">Open run</a>
+26 -26
View File
@@ -99,43 +99,43 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th>Name</th>
<th class="num">OG</th>
<th class="num">FG</th>
<th class="num">ABV</th>
<th class="num">Attenuation</th>
<th class="num">Days</th>
<th class="num">To 1.010</th>
<th>Finished</th>
<th class="col-run">Run</th>
<th class="col-name">Name</th>
<th class="num col-gravity">OG</th>
<th class="num col-gravity">FG</th>
<th class="num col-abv">ABV</th>
<th class="num col-abv" title="Attenuation"><span class="long">Attenuation</span><span class="short">Att.</span></th>
<th class="num col-abv col-days">Days</th>
<th class="num col-abv" title="Days to reach 1.010"><span class="long">To 1.010</span><span class="short">1.010</span></th>
<th class="col-finished" title="Finished"><span class="long">Finished</span><span class="short">Done</span></th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr{% if row.suspect %} class="is-suspect"{% endif %}>
<td class="mono">{{ row.beer_run_id }}</td>
<td>{{ row.name }}{% if row.suspect %} <span class="chip chip--warn">not counted</span>{% endif %}</td>
<td class="num">
<td class="col-run mono">{{ row.beer_run_id }}</td>
<td class="col-name">{{ row.name }}{% if row.suspect %} <span class="chip chip--warn">not counted</span>{% endif %}</td>
<td class="col-gravity num">
{% if row.og_points is not none %}
{{ '%.3f' % (row.og_points / 1000) }}
{% else %}—{% endif %}
</td>
<td class="num">
<td class="col-gravity num">
{% if row.fg_points is not none %}
{{ '%.3f' % (row.fg_points / 1000) }}
{% else %}—{% endif %}
</td>
<td class="num">
<td class="col-abv num">
{% if row.abv is not none %}{{ '%.2f' % row.abv }}%{% else %}—{% endif %}
</td>
<td class="num">
<td class="col-abv num">
{% if row.attenuation is not none %}
<strong>{{ row.attenuation }}%</strong>
{% else %}—{% endif %}
</td>
<td class="num">{{ row.days if row.days is not none else '—' }}</td>
<td class="num">{{ row.days_to_1010 if row.days_to_1010 is not none else '—' }}</td>
<td class="mono nowrap">{{ row.final_date or '—' }}</td>
<td class="col-abv col-days num">{{ row.days if row.days is not none else '—' }}</td>
<td class="col-abv num">{{ row.days_to_1010 if row.days_to_1010 is not none else '—' }}</td>
<td class="col-finished mono nowrap">{{ row.final_date or '—' }}</td>
</tr>
{% endfor %}
</tbody>
@@ -155,21 +155,21 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th class="num">OG</th>
<th class="num">FG</th>
<th>Problem</th>
<th class="col-run">Run</th>
<th class="num col-gravity">OG</th>
<th class="num col-gravity">FG</th>
<th class="col-comment">Problem</th>
</tr>
</thead>
<tbody>
{% for row in suspect %}
<tr>
<td class="mono">
<td class="col-run mono">
<a href="{{ url_for('brews.run_detail', run_id=row.beer_run_id) }}">{{ row.beer_run_id }}</a>
</td>
<td class="num">{{ '%.3f' % (row.og_points / 1000) }}</td>
<td class="num"><span class="chip chip--warn">{{ '%.3f' % (row.fg_points / 1000) }}</span></td>
<td class="comment">{{ row.problem }}</td>
<td class="col-gravity num">{{ '%.3f' % (row.og_points / 1000) }}</td>
<td class="col-gravity num"><span class="chip chip--warn">{{ '%.3f' % (row.fg_points / 1000) }}</span></td>
<td class="col-comment comment">{{ row.problem }}</td>
</tr>
{% endfor %}
</tbody>
+56 -29
View File
@@ -78,40 +78,67 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th>Name</th>
<th class="num">Gravity</th>
<th class="num">Est. ABV</th>
<th>Comment</th>
<th></th>
<th class="col-run">Run</th>
<th class="col-name">Name</th>
<th class="num col-gravity">Gravity</th>
<th class="num col-abv" title="Estimated alcohol by volume"><span class="long">Est. ABV</span><span class="short">ABV</span></th>
<th class="col-comment" title="Comment"><span class="long">Comment</span><span class="short">Note</span></th>
<th class="col-advice" title="Brewing advice"><span class="long">Brewing advice</span><span class="short">Advice</span></th>
<th class="col-action"></th>
</tr>
</thead>
<tbody>
{% for run in active_runs %}
<tr>
<td class="mono">{{ run.beer_run_id }}</td>
<td>{{ run.canonical_name }}</td>
<td class="num">
<td class="mono col-run">{{ run.beer_run_id }}</td>
<td class="col-name">{{ run.canonical_name }}</td>
<td class="num col-gravity">
{% if run.min_sg is not none %}
<span class="mono strong">{{ run.min_sg_decimal }}</span>
<div class="faint tiny">{{ run.min_sg_point_scale }} pts</div>
<div class="faint tiny point-scale">{{ run.min_sg_point_scale }} points</div>
{% else %}—{% endif %}
</td>
<td class="num">
<td class="num col-abv">
{% if run.projected_abv is not none %}
{{ '%.2f' % run.projected_abv }}%
{% else %}
<span class="faint" title="Record another reading, or set the original gravity, to get an estimate">—</span>
{% endif %}
</td>
<td class="comment">
<td class="comment col-comment">
{% if run.comments %}
{{ run.comments[-1] }}
{% else %}
<span class="faint">—</span>
{% endif %}
</td>
<td class="right">
<td class="advice-cell col-advice">
{% if run.advice %}
<button type="button"
class="advice-trigger{% if not run.advice_ok %} advice-trigger--failed{% endif %}"
aria-expanded="false">
<span class="advice-trigger__icon" aria-hidden="true">&#9998;</span>
<span class="advice-trigger__label">
{% if run.advice_ok %}
<span class="long">Read the advice</span><span class="short">Advice</span>
{% else %}
<span class="long">Advice failed</span><span class="short">Failed</span>
{% endif %}
</span>
</button>
<div class="advice-pop" role="tooltip" hidden>
<div class="advice-pop__head">
<span class="advice__label">Brewing advice</span>
<button type="button" class="advice-pop__close"
aria-label="Close">&times;</button>
</div>
<p class="advice-pop__text">{{ run.advice }}</p>
</div>
{% else %}
<span class="faint">Thinking…</span>
{% endif %}
</td>
<td class="right col-action">
<a class="btn btn--ghost btn--sm"
href="{{ url_for('brews.run_detail', run_id=run.beer_run_id) }}">Open</a>
</td>
@@ -140,41 +167,41 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th>Name</th>
<th class="num">OG</th>
<th class="num">FG</th>
<th class="num">ABV</th>
<th>Finished</th>
<th>Comment</th>
<th></th>
<th class="col-run">Run</th>
<th class="col-name">Name</th>
<th class="num col-gravity">OG</th>
<th class="num col-gravity">FG</th>
<th class="num col-abv">ABV</th>
<th class="col-finished" title="Finished"><span class="long">Finished</span><span class="short">Done</span></th>
<th class="col-comment" title="Comment"><span class="long">Comment</span><span class="short">Note</span></th>
<th class="col-action"></th>
</tr>
</thead>
<tbody>
{% for run in completed_runs %}
<tr>
<td class="mono">{{ run.beer_run_id }}</td>
<td>{{ run.canonical_name }}</td>
<td class="num">
<td class="mono col-run">{{ run.beer_run_id }}</td>
<td class="col-name">{{ run.canonical_name }}</td>
<td class="num col-gravity">
{% if run.og_points is not none %}{{ run.og_points }}{% else %}—{% endif %}
</td>
<td class="num">
<td class="num col-gravity">
{% if run.fg_points is not none %}{{ run.fg_points }}{% else %}—{% endif %}
</td>
<td class="num">
<td class="num col-abv">
{% if run.abv is not none %}
<strong>{{ '%.2f' % run.abv }}%</strong>
{% else %}—{% endif %}
</td>
<td class="mono nowrap">{{ run.final_date or '—' }}</td>
<td class="comment">
<td class="mono nowrap col-finished">{{ run.final_date or '—' }}</td>
<td class="comment col-comment">
{% if run.comments %}
{{ run.comments[-1] }}
{% else %}
<span class="faint">—</span>
{% endif %}
</td>
<td class="right">
<td class="right col-action">
<a class="btn btn--ghost btn--sm"
href="{{ url_for('brews.run_detail', run_id=run.beer_run_id) }}">Open</a>
</td>
+44 -44
View File
@@ -84,21 +84,21 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th>Name</th>
<th>Date</th>
<th class="num">Reading</th>
<th>Comment</th>
<th class="col-run">Run</th>
<th class="col-name">Name</th>
<th class="col-finished">Date</th>
<th class="num col-gravity">Reading</th>
<th class="col-comment" title="Comment"><span class="long">Comment</span><span class="short">Note</span></th>
</tr>
</thead>
<tbody>
{% for row in outliers %}
<tr>
<td class="mono">{{ row.beer_run_id }}</td>
<td>{{ row.name }}</td>
<td class="mono nowrap">{{ row.date or '—' }}</td>
<td class="num"><span class="chip chip--warn">{{ row.sg }}</span></td>
<td class="comment">{{ row.comment or '—' }}</td>
<td class="col-run mono">{{ row.beer_run_id }}</td>
<td class="col-name">{{ row.name }}</td>
<td class="col-finished mono nowrap">{{ row.date or '—' }}</td>
<td class="col-gravity num"><span class="chip chip--warn">{{ row.sg }}</span></td>
<td class="col-comment comment">{{ row.comment or '—' }}</td>
</tr>
{% endfor %}
</tbody>
@@ -118,45 +118,45 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th>Name</th>
<th>Status</th>
<th class="num">OG</th>
<th class="num">FG</th>
<th class="num">Drop</th>
<th class="num">ABV</th>
<th class="num">Legacy</th>
<th>Finished</th>
<th>Comment</th>
<th></th>
<th class="col-run">Run</th>
<th class="col-name">Name</th>
<th class="col-finished" title="Status"><span class="long">Status</span><span class="short">Stat</span></th>
<th class="num col-gravity">OG</th>
<th class="num col-gravity">FG</th>
<th class="num col-drop">Drop</th>
<th class="num col-abv">ABV</th>
<th class="num col-legacy">Legacy</th>
<th class="col-finished" title="Finished"><span class="long">Finished</span><span class="short">Done</span></th>
<th class="col-comment" title="Comment"><span class="long">Comment</span><span class="short">Note</span></th>
<th class="col-action"></th>
</tr>
</thead>
<tbody>
{% for run in summaries %}
<tr>
<td class="mono">{{ run.beer_run_id }}</td>
<td>{{ run.canonical_name }}</td>
<td>
<td class="col-run mono">{{ run.beer_run_id }}</td>
<td class="col-name">{{ run.canonical_name }}</td>
<td class="col-finished">
{% if run.active %}
<span class="chip chip--active">Active</span>
{% else %}
<span class="chip chip--done">Finished</span>
{% endif %}
</td>
<td class="num">{{ run.og_points or '—' }}</td>
<td class="num">{{ run.fg_points or '—' }}</td>
<td class="num">{{ run.drop_points if run.drop_points is not none else '—' }}</td>
<td class="num">
<td class="col-drop col-gravity num">{{ run.og_points or '—' }}</td>
<td class="col-gravity num">{{ run.fg_points or '—' }}</td>
<td class="col-gravity num">{{ run.drop_points if run.drop_points is not none else '—' }}</td>
<td class="col-abv num">
{% if run.abv is not none %}<strong>{{ '%.2f' % run.abv }}%</strong>
{% elif run.projected_abv is not none %}{{ '%.2f' % run.projected_abv }}%*
{% else %}—{% endif %}
</td>
<td class="num muted">{{ run.legacy_abv if run.legacy_abv is not none else '—' }}</td>
<td class="mono nowrap">{{ run.final_date or '—' }}</td>
<td class="comment">
<td class="col-legacy col-abv num muted">{{ run.legacy_abv if run.legacy_abv is not none else '—' }}</td>
<td class="col-finished mono nowrap">{{ run.final_date or '—' }}</td>
<td class="col-comment comment">
{% if run.comments %}{{ run.comments[-1] }}{% else %}<span class="faint">—</span>{% endif %}
</td>
<td class="right">
<td class="right col-action">
<a class="btn btn--ghost btn--sm"
href="{{ url_for('brews.run_detail', run_id=run.beer_run_id) }}">Open</a>
</td>
@@ -178,29 +178,29 @@
<table class="data">
<thead>
<tr>
<th>Run</th>
<th>Name</th>
<th class="num">Standard ABV</th>
<th class="num">Legacy ABV</th>
<th class="num">Overstated by</th>
<th>Finished</th>
<th class="col-run">Run</th>
<th class="col-name">Name</th>
<th class="num col-abv" title="Standard ABV"><span class="long">Standard ABV</span><span class="short">Std</span></th>
<th class="num col-legacy col-abv" title="Legacy ABV"><span class="long">Legacy ABV</span><span class="short">Old</span></th>
<th class="num col-abv" title="Overstated by"><span class="long">Overstated by</span><span class="short">Over</span></th>
<th class="col-finished" title="Finished"><span class="long">Finished</span><span class="short">Done</span></th>
</tr>
</thead>
<tbody>
{% for row in abv_rows %}
<tr>
<td class="mono">{{ row.beer_run_id }}</td>
<td>{{ row.name }}</td>
<td class="num">{{ '%.2f' % row.abv }}%</td>
<td class="num muted">{{ '%.2f' % row.legacy_abv }}%</td>
<td class="num">
<td class="col-run mono">{{ row.beer_run_id }}</td>
<td class="col-name">{{ row.name }}</td>
<td class="col-abv num">{{ '%.2f' % row.abv }}%</td>
<td class="col-abv num muted">{{ '%.2f' % row.legacy_abv }}%</td>
<td class="col-abv num">
{% if row.delta > 0 %}
<span class="chip chip--warn">+{{ '%.2f' % row.delta }}</span>
{% else %}
<span class="faint">{{ '%.2f' % row.delta }}</span>
{% endif %}
</td>
<td class="mono nowrap">{{ row.final_date or '—' }}</td>
<td class="col-finished mono nowrap">{{ row.final_date or '—' }}</td>
</tr>
{% endfor %}
</tbody>
+6
View File
@@ -144,6 +144,12 @@
{% else %}
<div class="faint tiny">No comment</div>
{% endif %}
{% if reading.advice %}
<div class="advice advice--reading{% if not reading.advice_ok %} advice--failed{% endif %}">
<span class="advice__label">Brewing advice</span>
{{ reading.advice }}
</div>
{% endif %}
</div>
{% if reading.final_reading %}
<span class="chip chip--done">Final</span>
+158 -4
View File
@@ -2,15 +2,22 @@
from __future__ import annotations
from flask import (Blueprint, flash, jsonify, redirect, render_template,
request, session, url_for)
import logging
import os
import threading
from flask import (Blueprint, current_app, flash, jsonify, redirect,
render_template, request, session, url_for)
from flask_wtf import FlaskForm
from wtforms import (BooleanField, DateField, IntegerField, StringField,
SubmitField, TextAreaField)
from wtforms.validators import DataRequired, Length, NumberRange, Optional
import brew_advice
from brewing import implausible_runs, is_plausible_sg, run_summary
log = logging.getLogger(__name__)
bp = Blueprint("brews", __name__)
@@ -34,6 +41,139 @@ def login_required(fn):
return wrapper
def advice_enabled() -> bool:
"""Whether the LLM advice should be generated.
It is off in testing, so the suite never reaches out to a model, and
it can be turned off in production with ``LLM_ADVICE=0`` if the model
is misbehaving.
"""
if current_app.config.get("TESTING"):
return False
return os.getenv("LLM_ADVICE", "1").strip().lower() not in {"0", "false", "no"}
def _start_advice(run_id: str, reading_id: str, corrected: bool = False) -> None:
"""Generate the LLM's advice for a reading, in the background.
The advice is a separate field on the reading, so the brewer's own
comment is never touched.
The background thread cannot use the request-scoped repository - that
client is closed when the request ends - so it uses the shared
process-wide one.
"""
if not reading_id:
return
if not advice_enabled():
return
try:
repository = repo()
run = repository.run(run_id)
if run is None:
return
meta = repository.run_metadata(run_id)
summary = run_summary(run, og_override=meta.get("og_points"))
run_info = {
"canonical_name": meta.get("name") or run.display_name(),
"name": run.display_name(),
"og_points": summary.get("og_points"),
"og_decimal": summary.get("og_decimal"),
"tap_number": meta.get("tap_number"),
"notes": meta.get("notes", ""),
}
# The model's view of the run: every reading, with the gravity in
# both forms a brewer would recognise.
readings = []
for reading in run.readings:
points = reading.sg_points
readings.append({
"_id": str(reading._id),
"advice_token": reading.advice_token,
"date": reading.date.isoformat() if reading.date else "",
"sg": points,
"sg_decimal": reading.sg_decimal,
"point_scale": f"{points} points" if points is not None else "",
"comment": reading.comment or "",
"final": bool(reading.final_reading),
})
# The reading that is actually being advised about. It is not
# necessarily the newest one: the brewer may be editing an older
# reading, and advice about the newest reading would be about the
# wrong number.
saved = next((r for r in readings if r.get("_id") == str(reading_id)), None)
if saved is None:
# The reading is not in the run. Advising about the newest
# reading instead would describe the wrong number, and the
# conditional write would then refuse it anyway - so it is
# better to say so plainly and stop.
log.info(
"no advice for reading %s: it is not one of the run's readings",
reading_id,
)
return
latest = dict(saved)
latest["_id"] = reading_id
except Exception: # noqa: BLE001 - advice must never break the save
log.exception("could not gather the reading for the advice")
return
# The gravity and the editing token of the reading being advised
# about. The write is conditional on both, so a slow advice thread
# cannot overwrite a correction with advice about the old value.
advice_sg = latest.get("sg")
advice_token = latest.get("advice_token")
# The comment is part of what the advice describes, so it is a
# second, independent guard on the write. The token covers every
# edit the application makes; this also covers a document edited
# outside it.
advice_comment = latest.get("comment") or ""
def write(read_id: str, ok: bool, text: str) -> None:
# The client is SHARED, not built per reading. A MongoClient
# spawns three monitor threads and pymongo does not reap them
# on close(), so building one per advice write accumulated three
# threads and a connection pool for every reading recorded.
#
# The shared client is created on first use and lives for the
# life of the process, which is what the request-scoped
# repository does too.
from mongo.repository import get_shared_repository
try:
shared = get_shared_repository()
written = shared.set_reading_advice(
read_id, text, ok,
expected_sg=advice_sg,
expected_token=advice_token,
expected_comment=advice_comment,
)
if not written:
# The reading was corrected while the advice was being
# generated, so the advice no longer matches it. That is
# the guard working - the fresh advice for the corrected
# reading will land in its own turn.
log.info(
"the advice for reading %s was not stored: the reading "
"has been edited since the advice was generated, so its "
"editing token or comment no longer matches the advice",
read_id,
)
except Exception: # noqa: BLE001 - never let the thread die noisily
log.exception("could not store the generated advice")
thread = threading.Thread(
target=brew_advice.generate_advice_in_background,
args=(run_info, latest, readings, write, corrected),
daemon=True,
)
thread.start()
def _last_reading_date(run) -> str | None:
"""The ISO date of the most recent reading in a run."""
last = run.last_reading()
@@ -104,8 +244,17 @@ def index():
"(990-1200). It was saved anyway — double-check the reading.",
"warning",
)
repo().upsert_reading(
beer_run_id=str(form.beer_run_id.data),
run_id = str(form.beer_run_id.data)
# Whether the reading was already there: a re-submitted reading
# is a CORRECTION, and the advice should say so.
existing = repo().reading_docs_for_run(run_id)
was_existing = any(
str(doc.get("date")) == form.Date.data.isoformat()
for doc in existing
)
reading_id = repo().upsert_reading(
beer_run_id=run_id,
beer_type=(form.beer_run_type.data or "").strip(),
sg=sg_points,
reading_date=form.Date.data.isoformat(),
@@ -113,6 +262,11 @@ def index():
comment=(form.comment.data or "").strip(),
)
flash("Reading saved.", "success")
# The advice is generated in the background: recording a reading
# must not block on the model. The page shows the reading straight
# away and the advice is there on a later visit.
_start_advice(run_id, reading_id, corrected=was_existing)
return redirect(url_for("brews.index"))
runs = repo().runs()
+12
View File
@@ -714,3 +714,15 @@ def test_the_api_exposes_the_attenuation_and_curve(logged_in, repo):
assert len(entry["curve"]) == 2
assert entry["curve"][0]["progress"] == 0.0
assert entry["curve"][1]["progress"] == 1.0
def test_the_pages_are_not_cached(client):
"""The HTML pages must not be cached by the browser.
A phone held on to a cached copy of the brewing page and kept
showing the old inline advice after the button and the pop-out had
been deployed, so the change was invisible until the cache was
cleared by hand.
"""
response = client.get("/login")
assert "no-store" in response.headers.get("Cache-Control", "")
File diff suppressed because it is too large Load Diff