Skip to content

_persist_history() truncates the live in-memory history instead of only the written data #1789

Closed

Description

@tleonhardt

Follow-up from #1787 (fix for #1785).

Cmd._persist_history() (cmd2/cmd2.py) calls self.history.truncate(self._persistent_history_length) to cut down the live History object before serializing it to the persistent history file.

Today this is harmless in normal use, because _persist_history() is only registered with atexit. If it ever runs while the app is still in use (a direct call from an app or a test, or a future change to call it periodically or on cmdloop() exit), the in-memory history silently loses its oldest items:

  • Every history command number shifts (e.g. old #5 becomes #2), so history -r N and similar selections can refer to different commands than the user saw.
  • The prompt-toolkit history (Cmd2History) is not truncated, so up-arrow history and cmd2 history no longer match.

Suggested fix: serialize only the most recent N items, e.g. self.history[-n:] or a copy, and leave the runtime History alone. max_length <= 0 should keep its current meaning. With that change, _persist_history() would no longer need truncate() at all.

Activity

  1. ungaaaabungaaa commented on Oct 30, 2026

    @ungaaaabungaaa
    Contributor

    I will work on preserving the live History object while _persist_history() writes a bounded temporary History copy. I will keep the existing file format and limit semantics, and test with synthetic history and temporary files. Codex will assist with implementation and validation. I understand that the normal current call is at exit; this is not an autosave or current data-loss incident.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions