Repository navigation
Conversation
|
|
d7c255f to
fbcbf94
Compare
|
For the record on the four red Failures:
All three report Baseline (main @ |
fbcbf94 to
c17487b
Compare
|
Force-pushed
Test scope in the description predates this: |
ployts
left a comment
There was a problem hiding this comment.
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, andtest_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 --checkpassed. I did not run the full test suite or pre-commit locally.- I also compared the CI logs with baseline run
43358116256: the three failingplugins/homesandbox tests are present on the baseline as well, so those failures are separate from this review.
| """ | ||
| evidence = merge_evidence(existing.evidence, incoming.evidence) | ||
| aliases = merge_aliases(existing, incoming) | ||
| if incoming.last_updated < existing.last_updated: |
There was a problem hiding this comment.
[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.
| 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 |
There was a problem hiding this comment.
[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.
| if incoming.id in self._items: | ||
| return incoming.id |
There was a problem hiding this comment.
[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.
| self._items[merged.id] = merged | ||
| self._index_aliases(merged) | ||
| stored.append(merged) | ||
| if stored: | ||
| self._write() |
There was a problem hiding this comment.
[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)] |
There was a problem hiding this comment.
[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)) |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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.
c17487b to
b4404ac
Compare
|
@ployts Thanks for the careful review and for reproducing all seven cases — they are addressed in [P1] Order state transitions by their evidence timeYou are right that comparing
[P1] Prevent independently named stores from overwriting each other's records
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
Covered by [P2] Publish the in-memory update only after persistence succeeds
[P2] Return detached records instead of mutable store-owned objects
[P2] Preserve unknown fields in otherwise readable recordsBoth
[P2] Keep the configured persistence file inside the workspace
Test scope
Also covered: |
ployts
left a comment
There was a problem hiding this comment.
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.
| temporary = destination.with_name(f"{destination.name}.tmp") | ||
| try: | ||
| with temporary.open("w", encoding="utf-8", newline="\n") as handle: |
There was a problem hiding this comment.
[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.
| async def _close(self) -> None: | ||
| if self.is_started: | ||
| await self.dump() |
There was a problem hiding this comment.
[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.
| 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}") |
There was a problem hiding this comment.
[P2] Anchor containment to the workspace and validate before reads or mkdir
Two bypasses remain despite rejecting path-like file_name values:
_filealso incorporatesself.name, which is not validated. An absolute component name selects an outside directory, andload()opens that outside JSONL without calling this guard. I reproducedstart()followed byquery()returning an outside record. The write path also callsmkdirbefore checking containment.- If
workspace/metadata/action_item_storeitself is a symlink to an outside directory,base = self.component_metadata_path.resolve()trusts that outside directory as the root. The check passes andupsert()successfully creates the JSONL outside the workspace; I reproduced this with the ordinary namework.
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.
| key = (evidence.path, evidence.locator, evidence.observed_at, evidence.excerpt) | ||
| if key in seen: | ||
| continue |
There was a problem hiding this comment.
[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.
b4404ac to
a96f508
Compare
|
@ployts Thanks for the second pass — all four findings are addressed in [P1] The staging file is created exclusivelyReplaced the fixed
[P1] Stale same-name instances can no longer erase recordsTwo separate mechanisms, because the read-only case and the write case fail differently:
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
Coverage: [P2] Deduplicated evidence keeps newly supplied extension fields
Validation
Scope is unchanged: schema/store only, extraction and QwenPaw delivery remain follow-ups. |
a96f508 to
a86db9c
Compare
|
Replaced the head with The only change against the previous push is dropping a dead 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. |
a86db9c to
1161348
Compare
|
@ployts Rebased onto the current The rebase met three conflicts, all of them registry appends in the same spot:
Upstream renamed Still a single commit ( |
ployts
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
[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: |
There was a problem hiding this comment.
[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/worksymlinked to an outside directory containing a validaction_items.jsonl;- a regular
workdirectory whoseaction_items.jsonlis 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.
1161348 to
05ea653
Compare
|
@ployts Both are addressed in 1. Snapshot validation and replacement are one coordinated operation. 2. The fully resolved read target is validated, directory and file alike. Verification: 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
left a comment
There was a problem hiding this comment.
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, andtest_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 --checkpassed. 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): |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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.
05ea653 to
f0d02ce
Compare
|
@ployts Both addressed in 1. [P1] JSONL is split on LF only. 2. [P2] The sidecar is validated and opened without following a link. Rebase note: Validation on Windows / Python 3.12:
Both negative controls were run on this head: reverting the parse to |
ployts
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
[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.
c690f74 to
198e469
Compare
|
Addressed in 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:
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 Regression: Verification
I did not run the full suite or native Windows locking tests. |
198e469 to
4fb3c39
Compare
|
Nothing in this PR touches The case looks load-sensitive rather than broken: it waits on four hard-coded two-second budgets ( I cannot re-run the job myself: |
4fb3c39 to
44546e5
Compare
ployts
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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.
e5fbecf to
3ed91bf
Compare
|
@ployts Both addressed in 1. [P2] Concurrent callers now reach the byte-range lock
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:
Both go red when 2. [P2] Fail closed when there is no atomic no-follow open The 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 scope: 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. |
3ed91bf to
4ce16f9
Compare
ployts
left a comment
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
[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
4ce16f9 to
614e261
Compare
|
@ployts Both addressed in 1. [P2] No initialisation write before the lock
2. Regression on a fresh sidecar
3. Rebase Rebased onto
Test scope
|
ployts
left a comment
There was a problem hiding this comment.
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.
What this PR does
Adds the minimal read-only contract for action items, as agreed in #744:
ActionItemState:unresolved,blocked,completed,uncertain,cancelled.ActionItem: stableid, sourcenote, shortdescription,state,evidence entries (path, locator, excerpt, observed time, optional source),
aliases, andfirst_seen/last_updated.LocalActionItemStore: one JSONL file per named store under the workspacemetadata directory, reloaded on start; the in-memory map is only an index that
can always be rebuilt from the file.
query: read-only filter bystates,updated_sinceandlimit.It never triggers extraction, model calls or writes.
Contract details
uncertainrequires at leastone evidence entry. Missing frontmatter or a successful AutoDream run cannot
establish a state, and unknown material stays
uncertain— a missing fieldcan therefore never turn into a reminder.
id = sha1(note + normalized text)[:16], so laterevidence 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 checksid, then the alias index, then the incomingaliases, so a reworded item updates the record instead of forking a second one.
records that are already stored, they are merged into the one with the earlier
first_seen, and the later id joins itsaliases; the alias can therefore notleave two inconsistent records behind.
but processed later keeps the newer resolution and only extends the evidence
list. Ordering is decided by the newest evidence
observed_atrather thanlast_updated, so rewording a description cannot reopen a resolved item.Repeated evidence is dropped by
(path, locator, observed_at, excerpt)and thelist stays in observation order.
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.
get(),query()andupsert()copy at the boundary,including nested evidence and alias collections, so a caller cannot mutate
store state without going through
upsert().entries survive a read/write cycle (
extra="allow"plusmodel_dump), sostarting and closing a store cannot silently drop fields written by a newer
version.
first_seen,last_updated, evidenceobserved_atandupdated_sinceareAwareDatetime: a naive datetime failsvalidation with a clear message instead of raising
TypeErrorinside acomparison.
file_namemust be a bare name:./.., pathseparators, 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.
<workspace>/<metadata_dir>/action_item_store/<name>/action_items.jsonl. Onread, 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 towrite and reads raise, while
start()still completes.limitisNoneunless the callersets 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
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_namerejected, 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).
21 passed.
tests/unit/test_file_catalog.pyandtests/unit/test_component_registry.py— 43 passed together with the targetfile.
pre-commit run --files <changed>— 11 hooks passed(ast, private key, whitespace, trailing comma, black, flake8, pylint, pyroma).