Skip to content

fix: dump user sequences and skip system databases for -db all - #68

Merged
XuPeng-SH merged 17 commits into
matrixorigin:mainfrom
ck89119:issue-30577-main
Oct 28, 2026
Merged

XuPeng-SH merged 17 commits into
matrixorigin:mainfrom
ck89119:issue-30577-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Linked issues

Root cause

dumpData only dispatched ordinary tables, external tables and views, so any user sequence aborted the whole-database export (not supported: table ... table type: S), and -db all sent the built-in catalog relations of every tenant through the ordinary dispatcher, failing a clean tenant.

Fix

  • Sequences are exported before the tables that reference them. CREATE SEQUENCE is rebuilt from the sequence's live backing row — so the definition reflects the state after any ALTER SEQUENCE — and the allocation state is replayed with SELECT setval(seq, last, !is_called), verified against the current SETVAL semantics on MatrixOne main (direct UPDATE on the backing row is rejected for regular users). A restored sequence continues exactly where the source stopped: the issue reproducer dumped as (last=15, called) restores and yields nextval=20, not 15 or 10. -no-data exports the definition only and the restored sequence starts at START WITH.
  • -db all is a whole-user backup: the seven platform databases (information_schema, mo_catalog, mo_debug, mo_task, mysql, system, system_metrics) are skipped, and a tenant with no user database fails clearly instead of producing an empty success marker.
  • Output is staged for failure safety: the whole SQL script is spooled to a hidden file next to the csv artifacts and streamed to stdout only after export generation completes successfully; each csv data file is published by an atomic rename. Failures before stdout publication exit non-zero and leave stdout empty. Stdout publication itself is streaming, not atomic: a write failure (for example, ENOSPC or a closed pipe) can leave an already-written prefix, possibly including DROP DATABASE statements, that cannot be retracted and must not be restored. Such write failures exit non-zero and trigger cleanup of this run's staged and published csv files, without truncating or deleting previous backups. The csv reminder precedes the final complete MODUMP SUCCESS line; require both a zero exit status and that complete final line before treating the output as a backup.
  • Identifiers in emitted statements are backtick-quoted with embedded backticks doubled, so names like s`q round-trip.

Evidence

  • go test ./cmd/mo-dump green; package coverage 79.0% (new sequence.go 81-100% per function); gofmt/vet clean; golangci-lint (v2-converted config, --new-from-rev incremental) 0 issues.
  • New UT: sequence restore-SQL matrix (called/never-called, unsigned max, cycle, backtick names, missing/multi/bad state rows), stable sequence-before-tables/view-last ordering, -db all filtering, sink staging/publish/discard/cleanup, csv stage-then-rename on every path, helper-process exit-status cases including the all-system-databases error.
  • Real-service round trips on MatrixOne main (c0e826888b): issue reproducer dump/restore with nextval continuing at 20; normal-tenant -db all (two user DBs) dump/restore with nextval continuing at 104; clean tenant -db all fails clearly; -csv and -no-data modes; ALTERed sequence definition; exhausted sequence restores to the same Reached maximum value behavior; no staging leftovers.

Accepted tradeoffs / out of scope

  • Sequence state replay uses the three-argument SETVAL and therefore targets MatrixOne servers with the current (post-#30650) semantics; older servers do not guarantee that restore semantics.
  • root on the sys account running -db all still sees other tenants' databases (pre-existing getTables semantics); the documented -db all scope is a normal account's user databases.
  • LOAD DATA delimiter escaping and raw literal concatenation inside catalog queries are pre-existing behavior owned by the open restore-safety PR fix: make SQL/CSV dump scripts restore-safe (#30596 #30598 #30587 #30590 #30628 #30481) #58.

Whole-database export failed on any user database containing a sequence
(not supported: table ... type: S) and -db all failed in a clean tenant on
built-in catalog relations (matrixorigin#30577, matrixorigin#30601).

- dump sequences before the tables that reference them: CREATE SEQUENCE is
  rebuilt from the live backing row (definition after any ALTER) and the
  allocation state is replayed with SELECT setval(seq, last, !is_called)
  so a restored sequence continues without reusing consumed values;
  -no-data exports the definition only.
- -db all now skips the seven platform databases and fails clearly when
  no user database is visible.
- all output is staged: the SQL script is spooled to a hidden temp file
  and streamed to stdout only after the whole dump succeeded, and csv
  data files are published by atomic rename, so a failed run neither
  emits a DROP DATABASE-only partial script nor cuts a previous dump.
- identifiers in emitted statements are backtick-quoted (doubling
  embedded backticks); stage csv temp files are cleaned on every path.
Review findings on head 9a6f723, all reproduced before fixing:

- P1: csv publish replaced the previous backup's files partway and a later
  rename failure left the old script referencing mixed data. csv files are
  now published under per-run unique names (base.mo-dump-<id>, the staged
  hidden name minus its leading dot), so no run can ever overwrite or
  partially replace another set, and a failed run also removes csv files
  that were already renamed before the failure (publishedAll gate).
- P2: the sys account's mo_catalog view is not tenant-isolated and the new
  type query answered with another tenant's same-name sequence. Scope the
  metadata query with account_id = 0 under -sys and require the query to
  find exactly one row, failing clearly on ambiguity.
- P2: ALTER SEQUENCE can leave last_seq_num outside [min, max] (it
  pre-advances last in the session that called NEXTVAL), and the emitted
  setval is then rejected on restore while the dump claimed success. A
  state that SETVAL cannot replay exactly now fails the export with an
  explicit error.
Second review round on the PR, both findings reproduced before fixing:

- P2: the published csv name was only protected by the staged hidden
  name's CreateTemp uniqueness; a hidden-name slot becomes free after a
  run published, so a later run whose random suffix collides with an
  existing published file would rename onto it and could even delete it
  on a failed run. startCsv now reserves the final name exclusively with
  O_CREATE|O_EXCL before any data flows, retires a candidate on
  collision, and abort/discard release both the staged file and its
  reservation. Deterministically covered by the reservation unit tests.
- P2: a sequence whose allocation state cannot be replayed exactly (ALTER
  pre-advances last_seq_num on a called session, e.g. last=11 with
  MAXVALUE 10) was rejected unconditionally, which wrongly blocks
  -no-data dumps: those never replay the state while the definition is
  still legal and restores with NEXTVAL at START WITH 10. Validation is
  now split into checkSequenceDefinition (always, start within bounds)
  and checkSequenceAllocation (only for state-carrying dumps), the
  full-dump error points the operator at -no-data, and -no-data now
  returns stateSQL empty.
Third review round, reproduced with fixed candidates and a barrier:

After the publish rename a staged hidden name is no longer owned by the
run — it is back in the shared namespace and a concurrent run whose
random candidate collides can immediately hold a new staged file under
it. discard still removed tmp unconditionally, so a run whose publish
failed partway could delete a concurrent run's staged file and make its
publish fail with ENOENT.

Cleanup ownership now follows the rename: entries that were already
published are cleaned only at their exclusively reserved published
name, and the staged hidden name is removed only while the entry was
never published. Unit tests pin the mechanism: the staged name is
re-created by a stand-in concurrent run right after the rename, and
discard removes the published file while the concurrent staged file
survives; also green under -race for the sink group.
@ck89119
ck89119 marked this pull request as ready for review October 23, 2026 07:17
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-25T14:08:50.471884Z 3931bc2 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@mergify

mergify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f80d41cda6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread cmd/mo-dump/main.go Resolved
Comment thread cmd/mo-dump/output.go Resolved
Comment thread cmd/mo-dump/output.go Resolved
- csv field doc: ports -> tracks; dumpSink doc updated to the
  hidden-staged-name/until-rename-published wording
- discard doc now states the cleanup-ownership rule added for concurrent
  runs (renamed entries are cleaned at their reserved published name only)
- sequence dispatch comment: full sentence for the -no-data branch;
  showLoad comment: can not -> cannot
…put on top of the global view pipeline

mo/main merged PR matrixorigin#53 (global view ordering with persisted parser modes)
and the restore-safety hardening, while this branch added sequence export,
-db all system-database filtering and fully staged output. Conflict
resolution:

- dumpData keeps mo/main view collection (getDumpView/orderDumpViews/
  showDumpView, parameterized catalog queries) and routes every emission
  through the staged sink, including a new showDumpView sink parameter;
  the script shape otherwise matches mo/main (per-database headers,
  collected views emitted after all selected databases).
- Sequence export (CREATE SEQUENCE from the live backing row, setval
  state replay, -no-data definition-only) and reorderDumpObjects stay;
  views no longer take part in per-database ordering, so the partition is
  now two ranks with views carried by the global pipeline.
- -db all filtering, the empty-user-database clear error, newDumpSink
  staging, exclusive csv published-name reservation and ownership-scoped
  discard are preserved; the LOAD DATA path/target quoting follows
  mo/main quoteString/quoteIdentifier instead of the branch-local twins.
- internal/catalog gains SystemSequenceRel; TestDumpExitStatus keeps
  mo/main empty_default child while asserting the staged contract (a
  failed analysis publishes nothing); the merged view suites run through
  runDumpDataOverStdout, which mirrors dumpData output to real stdout for
  the capture fixtures; the identifier suites assert the staged csv/
  reservation pair at the genOutput layer.
…mits

Fourth review round on the branch, blocking finding plus the two
carried discussions:

- P2 (blocker): os.CreateTemp stages csv files as 0600, and rename kept
  that mode for the published data file. Restore pipelines run as a
  different Unix user more often than not, and the pre-merge behavior
  published 0644/0664 by the operator's umask. The mode is now probed
  once at process start (0666 &^ umask, same as os.Create) and applied
  on the staged name inside the exclusive reservation window, before the
  rename hands the name over. umask 022 publishes 0644, umask 002
  publishes 0664; unit tests pin the probe and the published Stat mode.
- The stdout atomicity claim was stronger than the mechanism: bytes
  already written to a failing stdout cannot be taken back. The script
  build stage still emits nothing until publication; publish now reports
  the exact byte count that escaped when the output channel fails, keeps
  the non-zero exit and no-success-marker contract, and the README states
  the boundary and the online-consistency limitation (no locks, not a
  snapshot) explicitly.
The merged view tests drive showDumpView and dumpData through the staged
sink (runDumpDataOverStdout for the capture fixtures, sinkOver(os.Stdout)
for direct showDumpView calls, io imports); without them the tree does
not compile against the merged signatures.
PR matrixorigin#65 (issue-30559) removed the legacy /*!EXTERNAL TABLE*/ marker from
the external-table section: a table name containing */ terminates block
comments early and a regular mysql client executes /*!...*/ content, so
the section carries no comment at all. The merge keeps that decision and
emits through the staged sink; TestDumpDataExternalTableCommentInjection
runs via runDumpDataOverStdout and the branch-side external-table script
expectation drops the marker line.
Fifth review round, one blocker and one test hygiene finding:

- P2 (blocker): writing to a stdout whose reader closed early killed the
  real CLI with SIGPIPE (exit signal 13, empty stderr), bypassing the
  deferred cleanup and leaving the staged spool and already-renamed csv
  files behind. main now ignores SIGPIPE before any work: Go escalates
  fd-1/2 SIGPIPE to a kill only while the signal is unhandled, so the
  same write surfaces as EPIPE inside publish, the error reports the
  emitted byte count, the exit code stays non-zero and discard runs.
  mo-dump | head therefore fails loudly and leaves nothing behind.
  TestDumpSinkPublishAgainstClosedStdout pins the contract (test process
  ignores SIGPIPE the same way so a regression cannot kill the binary):
  publish fails with EPIPE and the byte-count message, and discard
  removes the spool plus the renamed csv file.
- P3: TestDumpSinkPublishesUmaskMode ended by hardcoding umask 022
  without restoring the pre-test value (077 leaked as 022). Both umask
  tests now save the incoming umask and restore it in Cleanup, re-probing
  the publish mode so later tests observe a consistent pair.
@ck89119

ck89119 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b1f03aa7e5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread cmd/mo-dump/main.go Resolved
Comment thread cmd/mo-dump/main.go Resolved
- issue-30559 external-table comment justified the removal with the
  inverted argument (clients do execute /*!...*/ content; that is the
  risk, not a claim the marker is not executable SQL) — say what mysql
  clients do and why the section emits no comment at all
- reorderDumpObjects kept a rank explanation from the abandoned
  three-way partition (non-view prefix, registry loop) — the buffers
  are write cursors for a two-way stable partition
- TestDumpSinkPublishesUmaskMode cleanup dropped review-committee
  trivia; TestProbeFileMode doc simplified to the actual contract
- runDumpDataOverStdout: sub-prefix -> partial prefix
TestDumpDataExternalTableScript still claimed the emit was unchanged;
issue-30559 removed the /*!EXTERNAL TABLE*/ marker, so the doc now pins
the DROP/CREATE-only form.
Sixth review round, blocking: after sink.publish completed, the deferred
success marker and csv note writes ignored their errors, so a consumer
closing the pipe right after the published script let both SQL and csv
runs exit 0 with empty stderr (reproduced under normal and race probes).
The footnote emission is factored into writeSuccessFootnotes and the
deferred block now reports the failure on stderr and exits 1, leaving
nothing that claims a successful backup. Unit tests pin both failure
stages: the EPIPE marker write (SIGPIPE is already ignored) and the
failing csv note after a successful marker.
Seventh review round, one blocker and one test-hygiene finding:

- P2 (blocker): the tail-note failure branch exited 1 without cleaning
  up. os.Exit skips the remaining defers, and publish had already set
  publishedAll, so even a discard call would have been a no-op — two
  consecutive failing runs each stranded a newly published csv file,
  breaking the failed-run cleaning contract. main now declares the sink
  up front and the failing branch calls revoke before reporting:
  revoke resets the completion flag and runs the existing discard
  ownership rules, taking renamed csv files back. TestDumpSinkRevoke-
  RemovesPublishedFiles pins the contract: after a successful publish
  the file exists, revoke removes it with nothing left staged, and a
  following discard stays a no-op.
- P3: the two tests that ignore SIGPIPE now reset the disposition in
  Cleanup, restoring the Go default for the rest of the binary.
Eighth review round, one blocker and one test-hygiene finding:

- P2 (blocker): the csv-path reminder was written after the MODUMP
  SUCCESS marker, so a failing reminder write left a script whose final
  complete marker promised a successful backup while the deferred
  revoke withdrew the csv files — restoring it then failed on missing
  data files (exit 1 with a fully marked script). The marker is now the
  very last note: writing the csv reminder first makes any note failure
  keep the marker undelivered, so a visible MODUMP SUCCESS guarantees
  the script, the csv files and their reminder were all written. The
  unit test asserts the new order and that a failing csv note leaves no
  marker at all.
- P3: signal.Reset cannot undo a prior signal.Ignore (the Go contract
  only covers Notify), so both tests still leaked the changed SIGPIPE
  disposition into the whole test binary. TestWriteSuccessFootnotes now
  drives the error path with a stub EPIPE writer and touches no signal
  state at all; TestDumpSinkPublishAgainstClosedStdout moved into an
  exec'd child process (MO_DUMP_TEST_CLOSED_STDOUT=1) whose Ignore dies
  with the process, and the parent requires a clean child exit.
@ck89119

ck89119 commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

…he staged pipeline

mo/main merged PR matrixorigin#66 (issues #30562 / #30579): current_account_id()
scoping for getDatabaseType/getTables, mo_indexes-based hidden-helper
removal, explicit refusal (or -tbl opt-in) for ambiguous legacy
temporary rows, empty relkind exported as an ordinary table with
getCreateTable requiring a CREATE head, and account-scoped view
metadata reads.

Conflict resolution keeps this branch's behavior on top:

- dumpData preflight and emit cases absorb emptyRelKind into the merged
  ordinary/external branch; the sequence export (CREATE SEQUENCE from
  the live backing row, setval replay, -no-data definition-only), the
  staged sink emission, -db all filtering and the csv reservation/
  revoke chain are untouched.
- identifiers view/select case merges the account-scoped view SQL with
  the sink-parameter genOutput tail; exportTestStdout returns as a thin
  wrapper over the current swap, so the merged catalog-scope suites
  read captured output as before; the new dump_empty_kind tests run
  dumpData through runDumpDataOverStdout.
- All branch-side mock expectations move to dbScopePredicate /
  tablesScopePredicate / hiddenHelpersFor in one pass (-tbl selected
  runs keep the relname IN tail, whole-db runs drop it), and two
  merge remnants (an emptied if body and unused loop indexes) are
  cleaned up.

Green: full package tests, -race on the sink/footnote/dump groups,
vet/gofmt and incremental lint against the new merge base; coverage 85.6%.
@XuPeng-SH
XuPeng-SH merged commit 1fe1d16 into matrixorigin:main Oct 28, 2026
2 checks passed
@ck89119
ck89119 deleted the issue-30577-main branch October 28, 2026 03:51
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.

[Bug]: mo-dump full-database export must handle user sequences and built-in catalog relations

2 participants