Consolidation: earlier-state note on an observation is dated in UTC, not the bank's default_timezone (follow-up to #6441)

Aperta Adatta ai principianti
#6,978 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
76/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Leggi hindsight-api-slim/hindsight_api/engine/consolidation/consolidator.py, in particolare _consolidate_batch_with_llm, dove il fuso orario è già stato ottenuto e viene formattata la nota sullo stato precedente. Confronta questa formattazione con le chiamate a _prompt_time che tengono conto del fuso orario. Poi esegui la riproduzione descritta nell’issue e i test di consolidamento pertinenti, incluso tests/test_consolidation_fact_format.py. Il lavoro è terminato quando la nota usa l’ora locale della banca e il testo dell’osservazione corrisponde all’ora mostrata per il relativo fatto sorgente.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

core
Bug Description

On a bank with a non-UTC default_timezone, the earlier-state note that consolidation appends to an observation, (YYYY-MM-DD HH:MM: <fact>), is dated in UTC. Since #6835 (the fix for #6441) the consolidation prompt shows the times of facts, observations and their source memories in the bank's zone and says so (Every time below is local time in <zone>). The date in this note did not move with them.

The note is part of the observation's text, so the model reads it again in the next consolidation prompt that includes the observation, under that same TIMEZONE line and with no offset on it. There it differs from the time the prompt shows for the same fact (the latest of its occurred_start, occurred_end and mentioned_at) by the UTC offset, and falls on a different day when that time is within the offset of midnight. The observation tree lists the same text in a file that says Times are <zone>., next to a local time in the same YYYY-MM-DD HH:MM format.

Example with bank zone Europe/Berlin and a fact stated at 23:30 UTC on 9 Nov (00:30 on 10 Nov local):

  • the fact as the prompt shows it: mentioned_at=2026-11-10T00:30+01:00
  • the note written into the observation: (2026-11-09 23:30: The team deploys on Tuesdays.)

Not provider-specific: the note is written by code, not by the model, and this is reproduced with a stub LLM. Banks on UTC (the default) are not affected.

Not checked: how often a real model takes the wrong date or hour from the note, and how the note reads in recall, reflect or the control plane. I only ran the consolidation step and the tree renderer, with no server.

Steps to Reproduce

No model, database or server is needed. The script calls _consolidate_batch_with_llm with a stub LLM that returns a fixed answer, the same way tests/test_consolidation_fact_format.py does.

  1. Check out main at 9f471cdb and save the script below as hindsight-api-slim/repro_earlier_state_timezone.py.
  2. Run cd hindsight-api-slim && uv run python repro_earlier_state_timezone.py.
  3. Round 1: the config has default_timezone="Europe/Berlin" and the pool holds one observation, "The team deploys on Thursdays." (stated 20 Nov). An older fact, "The team deploys on Tuesdays.", stated at 23:30 UTC on 9 Nov, is consolidated. The stub answers what the system prompt asks for in that case ("effect": "changes" with empty text), so the fact is appended to the observation as its earlier state.
  4. Round 2: the updated observation is put back in the pool of the next prompt.
  5. The script prints both prompts and the written text. It exits 1 when the note is dated in UTC and 0 when it is dated in the bank's zone.
repro_earlier_state_timezone.py
"""Repro: the date in an observation's earlier-state note ignores the bank's default_timezone.

Run from hindsight-api-slim:

    uv run python repro_earlier_state_timezone.py

No model, database or server: the LLM is a stub that returns a fixed answer, the same way
tests/test_consolidation_fact_format.py drives _consolidate_batch_with_llm.

Round 1: an older fact changes an observation that was stated after it, so consolidation keeps the
observation and appends the fact as "(YYYY-MM-DD HH:MM: <fact>)".
Round 2: that observation is back in the pool of the next prompt, next to its source fact.

Exits 1 when the note's date is the UTC wall clock, 0 when it is the bank's local time.
"""

import asyncio
import sys
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any
from zoneinfo import ZoneInfo

from hindsight_api.engine.consolidation.consolidator import _consolidate_batch_with_llm
from hindsight_api.engine.response_models import LLMCallResult

BANK_ZONE = "Europe/Berlin"

# Stored times are UTC. 23:30 UTC on 9 Nov is 00:30 on 10 Nov in Berlin (UTC+01:00).
OLD_FACT_AT = datetime(2026, 11, 9, 23, 30, tzinfo=timezone.utc)
OBSERVATION_AT = datetime(2026, 11, 20, 9, 0, tzinfo=timezone.utc)
NEXT_FACT_AT = datetime(2026, 11, 23, 8, 15, tzinfo=timezone.utc)

CONFIG = SimpleNamespace(
    llm_output_language=None,
    observations_mission=None,
    consolidation_max_attempts=1,
    consolidation_llm_max_retries=None,
    llm_temperature_consolidation=0.0,
    llm_strict_schema_consolidation=False,
    consolidation_max_completion_tokens=None,
    default_timezone=BANK_ZONE,
)


class StubLLM:
    """Records the request and returns a fixed answer."""

    def __init__(self, answer: dict[str, Any]) -> None:
        self.answer = answer
        self.user_message = ""

    async def call(self, **kwargs: Any) -> Any:
        self.user_message = kwargs["messages"][-1]["content"]
        return LLMCallResult(content=kwargs["response_format"].model_validate(self.answer))


def stored(text: str, at: datetime, oid: str | None = None, sources: list[str] | None = None) -> SimpleNamespace:
    return SimpleNamespace(
        id=oid, text=text, occurred_start=None, occurred_end=None, mentioned_at=at, source_fact_ids=sources or []
    )


def from_timezone_section(prompt: str) -> str:
    return prompt[prompt.index("## TIMEZONE") :].rstrip()


async def main() -> bool:
    # Round 1. The pool holds one observation, stated on 20 Nov. A fact stated at 23:30 UTC on
    # 9 Nov (00:30 on 10 Nov in Berlin) arrives late and "changes" it: the observation keeps its
    # text and the fact is appended as its earlier state.
    old_fact = {"id": "f-old", "text": "The team deploys on Tuesdays.", "mentioned_at": OLD_FACT_AT}
    observation = stored("The team deploys on Thursdays.", OBSERVATION_AT, oid="o-deploy")
    llm = StubLLM(
        {
            "facts": [
                {
                    "fact_id": "F1",
                    "kind": "lasting",
                    "existing": [{"observation_id": "O1", "effect": "changes", "text": ""}],
                    "adds": "no",
                }
            ]
        }
    )
    result = await _consolidate_batch_with_llm(
        llm, [old_fact], [observation], {}, CONFIG, closest={"f-old": ["o-deploy"]}
    )
    [update] = result.updates

    print("=== Round 1: what the model is shown ===")
    print(from_timezone_section(llm.user_message))
    print()
    print("=== Round 1: the observation text consolidation writes ===")
    print(update.text)
    print()

    # Round 2. The updated observation is in the pool again, with the fact it now cites.
    updated = stored(update.text, OBSERVATION_AT, oid="o-deploy", sources=["f-old"])
    next_fact = {"id": "f-next", "text": "The office kitchen is cleaned on Fridays.", "mentioned_at": NEXT_FACT_AT}
    llm = StubLLM(
        {"facts": [{"fact_id": "F1", "kind": "lasting", "existing": [], "adds": "yes", "new": [next_fact["text"]]}]}
    )
    await _consolidate_batch_with_llm(
        llm, [next_fact], [updated], {"f-old": stored(old_fact["text"], OLD_FACT_AT)}, CONFIG
    )
    print("=== Round 2: the same observation in the next prompt ===")
    print(from_timezone_section(llm.user_message))
    print()

    local = OLD_FACT_AT.astimezone(ZoneInfo(BANK_ZONE))
    expected = f"{local:%Y-%m-%d %H:%M}"
    in_utc = f"{OLD_FACT_AT:%Y-%m-%d %H:%M}"
    print("=== Check ===")
    print(f"bank default_timezone          : {BANK_ZONE}")
    print(f"fact time shown in the prompt  : {local.isoformat(timespec='minutes')}")
    print(f"expected date in the bracket   : {expected}")
    if f"({expected}: " in update.text:
        print(f"date in the bracket            : {expected}  -> OK, bank zone")
        return True
    if f"({in_utc}: " in update.text:
        print(f"date in the bracket            : {in_utc}  -> BUG, UTC wall clock")
    else:
        print("date in the bracket            : not found, see the text above")
    return False


if __name__ == "__main__":
    sys.exit(0 if asyncio.run(main()) else 1)

Environment: Linux x86_64, Python 3.12.3, dependencies as pinned in uv.lock. I ran step 2 as uv run --frozen --python 3.12 python repro_earlier_state_timezone.py (this machine has no Python 3.11).

Expected Behavior

The note is dated in the bank's zone, like the time the same prompt shows for the fact:

The team deploys on Thursdays. (2026-11-10 00:30: The team deploys on Tuesdays.)

This is how the configuration docs describe HINDSIGHT_API_DEFAULT_TIMEZONE: "It is also the zone every memory time is shown to the LLM in (consolidation, reflect and the observation tree), so observation text and answers write local dates and times".

Actual Behavior

The note is dated in UTC. Here that is the day before the local date the prompt shows for the same fact:

The team deploys on Thursdays. (2026-11-09 23:30: The team deploys on Tuesdays.)

In round 2 of the script the observation's text carries 2026-11-09 23:30 while its source memory, one field later, carries 2026-11-10T00:30+01:00. stderr only had the import-time warning that sentence-transformers is not installed, which does not affect the run.

Standard output of the script on 9f471cdb (exit code 1)
=== Round 1: what the model is shown ===
## TIMEZONE

Every time below is local time in Europe/Berlin, offset included. When the text states a date or a time of day, write that local one as shown.

## INPUT

### New facts

[F1] The team deploys on Tuesdays. (mentioned_at=2026-11-10T00:30+01:00)
  closest existing observations: O1 (stated after this fact)

### Existing observations

[
{"id": "O1", "text": "The team deploys on Thursdays.", "proof_count": 1, "mentioned_at": "2026-11-20T10:00+01:00", "newer_than_input_facts": true}
]

=== Round 1: the observation text consolidation writes ===
The team deploys on Thursdays. (2026-11-09 23:30: The team deploys on Tuesdays.)

=== Round 2: the same observation in the next prompt ===
## TIMEZONE

Every time below is local time in Europe/Berlin, offset included. When the text states a date or a time of day, write that local one as shown.

## INPUT

### New facts

[F1] The office kitchen is cleaned on Fridays. (mentioned_at=2026-11-23T09:15+01:00)

### Existing observations

[
{"id": "O1", "text": "The team deploys on Thursdays. (2026-11-09 23:30: The team deploys on Tuesdays.)", "proof_count": 1, "mentioned_at": "2026-11-20T10:00+01:00", "source_memories": [{"text": "The team deploys on Tuesdays.", "mentioned_at": "2026-11-10T00:30+01:00"}]}
]

=== Check ===
bank default_timezone          : Europe/Berlin
fact time shown in the prompt  : 2026-11-10T00:30+01:00
expected date in the bracket   : 2026-11-10 00:30
date in the bracket            : 2026-11-09 23:30  -> BUG, UTC wall clock
Where it is in the code

hindsight-api-slim/hindsight_api/engine/consolidation/consolidator.py, in _consolidate_batch_with_llm (line numbers at 9f471cdb):

  • L3973: tz = bank_timezone(config) is already there and is passed to every _prompt_time(..., tz) call for this prompt.

  • L4115: the note is built without it:

    str(m["id"]): f"{t:%Y-%m-%d %H:%M}: {fact_sentence(m)}"
    

    t comes from _latest_time(...), so it is always timezone-aware. The line prints it in whatever offset the value carries, which is UTC for times read back from the store.

  • L1489-1498: _EARLIER_STATE_START and _with_earlier_states are the only code I found that reads the note back (split on the date pattern, dedup, string sort, keep 3). prompts.py L33 explains the bracket to the model and does not name a zone.

Already fixed, a duplicate, or by design?
  • Not fixed on main at 9f471cdb (2026-11-26), which was the head when I checked on 2026-11-27. The last commit that touches consolidator.py is c5b696c7 (#6835), and v1.3.0 includes it, so the release has the same line.
  • I found no existing report. I searched issues and PRs, open and closed, for "earlier state" / "earlier-state" together with timezone and UTC, and for timezone issues opened since #6835 merged.
  • By design? Probably not, but I can't be sure. #6835 says "Every place a model reads memory times now uses the bank's default_timezone and names it", and its diff changes _prompt_time and its callers and leaves this line alone. It also changed the comment on _stamp (engine/observation_tree.py, L405-408) from "Date and time in UTC, the way observation notes write them" to "Date and time in the bank's zone (...), the way observation notes write them (#6441)". If that means these notes, they do not write the bank's zone. No test or doc says the note stays in UTC. One reason it could be deliberate is the string sort described under "Side effects of the one-line change".
One-line change that makes the script pass
--- a/hindsight-api-slim/hindsight_api/engine/consolidation/consolidator.py
+++ b/hindsight-api-slim/hindsight_api/engine/consolidation/consolidator.py
@@ -4112,7 +4112,7 @@
             response = answer.with_real_ids(real_id).to_actions(
                 {str(o.id): o.text for o in union_observations},
                 {
-                    str(m["id"]): f"{t:%Y-%m-%d %H:%M}: {fact_sentence(m)}"
+                    str(m["id"]): f"{t.astimezone(tz):%Y-%m-%d %H:%M}: {fact_sentence(m)}"
                     if (t := fact_time[str(m["id"])])
                     else fact_sentence(m)
                     for m in ordered

With it the script exits 0 and the note reads (2026-11-10 00:30: The team deploys on Tuesdays.). With default_timezone unset, empty or UTC, the note is the same string as before for every time that carries UTC or no offset, which is what the store returns (checked with aware-UTC datetimes, naive datetimes and ISO strings ending in Z or +00:00). The one input that changes is a value carrying another offset: today the note uses that value's own wall clock (2026-11-10 08:30 for a +09:00 datetime), and with the change it uses the bank's zone (2026-11-09 23:30 on a UTC bank), as _prompt_time already does.

A test that could go with it

In tests/test_consolidation_fact_format.py, after test_the_prompt_uses_short_ids_oldest_first_and_marks_later_observations, which already pins the UTC case. It needs no new imports.

test_an_earlier_state_note_is_dated_in_the_bank_zone
async def test_an_earlier_state_note_is_dated_in_the_bank_zone() -> None:
    """#6441: the note's date is a time the model reads too, in the next prompt that holds the
    observation. 23:30 UTC on 9 Nov is 00:30 on 10 Nov in Berlin, which is what the prompt shows."""
    pool = [
        SimpleNamespace(
            id="o-deploy",
            text="The team deploys on Thursdays.",
            occurred_start=None,
            occurred_end=None,
            mentioned_at=datetime(2026, 11, 20, 9, 0, tzinfo=timezone.utc),
            source_fact_ids=[],
        )
    ]
    sent: dict[str, Any] = {}

    class _LLM:
        async def call(self, **kwargs: Any) -> Any:
            sent.update(kwargs)
            answer = {
                "facts": [
                    {
                        "fact_id": "F1",
                        "kind": "lasting",
                        "existing": [{"observation_id": "O1", "effect": "changes", "text": ""}],
                        "adds": "no",
                    }
                ]
            }
            return LLMCallResult(content=kwargs["response_format"].model_validate(answer))

    config = SimpleNamespace(
        llm_output_language=None,
        observations_mission=None,
        consolidation_max_attempts=1,
        consolidation_llm_max_retries=None,
        llm_temperature_consolidation=0.0,
        llm_strict_schema_consolidation=False,
        consolidation_max_completion_tokens=None,
        default_timezone="Europe/Berlin",
    )
    stated = datetime(2026, 11, 9, 23, 30, tzinfo=timezone.utc)
    memories = [{"id": "f-old", "text": "The team deploys on Tuesdays.", "mentioned_at": stated}]
    result = await _consolidate_batch_with_llm(_LLM(), memories, pool, {}, config, closest={"f-old": ["o-deploy"]})

    user = sent["messages"][-1]["content"]
    assert "local time in Europe/Berlin" in user
    assert "[F1] The team deploys on Tuesdays. (mentioned_at=2026-11-10T00:30+01:00)" in user
    # The note carries the wall clock the prompt showed for the fact, not the UTC one.
    assert [u.text for u in result.updates] == [
        "The team deploys on Thursdays. (2026-11-10 00:30: The team deploys on Tuesdays.)"
    ]

What I ran, with the dependencies pinned in uv.lock:

  • This test fails on 9f471cdb (... (2026-11-09 23:30: ...) instead of ... (2026-11-10 00:30: ...)) and passes with the one-line change.
  • tests/test_consolidation_fact_format.py: 23 passed as it is on main, 24 passed with the test and the change.
  • Together with test_consolidation_recency_prompt_5938.py, test_consolidation_retry_budget.py and test_prompt_timezone.py: 52 passed with the change.
  • ruff format --check and ruff check (0.14.9) pass on both changed files, and ty check hindsight_api/ (0.0.84) passes.
  • Not run: the consolidation tests that need a database or a real LLM, and hindsight-system-tests.
Side effects of the one-line change

_with_earlier_states (the dedup, sort and keep-3 from #6399) compares notes as strings. That is exact while every note is in one zone with a fixed offset, which today is always UTC. With the one-line change, on a Europe/Berlin config and the same stub:

  • Notes already stored in UTC stay as they are and mix with new local ones. The same fact consolidated again is no longer deduplicated: (2026-11-10 00:30: The team deploys on Tuesdays.) (2026-11-09 23:30: The team deploys on Tuesdays.). A new fact that is less than the UTC offset older than a stored note sorts ahead of it and can push a newer stored note out of the three that are kept. Changing a bank's default_timezone later would mix notes the same way (from reading the code, not run).
  • The repeated hour when daylight saving ends. Facts stated at 00:30 UTC (02:30 CEST) and 01:10 UTC (02:10 CET) on 2026-10-25 sort in the wrong order as local strings. As UTC strings they sort correctly.

I did not try the alternatives: sorting notes by their real time, rewriting stored notes, or keeping the note in UTC and marking it as UTC.

Version

1.3.0 (main @ 9f471cdb, 2026-11-26)

LLM Provider

Anthropic

Lingua principale
Python
Stelle
45.2k
Fork
5.9k
Merge medio
5h 46m
PR unite (30g)
389

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di vectorize-io/hindsight

Tutte le issue di vectorize-io/hindsight

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.