Skip to content

feat(action-items): add a read-only action-item contract and local store - #748

Open
BeiMu-new wants to merge 1 commit into
agentscope-ai:mainfrom
BeiMu-new:feat/action-items
Open

BeiMu-new wants to merge 1 commit into
agentscope-ai:mainfrom
BeiMu-new:feat/action-items

Conversation

@BeiMu-new

@BeiMu-new BeiMu-new commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Adds the minimal read-only contract for action items, as agreed in #744:

  • ActionItemState: unresolved, blocked, completed, uncertain, cancelled.
  • ActionItem: stable id, source note, short description, state,
    evidence entries (path, locator, excerpt, observed time, optional source),
    aliases, and first_seen / last_updated.
  • LocalActionItemStore: one JSONL file per named store under the workspace
    metadata directory, reloaded on start; the in-memory map is only an index that
    can always be rebuilt from the file.
  • query: read-only filter by states, updated_since and limit.
    It never triggers extraction, model calls or writes.

Contract details

  • Evidence-based states. Any state other than uncertain requires at least
    one evidence entry. Missing frontmatter or a successful AutoDream run cannot
    establish a state, and unknown material stays uncertain — a missing field
    can therefore never turn into a reminder.
  • Stable identity. id = sha1(note + normalized text)[:16], so later
    evidence refers to the same record across restarts and index rebuilds, and
    whitespace/case differences do not create duplicates. When the description of
    an existing item is reworded, the stored id is kept and the new id goes into
    aliases; lookup checks id, then the alias index, then the incoming
    aliases, so a reworded item updates the record instead of forking a second one.
  • Aliases reconcile existing records. When an incoming alias links two
    records that are already stored, they are merged into the one with the earlier
    first_seen, and the later id joins its aliases; the alias can therefore not
    leave two inconsistent records behind.
  • Update rule. Later evidence updates the state; evidence observed earlier
    but processed later keeps the newer resolution and only extends the evidence
    list. Ordering is decided by the newest evidence observed_at rather than
    last_updated, so rewording a description cannot reopen a resolved item.
    Repeated evidence is dropped by (path, locator, observed_at, excerpt) and the
    list stays in observation order.
  • Write before publish. upsert() merges into a staged copy of the index,
    writes that copy, and only after the atomic replace succeeds swaps it into
    memory. A failed write leaves the stored state untouched and removes the
    staging file, so a caller is never told a write failed while a later query
    reports the new state.
  • Detached records. get(), query() and upsert() copy at the boundary,
    including nested evidence and alias collections, so a caller cannot mutate
    store state without going through upsert().
  • Forward-compatible records. Unknown fields on a record and on its evidence
    entries survive a read/write cycle (extra="allow" plus model_dump), so
    starting and closing a store cannot silently drop fields written by a newer
    version.
  • Timezone-aware timestamps. first_seen, last_updated, evidence
    observed_at and updated_since are AwareDatetime: a naive datetime fails
    validation with a clear message instead of raising TypeError inside a
    comparison.
  • Contained file name. file_name must be a bare name: ./.., path
    separators, drive colons and surrounding whitespace are rejected at
    construction, and the resolved parent directory must stay inside the metadata
    root before the atomic replace, so a configured name cannot escape the
    workspace. Stores with different names no longer share a default file.
  • File-native. Records live in
    <workspace>/<metadata_dir>/action_item_store/<name>/action_items.jsonl. On
    read, a line this version cannot parse (bad JSON, unknown state, missing
    field) is skipped with a warning; on write, such a line is appended back
    exactly as it was read, so a file produced by a newer version is never
    truncated and the preserved line is not duplicated on repeated writes. A file
    that exists but cannot be decoded is never overwritten: upsert() refuses to
    write and reads raise, while start() still completes.
  • Query returns everything by default. limit is None unless the caller
    sets it; the store does not cap the result set silently.

Scope

Deliberately limited to the schema, persistence and query contract suggested in
the review. Item extraction from daily notes and the host-side reminder live in
follow-up changes; no existing note needs migration and no new required
frontmatter is introduced.

Test scope

  • Target: tests/unit/test_action_item_store.py — 30 passed
    (roundtrip and query, restart survival, later-evidence resolution,
    stale-evidence guard, evidence-order guard against a reworded record,
    duplicate evidence merge, state-needs-evidence, uncertain-without-evidence,
    naive datetime rejection, path normalization, query filters, unlimited query,
    reworded item merged by alias, alias linking two stored records, failed write
    leaves memory unchanged, detached query results, unknown fields kept through a
    round trip, path-like file_name rejected, corrupt line skipped on read,
    unreadable lines preserved verbatim, legacy record without timezone preserved,
    undecodable file never overwritten, empty workspace, id stability,
    construction touches no files, JSONL shape, no temporary file left behind).
  • Reverting only the source changes while keeping these tests: 9 failed,
    21 passed.
  • Adjacent: tests/unit/test_file_catalog.py and
    tests/unit/test_component_registry.py — 43 passed together with the target
    file.
  • Lint: pre-commit run --files <changed> — 11 hooks passed
    (ast, private key, whitespace, trailing comma, black, flake8, pylint, pyroma).

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

For the record on the four red Unit Tests jobs: they are red on main too, with the same three failures, and none of them touch this change.

Failures:

  • plugins/home/tests/test_candidate_gate.py::test_real_gate_sandbox_denies_evidence_live_code_writes_and_network
  • plugins/home/tests/test_construction_equivalence.py::test_real_equivalence_sandbox_allows_only_copied_construction_and_source
  • plugins/home/tests/test_workflows.py::test_workflow_sandbox_enforces_read_write_and_git_boundaries

All three report Failed: DID NOT RAISE OSError. The runner executes as root, so the read-only file permissions those sandbox tests rely on do not deny writes.

Baseline (main @ b13034ba, run 43358116256): 3 failed, 4552 passed, 52 skipped.
This PR (fbcbf949): 3 failed, 4563 passed, 52 skipped — the extra 11 are the new tests added here.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

Force-pushed c17487b (single commit on b13034b, +1018 -0, same 8 files) after re-reading the store against the contract. Each item below is a behaviour fix, not a refactor:

  • Identity survives rewording. id is still sha1(note + first description)[:16], but a later description now updates the record instead of minting a second one: the stored id is kept, the new id goes into aliases, and lookup checks id, then the alias index, then the incoming aliases. Previously a rephrased action item became a duplicate, which defeats "evidence observed earlier but processed later still refers to the same record".
  • Unreadable lines are preserved. Bad JSON, an unknown state or a missing field no longer gets deleted on the next upsert(): those lines are kept aside and appended verbatim after the readable records, so a file written by a newer version cannot lose data, and it does not accumulate copies on repeated writes.
  • Timezone-aware timestamps. first_seen, last_updated, evidence observed_at and updated_since use AwareDatetime, so a naive datetime fails validation with a clear message instead of raising TypeError inside a comparison.
  • A file that cannot be decoded is never overwritten. If the file exists but cannot be decoded, reads raise and upsert() refuses to write, rather than replacing the contents with an empty store; start() still completes.
  • query() returns every match unless limit is given. The previous default silently capped at 100.
  • Evidence is deduplicated by (path, locator, observed_at, excerpt) and kept in observation order, so re-reporting the same fact does not grow the list.
  • Minor: the JSONL test now asserts real properties (one JSON object per line, \n terminated, no BOM, sorted by id), the temporary file is asserted to be gone, and the directory is created on write instead of in the constructor.

Test scope in the description predates this: tests/unit/test_action_item_store.py is now 21 passed, and 43 passed together with test_file_catalog.py and test_component_registry.py; pre-commit run --files passes all 11 hooks.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for implementing the first schema/store layer. Keeping extraction and QwenPaw delivery in follow-up PRs matches the scope agreed in #744.

I reviewed c17487b and reproduced seven edge cases affecting state ordering, persistence, identity merging, workspace containment, and the read-only boundary. Please address the inline comments before merging and add focused regression coverage for these cases.

Validation:

  • test_action_item_store.py, test_file_catalog.py, and test_component_registry.py: 43 passed.
  • Seven independent edge-case checks reproduced the issues below, including on Python 3.12 with Pydantic 2.14.3.
  • git diff --check passed. I did not run the full test suite or pre-commit locally.
  • I also compared the CI logs with baseline run 43358116256: the three failing plugins/home sandbox tests are present on the baseline as well, so those failures are separate from this review.

Comment thread reme/schema/action_item.py Outdated
"""
evidence = merge_evidence(existing.evidence, incoming.evidence)
aliases = merge_aliases(existing, incoming)
if incoming.last_updated < existing.last_updated:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Order state transitions by their evidence time

This compares record-editing time (last_updated) rather than the supporting evidence's observed_at. A completed item supported by Nov 6 evidence can be reopened by an incoming unresolved observation supported only by Nov 1 evidence if its description was reworded on Nov 11 and last_updated reflects that edit. I reproduced exactly that case using the original ID in aliases: the stored state becomes unresolved even though the merged evidence still contains the newer completion.

Please track the timestamp supporting the state separately from description/record edits, or otherwise enforce the evidence ordering contract. The current stale-evidence test sets last_updated == observed_at, which hides this failure.

Comment on lines +33 to +36
def __init__(self, file_name: str = "action_items.jsonl", **kwargs):
super().__init__(**kwargs)
self.file_name = file_name
self._file = self.component_metadata_path / file_name

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Prevent independently named stores from overwriting each other's records

component_metadata_path is scoped by component type, not component name, so LocalActionItemStore(name="work") and LocalActionItemStore(name="personal") use the same default file. Each instance has an independent snapshot and _io_lock. Starting both, writing A through the first, then B through the second leaves only B on disk; a later close can overwrite it again with the other snapshot.

Please isolate the default file by component name, or explicitly enforce a single writer/shared store with conflict detection. Atomic replacement prevents a partial file but does not prevent this lost update.

Comment on lines +124 to +125
if incoming.id in self._items:
return incoming.id

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Handle aliases that connect two existing canonical records

Returning immediately for a direct ID match bypasses incoming aliases that identify another existing item. Repro: insert unresolved A and unresolved B separately, then upsert completed B with aliases=[A.id]. The query still returns unresolved A and completed B, and the alias index skips A because A is already a primary key. A consumer will continue reminding about the supposedly resolved work.

Please reconcile all records reached by the ID and aliases into one canonical identity, or explicitly reject the collision instead of silently retaining two inconsistent records. The existing alias test covers only an incoming ID that is not already stored.

Comment on lines +168 to +172
self._items[merged.id] = merged
self._index_aliases(merged)
stored.append(merged)
if stored:
self._write()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Publish the in-memory update only after persistence succeeds

The item map and alias index are modified before _write(). I patched os.replace to raise OSError during an unresolved-to-completed update: upsert() raises, but subsequent queries report completed while the JSONL file still says unresolved. Restarting changes the visible state back, and a later successful close can instead persist an update whose caller was told it failed.

Please stage the item/alias changes and commit them only after the atomic replacement succeeds, or roll them back on failure. Add failure-path coverage and clean up the staging file on errors.

filter_ = query or ActionItemQuery()
async with self._io_lock:
self._fail_if_broken()
matched = [item for item in self._items.values() if filter_.matches(item)]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Return detached records instead of mutable store-owned objects

query() and get() return the actual ActionItem objects in _items; inserting a new item also retains the caller's object. A consumer can therefore mutate a query result without upsert(), locking, timestamp updates, or validation. I set a returned item's state to completed and cleared its evidence, then closed and restarted the store: close persisted that invalid combination, and load skipped the item on restart.

Please isolate both incoming records and returned results with deep copies or a genuinely immutable representation, including nested evidence/alias collections.

if not text:
continue
try:
item = ActionItem.model_validate(json.loads(text))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve unknown fields in otherwise readable records

Unreadable-line preservation does not cover forward-compatible records with additional optional fields. Both ActionItem and ActionItemEvidence use Pydantic's default extra-field handling, so those fields are silently discarded by this successful parse. Because close always dumps, simply starting, querying, and closing an older store removes the newer fields from the durable file even without an upsert. I reproduced this with an extra item field and an extra evidence provenance field.

Please retain unknown fields/raw payloads through serialization, or reject and preserve unsupported records rather than accepting a lossy parse. Add a round-trip test for known-state records containing unknown fields at both levels.

def __init__(self, file_name: str = "action_items.jsonl", **kwargs):
super().__init__(**kwargs)
self.file_name = file_name
self._file = self.component_metadata_path / file_name

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the configured persistence file inside the workspace

file_name is joined directly onto the metadata directory. An absolute value discards that prefix, and parent traversal can also escape it. I reproduced upsert() creating a JSONL file outside the configured workspace by supplying an absolute file_name. Existing outside files can also be read and rewritten through this path.

Please validate this as a file name (or explicitly supported relative path) and ensure the resolved destination stays within the workspace, including symlinked parents. Add absolute-path and traversal regression cases.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Thanks for the careful review and for reproducing all seven cases — they are addressed in b4404ac. Each fix below is paired with the regression that would fail without it.

[P1] Order state transitions by their evidence time

You are right that comparing last_updated mixes record edits with observation time. I added state_basis(item): it takes max(observed_at) over the item's evidence and falls back to last_updated only when the item carries no evidence. apply_update() now compares that basis instead of last_updated, so a newer completion can no longer be reopened by an older unresolved observation, while a reworded description is still merged without moving the state.

test_older_evidence_does_not_reopen_completed_item builds your exact case — completed with Nov 6 evidence, incoming unresolved with Nov 1 evidence and a later last_updated — and asserts the state stays completed, the description keeps the resolution wording, and last_updated becomes the max of both sides.

[P1] Prevent independently named stores from overwriting each other's records

_file is now component_metadata_path / self.name / file_name, so work and personal no longer share a default file. test_named_stores_do_not_share_a_file starts two differently named stores, writes through each, re-loads both, and asserts each sees only its own row.

Same-name instances still share a file, which follows from scoping by name: one name denotes one logical store, consistent with how the rest of component metadata is keyed.

[P2] Handle aliases that connect two existing canonical records

_related_keys() now collects the incoming ID plus every stored record reachable through the incoming aliases, and _absorb() merges them into the record with the earliest first_seen, demoting the other IDs to aliases. Your repro (unresolved A and unresolved B stored separately, then completed B upserted with aliases=[A.id]) now yields one row: id of the earliest record, state completed, the later ID in aliases, and both IDs resolvable through get().

Covered by test_alias_link_reconciles_two_stored_records, which also asserts the late ID is no longer a primary key.

[P2] Publish the in-memory update only after persistence succeeds

upsert() now merges into a staged copy of the item map, writes that copy, and only after the atomic replace succeeds swaps it into self._items and rebuilds the alias index. On failure the staging file is removed and the in-memory state is untouched.

test_failed_write_leaves_memory_unchanged patches the atomic replace to raise during an unresolved-to-completed update and asserts the subsequent get() still reports the stored state, the JSONL still says unresolved, and no .tmp file remains.

[P2] Return detached records instead of mutable store-owned objects

get(), query() and upsert() deep-copy at the boundary, and upsert() deep-copies the incoming record before merging, so callers hold no reference to store state. test_query_returns_detached_records mutates a returned item (state and evidence) and asserts the next query is unaffected and the reopened store still loads the item.

[P2] Preserve unknown fields in otherwise readable records

Both ActionItem and ActionItemEvidence now use model_config = ConfigDict(extra="allow"); as_record() serialises through model_dump so extras are written back out, and apply_update() merges the two extra bags instead of picking one side.

test_unknown_fields_survive_a_round_trip stores an item carrying an extra item-level field and an extra evidence-level field, closes, and re-opens — the assertion is on the rewritten JSONL content, not on the in-memory object.

[P2] Keep the configured persistence file inside the workspace

file_name is validated at construction: empty strings, ., .., and anything with leading or trailing whitespace or containing /, \\ or : is rejected. Immediately before the atomic replace, _guard_destination() resolves the parent directory and requires it to remain inside the metadata root, so a symlinked parent cannot escape either.

test_store_rejects_path_like_file_name covers a parent-traversal name, a nested relative path, and an absolute path.

Test scope

  • Target: tests/unit/test_action_item_store.py — 30 passed (23 existing + 7 new; the path case is parametrised, so 9 regression assertions in total).
  • Reverting only the source changes while keeping the new tests: 9 failed, 21 passed. Restoring them: 30 passed.
  • Neighbour: the same run also covers test_file_catalog.py and test_component_registry.py — 43 passed together.
  • pre-commit with the repository-pinned hook versions: 11 hooks passed (black rewrote one file on the first pass, re-ran after staging).
  • Full suite: not run locally; CI remains the reference, and I agree with your read that the three plugins/home sandbox failures match baseline 43358116256.

Also covered: reme/components/action_item_store/ is introduced by this PR (git log -- reme/components/action_item_store/ shows only this commit), so the name-scoped directory from the second point cannot orphan any pre-existing file.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I checked b4404ac: all seven reproduction cases from the previous review now pass. The targeted repository tests (52) plus those seven independent checks give 59 passing checks, and git diff --check passes.

There are still four findings below, reproduced by five additional boundary checks: a staging-file symlink can overwrite a file outside the workspace; closing a stale same-name instance can erase another instance's records; destination checks do not cover the component name and an escaped component root; and deduplication drops newly supplied evidence extension fields. Please address these before merging, with regression coverage.

The schema/store-only scope remains appropriate; extraction and QwenPaw integration can stay in follow-up PRs. I did not run the full suite or pre-commit locally. The current Python 3.11 CI log still shows the same three plugins/home sandbox failures as the baseline, separate from these findings.

Comment on lines +185 to +187
temporary = destination.with_name(f"{destination.name}.tmp")
try:
with temporary.open("w", encoding="utf-8", newline="\n") as handle:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Create the staging file exclusively instead of following an existing symlink

The parent-directory guard does not protect the fixed staging path. With an otherwise normal workspace/name/file_name, pre-create action_items.jsonl.tmp as a symlink to a file outside the workspace, then call upsert(). temporary.open("w") follows that link and truncates/rewrites the outside file before os.replace() runs. I reproduced an outside file containing user-owned content being replaced with the serialized action item; the rename also moves the symlink to the destination name.

Please use a uniquely named, exclusively created staging file in the validated directory (for example, an appropriate mkstemp/file-descriptor based flow), and never follow an existing staging-file link. Add a regression asserting the outside file remains unchanged.

Comment on lines +37 to +39
async def _close(self) -> None:
if self.is_started:
await self.dump()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Prevent stale same-name instances from overwriting the durable record

Name scoping fixes differently named stores, but same-name instances still have independent snapshots and locks with no ownership/conflict check. This also affects an instance that only reads: writer stores A; reader starts and queries A; writer adds B; reader closes. This unconditional dump rewrites its stale snapshot and silently removes B. I reproduced the reopened file containing only A. Calling both instances one logical store does not serialize their access.

If one live instance per physical store is the supported contract, enforce that ownership and reject the second start. Otherwise updates need shared/inter-process coordination plus a fresh snapshot or version-conflict check before replacement. Avoid rewriting an unchanged reader snapshot on close as well. Merely atomically replacing the file does not prevent lost updates.

Comment on lines +200 to +205
def _guard_destination(self, destination: Path) -> None:
"""Refuse a destination that resolves outside the metadata directory."""
base = self.component_metadata_path.resolve()
parent = destination.parent.resolve()
if parent != base and base not in parent.parents:
raise ValueError(f"refusing to write outside the metadata directory: {destination}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Anchor containment to the workspace and validate before reads or mkdir

Two bypasses remain despite rejecting path-like file_name values:

  1. _file also incorporates self.name, which is not validated. An absolute component name selects an outside directory, and load() opens that outside JSONL without calling this guard. I reproduced start() followed by query() returning an outside record. The write path also calls mkdir before checking containment.
  2. If workspace/metadata/action_item_store itself is a symlink to an outside directory, base = self.component_metadata_path.resolve() trusts that outside directory as the root. The check passes and upsert() successfully creates the JSONL outside the workspace; I reproduced this with the ordinary name work.

Please validate/encode the component-name path segment and establish containment against a trusted workspace root. Run the checks before any file read or directory creation, including validation of the resolved component metadata root.

Comment thread reme/schema/action_item.py Outdated
Comment on lines +180 to +182
key = (evidence.path, evidence.locator, evidence.observed_at, evidence.excerpt)
if key in seen:
continue

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve added extension fields when deduplicating an existing observation

extra="allow" now protects unknown fields through load/dump, but this duplicate branch silently discards fields newly supplied through upsert(). Repro: store an observation without extras, then upsert the same (path, locator, observed_at, excerpt) carrying an additional source_event_id="event-123". The stored evidence and rewritten JSONL never contain that field because the incoming observation is skipped entirely. I reproduced this on the new head.

Please reconcile metadata for matching observations rather than dropping the incoming entry wholesale. At least retain nonconflicting extension fields while keeping a single evidence entry, and define/test how conflicting metadata is handled.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Thanks for the second pass — all four findings are addressed in a96f508, and each one now has a regression that fails on b4404ac.

[P1] The staging file is created exclusively

Replaced the fixed <name>.tmp path with tempfile.mkstemp(dir=<validated parent>, prefix=".<name>.", suffix=".tmp"), so the staging file is a fresh, uniquely named, exclusively created file. An existing link at a predictable staging name is never opened, so it cannot become the write target, and os.replace now moves a regular file into place instead of moving the link.

test_staging_symlink_cannot_redirect_the_write pre-creates action_items.jsonl.tmp as a symlink to a file outside the workspace, runs upsert(), and asserts the outside file still reads user-owned content while the destination is a regular file, not a symlink.

[P1] Stale same-name instances can no longer erase records

Two separate mechanisms, because the read-only case and the write case fail differently:

  • Unchanged snapshots are not rewritten on close. dump() now returns early when the file already exists and no write is pending (upsert() writes through). A reader that only loaded the file no longer replaces newer records on close.
  • A stale write is refused instead of applied. load() records the file's SHA-256; _write() recomputes it and raises RuntimeError if the file changed since that load. A stale instance that tries to write fails loudly rather than silently dropping the other instance's rows.

test_reader_close_does_not_erase_newer_records reproduces your sequence exactly: writer stores A, reader loads A, writer adds B, reader closes; reopening shows both A and B. test_writer_refuses_to_overwrite_a_file_changed_since_load covers the write path and asserts the file still holds both rows after the refusal.

One boundary worth stating: a store whose file does not exist yet still writes an empty file on close. That is the previous behaviour and it cannot overwrite anything, so I kept it.

[P2] Containment is anchored to the workspace and checked before I/O

  • self.name is now validated as a single path segment (/, \, : and ./.. rejected), the same rule already applied to file_name, so an absolute or relative component name cannot select another directory.
  • The trusted root is workspace_path.resolve(). component_metadata_path is resolved and required to sit inside it, so a metadata tree redirected by a symlink is rejected rather than treated as the root.
  • Both checks run in _file and _guard_destination before any open or mkdir, so reads are covered too — previously only the write path called the guard, and it ran after mkdir.

Coverage: test_component_name_must_be_a_single_path_segment (four names) and test_symlinked_metadata_root_is_rejected (redirected metadata root, also asserts nothing was created outside).

[P2] Deduplicated evidence keeps newly supplied extension fields

merge_evidence() no longer skips the incoming row wholesale. Matching observations are folded into the stored row: the identity fields (path, locator, observed_at, excerpt, source) stay as stored, extension fields are merged, and an incoming value wins a name conflict. test_duplicate_evidence_keeps_new_extension_fields stores an observation without extras, upserts the same identity carrying source_event_id="event-123" and owner="release-team", and asserts both survive in memory and in the rewritten JSONL.

Validation

  • tests/unit/test_action_item_store.py: 39 passed (30 before + 9 new).
  • With test_file_catalog.py and test_component_registry.py: 61 passed.
  • Reverting only the source changes makes all 9 new tests fail; restoring them makes them pass.
  • pre-commit run --files with the repository config: all 12 hooks passed (black reformatted one test file on the first run, second run clean).
  • I did not run the full suite; the three plugins/home sandbox failures you compared against 43358116256 are unrelated to this change and still present on main.

Scope is unchanged: schema/store only, extraction and QwenPaw delivery remain follow-ups.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

Replaced the head with a86db9c (still a single commit, no new commit added).

The only change against the previous push is dropping a dead _dirty flag I had introduced: nothing ever set it to True, so it was carrying no information and the guard is now simply if self._file.exists(): return. No behavioural change — 61 tests still pass and pre-commit is clean.

Sorry for the extra force-push; I spotted it while reviewing my own diff and preferred to remove it rather than leave a misleading field in the store.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Rebased onto the current main after the last review, so the PR is mergeable again.

The rebase met three conflicts, all of them registry appends in the same spot:

  • reme/components/__init__.py
  • reme/enumeration/component_enum.py
  • reme/schema/__init__.py

Upstream renamed CodexAppServer to BaseCodexAppServer / SdkCodexAppServer, replaced PaRuntime with agent_runtime, and added anthropic_relay, asr, agent_inbox and tts. Both sides are kept: those new exports plus the action_item_store / ActionItem additions.

Still a single commit (11613480, 8 files). tests/unit/test_action_item_store.py: 39 passed. Every name in reme.components.__all__ (38) and reme.schema.__all__ (95) resolves, and ComponentEnum.ACTION_ITEM_STORE is present.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update and the rebase. I checked 11613480: all 12 independent reproduction scenarios from the previous two reviews now pass. The targeted repository tests plus those scenarios give 74 passing checks. The rebased component/schema exports (38/95), local store registration, and git diff --check also pass.

Two areas still need attention before merging: the file fingerprint check is not atomic with reading/replacing the snapshot, and reads can still follow a symlink in a named store directory or the JSONL file outside the workspace. I reproduced these with four additional controlled scenarios, detailed inline. The current CI Python 3.11–3.14 tests and pre-commit checks are green; I did not run the full suite or pre-commit locally.

For planning, please also see #766 — ReMe 0.5 Proactive Runtime preview. We are moving toward 0.5, and many existing features and workflows will be replaced or implemented differently. The preview describes Work taking over Auto Memory's role, Auto Dream becoming three scheduled agents, and planned Todo/Daily Summary workflows.

Please keep that direction in mind for the follow-up extraction and QwenPaw integration work. The evidence-backed action-item use case remains relevant, while its producer, lifecycle owner, and query/integration points may fit differently in the new runtime. Keeping this PR focused on the schema/store contract is appropriate; we should align the follow-up design with 0.5 as those interfaces settle.

return False
destination = self._file
self._guard_destination(destination)
self._assert_unchanged(destination)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Make snapshot validation and replacement one coordinated operation

The SHA-256 check catches a write that finished before _assert_unchanged(), but it does not prevent a change between this check and os.replace(). I synchronized two independent writers immediately after the check (at staging-file creation): both started from A, one added B and the other C, both upsert() calls returned successfully, and the durable file contained only A and C. The per-instance asyncio locks do not coordinate these writers.

There is also a snapshot/stamp mismatch during load(): the JSONL is parsed first, then line 143 opens the path again to calculate its fingerprint. Replacing A with A+B between those reads gives this instance the A snapshot with the A+B fingerprint. A subsequent upsert of C passes the guard and persists A+C, dropping B; I reproduced that interleaving as well.

Please coordinate access by physical store file across instances/processes (or enforce exclusive writer ownership), and keep fingerprint validation plus replacement inside the protected operation. Compute a loaded snapshot's fingerprint from the exact bytes that were parsed, rather than re-opening the pathname for a potentially different version. Both controlled interleavings need regression coverage.

loaded: dict[str, ActionItem] = {}
unreadable: list[str] = []
try:
with self._file.open("r", encoding="utf-8") as handle:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate the fully resolved read target, including the named directory and final file

_metadata_root now rejects an escaped metadata root, but _file appends the validated name/file_name without checking where those entries resolve. load() then opens that path without _guard_destination(), and that guard checks only the parent anyway.

With a normal metadata root and name="work", I reproduced both:

  • metadata/action_item_store/work symlinked to an outside directory containing a valid action_items.jsonl;
  • a regular work directory whose action_items.jsonl is a symlink to an outside file.

In each case, start() succeeds and query() returns the outside records. Please verify containment of the complete read target against the workspace before opening it, covering both directory and final-file links, and reject any resolution that escapes the workspace. Add these two cases alongside the existing metadata-root symlink test.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Both are addressed in 05ea6534.

1. Snapshot validation and replacement are one coordinated operation.
Writers now take a sidecar lock on the store file — flock on POSIX, a byte-range lock on Windows — and the fingerprint check runs inside it, immediately before os.replace(). The check therefore cannot finish while another writer's replace is pending; the loser now fails with RuntimeError instead of committing a snapshot that drops the other's records. load() also reads the file once and derives the digest from exactly those bytes, so a snapshot can no longer be paired with the fingerprint of a newer version.

2. The fully resolved read target is validated, directory and file alike.
_read_target() resolves the complete path — named directory and JSONL file — and refuses anything outside the workspace, and load() opens that resolved path. _guard_destination() still requires the parent inside the metadata directory and now also resolves the final component, so a regular directory holding a linked action_items.jsonl is caught as well.

Verification: tests/unit/test_action_item_store.py 44 passed (5 new). The two interleavings have regression coverage: a second writer over the same file must fail rather than drop records, a file rewritten after load must not be overwritten, and the ordering of lock-enter → check → replace → lock-exit is pinned so the window cannot reopen silently. Two symlink cases cover a linked store directory and a linked store file.

Falsification: taking the check outside the lock and reading the unresolved path each turn exactly one new case red.

On #766: understood — I will keep this PR to the schema/store contract and align the follow-up producer, lifecycle owner and query points with the 0.5 runtime once those interfaces settle.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked 05ea6534. The previous concurrency and read-target findings now pass independent verification: competing writers no longer both commit stale snapshots, the parsed snapshot keeps the digest of its own bytes, and both outside-directory and outside-file read links are rejected.

Two new findings remain below: valid Unicode text is split into malformed JSONL fragments on reload, and a symlink at the new lock sidecar path can still cause a file to be created outside the workspace. Please address these before merging and add focused regressions.

Validation on macOS / Python 3.12 / Pydantic 2.14.3:

  • test_action_item_store.py, test_file_catalog.py, and test_component_registry.py: 67 passed.
  • Eight additional independent checks: four passed for the previous findings; four reproduced the new findings (three Unicode separators and one lock-sidecar link).
  • git diff --check passed. Current CI is green.
  • I did not run the full suite, local pre-commit, or the Windows locking branch.

"is repaired or removed, so its contents are never overwritten.",
)
return
for number, line in enumerate(text.splitlines(), start=1):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Split JSONL on LF rather than every Unicode line separator

str.splitlines() treats U+0085, U+2028 and U+2029 as line boundaries, including when they occur inside a JSON string. _write() uses ensure_ascii=False, so an item with description="Submit\u2028expenses" is written as one valid JSONL line containing the literal character. Reload then splits that record in the middle of the string, logs both fragments as malformed, and returns no item.

I reproduced the round trip with all three characters: the file contains exactly one LF-terminated record and json.loads(raw) reads the original description correctly, but start() followed by query() loses the record from the result. The same parsing issue applies to other text fields such as evidence excerpts.

Please split only on the JSONL LF delimiter (for example text.split("\n") or the corresponding byte split), keeping valid Unicode characters inside each JSON string intact. Add round-trip tests for these characters.

the handle closes, so a crashed holder cannot wedge the store.
"""
lock_path.parent.mkdir(parents=True, exist_ok=True)
handle = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o600)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Apply containment and no-follow protection to the lock sidecar itself

The JSONL target is validated, but this O_CREAT | O_RDWR open follows a pre-existing symlink at the sidecar path. Repro: seed an ordinary store, replace .action_items.jsonl.lock with a symlink to a nonexistent file outside the workspace, then start another instance over the valid JSONL. On POSIX, start() succeeds and creates the empty outside file while opening the lock. I reproduced this without changing the store name, metadata root, or JSONL target.

Please validate the sidecar path as well and use a race-safe open that does not follow an existing lock-file symlink, checking that an existing sidecar is an acceptable regular lock file. Include a regression that the outside target remains absent/unchanged when the sidecar is a link.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Both addressed in f0d02ce, rebased onto the current main (54fa338).

1. [P1] JSONL is split on LF only. load() now uses text.split("\n") instead of str.splitlines(), so U+0085, U+2028 and U+2029 inside a JSON string stay part of the record. test_unicode_line_separators_stay_inside_one_record is parameterised over all three characters and covers both a description and an evidence locator: it asserts the file holds exactly one LF-terminated record, then that start() + query() returns the item with both fields intact. Restoring splitlines() makes those three cases 3 failed; with the fix they pass.

2. [P2] The sidecar is validated and opened without following a link. _lock_path_for() now proves the sidecar's resolved parent sits inside the metadata directory and inside the workspace — the same containment the JSONL target already gets. _open_lock_file() opens it with O_CREAT | O_RDWR | O_NOFOLLOW, so a pre-placed link fails with ELOOP instead of creating its target, and a handle that is not a regular file is refused. Where O_NOFOLLOW does not exist (Windows), the link is refused by lstat before the open — so the open cannot be the step that creates the outside file — and the handle is compared with the path afterwards to catch a swap in between. load() marks the store unusable when this refuses, so the file is never overwritten later. test_lock_sidecar_symlink_cannot_create_an_outside_file seeds a store, replaces .action_items.jsonl.lock with a link to a file in another directory, asserts start() raises ValueError, and asserts the outside path still does not exist. Restoring the plain O_CREAT open makes it 1 failed.

Rebase note: main renamed components/base_component.py to components/base.py and moved the registry to core/registry.py (#769), so the two imports this PR carries were updated to ..base and ...core.registry.

Validation on Windows / Python 3.12:

  • tests/unit/test_action_item_store.py: 48 passed; test_file_catalog.py + test_component_registry.py: 23 passed (71 together).
  • pre-commit run --files on the three touched files: every hook passed, including black after it reformatted the new test.

Both negative controls were run on this head: reverting the parse to splitlines() gives 3 failed, and reverting the sidecar open gives 1 failed.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked f0d02ce. The previous Unicode JSONL round trips and pre-existing lock-sidecar symlink cases now pass. The targeted repository tests (71) plus the previous eight independent checks give 79 passing checks. Registration, exports, and git diff --check also pass, and current CI is green.

One P2 issue remains in the no-O_NOFOLLOW compatibility branch, detailed inline: a link swap between the pre-check and os.open() can create an outside file before the post-open comparison rejects it. I reproduced this on macOS by explicitly exercising that fallback and controlling the swap at the open boundary. This is not a native Windows test result.

Please close that remaining window before merging and add a regression for the check/open interleaving. I did not run the full suite, local pre-commit, or native Windows locking tests.

f"refusing to use a lock file that is a symbolic link: {lock_path}",
)
try:
handle = os.open(str(lock_path), os.O_CREAT | os.O_RDWR | nofollow, 0o600)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Prevent the fallback open from creating an outside file before rejection

The no-O_NOFOLLOW branch used on Windows still has a check/open race. lstat() can observe a normal file (or no entry), then the entry can become a symlink before this O_CREAT open. The open follows the new link and creates its outside target. The later fstat/lstat comparison correctly raises, but the outside file has already been created.

I reproduced this on macOS by setting the module's os.O_NOFOLLOW to zero and wrapping os.open to replace an initially regular sidecar with a link to a nonexistent outside target immediately before calling the real open. _open_lock_file() raises ValueError("...changed while it was opened..."), while the outside target nevertheless exists afterward. This exercises the compatibility branch; I have not verified it on native Windows.

Please use a platform-appropriate atomic open that refuses links/reparse-point redirection before following them, or fail closed when that guarantee is unavailable. A comparison after a side-effecting O_CREAT open cannot provide the containment guarantee. Add a controlled swap test in addition to the already-passing static-symlink regression.

@BeiMu-new
BeiMu-new force-pushed the feat/action-items branch 3 times, most recently from c690f74 to 198e469 Compare November 24, 2026 04:10
@BeiMu-new

Copy link
Copy Markdown
Contributor Author

Addressed in 198e469.

The window is real, and another pre-check would not have closed it. I measured what the flags actually do on this platform before changing anything:

  • os.open(..., O_CREAT | O_RDWR) follows a link already sitting at the path and creates its target — the behaviour you reproduced.
  • os.open(..., O_CREAT | O_EXCL | O_RDWR) behaves the same way: the target is still created. Measured with a probe, so O_EXCL alone does not close it either.

os.open exposes no equivalent of FILE_FLAG_OPEN_REPARSE_POINT, so the entry itself has to be addressed through CreateFileW:

  • CREATE_NEW | FILE_FLAG_OPEN_REPARSE_POINT fails with ERROR_FILE_EXISTS when a link sits at the path. The target is not created and not touched.
  • OPEN_EXISTING | FILE_FLAG_OPEN_REPARSE_POINT returns the entry the path names rather than its target, and _open_lock_file then refuses it: lstat reports the link, and the inode comparison has nothing left that a redirect can fool.

One platform detail worth writing down: on Windows an already open entry cannot be replaced — the handle is exclusive — so the remaining gap is between the failed create and the reopen, not around the open itself. That is the interleaving the regression exercises.

The dispatch is now os.name == "nt" guarded. A platform without O_NOFOLLOW that is not Windows keeps the previous pre-check rather than reaching for an API that does not exist there.

Regression: test_lock_sidecar_swapped_between_create_and_reopen_is_refused swaps in a link exactly between the two calls and asserts both the ValueError and that the target was never created. It is skip-guarded to the branch that only exists where O_NOFOLLOW is unavailable.

Verification

  • tests/unit/test_action_item_store.py: 49 passed
  • Removing the source change makes the new test fail; restoring it returns 49 passed
  • Neighbours (test_atomic_file_write, test_write_metadata_lock, test_path_permission, test_component_registry): 93 passed, 4 skipped. test_atomic_file_write::test_overwrite_preserves_complete_old_content_until_commit fails with assert 438 == 416 with and without this change — it asserts a POSIX mode, which this platform cannot honour.
  • pre-commit run --files on both changed files: all hooks pass
  • Rebased onto b3a5eac for a conflict in reme/components/__init__.py (proactive_runtime landed on main); the PR now reports mergeable: true

I did not run the full suite or native Windows locking tests.

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

Pre-commit is green on 4fb3c39 now. Unit Tests - py3.13 failed on one case that this change does not touch:

FAILED tests/unit/test_cc_active_sessions.py::test_concurrent_append_batches_wait_for_previous_native_persistence - TimeoutError
1 failed, 5600 passed, 48 skipped

Nothing in this PR touches test_cc_active_sessions.py or the session wrapper it exercises — the diff is limited to reme/components/action_item_store/*, reme/schema/action_item.py, their exports, and tests/unit/test_action_item_store.py.

The case looks load-sensitive rather than broken: it waits on four hard-coded two-second budgets (asyncio.wait_for(state.entered.wait(), 2), state.submitted.wait(), 2, asyncio.timeout(2), and a final two-second gather), and the failure is a TimeoutError rather than an assertion on behaviour. Locally the whole file passes (13 passed in 5.7s), and main at b3a5eac is green on the same job — though a single green run on an idle runner does not prove it never trips.

I cannot re-run the job myself: rerun-failed-jobs on this run needs repository admin rights and returns 403 for my account. Could you re-run Unit Tests - py3.13? If it comes back red again with the same case, that changes the picture and I will dig into it rather than assume flakiness.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for switching the Windows sidecar open to CreateFileW with FILE_FLAG_OPEN_REPARSE_POINT. I reviewed 44546e5 and found two remaining issues with lock acquisition, described inline.

The current CI checks pass, including Python 3.13. Locally, 79 checks passed, one Windows-specific test was skipped, and the forced fallback regression still failed. Component registration, exports, and git diff --check passed. The Windows contention finding is based on Microsoft's sharing rules and a simulated Win32 call, with native Windows verification still pending.

handle = kernel32.CreateFileW(
str(lock_path),
generic_read | generic_write,
0,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Let concurrent Windows callers reach the byte-range lock

dwShareMode=0 makes the first read/write handle exclusive. While it is open, a second instance opening the same sidecar can receive ERROR_SHARING_VIOLATION. That error propagates before msvcrt.locking() runs, so normal contention can abort a load or upsert. I confirmed the control flow with simulated Win32 sharing rules. The current Windows CI jobs do not exercise test_action_item_store.py. Microsoft's CreateFileW sharing rules

Please keep FILE_FLAG_OPEN_REPARSE_POINT, allow read/write sharing without delete sharing, and use the byte-range lock to serialize access. A native Windows test with two overlapping instances should check that the second waits and then proceeds or detects a stale snapshot.

raise ValueError(
f"refusing to use a lock file that is a symbolic link: {lock_path}",
)
handle = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o600)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Fail closed when no safe lock-file open is available

The non-Windows branch without O_NOFOLLOW still performs a separate lstat() before a side-effecting O_CREAT open. The previous regression still fails when I force this branch on macOS. The post-open check raises, but the outside file already exists.

Please reject this configuration before opening the lock file unless the platform provides an atomic no-follow operation. Add coverage for the unsupported branch alongside the Windows regression.

@BeiMu-new
BeiMu-new force-pushed the feat/action-items branch 2 times, most recently from e5fbecf to 3ed91bf Compare November 25, 2026 03:44
@BeiMu-new

BeiMu-new commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@ployts Both addressed in 4ce16f9, and both regressions run on a real Windows host (Windows Server 2022, Python 3.12) rather than a simulated Win32 call.

1. [P2] Concurrent callers now reach the byte-range lock

dwShareMode is FILE_SHARE_READ | FILE_SHARE_WRITE — read/write sharing, still no FILE_SHARE_DELETE. FILE_FLAG_OPEN_REPARSE_POINT stays.

The reasoning for keeping delete sharing off: read/write sharing is what lets a second store in the same workspace obtain a handle at all; delete sharing is what would let a different handle rename or remove the entry while a lock is held, which is the property the reparse-point work depends on. Two handles existing is exactly the contention the byte-range lock is there to serialise.

Two regressions:

  • test_second_instance_opens_the_sidecar_instead_of_failing — two overlapping handles on one sidecar; the second must open, not raise ERROR_SHARING_VIOLATION.
  • test_second_exclusive_lock_waits_for_the_first — two holders entered through _exclusive_lock; the second must wait and then proceed. Asserted on the observed order (a-in, a-out, b-in, b-out), so a second holder that slipped in early fails the test rather than passing quietly.

Both go red when dwShareMode is put back to 0 — I ran each one that way and reverted.

2. [P2] Fail closed when there is no atomic no-follow open

The lstat + O_CREAT fallback is gone. That branch now raises before opening anything:

raise RuntimeError(
    "this platform cannot open the lock file without following a "
    f"symbolic link: {lock_path}",
)

You're right that the post-open check did not help — the outside file already existed by then, which is precisely what a check can never undo. A lock that may be guarding a file the store does not write is worse than a refusal the caller can surface.

test_open_lock_file_refuses_when_no_atomic_no_follow_is_available forces the branch (O_NOFOLLOW=0, os.name="posix"), asserts RuntimeError, and asserts the lock path was never created. Also goes red when the old fallback is restored.

Test scope: tests/unit/test_action_item_store.py 53 passed (up from 49: four new, two of which are Windows-only). pre-commit run --files clean (black/flake8/pylint). Head is 4ce16f9.

I also measured the case I was going to leave open: the byte-range lock across two separate processes, not two threads in one process. test_two_processes_serialise_on_the_byte_range_lock spawns two Python processes against one sidecar and asserts the second one's b-in timestamp lands after the first one's a-out, so the serialisation is real and not an artefact of one interpreter. It goes red when dwShareMode is put back to 0 — the second process exits with ERROR_SHARING_VIOLATION.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update and for running the contention tests on Windows. The two findings from the previous review are addressed in 4ce16f9. The Windows open permits read/write sharing while retaining the reparse-point protection, and the unsupported fallback now rejects the operation before creating a file. My local checks passed with 81 tests and four platform-specific skips. git diff --check and the current CI checks also passed.

One first-use race remains in the Windows lock initialization, detailed inline. My independent verification used a controlled simulation of the Windows file-locking rules on macOS. The author’s native Windows results cover the cases described in their update.

There is also a merge conflict in reme/components/__init__.py. I confirmed it against current main at 7b23175 with git merge-tree. Please rebase onto main and retain both the proactive_manager imports and exports introduced by #776 and this PR’s action_item_store registration. Upstream change #776

import msvcrt

if os.fstat(handle).st_size == 0:
os.write(handle, b"\0")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Acquire the Windows lock without first writing an initialization byte

On a newly created empty sidecar, both instances can observe st_size == 0. If the first writes the byte and acquires its range lock before the second reaches os.write(), the second handle’s write overlaps the locked byte and fails. The exception occurs before the lock acquisition loop, so the second operation exits instead of waiting. I reproduced that ordering with a simulated Windows backend on macOS. Win32 byte-range lock behavior

msvcrt.locking() supports locking beyond EOF. Please lock byte zero directly so there is no initialization write, and add a regression that synchronizes the first two callers on a fresh sidecar. Microsoft _locking documentation

- create the staging file exclusively under a random name, so a symlink
  pre-created at a predictable staging path can never become the write target
- stamp the file this instance loaded and refuse to overwrite it once another
  instance changed it; closing an unchanged reader no longer rewrites its stale
  snapshot over newer records
- validate the store name as a single path segment and anchor containment to
  the resolved workspace root, checked before any read or mkdir, so an absolute
  name or a redirected metadata tree cannot select a directory outside the
  workspace
- merge extension fields of a deduplicated evidence row instead of dropping the
  incoming observation as a whole
@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Both addressed in 614e2617.

1. [P2] No initialisation write before the lock

_exclusive_lock no longer writes a byte when the sidecar is empty. msvcrt.locking goes through the Win32 byte-range lock, which covers bytes past EOF, so offset 0 can be locked on a zero-length file directly. With the write gone there is nothing for a second caller to collide with: both callers reach the retry loop and queue on the lock instead of one of them aborting at os.write.

2. Regression on a fresh sidecar

test_locking_a_fresh_sidecar_does_not_write_to_it asserts st_size == 0 after the lock is released, which is the property that removes the collision. Reverting the fix makes it fail exactly:

E       assert 1 == 0
E        +  where 1 = os.stat_result(...).st_size

test_first_callers_serialise_on_a_fresh_sidecar adds the rendezvous case: two threads wait on a threading.Barrier and then enter the lock on a sidecar that does not exist yet, asserting both get through and run one after the other. That one passes on the old code as well — it is a guard rather than proof, because the collision needs a particular interleaving to surface.

3. Rebase

Rebased onto 7b23175. reme/components/__init__.py keeps both sides:

"proactive_manager",    # from #776
"action_item_store",    # this PR

proactive_runtime is not carried over: current main renamed it to proactive_manager, so keeping the old export would name a module that no longer exists.

Test scope

  • target: tests/unit/test_action_item_store.py — 55 passed
  • adjacent: tests/unit -k "schema or component or action_item" — 219 passed, 6 skipped, 1 failed. The failure is test_base_component.py::test_to_workspace_relative_outside_workspace, which maps /some/other/path to C:/some/other/path on Windows; none of this PR's eight files touch base_component.py.
  • pre-commit run --files on the eight changed files — every hook passed.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked 614e2617. The previous findings are addressed, including the Windows first-use lock initialization race and the rebase conflict. I have no remaining blocking findings for this schema/store scope.

Local focused verification passed with 81 checks and six Windows-specific skips. Component exports/registration and git diff --check passed, and the current CI checks are green. Native Windows tests were not run locally.

Thanks for addressing the feedback and adding regression coverage.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants