fix(job_store): persist Jobs to disk and accept either ID in job tools

Two user-reported bugs, same root cause: the in-memory JobStore + the
'job_id must be the 12-char hex' tool contract.

Bug 1: 'Unknown job_id' reported frequently
  JobStore was a process-local dict (spark_executor/core/job_store.py).
  Under gunicorn workers > 1, a job created by confirm_submit_job
  landing on worker A was invisible to worker B, so a follow-up
  get_job_status / get_job_result / get_job_logs / kill_job landing on
  a different worker returned 'Unknown job_id'. Same multi-worker
  problem that bit the MCP session layer; only the affected data was
  different.

Bug 2: 'get_job_logs frequently confuses job_id and application_id'
  confirm_submit_job returns BOTH identifiers in SubmitResult, but
  get_job_logs (and friends) only accepted the local 12-char job_id
  and never said so in their description. When the agent passed the
  YARN application_id, the error message itself was misleading:
  'Unknown job_id: application_17400000001_0001' — the agent had
  passed an id, just the wrong kind.

This change fixes both at the root:

  * JobStore is now JSON-backed at data/jobs.json (atomic tempfile +
    os.replace), with cross-process safety via fcntl.flock on a sibling
    .lock file. Stage 3's SQLite migration is still planned; the file
    format is intentionally simple so it is a straight
    'for j in read_all(): db.insert(j)'.

  * New JobStore.get_either(uid) looks up by job_id first, then
    application_id. All four job-lifecycle tools (get_job_status,
    get_job_result, get_job_logs, kill_job) call get_either instead
    of get(job_id), so the agent can pass either identifier and get
    the same answer.

  * The 'neither matched' KeyError now spells out both id forms and
    what they look like, so the agent isn't left guessing.

  * server.py tool descriptions for the four job tools explicitly
    state 'job_id accepts BOTH identifiers' so this is visible to the
    LLM at tool-selection time, not only at error time.

Tests:
  * test_job_store.py: tmp_path isolation, persistence across
    instances, human-readable JSON, corrupt-file resilience,
    get_either (by job_id, by application_id, collision preference,
    unknown), put idempotency.
  * test_{logs,status,kill,result}_tool.py: per-test tmp_path fixture,
    'accepts application_id' regression for each tool, and an
    explicit assertion that the unknown-id error message mentions
    BOTH id forms. test_result_raises_keyerror_for_unknown_job's
    match pattern updated for the new message.

242 tests pass (was 226; +16 new). Zero regressions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Claude
2026-06-29 18:57:31 +08:00
co-authored by Claude Fable 5
parent 565f6a9c9d
commit 0fef77c0b8
12 changed files with 541 additions and 42 deletions
+107 -8
View File
@@ -1,14 +1,17 @@
# coding=utf-8
from datetime import datetime
from pathlib import Path
import pytest
from spark_executor.core.job_store import JobStore
from spark_executor.models import Job
def _job(jid: str) -> Job:
def _job(jid: str, app_id: str | None = None) -> Job:
return Job(
job_id=jid,
application_id=f"application_{jid}",
application_id=app_id or f"application_{jid}",
script_path="/tmp/j.py",
queue="default",
submit_time=datetime(2026, 6, 24),
@@ -16,20 +19,116 @@ def _job(jid: str) -> Job:
)
def test_put_then_get_roundtrip():
store = JobStore()
@pytest.fixture
def store(tmp_path: Path) -> JobStore:
"""Per-test file-backed JobStore rooted in tmp_path. No cross-test leakage."""
return JobStore(data_dir=str(tmp_path))
# --- Basic CRUD (was the entire file before the persistence fix) ---
def test_put_then_get_roundtrip(store):
store.put(_job("a"))
assert store.get("a") is not None
assert store.get("a").application_id == "application_a"
def test_get_missing_returns_none():
store = JobStore()
def test_get_missing_returns_none(store):
assert store.get("nope") is None
def test_list_returns_all_jobs():
store = JobStore()
def test_list_returns_all_jobs(store):
store.put(_job("a"))
store.put(_job("b"))
assert {j.job_id for j in store.list()} == {"a", "b"}
# --- Persistence: writes go to disk and survive a fresh instance ---
def test_data_persists_across_instances(tmp_path: Path):
"""The whole reason this used to be in-memory: gunicorn workers don't
share memory. A second JobStore pointed at the same data_dir MUST see
the records the first one wrote, otherwise we're back to the
"Unknown job_id" bug from the multi-worker setup."""
writer = JobStore(data_dir=str(tmp_path))
writer.put(_job("a1b2c3d4e5f6", app_id="application_17400000001_0001"))
reader = JobStore(data_dir=str(tmp_path))
assert reader.get("a1b2c3d4e5f6") is not None
assert reader.get("a1b2c3d4e5f6").application_id == "application_17400000001_0001"
def test_data_file_is_human_readable_json(tmp_path: Path):
"""If we're going to disk at all, the file should be inspectable
without the application running — saves an ops engineer a forensics
trip at 2am."""
import json
store = JobStore(data_dir=str(tmp_path))
store.put(_job("abc", app_id="application_1"))
raw = json.loads((tmp_path / "jobs.json").read_text(encoding="utf-8"))
assert "abc" in raw
assert raw["abc"]["application_id"] == "application_1"
assert raw["abc"]["connection"] == "prod"
def test_corrupt_file_does_not_crash(store, tmp_path):
"""A partial write (e.g. killed mid-dump, full disk) shouldn't take
the whole tool surface down — log it and treat as empty."""
(tmp_path / "jobs.json").write_text("{not valid json", encoding="utf-8")
# Should not raise; should return None / empty.
assert store.get("anything") is None
assert store.list() == []
# And we should still be able to write through it.
store.put(_job("x"))
assert store.get("x") is not None
# --- get_either: accept job_id OR application_id ---
def test_get_either_finds_by_job_id(store):
store.put(_job("a1b2c3d4e5f6", app_id="application_1"))
job = store.get_either("a1b2c3d4e5f6")
assert job is not None
assert job.application_id == "application_1"
def test_get_either_finds_by_application_id(store):
"""The fix for 'agent passed the wrong id and got Unknown job_id':
if the caller has a YARN application_id on hand, look it up by that."""
store.put(_job("a1b2c3d4e5f6", app_id="application_17400000001_0001"))
job = store.get_either("application_17400000001_0001")
assert job is not None
assert job.job_id == "a1b2c3d4e5f6"
def test_get_either_prefers_job_id_on_collision(store):
"""If a job_id and an application_id collide (unlikely but possible —
e.g. someone seeds both), the direct job_id lookup wins."""
store.put(_job("collide", app_id="not-collide"))
store.put(_job("other", app_id="collide"))
job = store.get_either("collide")
assert job is not None
assert job.job_id == "collide"
def test_get_either_returns_none_for_unknown(store):
assert store.get_either("nothing-here") is None
def test_get_by_application_id_is_distinct(store):
"""get_by_application_id should NOT match by job_id (it's the explicit
application_id-only lookup). get_either is the forgiving one."""
store.put(_job("a1b2c3d4e5f6", app_id="application_1"))
assert store.get_by_application_id("a1b2c3d4e5f6") is None
assert store.get_by_application_id("application_1") is not None
# --- put is idempotent (re-put same job_id replaces, not duplicates) ---
def test_put_replaces_existing_job(store):
"""confirm_submit_job may retry; the second put of the same job_id
must replace, not append, so list() doesn't grow on every retry."""
store.put(_job("a", app_id="application_1"))
store.put(_job("a", app_id="application_2")) # same job_id, new app_id
assert len(store.list()) == 1
assert store.get("a").application_id == "application_2"
+44
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from datetime import datetime
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -11,6 +12,17 @@ from spark_executor.tools import kill
from spark_executor.tools import connections
@pytest.fixture
def fresh_stores(tmp_path: Path):
"""Wire up connection + job stores rooted in tmp_path. Per-test isolation
so file-backed JobStore doesn't leak between cases."""
store = connection_store.ConnectionStore(data_dir=str(tmp_path))
connection_store.store = store
connections.store = store
kill.conn_store = store
kill.store = JobStore(data_dir=str(tmp_path))
def _fresh_stores():
store = connection_store.ConnectionStore()
connection_store.store = store
@@ -65,3 +77,35 @@ def test_kill_job_raises_when_connection_missing():
)
with pytest.raises(KeyError, match="Connection not found"):
kill.kill_job("abc")
# --- application_id accepted (regression: "agent passed wrong id" bug) ---
def test_kill_job_accepts_application_id(fresh_stores):
kill.conn_store.save(Connection(name="prod", master="yarn", yarn_rm_url="http://rm:8088"))
kill.store.put(
Job(
job_id="a1b2c3d4e5f6",
application_id="application_17400000001_0001",
script_path="/tmp/j.py",
queue="default",
submit_time=datetime(2026, 6, 24),
connection="prod",
yarn_rm_url="http://rm:8088",
)
)
with patch("spark_executor.tools.kill.kill_application") as m:
result = kill.kill_job("application_17400000001_0001")
# Underlying YARN call uses the application_id, not the local job_id.
assert m.call_args.args[0] == "application_17400000001_0001"
# And the response still surfaces BOTH ids so the agent can confirm.
assert result["job_id"] == "a1b2c3d4e5f6"
assert result["application_id"] == "application_17400000001_0001"
def test_kill_job_unknown_error_message_mentions_both_ids(fresh_stores):
with pytest.raises(KeyError) as ei:
kill.kill_job("totally-fake")
msg = str(ei.value)
assert "job_id" in msg
assert "application_id" in msg
+42 -7
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from datetime import datetime
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -11,16 +12,23 @@ from spark_executor.tools import logs
from spark_executor.tools import connections
def _fresh_stores():
@pytest.fixture
def fresh_stores(tmp_path: Path):
"""Wire up connection + job stores rooted in tmp_path. Per-test isolation
so file-backed JobStore doesn't leak between cases."""
store = connection_store.ConnectionStore(data_dir=str(tmp_path))
connection_store.store = store
connections.store = store
logs.conn_store = store
logs.store = JobStore(data_dir=str(tmp_path))
def _seed(job_id="abc", app_id="application_1"):
store = connection_store.ConnectionStore()
connection_store.store = store
connections.store = store
logs.conn_store = store
logs.store = JobStore()
def _seed(job_id="abc", app_id="application_1"):
_fresh_stores()
logs.conn_store.save(Connection(name="prod", master="yarn", yarn_rm_url="http://rm:8088"))
logs.store.put(
Job(
@@ -60,8 +68,7 @@ def test_get_job_logs_raises_for_unknown_job():
logs.get_job_logs("missing")
def test_get_job_logs_raises_when_connection_missing():
_fresh_stores()
def test_get_job_logs_raises_when_connection_missing(fresh_stores):
logs.store.put(
Job(
job_id="abc",
@@ -74,3 +81,31 @@ def test_get_job_logs_raises_when_connection_missing():
)
with pytest.raises(KeyError, match="Connection not found"):
logs.get_job_logs("abc")
# --- application_id accepted (regression: "agent passed wrong id" bug) ---
def test_get_job_logs_accepts_application_id():
"""The agent gets both job_id and application_id back from
confirm_submit_job and routinely passes the wrong one. The tool must
accept EITHER and return the same logs."""
_seed(job_id="a1b2c3d4e5f6", app_id="application_17400000001_0001")
with patch(
"spark_executor.tools.logs.get_application_logs",
return_value="logs here",
) as m:
out = logs.get_job_logs("application_17400000001_0001")
assert out == "logs here"
# And the underlying YARN call used the YARN ID, not the local job_id.
assert m.call_args.args[0] == "application_17400000001_0001"
def test_get_job_logs_unknown_error_message_mentions_both_ids():
"""The "neither matched" error should explicitly call out BOTH
accepted id forms so the agent doesn't guess."""
_seed()
with pytest.raises(KeyError) as ei:
logs.get_job_logs("totally-fake")
msg = str(ei.value)
assert "job_id" in msg
assert "application_id" in msg
+52 -1
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from datetime import datetime
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -11,6 +12,17 @@ from spark_executor.tools import result
from spark_executor.tools import connections
@pytest.fixture
def fresh_stores(tmp_path: Path):
"""Wire up connection + job stores rooted in tmp_path. Per-test isolation
so file-backed JobStore doesn't leak between cases."""
store = connection_store.ConnectionStore(data_dir=str(tmp_path))
connection_store.store = store
connections.store = store
result.conn_store = store
result.store = JobStore(data_dir=str(tmp_path))
def _fresh_stores():
store = connection_store.ConnectionStore()
connection_store.store = store
@@ -114,8 +126,14 @@ def test_result_handles_missing_optional_fields():
def test_result_raises_keyerror_for_unknown_job():
_fresh_stores()
with pytest.raises(KeyError, match="Unknown job_id"):
with pytest.raises(KeyError) as ei:
result.get_job_result("missing")
# New error message must still flag "Unknown" so callers / agents can
# recognize the failure, AND mention application_id so the agent
# knows the other form is also accepted.
msg = str(ei.value)
assert "job_id" in msg
assert "application_id" in msg
def test_result_raises_when_connection_missing():
@@ -132,3 +150,36 @@ def test_result_raises_when_connection_missing():
)
with pytest.raises(KeyError, match="Connection not found"):
result.get_job_result("abc")
# --- application_id accepted (regression: "agent passed wrong id" bug) ---
def test_get_job_result_accepts_application_id(fresh_stores):
result.conn_store.save(Connection(name="prod", master="yarn", yarn_rm_url="http://rm:8088"))
result.store.put(
Job(
job_id="a1b2c3d4e5f6",
application_id="application_17400000001_0001",
script_path="/tmp/j.py",
queue="default",
submit_time=datetime(2026, 6, 24),
connection="prod",
yarn_rm_url="http://rm:8088",
)
)
raw = {
"app": {
"id": "application_17400000001_0001",
"state": "SUCCEEDED",
"finalStatus": "SUCCEEDED",
}
}
import json
with patch(
"spark_executor.tools.result.get_application_status",
return_value=("FINISHED", json.dumps(raw)),
) as m:
out = result.get_job_result("application_17400000001_0001")
assert out.application_id == "application_17400000001_0001"
assert out.state == "FINISHED"
assert m.call_args.args[0] == "application_17400000001_0001"
+44
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from datetime import datetime
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -11,6 +12,17 @@ from spark_executor.tools import connections, status
from spark_executor.core.yarn_client import YarnClientConfig
@pytest.fixture
def fresh_stores(tmp_path: Path):
"""Wire up connection + job stores rooted in tmp_path. Per-test isolation
so file-backed JobStore doesn't leak between cases."""
store = connection_store.ConnectionStore(data_dir=str(tmp_path))
connection_store.store = store
connections.store = store
status.conn_store = store
status.store = JobStore(data_dir=str(tmp_path))
def _fresh_stores():
"""Reset job store and connection store singletons for a single test."""
store = connection_store.ConnectionStore()
@@ -103,3 +115,35 @@ def test_get_job_status_passes_auth_config():
assert isinstance(args[1], YarnClientConfig)
assert args[1].auth_type == "basic"
assert args[1].auth_user == "hdfs"
# --- application_id accepted (regression: "agent passed wrong id" bug) ---
def test_get_job_status_accepts_application_id(fresh_stores):
status.conn_store.save(Connection(name="prod", master="yarn", yarn_rm_url="http://rm:8088"))
status.store.put(
Job(
job_id="a1b2c3d4e5f6",
application_id="application_17400000001_0001",
script_path="/tmp/j.py",
queue="default",
submit_time=datetime(2026, 6, 24),
connection="prod",
yarn_rm_url="http://rm:8088",
)
)
with patch(
"spark_executor.tools.status.get_application_status",
return_value=("RUNNING", "{}"),
):
out = status.get_job_status("application_17400000001_0001")
assert out.state == "RUNNING"
assert out.application_id == "application_17400000001_0001"
def test_get_job_status_unknown_error_message_mentions_both_ids(fresh_stores):
with pytest.raises(KeyError) as ei:
status.get_job_status("totally-fake")
msg = str(ei.value)
assert "job_id" in msg
assert "application_id" in msg