fix: treat SQLite database update time as UTC for session's last update time

Fixes https://github.com/google/adk-python/issues/1180

We are using `func.now()` to set the `onupdate` time for db, when SQLAlchemy generates the SQL to build the database, it actually translates `func.now()` into `NOW()` or `CURRENT_TIMESTAMP`. The value it returns depends on the database server settings. For example, if the global/default timezone for a db is set to be UTC, the update time will be set to be a UCT time; if the global time zone for a db is set to be a local time zone (e.g. America/Los_Angeles), the update time will be a local time.

Normally, the best practice is to set database server to use UTC. Applications will convert it into different time zones as needed.

For SQLite, there is no way to config the default timezone, it will just treat it as UTC. But because it is a naive datetime (with no timezone info), python will assume it is a local time and then covert it into a UTC, which is why we see the bug (e.g. we create a session at 2025-06-17 12:49:33 local time, but when we read the session, its last update time is 2025-06-17 19:49:33 local time).

The solution is converting the native datatime to be timezone aware before `.timestamp()`.

The change in this CL only affects SQLite database.

PiperOrigin-RevId: 776654443
This commit is contained in:
Xuan Yang
2025-06-27 11:22:23 -07:00
committed by Copybara-Service
parent 4e765ae2f3
commit 3f621ae6f2
2 changed files with 36 additions and 11 deletions
@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime
from datetime import timezone
import enum
from google.adk.events import Event
@@ -66,10 +68,17 @@ async def test_create_get_session(service_type):
assert session.id
assert session.state == state
assert (
await session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session.id
)
== session
session.last_update_time
<= datetime.now().astimezone(timezone.utc).timestamp()
)
got_session = await session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session.id
)
assert got_session == session
assert (
got_session.last_update_time
<= datetime.now().astimezone(timezone.utc).timestamp()
)
session_id = session.id