Skip to content

Add configurable PostgreSQL storage backends - #689

Open
mmpg-x86 wants to merge 31 commits into
sashiko-dev:mainfrom
mmpg-x86:feature/postgresql-storage
Open

mmpg-x86 wants to merge 31 commits into
sashiko-dev:mainfrom
mmpg-x86:feature/postgresql-storage

Conversation

@mmpg-x86

Copy link
Copy Markdown

Summary

Keep libSQL as the default and add two configurable PostgreSQL modes:

  • PostgreSQL for the complete daemon database.
  • Local libSQL reviews with a PostgreSQL catalog of shared bugs.

The full backend includes native versioned migrations, audit/projection
triggers, bound parameters, compressed payloads and canonical bug locking.
Operations serialize within the configured schema; independent schemas
have separate coordination locks. Ordinary sessions recover after
connection loss. Interrupted transactions and lock sessions fail safely.

Shared mode provides stable instance/event identities, public bug links,
a durable local outbox, a resumable import cursor and three-way merges.
Independent changes combine; conflicting triage retains the catalog
value and records an audit event. Analysis stays with the originating
instance. Imported history preserves its original attribution and local
review links never resolve against another instance's internal IDs.

Synchronization reuses its remote connection, processes bounded batches,
rotates deferred publications and prioritizes canonical outcomes. It has
a five-minute deadline and runs under the worker supervisor. Lease and
housekeeping updates do not republish histories. Local mirror migrations
are versioned independently of the main libSQL schema.

Configuration

[storage]
mode = "postgresql" # or "libsql_shared_bugs"
postgres_schema = "sashiko"
# postgres_ca_file = "/etc/sashiko/postgres-ca.pem"

Set credentials with SASHIKO__STORAGE__POSTGRES_URL. TLS and certificate
verification are required by default. The explicit
postgres_tls_require_only option supports trusted lab certificates.

Shared mode also uses the existing [database] libSQL configuration.
Legacy public bug IDs retain their identity within the stamped project.
Selecting plain libSQL disables catalog tracking; re-enabling it queues
edits made while tracking was off. Because tracking was disabled, this
reconciliation conservatively queues every report; subsequent publication
remains bounded.

Existing libSQL data is not automatically imported into full PostgreSQL
storage. See docs/configuration.md and designs/DESIGN_POSTGRESQL_STORAGE.md.

Validation

  • Complete-range make check-pr on Rust 1.90, including formatting,
    Clippy across feature profiles, YAML and 1,164 repository tests.
  • Two live PostgreSQL 17.11 integration scenarios with disposable schemas.
  • Full storage: repeated migrations, worker claims/leases, compressed
    evidence, review links, readable audits, severity projections, duplicate
    folding, listing, statistics and rollback.
  • Connection termination and canceled operations exercise reconnection,
    transaction failure, lock failure and schema isolation.
  • Shared storage: distinct local mirrors, producer-local evidence,
    ownership, merge conflicts, idempotent retry, public duplicate links,
    observed lock exclusion, reciprocal duplicate decisions, offline
    recovery and backlog/cursor resumption beyond one batch.
  • Unit regressions cover concurrent acknowledgements, scoped pending
    lookups, ASCII authorization parity, imported metadata/history,
    foreign analysis ownership, legacy identifiers, version upgrades,
    transient error classification and coordination deadlines. The native
    backlog fixture verifies that deduplication refuses pending imports and succeeds
    after the remaining records are accepted.
  • CI provisions PostgreSQL 17 with TLS and runs both native scenarios.

The default libSQL backend and minimal local review profiles remain
covered by the same repository checks.

Local Sashiko review

Completed the full feature review and reviewed the corrective changes in
local loops with --project sashiko --agent. Code findings were resolved,
and the final review of the actual proposed commit reports no findings.

Cumulative source snapshots were used for the large feature and correction
sets; the branch preserves separate signed-off commits. The review of the
last correction used the actual commit and its explanatory message.

The review also checked conservative reconciliation after tracking is
re-enabled and stopping on unimportable catalog data. These are explicit
execution boundaries: publication backlog alone does not prevent analysis,
but an incomplete import cannot safely support deduplication. Both are
now documented in the configuration guide and design.

Initial implementation limits

Operations serialize within one schema. Explicit transactions use
additional sessions, and shared updates transfer whole bug snapshots.
This implementation does not include a libSQL-to-PostgreSQL importer.

Transient catalog outages defer analysis without charging an attempt.
Already committed outcomes remain queued and keep their review links.
A crash or session loss between local commit and publication can admit
another report of the same defect; retrying one public UUID remains
idempotent. Catalog participants must share an attribution/permission
policy. Malformed records or incompatible formats stop synchronization
and analysis until corrected; imports are never skipped past a possible
canonical report. These boundaries are documented.

Local validation used macOS and the remote PostgreSQL test server.
Linux CI service bootstrap and Nix builds require those environments.

Define explicit full-daemon and shared-catalog storage modes while
keeping libSQL as the default. Record the execution boundary, public bug
identity, migration and synchronization requirements before
implementation.

Set review checkpoints for backend parity, retry safety and preservation
of the minimal local review profiles.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Allocate, grant and unlock test pseudoterminals through rustix before
querying terminal capabilities or changing window sizes. Opening the
master device alone does not initialize a usable terminal on macOS.

Reuse the initialized fixture across the display tests so the repository
checks can run on the development host.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Add typed storage mode settings for a full PostgreSQL database or a
PostgreSQL catalog beside libSQL. Preserve the existing configuration
default and require the fields each selected mode needs.

Reject PostgreSQL URLs in the legacy libSQL setting and keep connection
credentials out of settings debug output.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Introduce the optional PostgreSQL client dependencies and a versioned
catalog schema using public bug identifiers. Protect migration startup
with an advisory lock and keep the database client separate from local
review builds.

This establishes the driver and schema foundation for the configured
storage modes.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Add a backend-neutral execution boundary with bound parameters, typed
rows and owned transactions. Port the daemon schema, audit triggers,
projections and query vocabulary to native PostgreSQL operations.

Require encrypted connections with certificate verification by default
and select the backend through daemon configuration. Exercise
migrations, claims, compressed evidence, duplicate folding, statistics
and rollback against a live PostgreSQL schema.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Keep local review data in libSQL while publishing bug records to a
PostgreSQL catalog. Use stable instance and event identities, public bug
links, a durable mutation outbox and a sequence cursor for retries.

Merge independent edits and preserve conflicting triage proposals in
audit history. Retain origin-owned analysis and local review relations,
coordinate canonical decisions across instances, and expose pending
publication in the API and UI.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Preserve the last accepted catalog snapshot when a local edit races
with publication acknowledgement. The next pass can then merge the
pending edit without treating remote changes as new local changes.

Cover conflicting triage and independent title changes with a
regression test that also retains concurrent evidence.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Identify foreign evidence through stable shared event identities.
Retain its raw input for inspection while resolving patch and review
links only from evidence produced by the local instance.

Cover local link preservation and imported link suppression in a
regression test, and document the treatment of original payloads.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Open benchmark storage through the same configured constructor as the
daemon. This makes PostgreSQL selections apply to every production
database client.

Exercise full PostgreSQL storage through that constructor in the live
integration test with a deliberately unrelated libSQL URL.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
The PostgreSQL TLS connector uses OpenSSL on Linux. Add its library
and pkg-config to the Nix package and development shell so the new
server dependency can be discovered during builds.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Start an isolated PostgreSQL 17 service, configure its test TLS
certificate, and run both live backend scenarios after the normal
suite. Install the native TLS build dependencies on the Linux runner.

Document the explicit local test command and its disposable database
requirement. CI needs no access to a developer's PostgreSQL server.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Use the same ASCII case folding as authorization when filtering bug
lists and subsystem counts. Keep non-ASCII section names distinct
without losing exact matches in the default libSQL backend.

Cover both allowed and distinct Unicode scopes in the local tests and
in the live PostgreSQL scenario.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Imported audit targets contain producer-local row identifiers. A
collision with a readable mirror row must not grant access to the
original duplicate reasoning.

Conservatively redact foreign duplicate audit details and reasoning
for readers without global visibility. Cover both API views with a
colliding target and preserve the operator view.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Read pending publication state for the current bug or result page.
Avoid scanning and allocating the complete outbox for each API request
while a catalog outage leaves many local reports queued.

Keep the full pending query for the background publisher and cover
scoped lookups with unrelated queued reports.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Check duplicate chains while holding the catalog write lock. Defer
references to unpublished targets and reject reciprocal decisions
that would remove every canonical bug in a cycle. Retain the catalog
triage and record the rejected proposal in conflict history.

Import a newly selected target before acknowledging a dirty local
record. Exercise both acknowledgement and reciprocal triage races
against the live PostgreSQL catalog.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Classify failures before shared deduplication as catalog deferrals.
Requeue those claimed analyses without consuming an attempt, and keep
the lease ownership checks that reject stale workers.

Treat publication after a committed verdict as durable outbox work.
The workflow can finish linking the review and release its claim even
when PostgreSQL is unreachable. Cover retry accounting and retained
success, and document the interruption limits of semantic deduplication.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Reconnect a closed ordinary session before its next operation without
replaying failed writes. Keep transaction and deduplication sessions
bound to their original connection so losing a session remains an
error instead of silently losing transaction state or an advisory lock.

Skip schema creation when the configured schema already exists. This
also permits a schema owner without database-level CREATE privilege.
Terminate live PostgreSQL sessions to verify recovery and isolation.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Select the existing token index hint only for libSQL while leaving
the PostgreSQL join native. Preserve the default backend optimization
that avoids reading large AI interaction payloads for homepage totals.

Assert that the libSQL query plan uses the covering token index.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Build integration settings from an isolated fixture and observe the
second dedup session waiting on the actual server advisory lock before
releasing its owner. Connection setup latency cannot satisfy the lock
exclusion assertion.

Cover integer limits, negative and fractional NUMERIC values, invalid
wire input, quoted SQL names and nested comments in the adapter tests.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Explain permissions for pre-created schemas and the initial serialized
execution model. Record connection recovery, buffered query results and
whole-record catalog transfers so operators can size deployments and
review the implementation limits.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Retain legacy reports from other project prefixes in the local store.
Exclude them from the publication queue so enabling a shared catalog
cannot publish an incompatible record and wedge every import cursor.

Validate merged records before committing them remotely. Cover mixed
legacy and current reports in the live two-instance scenario.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Use separate advisory lock classes with the server hash of the schema
name. Keep writers and canonical decisions coordinated within their
schema while allowing independent deployments to make progress.

Exercise both lock classes across separate schemas. Identify the
second mirror by its application name when observing its lock wait,
so a concurrent test cannot satisfy that assertion.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Track the opt-in mirror schema independently of primary migrations.
Gate its triggers on the selected mode, and requeue local edits when
shared storage is enabled again after a period in libSQL mode.

Queue bug updates only when shared payload fields change. Lease renewal
and fix-check housekeeping no longer resend complete histories.

Cover mode transitions, unsupported mirror versions, housekeeping and
origin ownership across fix-check claims and lease recovery.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Initialize the catalog handle and bootstrap DDL once per local mirror.
Keep identity and format checks on every synchronization pass, and let
ordinary connection recovery reopen a closed session when needed.

Build the TLS connector and read its CA file on the blocking pool so
certificate setup cannot block a Tokio worker thread.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Own each connection driver and stop it when an operation is canceled
or fails. Reconnect ordinary callers on their next operation while
keeping dedicated transactions and lock sessions invalid after loss.

Discard unfinished transaction sessions immediately instead of
spawning a rollback that can itself wait forever. Preserve the driver
alongside its client during reconnects and verify cancellation against
a live advisory-lock wait.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Refund analysis attempts for connection loss, retryable PostgreSQL
errors, canceled sessions and timeouts. Keep configuration, schema,
identity and data errors on the ordinary failure path.

Cover connection refusal and permanent configuration failures without
requiring a live server, preserving the original error chain.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Use the explicit database project stamp to scope catalog membership.
A legacy public identifier can have a different prefix while still
belonging to that project, so preserve and share it without renaming
or omitting the report.

Validate record identity and triage before publication and exercise
legacy-ID sharing between both mirrors.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Limit each pass to 100 publications and 100 imports, loading one full
record at a time. Persist queue positions so deferred duplicate targets
cannot starve behind earlier reports. Publish verdicts and their
canonical targets first, and wait for committed imports before dedup.

Apply a five-minute deadline to coordination and supervise the daemon
sync task. Preserve a valid local duplicate graph while conflicting
triage is reconciled, and validate payload identities before replay.

Version the queue migration and cover upgrade, fairness, deadlines,
local conflicts and a live backlog larger than one batch.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Import audit entries and comments with their original authors, models,
and timestamps. Receiving worker defaults must not change foreign
history, including absent attribution and legacy zero timestamps.

Refresh report metadata and existing events from the accepted snapshot
so later publications cannot overwrite the catalog with local defaults.
Cover initial imports and subsequent updates through an attributed
receiver.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Restore readable before-and-after audit summaries for status, title,
duplicate, assignment and subsystem changes. The existing history UI
renders these summaries directly.

Give nullable assignment expressions explicit text and integer types
so PostgreSQL can prepare the CASE expression used by triage updates.
Exercise assignment, reassignment, unassignment and audit contents in
the live PostgreSQL scenario.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
Cover cancellation and PostgreSQL retry decisions, including permanent
configuration and data errors. Exercise the actual deduplication guard
while a catalog backlog remains and after it has been imported.

Document conservative reconciliation after tracking was disabled and
the requirement to stop on unimportable records. Advancing past unknown
catalog data would permit duplicate decisions without complete evidence.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
@sashiko-bot

sashiko-bot Bot commented Oct 15, 2026

Copy link
Copy Markdown

Sashiko review

Commit 5/31 — 282da5ec Support PostgreSQL for daemon storage

  • [HIGH] In src/storage.rs (Connection::query and Connection::execute), if
    the connection is not explicitly in a transaction, the method spawns a
    transaction and calls pg_advisory_xact_lock(WRITE_LOCK). Because WRITE_LOCK
    is a global exclusive advisory lock, and because Database::conn is
    initialized as a non-transaction connection, every single SELECT query in the
    application acquires this exclusive lock. This completely serializes all
    concurrent reads across the entire daemon against both other reads and active
    writes, destroying the concurrency benefits that SQLite WAL mode provided and
    causing severe API/UX stalls.

  • [HIGH] In src/db.rs (merge_patchsets), when merging patchsets, the UPDATE
    OR IGNORE statement for the patches table was translated to a blind UPDATE.
    PostgreSQL does not support OR IGNORE. If the two patchsets share any
    identical message_id, the UPDATE will violate the UNIQUE constraint and
    immediately crash the entire PostgreSQL transaction. The forge_outbox
    migration received a fallback AND NOT EXISTS to prevent collisions, but the
    patches table update was left unprotected.

  • [HIGH] In src/db.rs (merge_threads and merge_patchsets), the queries for
    threads_subsystems and patchsets_subsystems were converted to INSERT INTO
    ... SELECT ... ON CONFLICT DO NOTHING. However, this only copies the
    relationship rows instead of moving them. Because these tables do not have ON
    DELETE CASCADE defined in the schema, the copied rows are orphaned on the old
    identifiers. When the merge function subsequently attempts to delete the old
    thread or patchset, PostgreSQL will abort the transaction with a foreign key
    constraint violation.

  • [MEDIUM] In the Commit Message, the description explains what the change
    does but completely omits the motivation and rationale for introducing
    PostgreSQL support. Non-trivial architectural changes must explain both what
    the change does and why it is necessary to meet project guidelines.

  • [LOW] In src/db.rs (Database::postgres), the blocking synchronous function
    std::fs::read is called inside an async context to load the root
    certificate. While this executes only during database connection
    initialization, it violates the async guideline which mandates wrapping
    unavoidable synchronous file operations in tokio::task::spawn_blocking to
    prevent stalling the cooperative Tokio scheduler.

Commit 6/31 — 5ff2a613 Synchronize shared bug catalogs through PostgreSQL

  • [CRITICAL] In src/migrations/014_shared_bug_mirror.sql, the trigger
    definitions use a subquery in the WHEN NOT EXISTS clause. SQLite explicitly
    forbids subqueries within the WHEN clause of a CREATE TRIGGER statement.
    This causes a runtime syntax error when Database::initialize_shared_catalog
    executes the batch, crashing the daemon on startup and permanently
    preventing database initialization.

  • [HIGH] In src/workflows/linux_bug.rs (process_issue_worker_for_project),
    propagating a remote PostgreSQL network timeout from the
    Database::sync_shared_bugs call aborts the workflow after a successful
    local deduplication and LLM analysis. This unconditionally overwrites the
    successfully computed pipeline state to failed, wasting tokens and
    discarding persisted local work due to a transient remote error.

  • [HIGH] In src/db/shared.rs (Database::sync_shared_bugs), a malformed
    remote catalog payload causes the JSON parser to return an error without
    advancing the shared cursor. Because BugWorker::run indefinitely halts new
    task claims if synchronization fails, a single bad remote record causes an
    infinite retry loop on the exact same row, permanently stopping both
    background synchronization and all local bug analyses.

  • [HIGH] In src/db/shared.rs (sync_shared_bugs), external network operations
    to PostgreSQL are executed without explicit timeouts. If the remote
    database server hangs or blackholes the connection, the operation blocks
    indefinitely while holding the local shared lock. This permanently
    deadlocks both background synchronization and local bug processing, which
    waits for the lock before claiming tasks.

  • [HIGH] In src/db/shared.rs (shared_publish_record), the initial query to
    read the existing shared catalog payload does not acquire a row lock using
    a FOR UPDATE clause. Because PostgreSQL uses Read Committed isolation by
    default, concurrent daemons synchronizing changes to the same bug will
    both read the old payload, merge their local changes against it, and
    blindly overwrite each other's updates, causing permanent data loss.

  • [HIGH] In src/db/shared.rs (shared_accept), zstd compression is called
    synchronously inside an async function. Since compression is CPU-bound,
    this blocks the Tokio worker thread from cooperative scheduling. Because
    it happens while holding an active SQLite immediate write transaction, it
    halts all other database writers and massively increases the risk of
    SQLite busy timeouts for all other daemon tasks.

  • [HIGH] In src/db.rs (Database::migrate), the shared bug catalog schema is
    initialized unconditionally outside of the versioned migration loop.
    Executing the unversioned schema definition file every time the daemon
    boots bypasses the strict PRAGMA user_version tracking logic, violating
    sequential database migration invariants and unnecessarily executing schema
    statements.

  • [MEDIUM] In src/db/shared.rs (merge_value), the analysis struct is
    intentionally excluded from deep object merging. Because the analysis
    struct contains independent fields with no cross-field database
    constraints, treating it as an atomic unit causes concurrent updates to
    different sub-fields to entirely overwrite one another. This discards
    valid local edits and contradicts the design specification for concurrent
    merging.

  • [MEDIUM] In src/main.rs (run_daemon), the background catalog
    synchronization loop is detached using a bare tokio spawn call instead of
    the required spawn_supervised_worker function. This detaches the panic
    lifecycle from supervision, meaning that if the loop panics, the handle
    drops and background synchronization permanently and silently ceases for
    the remaining lifetime of the daemon.

Commit 7/31 — 0d7e9482 Keep catalog merge bases until local changes are acknowledged

  • [HIGH] In src/db/shared.rs (Database::shared_accept and merge_value),
    sequential local bug edits made while a background sync is in progress
    are permanently lost. Because the early return in shared_accept leaves
    base_json pinned to its pre-push state when a concurrent local edit
    occurs, merge_value misinterprets the user's own inflight push as a
    new remote change on the next sync. This causes the newer local edit
    to be silently overwritten by the older push, resulting in systematic
    data loss on the primary synchronization path.

Commit 11/31 — 9d635681 Run PostgreSQL integration coverage in CI

  • [MEDIUM] In .github/workflows/ci.yml (Configure PostgreSQL Test TLS), the
    CI script attempts to enable TLS on the running PostgreSQL service by
    executing ALTER SYSTEM SET ssl=on followed by SELECT pg_reload_conf().
    However, in PostgreSQL, ssl is a postmaster context parameter and cannot
    be enabled dynamically via SIGHUP. It requires a full server restart to
    take effect. As a result, the PostgreSQL service will continue running
    with TLS disabled, and the integration tests will fail to connect. The
    container must be restarted after modifying the ssl parameter.

Commit 12/31 — f74127a3 Preserve ASCII subsystem scope matching on both backends

  • [HIGH] In src/db.rs (Database::maintainer_section_fold_sql and list_bugs),
    the database query parameter folding is changed to ASCII-only, but the
    authorization logic in src/access.rs (SectionTitle::new) uses full Unicode
    case folding. This mismatch silently hides bugs from authorized
    maintainers' lists and subsystem counts when a bug is filed against a
    subsystem name containing non-ASCII characters.

  • [MEDIUM] In src/db.rs (list_bugs and get_subsystems_bug_counts), the
    queries replace the lower(subsystem) filter with an unindexed fold
    expression. Because the idx_bug_subsystems_authorizing partial index lacks
    an expression index on the fold function, the database planner must
    perform an O(N) scan across all bugs in the maintainers_section, degrading
    query scalability as the database grows.

Commit 23/31 — 592d15d7 Version shared mirror tracking and exclude local bookkeeping

  • [MEDIUM] In src/db.rs (Database::migrate), when an existing database with
    the older 014_shared_bug_mirror.sql schema is upgraded but the shared
    configuration is disabled, the code attempts to update the shared_enabled
    meta key. However, this key does not exist in the legacy schema's meta
    table, so the update does nothing. Additionally, the legacy triggers do
    not check shared_enabled and do not filter by specific columns. As a
    result, the old unoptimized triggers remain active and will continue to
    write to the shared_bug_sync table on every bugs table update, including
    periodic lease renewals. This defeats the intent to disable change
    tracking when shared storage is off.

Commit 25/31 — 35b5c79d Discard PostgreSQL sessions after interrupted operations

  • [LOW] In src/storage.rs (Connection::execute), the control command check
    matches BEGIN alongside COMMIT and ROLLBACK, setting the active flag to
    false. While correct for terminating commands, setting active to false on
    a BEGIN command incorrectly marks a newly started transaction as inactive
    (autocommit = true), breaking the is_autocommit check during connection
    drop.

Commit 28/31 — e875af3f Bound shared catalog synchronization with durable scheduling

  • [HIGH] In src/db/shared.rs (Database::sync_shared_bugs_inner), if
    self.shared_publish_record returns an error, the ? operator aborts the loop
    immediately. This bypasses self.shared_note_attempt, meaning the failing
    record's queue_order is never updated. The daemon will continuously fetch
    the exact same record and fail, creating a head-of-line blocking poison
    pill that permanently wedges the outbound catalog publication queue.

  • [HIGH] In src/db/shared.rs (Database::shared_import_batch), if an imported
    payload fails validation, the ? operator aborts the batch early before the
    cursor state can be updated. The next execution of the background task
    will start from the exact same cursor, read the identical problematic
    remote record, and fail again. This creates a poison pill that permanently
    stalls the instance from ingesting any further catalog updates.

Commit 29/31 — 490c9dc4 Preserve original metadata when importing shared bug history

  • [LOW] In src/db/shared.rs (Database::shared_accept), the code uses raw as
    casts to convert usize token counts to i64 for tokens_in, tokens_out, and
    tokens_cached. The codebase guidelines strictly forbid raw as casts between
    integers of different widths due to the risk of truncation or
    sign-extension. Safe conversions like i64::try_from(v).unwrap_or(i64::MAX)
    must be used instead.

Commit 30/31 — 13fd37c4 Match libSQL bug triage behavior on PostgreSQL

  • [HIGH] In src/migrations/postgresql/003_bug_triggers.sql and src/db.rs
    (Database::migrate), an existing migration file is modified in place instead
    of creating a new additive migration step. Because the initialization logic
    only executes 003_bug_triggers.sql for fresh databases, existing PostgreSQL
    deployments will silently skip the trigger updates and permanently retain
    the old audit log format. Database migrations must be additive and use a new
    version bump to ensure schema updates propagate to all existing databases.

Full review and stage logs on sashiko.sashiko.dev

@rgushchin

Copy link
Copy Markdown
Member

Hello! Thanks for the PR. What is the motivation here? Sqlite with all it's simplicity worked well so far and there were exactly 0 issues caused by it. So I'm somewhat resistant to add more code just in case. Thanks!

@mmpg-x86

Copy link
Copy Markdown
Author

Hi, thanks for taking a look! I agree that SQLite has worked well and should remain the default. I also agree that this PR has grown too large and needs some rethinking.

The motivation comes from our team working across multiple kernels. We want a shared catalog where developers can submit known issues, retain issues discovered by Sashiko, and make that information available during future analyses. Some findings remain useful even when they aren’t relevant to the kernel currently being reviewed.

Muting existing issues helps with repeated reports. A shared catalog would also let us preserve and share the investigation results. We’re already spending tokens discovering these issues, so keeping that knowledge available across developers and kernel versions seems valuable.

PostgreSQL seemed like a reasonable option because it’s open source, widely available, and has a strong community. It would be explicitly configured; SQLite would remain the default.

That said, the shared bug catalog is the concrete requirement motivating this work. I’ll rethink the scope around that use case and aim for a smaller proposal with a clearer justification for the added complexity, in case if this idea is something that you would consider supporting in upstream Sashiko.

@rgushchin

Copy link
Copy Markdown
Member

Ah, ok. We actually need to find a way to share bugs between various sashiko instances, but not in a form of a single shared database. Ideally we need something like git in a way, where we can push and pull stuff between sashiko instances (with additional filtering). Does it sound like something that might work for you too?

Btw just curious what company you're working at and how do you use sashiko? if it's ok to share

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.

2 participants