Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

SQLAlchemySession on PostgreSQL returns items out of order and pops the wrong item when created_at is not monotonic

Abierto Apto para principiantes
#5,459 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
85/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
postgresql, python, sqlalchemy
Área
databases

Línea de trabajo

Empieza en src/agents/extensions/memory/sqlalchemy_session.py, donde get_items y pop_item ordenan por created_at, id. Lee la definición de Column para created_at y las llamadas a order_by tanto en los métodos síncronos como asíncronos. Cambia el orden a solo id o guarda las marcas de tiempo como UTC, luego ejecuta el script de reproducción del issue para confirmar que los turnos se devuelven en orden de añadido. Hecho significa que get_items y pop_item coinciden con el comportamiento de SQLiteSession.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Please read this first
  • Have you read the docs? Agents SDK docs
    Yes
  • Have you searched for related issues? Others may have faced similar issues.
    Yes. #1900 fixed ties between equal timestamps by adding id as a tie-breaker. This report is about timestamps that go backwards.
Describe the bug

Currently, SQLAlchemySession.get_items and pop_item order rows by created_at first and id second. The column is TIMESTAMP(timezone=False) with server_default=CURRENT_TIMESTAMP. On PostgreSQL that value is the transaction start time, converted to the wall clock of the connection's TimeZone setting. It does not follow the order in which rows were appended:

  • writers whose connections use different TimeZone settings write timestamps that differ by the UTC offset;
  • on a server whose time zone observes daylight saving time, the wall clock repeats an hour when the clocks fall back, so rows written during the repeated hour can sort before rows written in the hour just before it.

In each case get_items() returns turns out of order, get_items(limit=1) returns an item that is not the latest, and pop_item() deletes and returns an item that is not the most recent. #1900 shows what such a reordering does to the next run: a reasoning item that sorts after its message makes the Responses API reject the input with Item 'msg_...' of type 'message' was provided without its required 'reasoning' item. SQLiteSession and AsyncSQLiteSession order by id and return the append order for the same calls. The Session docstrings say get_items returns items "in chronological order" and pop_item removes "the most recent item".

The same ordering is on main (src/agents/extensions/memory/sqlalchemy_session.py):

            Column(
                "created_at",
                TIMESTAMP(timezone=False),
                server_default=sql_text("CURRENT_TIMESTAMP"),
                nullable=False,
            ),
                .order_by(
                    self._messages.c.created_at.desc(),
                    self._messages.c.id.desc(),
                )
Debug information
  • Agents SDK version: 0.24.0
  • Related library versions (optional, e.g. any-llm, litellm, or pydantic): SQLAlchemy 2.1.6, asyncpg 0.32.0, PostgreSQL 17.11
  • Python version: 3.12.13
  • Operating system: macOS 26.6.2, arm64 (Darwin 25.6.0)
  • Model and model provider: none (session API only)
  • Does the issue reproduce with the latest Agents SDK release? Yes, 0.24.0; main has the same code.
  • Does the issue occur consistently or intermittently? Consistently with the script below.
Repro steps
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
from agents.extensions.memory import SQLAlchemySession

URL = "postgresql+asyncpg://postgres@localhost:5432/postgres"


async def main():
    # two app instances whose connections use different TimeZone settings
    utc = create_async_engine(URL, connect_args={"server_settings": {"timezone": "UTC"}})
    toronto = create_async_engine(URL, connect_args={"server_settings": {"timezone": "America/Toronto"}})
    a = SQLAlchemySession("conv", engine=utc, create_tables=True)
    b = SQLAlchemySession("conv", engine=toronto, create_tables=True)
    await a.clear_session()

    await a.add_items([{"role": "user", "content": "turn 1"}])
    await a.add_items([{"role": "user", "content": "turn 2"}])
    await b.add_items([{"role": "user", "content": "turn 3"}])

    print([i["content"] for i in await a.get_items()])
    # actual:   ['turn 3', 'turn 1', 'turn 2']
    # expected: ['turn 1', 'turn 2', 'turn 3']
    print([i["content"] for i in await a.get_items(limit=1)])
    # actual:   ['turn 2']
    # expected: ['turn 3']
    print((await a.pop_item())["content"])
    # actual:   turn 2
    # expected: turn 3


asyncio.run(main())

With both engines set to the same TimeZone, the output is the expected one. A server whose own time zone observes daylight saving time behaves like the second engine after the clocks fall back. With TimeZone set to America/Toronto, SELECT '2026-11-01 05:59:00+00'::TIMESTAMPTZ::TIMESTAMP, '2026-11-01 06:00:00+00'::TIMESTAMPTZ::TIMESTAMP returns 2026-11-01 01:59:00 and 2026-11-01 01:00:00: a row written one minute later gets a created_at 59 minutes earlier.

Expected behavior

get_items returns items in the order they were added, and pop_item removes the last item added, as SQLiteSession does for the same calls. Storing created_at as TIMESTAMP WITH TIME ZONE (or always in UTC) keeps the current created_at, id ordering correct; ordering by id alone also gives that order.

Lenguaje dominante
Python
Estrellas
30.4k
Forks
4.9k
Merge medio
15 h 56 min
PR fusionados (30 d)
117

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openai/openai-agents-python

Todos los issues de openai/openai-agents-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.