langgraph-api 0.20.0.dev3__py3-none-any.whl → 0.20.0.dev4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. langgraph_api/__init__.py +1 -1
  2. langgraph_api/_checkpointer/_adapter.py +5 -4
  3. langgraph_api/api/__init__.py +4 -7
  4. langgraph_api/api/assistants.py +2 -9
  5. langgraph_api/api/event_streaming.py +1 -5
  6. langgraph_api/api/mcp/_call_thread.py +1 -1
  7. langgraph_api/api/meta.py +5 -10
  8. langgraph_api/api/runs.py +8 -20
  9. langgraph_api/api/store.py +1 -1
  10. langgraph_api/api/threads.py +9 -24
  11. langgraph_api/cache.py +2 -15
  12. langgraph_api/cli.py +2 -11
  13. langgraph_api/cron_scheduler.py +2 -23
  14. langgraph_api/encryption/middleware.py +1 -66
  15. langgraph_api/errors.py +1 -2
  16. langgraph_api/feature_flags.py +8 -9
  17. langgraph_api/graph.py +3 -133
  18. langgraph_api/grpc/ops/runs.py +14 -2
  19. langgraph_api/grpc/ops/threads.py +2 -3
  20. langgraph_api/js/remote.py +3 -3
  21. langgraph_api/metrics_collector.py +15 -25
  22. langgraph_api/metrics_otlp.py +2 -2
  23. langgraph_api/models/run.py +1 -6
  24. langgraph_api/operator_routes.py +1 -6
  25. langgraph_api/queue_entrypoint.py +2 -2
  26. langgraph_api/runtime/encryption.py +11 -149
  27. langgraph_api/runtime/lifespan.py +2 -2
  28. langgraph_api/runtime/store.py +134 -2
  29. langgraph_api/self_hosted_metrics.py +2 -8
  30. langgraph_api/server.py +1 -1
  31. langgraph_api/store.py +47 -22
  32. langgraph_api/stream.py +14 -22
  33. langgraph_api/transcript/__init__.py +0 -0
  34. langgraph_api/transcript/input_ids.py +100 -0
  35. langgraph_api/worker.py +1 -6
  36. langgraph_api/worker_runtime.py +5 -16
  37. {langgraph_api-0.20.0.dev3.dist-info → langgraph_api-0.20.0.dev4.dist-info}/METADATA +3 -3
  38. {langgraph_api-0.20.0.dev3.dist-info → langgraph_api-0.20.0.dev4.dist-info}/RECORD +49 -52
  39. langgraph_grpc_common/proto/core_api_pb2.py +178 -174
  40. langgraph_grpc_common/proto/core_api_pb2.pyi +101 -6
  41. langgraph_runtime/__init__.py +27 -55
  42. langgraph_runtime/checkpoint.py +5 -1
  43. langgraph_runtime/database.py +5 -1
  44. langgraph_runtime/encryption.py +6 -13
  45. langgraph_runtime/routes.py +6 -9
  46. langgraph_runtime/store.py +5 -1
  47. langgraph_runtime/lifespan.py +0 -4
  48. langgraph_runtime/metrics.py +0 -4
  49. langgraph_runtime/ops.py +0 -4
  50. langgraph_runtime/queue.py +0 -4
  51. langgraph_runtime/retry.py +0 -4
  52. {langgraph_api-0.20.0.dev3.dist-info → langgraph_api-0.20.0.dev4.dist-info}/WHEEL +0 -0
  53. {langgraph_api-0.20.0.dev3.dist-info → langgraph_api-0.20.0.dev4.dist-info}/entry_points.txt +0 -0
  54. {langgraph_api-0.20.0.dev3.dist-info → langgraph_api-0.20.0.dev4.dist-info}/licenses/LICENSE +0 -0
langgraph_api/graph.py CHANGED
@@ -1,5 +1,4 @@
1
1
  import asyncio
2
- import functools
3
2
  import glob
4
3
  import importlib.util
5
4
  import inspect
@@ -7,7 +6,6 @@ import logging
7
6
  import os
8
7
  import sys
9
8
  import time
10
- import warnings
11
9
  from collections.abc import AsyncIterator, Callable, Generator
12
10
  from contextlib import asynccontextmanager, contextmanager
13
11
  from itertools import filterfalse
@@ -16,7 +14,6 @@ from uuid import UUID, uuid5
16
14
 
17
15
  import orjson
18
16
  import structlog
19
- from langchain_core.embeddings import Embeddings # noqa: TC002
20
17
  from langgraph.checkpoint.base import BaseCheckpointSaver
21
18
  from langgraph.constants import CONFIG_KEY_CHECKPOINTER
22
19
  from langgraph.graph import StateGraph
@@ -36,15 +33,16 @@ from langgraph_api._factory_utils import (
36
33
  )
37
34
  from langgraph_api.asyncio import as_asynccontextmanager
38
35
  from langgraph_api.feature_flags import (
39
- IS_POSTGRES_OR_GRPC_BACKEND,
40
36
  USE_RUNTIME_CONTEXT_API,
41
37
  )
42
38
  from langgraph_api.js.base import BaseRemotePregel, is_js_path
39
+ from langgraph_api.runtime.retry import retry_db
43
40
  from langgraph_api.schema import Config
44
41
  from langgraph_api.timing import profiled_import
45
42
  from langgraph_api.timing.startup import set_phase
46
43
  from langgraph_api.utils.config import run_in_executor, var_child_runnable_config
47
44
  from langgraph_api.utils.errors import GraphLoadError
45
+ from langgraph_runtime.database import connect
48
46
 
49
47
  logger = structlog.stdlib.get_logger(__name__)
50
48
 
@@ -80,12 +78,7 @@ async def register_graph(
80
78
  description: str | None = None,
81
79
  ) -> None:
82
80
  """Register a graph."""
83
- from langgraph_runtime.database import connect # noqa: PLC0415
84
-
85
- if IS_POSTGRES_OR_GRPC_BACKEND:
86
- from langgraph_api.grpc.ops import Assistants # noqa: PLC0415
87
- else:
88
- from langgraph_runtime.ops import Assistants # noqa: PLC0415
81
+ from langgraph_api.grpc.ops import Assistants # noqa: PLC0415
89
82
 
90
83
  GRAPHS[graph_id] = graph
91
84
  assistant_id = uuid5(NAMESPACE_GRAPH, graph_id)
@@ -93,8 +86,6 @@ async def register_graph(
93
86
  if callable(graph):
94
87
  classify_factory(graph, graph_id)
95
88
 
96
- from langgraph_runtime.retry import retry_db # noqa: PLC0415
97
-
98
89
  @retry_db
99
90
  async def register_graph_db():
100
91
  async with connect() as conn:
@@ -962,124 +953,3 @@ def _register_stream_transformers_from_module(graph_id: str, module: Any) -> Non
962
953
  )
963
954
  return
964
955
  GRAPH_STREAM_TRANSFORMERS[graph_id] = factory
965
-
966
-
967
- @functools.lru_cache(maxsize=1)
968
- def _get_init_embeddings() -> Callable[[str, ...], "Embeddings"] | None:
969
- try:
970
- from langchain.embeddings import ( # noqa: PLC0415 # ty: ignore[unresolved-import]
971
- init_embeddings,
972
- )
973
-
974
- return init_embeddings
975
- except ImportError:
976
- return None
977
-
978
-
979
- @timing.timer(
980
- message="Loading embeddings {embeddings_path}",
981
- metadata_fn=lambda index_config: {"embeddings_path": index_config.get("embed")},
982
- warn_threshold_secs=5,
983
- warn_message="Loading embeddings '{embeddings_path}' took longer than expected",
984
- error_threshold_secs=10,
985
- )
986
- def resolve_embeddings(index_config: dict) -> "Embeddings":
987
- """Return embeddings from config.
988
-
989
- Args:
990
- index_config: Configuration for the vector store index
991
- Must contain an "embed" key specifying either:
992
- - A path to a Python file and function (e.g. "./embeddings.py:get_embeddings")
993
- - A LangChain embeddings identifier (e.g. "openai:text-embedding-3-small")
994
-
995
- Returns:
996
- Embeddings: A LangChain embeddings instance
997
-
998
- Raises:
999
- ValueError: If embeddings cannot be loaded from the config
1000
- """
1001
- from langchain_core.embeddings import Embeddings # noqa: PLC0415
1002
- from langgraph.store.base import ensure_embeddings # noqa: PLC0415
1003
-
1004
- embed = index_config["embed"]
1005
- if isinstance(embed, Embeddings):
1006
- return embed
1007
- if callable(embed):
1008
- return ensure_embeddings(embed)
1009
- if not isinstance(embed, str):
1010
- raise ValueError(
1011
- f"Embeddings config must be a string or callable, got: {type(embed).__name__}"
1012
- )
1013
- if ".py:" in embed:
1014
- module_name, function = embed.rsplit(":", 1)
1015
- module_name = module_name.rstrip(":")
1016
-
1017
- try:
1018
- with profiled_import(embed):
1019
- if "/" in module_name:
1020
- # Load from file path
1021
- modname = (
1022
- module_name.replace("/", "__")
1023
- .replace(".py", "")
1024
- .replace(" ", "_")
1025
- )
1026
- modspec = importlib.util.spec_from_file_location(
1027
- modname, module_name
1028
- )
1029
- if modspec is None:
1030
- raise ValueError(
1031
- f"Could not find embeddings file: {module_name}"
1032
- )
1033
- module = importlib.util.module_from_spec(modspec)
1034
- sys.modules[modname] = module
1035
- modspec.loader.exec_module(module)
1036
- else:
1037
- # Load from Python module
1038
- module = importlib.import_module(module_name)
1039
-
1040
- embedding_fn = getattr(module, function, None)
1041
- if embedding_fn is None:
1042
- raise ValueError(
1043
- f"Could not find embeddings function '{function}' in module: {module_name}"
1044
- )
1045
-
1046
- if isinstance(embedding_fn, Embeddings):
1047
- return embedding_fn
1048
- elif not callable(embedding_fn):
1049
- raise ValueError(
1050
- f"Embeddings function '{function}' in module: {module_name} is not callable"
1051
- )
1052
-
1053
- return ensure_embeddings(embedding_fn)
1054
-
1055
- except ImportError as e:
1056
- e.add_note(f"Could not import embeddings module:\n{module_name}\n\n")
1057
- if lg_api_config.API_VARIANT == "local_dev":
1058
- e.add_note(
1059
- "If you're in development mode, make sure you've installed your project "
1060
- "and its dependencies:\n"
1061
- "- For requirements.txt: pip install -r requirements.txt\n"
1062
- "- For pyproject.toml: pip install -e .\n"
1063
- )
1064
- raise
1065
- except FileNotFoundError as e:
1066
- raise ValueError(f"Could not find embeddings file: {module_name}") from e
1067
-
1068
- else:
1069
- # Load from LangChain embeddings
1070
- init_embeddings = _get_init_embeddings()
1071
- if init_embeddings is None:
1072
- raise ValueError(
1073
- f"Could not load LangChain embeddings '{embed}'. "
1074
- "Loading embeddings by provider:identifier requires the langchain package (>=0.3.9). "
1075
- "Install it with: pip install 'langchain>=0.3.9'"
1076
- " or specify 'embed' as a path to a "
1077
- "variable in a Python file instead."
1078
- )
1079
- # Capture warnings
1080
- with warnings.catch_warnings():
1081
- warnings.filterwarnings(
1082
- "ignore",
1083
- message=("The function `init_embeddings` is in beta."),
1084
- )
1085
- return init_embeddings(embed)
@@ -67,6 +67,7 @@ from langgraph_api.priority_settings import (
67
67
  assign_priority_settings,
68
68
  get_priority_callback,
69
69
  )
70
+ from langgraph_api.runtime.retry import RETRIABLE_EXCEPTIONS
70
71
  from langgraph_api.serde import (
71
72
  json_dumpb,
72
73
  json_dumpb_optional,
@@ -625,9 +626,15 @@ class Runs(Authenticated):
625
626
  offset: int = 0,
626
627
  status: RunStatus | None = None,
627
628
  select: list[RunSelectField] | None = None,
629
+ before: tuple[datetime, UUID] | None = None,
628
630
  ctx: Any = None,
629
631
  ) -> AsyncIterator[Run]:
630
- """List all runs by thread."""
632
+ """List a thread's runs, newest first with ties broken by the larger run_id.
633
+
634
+ ``before`` is the ``(created_at, run_id)`` of the last run already read;
635
+ only runs after it in that order are returned. It can't be combined
636
+ with a nonzero ``offset``.
637
+ """
631
638
  auth_filters = await Runs.handle_event(
632
639
  ctx,
633
640
  "search",
@@ -648,6 +655,12 @@ class Runs(Authenticated):
648
655
  if select:
649
656
  request_kwargs["select"] = select
650
657
 
658
+ if before is not None:
659
+ created_at, run_id = before
660
+ request_kwargs["before"] = pb.RunSearchCursor(
661
+ created_at=created_at, run_id=pb.UUID(value=str(run_id))
662
+ )
663
+
651
664
  client = await get_shared_client()
652
665
  response = await client.runs.Search(pb.SearchRunsRequest(**request_kwargs))
653
666
 
@@ -1376,7 +1389,6 @@ class Runs(Authenticated):
1376
1389
  Yields:
1377
1390
  ValueEvent that will be set with UserInterrupt() or UserRollback() if cancelled
1378
1391
  """
1379
- from langgraph_runtime.retry import RETRIABLE_EXCEPTIONS # noqa: PLC0415
1380
1392
 
1381
1393
  @asynccontextmanager
1382
1394
  async def _enter_impl():
@@ -977,9 +977,8 @@ class Threads(Authenticated):
977
977
  ) -> dict[str, Any]:
978
978
  """Get the bytes a thread's checkpoints occupy, per table and per channel.
979
979
 
980
- Postgres only: the inmem runtime's ``Threads.storage`` counts its own
981
- in-memory checkpointer and never calls this. Go runs the same access
982
- check as ``get``, so a missing or hidden thread raises 404.
980
+ Go runs the same access check as ``get``, so a missing or hidden
981
+ thread raises 404.
983
982
  """
984
983
  auth_filters = await Threads.handle_event(
985
984
  ctx, "read", {"thread_id": str(thread_id)}
@@ -831,9 +831,9 @@ async def _get_passthrough_checkpointer():
831
831
  from langgraph_api import _checkpointer as api_checkpointer # noqa: PLC0415
832
832
 
833
833
  checkpointer = await api_checkpointer.get_checkpointer()
834
- # The in-memory runtime returns the saver Python graphs share, so swap the
835
- # serde on a copy; the copy still shares the saved data. Other runtimes
836
- # return a fresh saver per call.
834
+ # An InMemorySaver is shared with Python graphs, so swap the serde on a
835
+ # copy; the copy still shares the saved data. Other savers are fresh per
836
+ # call.
837
837
  if isinstance(checkpointer, InMemorySaver):
838
838
  checkpointer = copy.copy(checkpointer)
839
839
  # This checkpointer does not attempt to revive LC-objects.
@@ -11,14 +11,12 @@ metric group self-gates so it lands on the right process:
11
11
  process (``N_JOBS_PER_WORKER == 0``) has no workers and skips them.
12
12
  - **queue depth** (``num_pending_runs``/``num_running_runs``) — a single global
13
13
  value from ``Runs.stats`` (a gRPC call to the Go core). Emitted by the **API
14
- process only** (``not IS_QUEUE_ENTRYPOINT``) on the **postgres** runtime; inmem
15
- skips the DB round-trip entirely.
16
- - **Postgres + Redis pool stats** — recorded on **both** processes (postgres
17
- runtime only), each reporting its own pools via ``meta_pool_stats()``, which
18
- merges the local Python pools with the Go-core pools. Redis stats in particular
19
- come from the local Python pool — the Go core omits them unless it has a
20
- non-cluster redis client — so a Go-core-only source would drop them. inmem has
21
- no real Postgres/Redis pools, so nothing is reported.
14
+ process only** (``not IS_QUEUE_ENTRYPOINT``).
15
+ - **Postgres + Redis pool stats** — recorded on **both** processes, each
16
+ reporting its own pools via ``meta_pool_stats()``, which merges the local
17
+ Python pools with the Go-core pools. Redis stats in particular come from the
18
+ local Python pool — the Go core omits them unless it has a non-cluster redis
19
+ client — so a Go-core-only source would drop them.
22
20
 
23
21
  The two pool request counters are cumulative, so we push the delta since the
24
22
  previous sample (OTLP counters are additive).
@@ -36,7 +34,7 @@ import structlog
36
34
 
37
35
  from langgraph_api import config
38
36
  from langgraph_api.api.meta import meta_pool_stats
39
- from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
37
+ from langgraph_api.grpc.ops import Runs
40
38
  from langgraph_api.metrics_otlp import (
41
39
  COUNTER_PG_POOL_REQUESTS_ERRORS,
42
40
  COUNTER_PG_POOL_REQUESTS_QUEUED,
@@ -57,13 +55,8 @@ from langgraph_api.metrics_otlp import (
57
55
  GAUGE_WORKERS_MAX,
58
56
  get_otlp_metrics_reporter,
59
57
  )
58
+ from langgraph_api.runtime.metrics import get_metrics
60
59
  from langgraph_runtime.database import connect
61
- from langgraph_runtime.metrics import get_metrics
62
-
63
- if IS_POSTGRES_OR_GRPC_BACKEND:
64
- from langgraph_api.grpc.ops import Runs
65
- else:
66
- from langgraph_runtime.ops import Runs
67
60
 
68
61
  logger = structlog.stdlib.get_logger(__name__)
69
62
 
@@ -100,10 +93,9 @@ async def _collect_queue_and_workers(reporter) -> None:
100
93
  )
101
94
 
102
95
  # Queue depth is read from the run table via Runs.stats (a gRPC call to the
103
- # Go core on postgres). Emitted by the API process only — the queue worker
104
- # (IS_QUEUE_ENTRYPOINT) skips it. inmem skips the DB round-trip and reports
105
- # nothing.
106
- if IS_POSTGRES_OR_GRPC_BACKEND and not config.IS_QUEUE_ENTRYPOINT:
96
+ # Go core). Emitted by the API process only — the queue worker
97
+ # (IS_QUEUE_ENTRYPOINT) skips it.
98
+ if not config.IS_QUEUE_ENTRYPOINT:
107
99
  async with connect() as conn:
108
100
  stats = await Runs.stats(conn)
109
101
  reporter.record_gauge(GAUGE_NUM_PENDING_RUNS, stats["n_pending"])
@@ -195,12 +187,10 @@ async def _collect_once(prev_counters: dict[str, int]) -> None:
195
187
  "metrics collector: queue/worker sample failed", exc_info=exc
196
188
  )
197
189
 
198
- # Postgres/Redis pools live in the Go core (no real pools on inmem).
199
- if IS_POSTGRES_OR_GRPC_BACKEND:
200
- try:
201
- await _collect_pool(reporter, prev_counters)
202
- except Exception as exc:
203
- await logger.awarning("metrics collector: pool sample failed", exc_info=exc)
190
+ try:
191
+ await _collect_pool(reporter, prev_counters)
192
+ except Exception as exc:
193
+ await logger.awarning("metrics collector: pool sample failed", exc_info=exc)
204
194
 
205
195
 
206
196
  async def collector_loop() -> None:
@@ -269,8 +269,8 @@ GAUGE_PUBLISH_QUEUE_AVAILABILITY = def_gauge(
269
269
  )
270
270
  # Snapshot/state gauges pushed by the periodic
271
271
  # metrics collector loop (langgraph_api.metrics_collector).
272
- # Queue depth + workers_max are inmem-only (the Go core emits them on postgres);
273
- # pool stats are emitted on both runtimes.
272
+ # Queue depth comes from the API process, workers_max from wherever workers
273
+ # run, and pool stats from every process.
274
274
  GAUGE_WORKERS_MAX = def_gauge("workers_max", METRIC_TIER_CRITICAL, lsd_web_metric=True)
275
275
  GAUGE_NUM_PENDING_RUNS = def_gauge(
276
276
  "num_pending_runs",
@@ -12,12 +12,12 @@ from typing_extensions import TypedDict
12
12
 
13
13
  from langgraph_api import config as api_config
14
14
  from langgraph_api.auth.noop import UnauthenticatedUser
15
- from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
16
15
  from langgraph_api.graph import (
17
16
  GRAPHS,
18
17
  get_assistant_id,
19
18
  inject_current_dd_trace_context,
20
19
  )
20
+ from langgraph_api.grpc.ops import Runs
21
21
  from langgraph_api.otel_context import inject_current_trace_context
22
22
  from langgraph_api.schema import (
23
23
  All,
@@ -41,11 +41,6 @@ from langgraph_api.utils.uuids import uuid7
41
41
  from langgraph_api.validation import strip_reserved
42
42
  from langgraph_api.webhook import validate_or_drop_webhook
43
43
 
44
- if IS_POSTGRES_OR_GRPC_BACKEND:
45
- from langgraph_api.grpc.ops import Runs
46
- else:
47
- from langgraph_runtime.ops import Runs
48
-
49
44
  if TYPE_CHECKING:
50
45
  from starlette.authentication import BaseUser
51
46
 
@@ -24,14 +24,9 @@ from starlette.routing import Route
24
24
  from langgraph_api import config
25
25
  from langgraph_api.auth.langsmith.client import create_client
26
26
  from langgraph_api.errors import app_exception_handlers
27
- from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
27
+ from langgraph_api.grpc.ops import Runs
28
28
  from langgraph_runtime.database import connect
29
29
 
30
- if IS_POSTGRES_OR_GRPC_BACKEND:
31
- from langgraph_api.grpc.ops import Runs
32
- else:
33
- from langgraph_runtime.ops import Runs
34
-
35
30
  if TYPE_CHECKING:
36
31
  from starlette.requests import Request
37
32
  from starlette.types import ASGIApp, Message, Receive, Scope, Send
@@ -21,11 +21,11 @@ import structlog
21
21
 
22
22
  from langgraph_api.asyncio import NoSignalServer, run_main_loop
23
23
  from langgraph_api.go_prometheus_metrics import merge_go_prometheus_text
24
+ from langgraph_api.runtime import lifespan
25
+ from langgraph_api.runtime.metrics import get_metrics
24
26
  from langgraph_api.utils.errors import GraphLoadError, HealthServerStartupError
25
27
  from langgraph_api.utils.network import format_hostport, normalize_host
26
- from langgraph_runtime import lifespan
27
28
  from langgraph_runtime.database import healthcheck
28
- from langgraph_runtime.metrics import get_metrics
29
29
 
30
30
  logger = structlog.stdlib.get_logger(__name__)
31
31
 
@@ -1,4 +1,4 @@
1
- """Structural JSON encryption for the in-memory runtime.
1
+ """JSON decryption for the in-memory runtime; Go core encrypts.
2
2
 
3
3
  The Postgres runtime replaces this module with its own.
4
4
  """
@@ -8,38 +8,13 @@ from __future__ import annotations
8
8
  import asyncio
9
9
  from typing import TYPE_CHECKING, Any
10
10
 
11
- from langgraph_api.encryption.middleware import (
12
- decrypt_json_if_needed,
13
- encrypt_json_if_needed,
14
- )
15
- from langgraph_api.encryption.shared import (
16
- BLOB_ENCRYPTION_CONTEXT_KEY,
17
- ENCRYPTION_CONTEXT_KEY,
18
- )
19
- from langgraph_api.serde import json_dumpb, json_loads
11
+ from langgraph_api.encryption.middleware import decrypt_json_if_needed
20
12
 
21
13
  if TYPE_CHECKING:
22
- from collections.abc import Mapping
23
-
24
14
  from langgraph_api.encryption.aes_json import AesEncryptionInstance
25
15
  from langgraph_api.encryption.custom import JsonEncryptionWrapper, ModelType
26
16
 
27
- NESTED_ENCRYPTED_SUBFIELDS: dict[tuple[str, str], tuple[str, ...]] = {
28
- ("run", "kwargs"): ("input", "config", "context", "command"),
29
- ("run", "config"): ("configurable", "metadata"),
30
- ("cron", "payload"): ("metadata", "context", "input", "config"),
31
- ("cron", "config"): ("configurable", "metadata"),
32
- ("assistant", "config"): ("configurable",),
33
- ("thread", "config"): ("configurable",),
34
- }
35
-
36
- ENCRYPTION_FIELDS: dict[str, tuple[str, ...]] = {
37
- "thread": ("metadata", "config", "values", "interrupts", "error"),
38
- "run": ("metadata", "kwargs"),
39
- "assistant": ("metadata", "config", "context"),
40
- "cron": ("metadata", "payload"),
41
- "store": ("value",),
42
- }
17
+ ENCRYPTION_FIELDS: dict[str, tuple[str, ...]] = {"store": ("value",)}
43
18
 
44
19
  NEVER_ENCRYPT_FIELDS = frozenset(
45
20
  {
@@ -90,138 +65,25 @@ def should_skip_encryption(key: str, path: str) -> bool:
90
65
  return key in NEVER_ENCRYPT_FIELDS or f"{path}.{key}" in NEVER_ENCRYPT_PATHS
91
66
 
92
67
 
93
- def extract_blob_encryption_context(
94
- data: dict[str, Any] | None,
95
- ) -> dict[str, Any] | None:
96
- """Return checkpoint blob context carried by an encrypted resource."""
97
- if data is None:
98
- return None
99
-
100
- return data.get(BLOB_ENCRYPTION_CONTEXT_KEY) or data.get(ENCRYPTION_CONTEXT_KEY)
101
-
102
-
103
68
  def encryption_fields(model_type: ModelType) -> list[str]:
104
- """Return fields structurally encrypted by the local runtime."""
69
+ """Return fields Python still decrypts: custom-store values only."""
105
70
  return list(ENCRYPTION_FIELDS[model_type])
106
71
 
107
72
 
108
- async def _decrypt_field(
109
- obj: dict[str, Any],
110
- field_name: str,
111
- encryption_instance: JsonEncryptionWrapper | AesEncryptionInstance | None,
112
- model_type: ModelType,
113
- ) -> tuple[str, Any]:
114
- if not obj.get(field_name):
115
- return field_name, obj.get(field_name)
116
-
117
- decrypted = await decrypt_json_if_needed(
118
- obj[field_name], encryption_instance, model_type, field=field_name
119
- )
120
- nested_fields = NESTED_ENCRYPTED_SUBFIELDS.get((model_type, field_name), ())
121
- if decrypted is not None:
122
- results = await asyncio.gather(
123
- *(
124
- _decrypt_field(decrypted, name, encryption_instance, model_type)
125
- for name in nested_fields
126
- if isinstance(decrypted.get(name), dict)
127
- )
128
- )
129
- for name, value in results:
130
- decrypted[name] = value
131
- return field_name, decrypted
132
-
133
-
134
73
  async def decrypt_fields(
135
74
  obj: dict[str, Any],
136
75
  model_type: ModelType,
137
76
  fields: list[str],
138
77
  encryption_instance: JsonEncryptionWrapper | AesEncryptionInstance | None,
139
78
  ) -> None:
140
- """Decrypt configured fields, including local-runtime nested structure."""
141
- results = await asyncio.gather(
79
+ """Decrypt top-level fields in place."""
80
+ names = [name for name in fields if obj.get(name)]
81
+ values = await asyncio.gather(
142
82
  *(
143
- _decrypt_field(obj, name, encryption_instance, model_type)
144
- for name in fields
145
- if name in obj
146
- )
147
- )
148
- for name, value in results:
149
- obj[name] = value
150
-
151
-
152
- async def _encrypt_field(
153
- data: Mapping[str, Any],
154
- field_name: str,
155
- encryption_instance: JsonEncryptionWrapper | AesEncryptionInstance | None,
156
- model_type: ModelType,
157
- path: str | None = None,
158
- ) -> tuple[str, Any]:
159
- if field_name not in data or data[field_name] is None:
160
- return field_name, data.get(field_name)
161
-
162
- field_data = data[field_name]
163
- if model_type == "thread" and field_name == "values":
164
- field_data = json_loads(json_dumpb(field_data))
165
- current_path = f"{path}.{field_name}" if path else f"{model_type}.{field_name}"
166
- nested_fields = NESTED_ENCRYPTED_SUBFIELDS.get((model_type, field_name), ())
167
- extracted: dict[str, Any] = {}
168
- if nested_fields:
169
- if not isinstance(field_data, dict):
170
- raise TypeError(
171
- f"'{field_name}' must be a dict for encryption, "
172
- f"got {type(field_data).__name__}"
173
- )
174
- for name in nested_fields:
175
- value = field_data.get(name)
176
- if isinstance(value, dict) and value:
177
- extracted[name] = value
178
- if extracted:
179
- field_data = {k: v for k, v in field_data.items() if k not in extracted}
180
-
181
- encrypted = await encrypt_json_if_needed(
182
- field_data,
183
- encryption_instance,
184
- model_type,
185
- field=field_name,
186
- path=current_path,
187
- should_skip=should_skip_encryption,
188
- )
189
- if extracted and isinstance(encrypted, dict):
190
- results = await asyncio.gather(
191
- *(
192
- _encrypt_field(
193
- {name: value}, name, encryption_instance, model_type, current_path
194
- )
195
- for name, value in extracted.items()
83
+ decrypt_json_if_needed(
84
+ obj[name], encryption_instance, model_type, field=name
196
85
  )
197
- )
198
- for name, value in results:
199
- encrypted[name] = value
200
- marker = value.get("__encryption_context__")
201
- if (
202
- "__encryption_context__" not in encrypted
203
- and isinstance(marker, dict)
204
- and marker.get("__langgraph_encryption_type__") == "aes"
205
- ):
206
- encrypted["__encryption_context__"] = marker
207
- return field_name, encrypted
208
-
209
-
210
- async def encrypt_fields(
211
- data: Mapping[str, Any],
212
- model_type: ModelType,
213
- fields: list[str],
214
- encryption_instance: JsonEncryptionWrapper | AesEncryptionInstance | None,
215
- ) -> dict[str, Any]:
216
- """Encrypt configured fields, preserving local-runtime nested structure."""
217
- result = dict(data)
218
- encrypted_fields = await asyncio.gather(
219
- *(
220
- _encrypt_field(data, name, encryption_instance, model_type)
221
- for name in fields
222
- if name in data
86
+ for name in names
223
87
  )
224
88
  )
225
- for name, value in encrypted_fields:
226
- result[name] = value
227
- return result
89
+ obj.update(zip(names, values, strict=True))
@@ -11,7 +11,7 @@ from starlette.applications import Starlette
11
11
 
12
12
  from langgraph_api import config, embedded_core
13
13
  from langgraph_api.config import BG_JOB_SHUTDOWN_GRACE_PERIOD_SECS
14
- from langgraph_api.feature_flags import INMEM_USES_CORE
14
+ from langgraph_api.feature_flags import IS_INMEM_BACKEND
15
15
  from langgraph_api.runtime import queue
16
16
  from langgraph_license.validation import (
17
17
  check_license_periodically,
@@ -55,7 +55,7 @@ async def _embedded_core():
55
55
  LSD_GRPC_SERVER_ADDRESS is ignored: the in-memory runtime only talks to its
56
56
  own SQLite core, never to an external one.
57
57
  """
58
- if not INMEM_USES_CORE:
58
+ if not IS_INMEM_BACKEND:
59
59
  yield
60
60
  return
61
61
  if os.environ.get("LSD_GRPC_SERVER_ADDRESS"):