Проблема
Я столкнулся с очевидным несоответствием при откате ревизии поста, содержащего BBCode событий (Event BBCode).
После отката к более ранней ревизии отрисованный онебокс (onebox) события отображает более раннюю дату, но при открытии редактора поста видно, что исходный BBCode [event] всё ещё содержит дату из более новой ревизии.
Расхождение сохранялось после перезагрузки темы.
Интересно, связано ли это с недавними изменениями в способе отображения повторяющихся онебоксов событий.
Шаги для воспроизведения
Начните с поста, содержащего BBCode событий, включая даты начала и окончания.
Отредактируйте событие, изменив его дату или время, и сохраните.
Откройте историю ревизий поста.
Выполните откат к более ранней ревизии.
Заметьте, что отображаемый онебокс события изменяется на более раннюю дату.
Откройте редактор поста и проверьте атрибуты [event start="..." end="..."].
Заметьте, что BBCode всё ещё содержит более новую дату, несмотря на явный откат.
Ожидаемое поведение
Если откат ревизии предназначен для восстановления исходных дат события, я ожидал бы, что и отображаемое событие, и исходный BBCode будут отражать восстановленные значения.
Или, если онебокс события намеренно отображает динамически вычисленное вхождение, отличающееся от сохраненного BBCode, было бы полезно прояснить, как это должно взаимодействовать с историей ревизий.
Фактическое поведение
Онебокс события отразил более раннюю дату, в то время как редактор поста продолжал показывать более новую дату в своём BBCode.
Я вручную исправил BBCode для восстановления согласованности.
Релевантные изменения в upstream
Я заметил, что недавний PR @awesomerobot добавил информацию о повторениях и обновил обработку вхождений для онебоксов событий:
main ← event-onebox-recurrence
This adds recurrence information to event oneboxes, including the end date (when… set)
<img width="700" alt="image" src="https://github.com/user-attachments/assets/56f9416d-4695-4ae3-a51d-c228c15c187b" />
To accomplish this it:
- Adds a schema.org `eventSchedule` to the event JSON-LD (frequency, day, week of the month, end date, timezone), and has the onebox read it.
- Stores the schedule in the onebox as a recurrence rule, and works out the current occurrence on the server with the existing `rrule` setup. Posts get it through a new `event_onebox_occurrences` serializer field, and emails get it through `reduce_cooked`, so neither shows a past date.
- Updates the date badge's `<time datetime>` together with the visible date.
Насколько я понимаю, это изменение позволяет повторяющимся онебоксам событий отображать текущее вхождение, используя информацию о повторениях, а не обязательно отображая исходную дату, сохраненную в разметке онебокса.
Я также столкнулся с конфликтом слияния в upstream, связанным с обработкой повторений событий, при обновлении моего отдельного, все еще открытого PR:
main ← Ethsim12:feature-recurring-event-topic-mode
## Summary
Adds an opt-in mode for recurring Events where each completed occurr… ence is preserved in its own Topic and the next occurrence is created in a successor Topic.
The new `discourse_post_event_recurring_topic_mode` enum site setting has two values:
- `reuse_topic` — existing behavior and the default
- `create_next_topic` — archive the completed occurrence Topic and create a successor Topic for the next occurrence
The existing reuse-topic behavior is retained. Successor-topic creation applies only when the new mode is explicitly enabled.
Administrator-controlled changes to the site setting apply to existing and newly established recurring Events. Changes affect subsequent rollovers without retrospectively creating separate Topics for earlier occurrences. Series RSVPs are preserved when switching between modes.
## Details
When `create_next_topic` is enabled, the scheduled event-date monitor:
- preserves the completed Topic by converting its recurring Event into a one-off occurrence, retaining the completed dates and attendance
- renames the archived Topic using a distinctive date-bearing title, such as `Meeting (archived event on 2026-09-03)`, respecting title-length and duplicate-title validation
- creates a successor Topic from the original post content, advancing the Event start/end dates while preserving unrelated content and Event attributes
- preserves the category, tags, original displayed author and recurring Event metadata
- carries forward recurring `going` invitees while leaving one-off attendance associated with the completed occurrence
- links consecutive Topics so readers can follow the recurring series without accumulating older continuation links in later successors
- performs archival and successor creation transactionally, so a failed rollover leaves the occurrence pending for retry without partially archiving the Event
- emits the `discourse_post_event_event_ended` workflow trigger with the completed occurrence's recurring-series metadata
If the recurrence has no next occurrence, the completed Topic is retained as a one-off Event and no successor Topic is created.
### Archived Topic titles
The archived title initially uses the format:
`{original title} (archived event on {YYYY-MM-DD})`
The title is truncated where necessary to respect `SiteSetting.max_topic_title_length`, while preserving as much of the distinguishing suffix as possible.
Rather than querying for duplicate titles before every archival revision, the implementation relies on Discourse's existing Topic validation. If `PostRevisor#revise!` fails solely because the archived title is already in use, it retries with an additional Topic ID or numbered suffix.
The generic suffix-generation logic is implemented in `Topic#title_with_disambiguating_suffix`. Retries are bounded to five attempts, and unrelated revision failures are not retried.
The retry is attached to `PostRevisor`, because archival renames the **existing Topic**. `PostCreator.create!` subsequently creates the successor using the original title.
Duplicate-title validation retains Discourse's normal category and visibility rules, including the treatment of Topics hidden from the original author.
### Recurrence and editing
The implementation preserves the original recurrence anchor separately from the displayed occurrence start date. This allows successor Topics to retain recurrence patterns such as the last weekday of a month without drifting to a different ordinal weekday.
The Event serializer and frontend recurrence handling use this anchor when reconstructing the recurring schedule. Explicit changes to the recurrence pattern or relevant dates can update the anchor.
The successor service also:
- distinguishes rendered Event markup from examples inside fenced code blocks
- recognises unquoted BBCode attribute values containing characters such as apostrophes
- rewrites actual Event attributes positionally, without altering attribute-like words inside quoted names or locations
- handles differently capitalised aliases of Event attributes
- preserves seconds and fractional seconds in timed Event attributes where present, avoiding unintended changes to Event dates during archival
- preserves completed Event dates and RSVP information when archiving an occurrence, including Events without an explicit end time
- handles Events removed from a successor Topic and subsequently recreated without inheriting stale recurrence-anchor data
Generic BBCode parsing and attribute rewriting have been extracted from the successor service into reusable core functionality.
The implementation uses the `BbcodeRewriter` scan/mark/rewrite path. The separate, unused token-based `PrettyText.update_bbcode_attributes` API was removed from this PR in `6d13371`, avoiding two parallel rewriting mechanisms.
### Rendering principal and delegated edits
Displayed authorship is kept separate from the permissions used to render user-editable raw.
A post now persists a `rendering_user_id` representing the human principal whose permissions should bound cooking and post-processing of the current raw. This allows a delegated wiki editor to correct or maintain another user's recurring Event without causing the content to be recooked using the displayed author's broader permissions.
The persisted rendering principal is used across:
- ordinary cooking and rebakes
- full and inline oneboxes
- localized cooked-post processing
- queued `ProcessPost` jobs
- successor creation and subsequent rollovers
Human raw edits update the persisted rendering principal to the editor responsible for the changed content.
A queued post-processing job cannot overwrite a newer persisted principal with stale job arguments. Grace-period edits are also handled correctly even when they create no `PostRevision`: rollover prefers the current persisted post principal before revision history or inherited Topic metadata.
Mechanical system raw rewrites, including `Jobs::UpdateHotlinkedRaw`, preserve the existing human rendering principal instead of replacing it with `Discourse.system_user`.
This lets authorised delegated edits remain durable without rendering copied or rewritten content using permissions broader than those of the human responsible for the current raw.
### Generated rollover content and post-length validation
Successor creation adds system-generated content such as the continuation link and may also lengthen serialized Event attributes.
A valid Event close to `max_post_length` must therefore not fail solely because trusted rollover automation increases the raw length.
The service calculates the exact positive generated-length overhead and supplies a narrowly bounded allowance during automated successor creation.
That allowance is persisted for later occurrences so a near-limit successor can itself be archived and rolled over again. Archival also accounts for positive growth introduced by the archival rewrite, such as longer normalized hostnames or offset-bearing timestamps.
The allowance does not truncate or delete user-authored content.
Ordinary later edits of a valid oversized successor are also supported. The persisted allowance is reused only while the raw still begins with the exact system-generated continuation prefix stored for that successor. If that generated prefix is removed or modified, validation falls back to the normal post-length limit.
This prevents the persisted overhead value from becoming a general-purpose larger `max_post_length` allowance.
### Access control and moderation
Successor-topic creation is restricted to eligible standard Topics.
Recurring Events in private messages continue using their existing Topic, preserving the original private-message access restrictions rather than creating potentially public successors.
Shared drafts are also excluded from successor-topic rollover. A shared draft cannot be automatically copied into an ordinary Topic in the shared-drafts storage category without its `SharedDraft` access model; publication therefore continues to require the normal shared-draft publication flow.
Automated successor creation uses the system user as the acting user for creation and required Event validation. The original Topic author remains the displayed author of the successor, while the persisted rendering principal separately bounds rendering of the copied raw.
An established recurrence is treated as authorization for its scheduled successors. A later ordinary category ACL or Event-creation permission change does not automatically cancel the series.
In particular, the rollover path does not re-check `can_create_topic_on_category?` on every occurrence. This preserves the established behaviour that a series validly created before a later permission change can continue even though the author would no longer be able to create a new Topic manually.
Successor creation is still deferred when the source itself is no longer safe or eligible for automated publication, including when:
- the displayed author is suspended, silenced, inactive, staged or otherwise prevented from posting
- the original post is hidden or deleted
- the source Topic is non-visible or deleted
- the author can no longer see the source Topic
- the source is a shared draft or non-standard archetype
Trusted system-user revisions and metadata-only edits do not invalidate an established recurrence.
Authorised human raw edits also no longer automatically break the series. Instead, the current human rendering principal is persisted and carried forward so later cooking and rollover remain bounded by the permissions of the human responsible for the raw.
#### Authorization when establishing recurrence
A human establishing successor-topic recurrence must have permission to create Topics in the relevant category.
This prevents delegated wiki editors from establishing successor-topic recurrence in categories where they cannot create Topics directly.
Once established, the recurring series retains its authorization following ordinary permission changes. Re-establishing a completed recurrence requires the relevant authorization again.
Administrator-controlled changes from `reuse_topic` to `create_next_topic` also apply to existing recurring Events.
Regression coverage includes delegated wiki editors in reply-only categories, subsequent loss of ordinary topic-create permission, and attempts to re-establish completed recurrence without the required authorization.
#### Open policy question
Whether explicit account-level moderation of the persisted human rendering principal — for example later suspension or silencing — should independently defer rollover when the displayed author remains eligible remains a separate product-policy question.
### Event hosts
A recurring Event may retain hosts who subsequently become ineligible to host a newly created Event.
During rollover:
- the archived occurrence retains its existing eligible or ineligible host associations for historical accuracy
- archived hostnames are reconstructed from persisted host associations, avoiding failures caused by renamed or stale usernames
- the successor inherits only hosts who currently satisfy the relevant account and category eligibility requirements
- rollover can continue when no eligible hosts remain
This prevents an inherited suspended, inactive or otherwise ineligible host from repeatedly blocking successor creation.
### Service architecture and failure isolation
Successor creation uses Discourse's `Service::Base` framework, including parameter validation, model resolution, a `rollover_allowed` policy and transactional service steps.
The scheduled monitor handles exceptions separately for each Event date, logging the affected occurrence without preventing the remaining pending Events from being processed.
Failed successor creation rolls back the archival transaction. A subsequent monitor run can retry the occurrence without leaving a partially archived Event or duplicate successor.
When policy prevents rollover, the occurrence remains pending rather than being partially archived or republished.
Diagnostic warnings for deferred rollover are rate-limited so the scheduled monitor does not emit the same warning on every run.
## UI smoke test
The original UI and scheduled-job smoke tests were performed with `discourse_post_event_recurring_topic_mode` set to `create_next_topic`.
**Site setting**
<img width="678" height="142" alt="01-admin-setting-create-next-topic" src="https://github.com/user-attachments/assets/78dc6698-6886-4c10-81d4-22d991f0f452" />
**Before rollover — recurring occurrence on September 3**
<img width="1512" height="958" alt="02-before-rollover-sep-3-every-thursday" src="https://github.com/user-attachments/assets/3150b843-1264-4990-8dd8-2e931e28b9dc" />
**Completed occurrence preserved in the archived Topic**
<img width="2048" height="1076" alt="03-archived-topic-2026-09-03" src="https://github.com/user-attachments/assets/d6d28341-f684-4ba8-9b54-2fec0c537bb7" />
**Successor Topic created for the next weekly occurrence**
<img width="2048" height="1073" alt="04-successor-topic-sep-10-every-thursday" src="https://github.com/user-attachments/assets/0ff611b4-f316-4130-bb75-7948d36e61e9" />
These initial smoke tests confirmed that the completed Topic was preserved with a dated title and that a successor Topic was created for the following weekly occurrence, including through the normal supervised Sidekiq scheduler.
**Note:** These screenshots were captured before the subsequent review-driven changes, including the revised archived-title format. They demonstrate the original end-to-end functionality rather than the exact appearance of the latest implementation.
## Updated video demonstration
The following demonstration uses simulated time to illustrate the reviewed implementation across multiple recurring Event occurrences, including administrator-controlled changes to the site setting in both directions.
https://youtu.be/gDC9aSAhO-s
| Video timestamp | Simulated time (GMT) | Demonstration |
|---|---|---|
| [00:00](https://youtu.be/gDC9aSAhO-s?t=0s) | 30 Nov 2026, 12:00 | Initial configuration and recurring Event creation |
| [02:49](https://youtu.be/gDC9aSAhO-s?t=169s) | 30 Nov, 18:01 | First successor Topic creation |
| [05:12](https://youtu.be/gDC9aSAhO-s?t=312s) | 7 Dec, 12:00 | Intermediate calendar inspection |
| [06:00](https://youtu.be/gDC9aSAhO-s?t=360s) | 14 Dec, 17:59 | Inspection of the successor Event before completion |
| [07:19](https://youtu.be/gDC9aSAhO-s?t=439s) | 14 Dec, 18:01 | Second successor Topic creation and RSVP preservation |
| [09:52](https://youtu.be/gDC9aSAhO-s?t=592s) | 28 Dec, 18:01 | Further successor Topic creation |
| [13:32](https://youtu.be/gDC9aSAhO-s?t=812s) | 28 Dec, 18:01 | Creation of a new recurring Event, "Testing retrospective behaviour", using `reuse_topic` |
| [14:07](https://youtu.be/gDC9aSAhO-s?t=847s) | 11 Jan 2027, 18:01 | First rollover of the new series, with historical calendar retention |
| [19:27](https://youtu.be/gDC9aSAhO-s?t=1167s) | 24 Jan, 18:01 | Existing series transitioned to `create_next_topic` without retrospective Topic creation |
| [24:48](https://youtu.be/gDC9aSAhO-s?t=1488s) | 7 Feb, 18:01 | Transition back to `reuse_topic` with RSVP preservation |
| [27:03](https://youtu.be/gDC9aSAhO-s?t=1623s) | 21 Feb, 18:01 | Further rollover confirming continued RSVP preservation and historical calendar retention |
The demonstration complements the automated regression coverage by illustrating:
- successor Topic creation across multiple occurrences
- preservation of completed discussions and series RSVPs
- application of site setting changes to existing recurring Events
- prospective successor Topic creation without retrospective Topic creation
- continued series RSVP preservation following a return to `reuse_topic`
## Regression testing
The full Events backend test suite passed locally with 1,582 examples and no failures.
Я разрешил этот конфликт, сохранив обработку повторений из upstream и удержав поведение привязки повторений (recurrence-anchor), необходимое для реализации последующих тем.
Я упоминаю об этом для контекста разработки, а не для того, чтобы предположить, что PR #43187 ответственен за поведение, наблюдаемое на моём сайте.
Окружение
Вопросы
Можно ли проверить взаимодействие между откатом ревизии поста, сохраненным BBCode событий и новой обработкой повторений онебоксов событий?
В частности:
Ожидается ли, что откат ревизии может изменить онебокс события без восстановления соответствующих атрибутов BBCode?
Может ли новая логика вычисления вхождений объяснить, почему отображаемая дата меняется независимо от исходного кода поста, сохраненного в базе?
Если исходный BBCode должен был быть откатан, является ли это пробелом в процессе восстановления ревизий?
Буду признателен за уточнение, является ли это ожидаемым поведением или регрессией.