From 32d1a481c3228269bf465a21544b7b277d262bb1 Mon Sep 17 00:00:00 2001 From: xhaktm00 <153787023+xhaktm00@users.noreply.github.com> Date: Fri, 7 Aug 2026 11:24:52 +0900 Subject: [PATCH 1/5] [ZEPPELIN-6563] Detect diverged paragraph text in collaborative mode patch_apply never throws: it drops a hunk whose context is gone, and fuzzy matching can place one at the wrong offset while still reporting success, so neither shape is visible to the receiver. A diverged client then commits its whole paragraph and the server stores it unconditionally, making that text authoritative for everyone. Senders now attach checksums of their text before and after the patch. A receiver that started from the same text but did not reach the same result knows it diverged and asks for that single paragraph again via GET_PARAGRAPH, instead of refetching the whole note. Commits carry the checksum of the text the client believed the server held, and the server keeps its own copy when they disagree. Both fields are optional, so clients that omit them behave as before. PatchParagraphSend and PatchParagraphReceived were mapped to the opposite directions, which left the receiving side without noteId or the new fields; they are swapped to match what is actually sent and received. --- .../org/apache/zeppelin/common/Message.java | 1 + .../zeppelin/service/NotebookService.java | 54 +++++++++++++++++++ .../zeppelin/socket/NotebookServer.java | 42 ++++++++++++++- .../zeppelin/service/NotebookServiceTest.java | 35 ++++++++++++ .../projects/zeppelin-sdk/src/checksum.ts | 23 ++++++++ .../message-data-type-map.interface.ts | 6 ++- .../interfaces/message-operator.interface.ts | 1 + .../interfaces/message-paragraph.interface.ts | 18 ++++++- .../projects/zeppelin-sdk/src/message.ts | 25 +++++++-- .../projects/zeppelin-sdk/src/public-api.ts | 1 + .../app/core/paragraph-base/paragraph-base.ts | 11 +++- .../paragraph/paragraph-patch.spec.ts | 19 +++++++ .../notebook/paragraph/paragraph-patch.ts | 12 ++++- .../notebook/paragraph/paragraph.component.ts | 24 +++++++-- .../src/app/services/message.service.ts | 27 ++++++++-- 15 files changed, 278 insertions(+), 21 deletions(-) create mode 100644 zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts diff --git a/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java b/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java index b7d1ff1d4ab..de2e37d8b77 100644 --- a/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java +++ b/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java @@ -196,6 +196,7 @@ public enum OP { INTERPRETER_INSTALL_RESULT, // [s-c] Status of an interpreter installation COLLABORATIVE_MODE_STATUS, // [s-c] collaborative mode status PATCH_PARAGRAPH, // [c-s][s-c] patch editor text + GET_PARAGRAPH, // [c-s] resend a single paragraph after a failed patch NOTE_RUNNING_STATUS, // [s-c] sequential run status will be change NOTICE, // [s-c] Notice ASSISTANT_SEND_MESSAGE, // [c-s] send a message to the notebook assistant diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java index 7b509e8bda2..75f61860f8e 100644 --- a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java +++ b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java @@ -786,6 +786,23 @@ public void updateParagraph(String noteId, Map config, ServiceContext context, ServiceCallback callback) throws IOException { + updateParagraph(noteId, paragraphId, title, text, params, config, null, context, callback); + } + + /** + * @param baseChecksum checksum of the text the client believed the server held, or null to skip + * the check. When it does not match, the client text is stale or diverged, + * so it is not stored and the server copy is sent back instead. + */ + public void updateParagraph(String noteId, + String paragraphId, + String title, + String text, + Map params, + Map config, + Integer baseChecksum, + ServiceContext context, + ServiceCallback callback) throws IOException { if (!checkPermission(noteId, Permission.WRITER, Message.OP.COMMIT_PARAGRAPH, context, callback)) { return; @@ -802,6 +819,11 @@ public void updateParagraph(String noteId, callback.onFailure(new ParagraphNotFoundException(paragraphId), context); return null; } + if (baseChecksum != null && baseChecksum != checksum(p.getText())) { + LOGGER.info("Rejecting stale commit of paragraph {} in note {}", paragraphId, noteId); + callback.onSuccess(p, context); + return null; + } // In personalized mode only the note owner may update the master paragraph, so that // new users inherit the owner's changes while a non-owner's changes stay in their copy. if (!note.isPersonalizedMode() @@ -1507,6 +1529,38 @@ public void patchParagraph(final String noteId, final String paragraphId, String } } + /** + * Resend a single paragraph to a client whose patched text diverged, so that the note as a + * whole does not have to be reloaded. + */ + public void getParagraph(String noteId, String paragraphId, ServiceContext context, + ServiceCallback callback) throws IOException { + if (!checkPermission(noteId, Permission.READER, Message.OP.GET_PARAGRAPH, context, callback)) { + return; + } + notebook.processNote(noteId, + note -> { + if (note == null) { + callback.onFailure(new NoteNotFoundException(noteId), context); + return null; + } + Paragraph p = note.getParagraph(paragraphId); + if (p == null) { + callback.onFailure(new ParagraphNotFoundException(paragraphId), context); + return null; + } + callback.onSuccess(p, context); + return null; + }); + } + + /** + * Same algorithm as {@link String#hashCode()} so that the client can compute it identically. + */ + static int checksum(String text) { + return text == null ? "".hashCode() : text.hashCode(); + } + enum Permission { READER, diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java index d9d4e77d8e2..671ad9d7158 100644 --- a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java +++ b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java @@ -609,6 +609,9 @@ public void onMessage(NotebookSocket conn, String msg) { case ASSISTANT_SEND_MESSAGE: sendAssistantMessage(conn, context, receivedMessage); break; + case GET_PARAGRAPH: + getParagraph(conn, context, receivedMessage); + break; default: break; } @@ -1236,8 +1239,11 @@ private void updateParagraph(NotebookSocket conn, ServiceContext context, Messag String text = (String) fromMessage.get("paragraph"); Map params = (Map) fromMessage.get("params"); Map config = (Map) fromMessage.get("config"); + Integer baseChecksum = fromMessage.get("baseChecksum") == null + ? null : ((Number) fromMessage.get("baseChecksum")).intValue(); - getNotebookService().updateParagraph(noteId, paragraphId, title, text, params, config, context, + getNotebookService().updateParagraph(noteId, paragraphId, title, text, params, config, + baseChecksum, context, new WebSocketServiceCallback(conn) { @Override public void onSuccess(Paragraph p, ServiceContext context) throws IOException { @@ -1275,6 +1281,10 @@ private void patchParagraph(NotebookSocket conn, if (patchText == null) { return; } + // checksums of the sender's text before and after the patch, so receivers can tell whether + // their own patchApply produced the same text. Absent for clients that do not send them. + Object baseChecksum = fromMessage.get("baseChecksum"); + Object afterChecksum = fromMessage.get("afterChecksum"); getNotebookService().patchParagraph(noteId, paragraphId, patchText, context, new WebSocketServiceCallback(conn) { @@ -1283,7 +1293,10 @@ public void onSuccess(String result, ServiceContext context) throws IOException super.onSuccess(result, context); Message message = new Message(OP.PATCH_PARAGRAPH) .put("patch", result) - .put("paragraphId", paragraphId); + .put("paragraphId", paragraphId) + .put("noteId", noteId2) + .put("baseChecksum", baseChecksum) + .put("afterChecksum", afterChecksum); connectionManager.broadcastExcept(noteId2, message, conn); } }); @@ -1317,6 +1330,31 @@ private void sendAssistantMessage( ); } + private void getParagraph(NotebookSocket conn, + ServiceContext context, + Message fromMessage) throws IOException { + String paragraphId = fromMessage.getType("id", LOGGER); + if (paragraphId == null) { + return; + } + String noteId = connectionManager.getAssociatedNoteId(conn); + if (noteId == null) { + noteId = fromMessage.getType("noteId", LOGGER); + if (noteId == null) { + return; + } + } + + getNotebookService().getParagraph(noteId, paragraphId, context, + new WebSocketServiceCallback(conn) { + @Override + public void onSuccess(Paragraph p, ServiceContext context) throws IOException { + super.onSuccess(p, context); + conn.send(serializeMessage(new Message(OP.PARAGRAPH).put("paragraph", p))); + } + }); + } + private void cloneNote(NotebookSocket conn, ServiceContext context, Message fromMessage) throws IOException { diff --git a/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java b/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java index d9c23718e9e..57be82ddbd8 100644 --- a/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java +++ b/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java @@ -875,4 +875,39 @@ void testNormalizeFolderPath() throws IOException { assertThrows(IOException.class, () -> notebookService.normalizeFolderPath(null)); } + + @Test + void testUpdateParagraphChecksIsBasedOnCurrentServerText() throws IOException { + String noteId = notebookService.createNote("/note_checksum", "test", true, context, callback); + String paragraphId = notebook.processNote(noteId, note -> { + Paragraph p = note.getParagraph(0); + p.setText("server text"); + return p.getId(); + }); + + // a commit based on the text the server holds is stored + notebookService.updateParagraph(noteId, paragraphId, "title", "agreed text", + new HashMap<>(), new HashMap<>(), "server text".hashCode(), context, callback); + notebook.processNote(noteId, note -> { + assertEquals("agreed text", note.getParagraph(paragraphId).getText()); + return null; + }); + + // a commit based on text the server no longer holds is rejected, keeping the server copy + notebookService.updateParagraph(noteId, paragraphId, "stale title", "diverged text", + new HashMap<>(), new HashMap<>(), "text nobody has".hashCode(), context, callback); + notebook.processNote(noteId, note -> { + assertEquals("agreed text", note.getParagraph(paragraphId).getText()); + assertEquals("title", note.getParagraph(paragraphId).getTitle()); + return null; + }); + + // clients that send no checksum keep the previous behaviour + notebookService.updateParagraph(noteId, paragraphId, "no checksum", "text without checksum", + new HashMap<>(), new HashMap<>(), context, callback); + notebook.processNote(noteId, note -> { + assertEquals("text without checksum", note.getParagraph(paragraphId).getText()); + return null; + }); + } } diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts new file mode 100644 index 00000000000..fa28394647c --- /dev/null +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts @@ -0,0 +1,23 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Same algorithm as java.lang.String#hashCode(), so a checksum computed here matches the one + * NotebookService computes for the same text. + */ +export function textChecksum(text: string): number { + let hash = 0; + for (let i = 0; i < text.length; i++) { + hash = (Math.imul(31, hash) + text.charCodeAt(i)) | 0; + } + return hash; +} diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts index 1e94acdb846..2d2a3b1bbd0 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts @@ -77,6 +77,7 @@ import { ParagraphRemoved, ParagraphStatus, ParagraphUpdateOutput, + GetParagraph, ParasInfo, PatchParagraphReceived, PatchParagraphSend, @@ -116,7 +117,7 @@ export interface MessageReceiveDataTypeMap { [OP.PARAGRAPH]: UpdateParagraph; [OP.PARAGRAPH_APPEND_OUTPUT]: ParagraphAppendOutput; [OP.PARAGRAPH_UPDATE_OUTPUT]: ParagraphUpdateOutput; - [OP.PATCH_PARAGRAPH]: PatchParagraphSend; + [OP.PATCH_PARAGRAPH]: PatchParagraphReceived; [OP.PARAGRAPH_REMOVED]: ParagraphRemoved; [OP.EDITOR_SETTING]: EditorSettingReceived; [OP.PROGRESS]: Progress; @@ -168,7 +169,8 @@ export interface MessageSendDataTypeMap { [OP.PARAGRAPH_CLEAR_ALL_OUTPUT]: ParagraphClearAllOutput; [OP.COMPLETION]: Completion; [OP.COMMIT_PARAGRAPH]: CommitParagraph; - [OP.PATCH_PARAGRAPH]: PatchParagraphReceived; + [OP.PATCH_PARAGRAPH]: PatchParagraphSend; + [OP.GET_PARAGRAPH]: GetParagraph; [OP.IMPORT_NOTE]: ImportNote; [OP.CHECKPOINT_NOTE]: CheckpointNote; [OP.SET_NOTE_REVISION]: SetNoteRevision; diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts index a72942b1b97..48ca211eb88 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts @@ -468,6 +468,7 @@ export enum OP { * patch editor text */ PATCH_PARAGRAPH = 'PATCH_PARAGRAPH', + GET_PARAGRAPH = 'GET_PARAGRAPH', /** * [s-c] diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts index 2b98bfc6910..d51a1ec1085 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts @@ -212,6 +212,8 @@ export interface RunParagraph extends SendParagraph { export interface CommitParagraph extends SendParagraph { noteId: string; + // checksum of the text this client believed the server held; absent for older clients + baseChecksum?: number; } export interface RunAllParagraphs { @@ -315,14 +317,26 @@ export interface CompletionReceived { } export interface PatchParagraphReceived { - id: string; + paragraphId: string; noteId: string; patch: string; + // checksums of the sender's text before and after the patch; absent for older clients + baseChecksum?: number; + afterChecksum?: number; +} + +export interface GetParagraph { + id: string; + noteId: string; } export interface PatchParagraphSend { - paragraphId: string; + id: string; + noteId: string; patch: string; + // checksums of this client's text before and after the patch; let receivers verify the result + baseChecksum?: number; + afterChecksum?: number; } export interface ParagraphRemoved { diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts index 2f1ec939fa5..d14c79128a9 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts @@ -419,7 +419,8 @@ export class Message { paragraphData: string, paragraphConfig: ParagraphConfig, paragraphParams: ParagraphConfig, - noteId: string + noteId: string, + baseChecksum?: number ): string { return this.send(OP.COMMIT_PARAGRAPH, { id: paragraphId, @@ -427,18 +428,34 @@ export class Message { title: paragraphTitle, paragraph: paragraphData, config: paragraphConfig, - params: paragraphParams + params: paragraphParams, + baseChecksum }); } - patchParagraph(paragraphId: string, noteId: string, patch: string): void { + patchParagraph( + paragraphId: string, + noteId: string, + patch: string, + baseChecksum?: number, + afterChecksum?: number + ): void { // javascript add "," if change contains several patches // but java library requires patch list without "," const normalPatch = patch.replace(/,@@/g, '@@'); this.send(OP.PATCH_PARAGRAPH, { id: paragraphId, noteId, - patch: normalPatch + patch: normalPatch, + baseChecksum, + afterChecksum + }); + } + + getParagraph(paragraphId: string, noteId: string): void { + this.send(OP.GET_PARAGRAPH, { + id: paragraphId, + noteId }); } diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts index 7ae587d3811..d24c2a90806 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts @@ -13,6 +13,7 @@ export * from './angular-object'; export * from './assistant'; export * from './assistant-ui'; +export * from './checksum'; export * from './interfaces/public-api'; export * from './message'; export * from './paragraph-state'; diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts index aabdd3ecb0d..628e0530cc1 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts @@ -28,7 +28,8 @@ import { isTerminalParagraphState, ParagraphItem, ParagraphIResultsMsgItem, - WebSocketMessage + WebSocketMessage, + textChecksum } from '@zeppelin/sdk'; import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch'; @@ -206,8 +207,16 @@ export abstract class ParagraphBase extends MessageListenersManager { if (!this.paragraph.text) { this.paragraph.text = ''; } + // patch_apply never throws: it drops a hunk it cannot place, and fuzzy matching can apply + // one at the wrong offset while still reporting success. Comparing against the sender's + // checksums is the only way to tell both apart. + const startedFromSameText = data.baseChecksum === textChecksum(this.paragraph.text); this.paragraph.text = this.diffMatchPatch.patch_apply(patch, this.paragraph.text)[0]; this.originalText = this.paragraph.text; + if (startedFromSameText && data.afterChecksum !== textChecksum(this.paragraph.text)) { + // we no longer hold the text the sender produced, so ask for this paragraph again + this.messageService.getParagraph(this.paragraph.id, data.noteId); + } this.cdr.markForCheck(); } } diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts index cb72ffe5144..7e01ce35471 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts @@ -13,6 +13,8 @@ import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch'; import { describe, expect, it } from 'vitest'; +import { textChecksum } from '@zeppelin/sdk'; + import { makeParagraphPatch } from './paragraph-patch'; describe('makeParagraphPatch', () => { @@ -29,4 +31,21 @@ describe('makeParagraphPatch', () => { it('rejects text that was never set', () => { expect(() => makeParagraphPatch(new DiffMatchPatch(), 'abc', undefined)).toThrow('dirtyText is required'); }); + + it('carries checksums of the text before and after the patch', () => { + const { baseChecksum, afterChecksum } = makeParagraphPatch(new DiffMatchPatch(), 'alpha', 'alpha!'); + + // a receiver compares these against its own text to tell an applied patch from a dropped or + // misapplied one, so they have to describe the sender's text on both sides of the edit + expect(baseChecksum).toBe(textChecksum('alpha')); + expect(afterChecksum).toBe(textChecksum('alpha!')); + expect(baseChecksum).not.toBe(afterChecksum); + }); + + it('treats missing original text as empty when checksumming', () => { + const { baseChecksum } = makeParagraphPatch(new DiffMatchPatch(), undefined, 'alpha'); + + // the server checksums "" for a paragraph it has no text for, so the first patch must agree + expect(baseChecksum).toBe(textChecksum('')); + }); }); diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts index 0888a70763a..206a834c1c1 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts @@ -12,21 +12,29 @@ import * as DiffMatchPatch from 'diff-match-patch'; +import { textChecksum } from '@zeppelin/sdk'; + /** * Builds the patch a collaborating client sends after an edit. An empty string is a valid * paragraph state, so only text that was never set is rejected. + * + * The checksums let a receiver tell whether its own patch_apply reached the same text as the + * sender: patch_apply drops a hunk it cannot place and can also apply one at the wrong offset + * while reporting success, neither of which is visible from the result alone. */ export function makeParagraphPatch( diffMatchPatch: DiffMatchPatch, originalText: string | undefined, dirtyText: string | undefined -): { patch: string; originalText: string } { +): { patch: string; originalText: string; baseChecksum: number; afterChecksum: number } { if (dirtyText === undefined) { throw new Error('dirtyText is required'); } const previousText = originalText ? originalText : ''; return { patch: diffMatchPatch.patch_make(previousText, dirtyText).toString(), - originalText: dirtyText + originalText: dirtyText, + baseChecksum: textChecksum(previousText), + afterChecksum: textChecksum(dirtyText) }; } diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts index bd788f81890..2594980fd6a 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts @@ -41,7 +41,8 @@ import { Note, ParagraphConfigResult, ParagraphItem, - ParagraphIResultsMsgItem + ParagraphIResultsMsgItem, + textChecksum } from '@zeppelin/sdk'; import { MessageService, @@ -200,9 +201,13 @@ export class NotebookParagraphComponent } sendPatch() { - const { patch, originalText } = makeParagraphPatch(this.diffMatchPatch, this.originalText, this.dirtyText); + const { patch, originalText, baseChecksum, afterChecksum } = makeParagraphPatch( + this.diffMatchPatch, + this.originalText, + this.dirtyText + ); this.originalText = originalText; - this.messageService.patchParagraph(this.paragraph.id, this.note.id, patch); + this.messageService.patchParagraph(this.paragraph.id, this.note.id, patch, baseChecksum, afterChecksum); } startSaveTimer() { @@ -513,7 +518,18 @@ export class NotebookParagraphComponent config, settings: { params } } = this.paragraph; - const msgId = this.messageService.commitParagraph(id, title, text, config, params, this.note.id); + // in collaborative mode let the server reject this commit when our text is based on a + // paragraph state the server no longer holds + const baseChecksum = this.collaborativeMode ? textChecksum(this.originalText || '') : undefined; + const msgId = this.messageService.commitParagraph( + id, + title, + text, + config, + params, + this.note.id, + baseChecksum + ); this.trackParagraphSave(msgId); this.cdr.markForCheck(); } diff --git a/zeppelin-web-angular/src/app/services/message.service.ts b/zeppelin-web-angular/src/app/services/message.service.ts index 5559cfbebe3..1067eff5c4e 100644 --- a/zeppelin-web-angular/src/app/services/message.service.ts +++ b/zeppelin-web-angular/src/app/services/message.service.ts @@ -255,13 +255,32 @@ export class MessageService extends Message implements OnDestroy { paragraphData: string, paragraphConfig: ParagraphConfig, paragraphParams: ParagraphConfig, - noteId: string + noteId: string, + baseChecksum?: number ): string { - return super.commitParagraph(paragraphId, paragraphTitle, paragraphData, paragraphConfig, paragraphParams, noteId); + return super.commitParagraph( + paragraphId, + paragraphTitle, + paragraphData, + paragraphConfig, + paragraphParams, + noteId, + baseChecksum + ); + } + + patchParagraph( + paragraphId: string, + noteId: string, + patch: string, + baseChecksum?: number, + afterChecksum?: number + ): void { + super.patchParagraph(paragraphId, noteId, patch, baseChecksum, afterChecksum); } - patchParagraph(paragraphId: string, noteId: string, patch: string): void { - super.patchParagraph(paragraphId, noteId, patch); + getParagraph(paragraphId: string, noteId: string): void { + super.getParagraph(paragraphId, noteId); } importNote(note: ImportNote['note']): void { From 4ceb67a667a3782857629e74e0df5de109b035e8 Mon Sep 17 00:00:00 2001 From: xhaktm00 <153787023+xhaktm00@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:22:16 +0900 Subject: [PATCH 2/5] [ZEPPELIN-6563] Checksum the paragraph the client edits, and keep edits made during recovery Addresses two correctness cases raised in review. In personalized mode GET_NOTE hands the client its own copy of a paragraph, but updateParagraph() compared baseChecksum against the master paragraph, because the switch to the user copy happened after the guard. Once the two texts differ, a valid commit from a non-owner is rejected, and the rejection answered with the master paragraph, so the client had no way back to the copy it was editing. getParagraph() had the same problem. Both now resolve the paragraph the client edits before using it. getUserParagraph() clones the master when no copy exists yet, so a first edit still compares equal. A diverged patch makes the client ask for the paragraph again. That answer carries text the client has not seen, and an edit typed while the request was in flight is not in it. The reply now echoes the request msgId, the way the other paragraph broadcasts already do, and the client tracks recovery requests separately from saves: pendingParagraphSaves acknowledges text this client sent, while a recovery answer must not discard what came after it. The later edit stays in dirtyText and the editor re-bases on the server text. Verified with: ./mvnw test -pl zeppelin-server --am -Dtest=NotebookServiceTest cd zeppelin-web-angular && npm run test:shell 16 server tests and 251 frontend tests pass. Reverting each fix fails the matching test rather than passing by construction: expected: but was: expected: but was: AssertionError: expected undefined to be 'edit typed while waiting' --- .../zeppelin/service/NotebookService.java | 12 ++- .../zeppelin/socket/NotebookServer.java | 4 +- .../zeppelin/service/NotebookServiceTest.java | 65 ++++++++++++++ .../interfaces/message-operator.interface.ts | 7 ++ .../projects/zeppelin-sdk/src/message.ts | 4 +- .../paragraph-base/paragraph-base.spec.ts | 89 ++++++++++++++++++- .../app/core/paragraph-base/paragraph-base.ts | 23 ++++- .../src/app/services/message.service.ts | 4 +- 8 files changed, 197 insertions(+), 11 deletions(-) diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java index 75f61860f8e..e87634b35f8 100644 --- a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java +++ b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java @@ -819,9 +819,13 @@ public void updateParagraph(String noteId, callback.onFailure(new ParagraphNotFoundException(paragraphId), context); return null; } - if (baseChecksum != null && baseChecksum != checksum(p.getText())) { + // The client edits the paragraph GET_NOTE handed it, which in personalized mode is the + // user's copy, so that is the text its checksum describes and the one to send back. + Paragraph edited = note.isPersonalizedMode() + ? p.getUserParagraph(context.getAutheInfo().getUser()) : p; + if (baseChecksum != null && baseChecksum != checksum(edited.getText())) { LOGGER.info("Rejecting stale commit of paragraph {} in note {}", paragraphId, noteId); - callback.onSuccess(p, context); + callback.onSuccess(edited, context); return null; } // In personalized mode only the note owner may update the master paragraph, so that @@ -1549,7 +1553,9 @@ public void getParagraph(String noteId, String paragraphId, ServiceContext conte callback.onFailure(new ParagraphNotFoundException(paragraphId), context); return null; } - callback.onSuccess(p, context); + // Answer with the copy the client is editing, matching what GET_NOTE handed it. + callback.onSuccess(note.isPersonalizedMode() + ? p.getUserParagraph(context.getAutheInfo().getUser()) : p, context); return null; }); } diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java index 671ad9d7158..8327ac7e86f 100644 --- a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java +++ b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java @@ -1350,7 +1350,9 @@ private void getParagraph(NotebookSocket conn, @Override public void onSuccess(Paragraph p, ServiceContext context) throws IOException { super.onSuccess(p, context); - conn.send(serializeMessage(new Message(OP.PARAGRAPH).put("paragraph", p))); + conn.send(serializeMessage(new Message(OP.PARAGRAPH) + .withMsgId(fromMessage.msgId) + .put("paragraph", p))); } }); } diff --git a/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java b/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java index 57be82ddbd8..09ea2ee079b 100644 --- a/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java +++ b/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java @@ -876,6 +876,71 @@ void testNormalizeFolderPath() throws IOException { assertThrows(IOException.class, () -> notebookService.normalizeFolderPath(null)); } + @Test + void testUpdateParagraphChecksumUsesTheUserCopyInPersonalizedMode() throws IOException { + String noteId = notebookService.createNote("/note_personalized_checksum", "test", true, + context, callback); + // make "admin" the owner so that "user1" below edits only its own copy + authorizationService.setOwners(noteId, Collections.singleton("admin")); + ServiceContext user1Context = new ServiceContext(new AuthenticationInfo("user1"), + new HashSet<>(Collections.singleton("user1"))); + + String paragraphId = notebook.processNote(noteId, + note -> { + note.setPersonalizedMode(true); + Paragraph p = note.getParagraph(0); + p.setText("master text"); + // user1 has already diverged from the master copy, which is what GET_NOTE handed it + p.getUserParagraph("user1").setText("user1 text"); + return p.getId(); + }); + + // a commit based on the user's own text is stored, even though the master text differs + notebookService.updateParagraph(noteId, paragraphId, "user1 title", "user1 edit", + new HashMap<>(), new HashMap<>(), "user1 text".hashCode(), user1Context, callback); + notebook.processNote(noteId, + note -> { + Paragraph p = note.getParagraph(paragraphId); + assertEquals("user1 edit", p.getUserParagraph("user1").getText()); + assertEquals("master text", p.getText()); + return null; + }); + + // the master text is not a valid base for a non-owner, so a commit using it is rejected + notebookService.updateParagraph(noteId, paragraphId, "stale title", "stale edit", + new HashMap<>(), new HashMap<>(), "master text".hashCode(), user1Context, callback); + notebook.processNote(noteId, + note -> { + assertEquals("user1 edit", + note.getParagraph(paragraphId).getUserParagraph("user1").getText()); + return null; + }); + } + + @Test + void testGetParagraphReturnsTheUserCopyInPersonalizedMode() throws IOException { + String noteId = notebookService.createNote("/note_personalized_get", "test", true, + context, callback); + authorizationService.setOwners(noteId, Collections.singleton("admin")); + ServiceContext user1Context = new ServiceContext(new AuthenticationInfo("user1"), + new HashSet<>(Collections.singleton("user1"))); + + String paragraphId = notebook.processNote(noteId, + note -> { + note.setPersonalizedMode(true); + Paragraph p = note.getParagraph(0); + p.setText("master text"); + p.getUserParagraph("user1").setText("user1 text"); + return p.getId(); + }); + + reset(callback); + notebookService.getParagraph(noteId, paragraphId, user1Context, callback); + ArgumentCaptor captor = ArgumentCaptor.forClass(Paragraph.class); + verify(callback).onSuccess(captor.capture(), any(ServiceContext.class)); + assertEquals("user1 text", captor.getValue().getText()); + } + @Test void testUpdateParagraphChecksIsBasedOnCurrentServerText() throws IOException { String noteId = notebookService.createNote("/note_checksum", "test", true, context, callback); diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts index 48ca211eb88..63b7336f6ce 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts @@ -468,6 +468,13 @@ export enum OP { * patch editor text */ PATCH_PARAGRAPH = 'PATCH_PARAGRAPH', + + /** + * [c-s] + * resend a single paragraph after a failed patch + * @param id paragraph id + * @param noteId note id + */ GET_PARAGRAPH = 'GET_PARAGRAPH', /** diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts index d14c79128a9..fa0756d5c3c 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts @@ -452,8 +452,8 @@ export class Message { }); } - getParagraph(paragraphId: string, noteId: string): void { - this.send(OP.GET_PARAGRAPH, { + getParagraph(paragraphId: string, noteId: string): string { + return this.send(OP.GET_PARAGRAPH, { id: paragraphId, noteId }); diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts index 9f0c179f196..53feffa4d68 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts @@ -11,7 +11,7 @@ */ import { ChangeDetectorRef } from '@angular/core'; -import { DatasetType, Message, OP, ParagraphItem, ParagraphState } from '@zeppelin/sdk'; +import { DatasetType, Message, OP, ParagraphItem, ParagraphState, textChecksum } from '@zeppelin/sdk'; import { EMPTY } from 'rxjs'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -302,6 +302,93 @@ const createSaveTestParagraph = (text: string, dirtyText?: string): SaveTestPara return paragraph; }; +describe('ParagraphBase recovery responses', () => { + const createRecoveryParagraph = (serverText: string) => { + const getParagraph = vi.fn(() => 'fetch-1'); + const paragraph = new SaveTestParagraph( + { receive: () => EMPTY, receiveEnvelope: () => EMPTY, getParagraph } as unknown as Message, + { isParagraphRunning: () => false, isEntireNoteRunning: () => false }, + { + setContextValue: vi.fn(), + unsetContextValue: vi.fn(), + contextChanged: () => EMPTY, + runParagraphAction: () => EMPTY + } as unknown as AngularContextManager, + { markForCheck: vi.fn() } as unknown as ChangeDetectorRef + ); + paragraph.paragraph = { id: 'A', text: serverText } as ParagraphItem; + paragraph.originalText = serverText; + saveTestParagraphs.push(paragraph); + return { paragraph, getParagraph }; + }; + + // A patch that cannot be reproduced locally makes the client ask for the paragraph again. The + // answer carries text the client has not seen, so an edit typed meanwhile is not in it. + const divergeAndRequestRecovery = (paragraph: SaveTestParagraph) => { + const patch = paragraph.diffMatchPatch.patch_make('server text', 'sender text').toString(); + paragraph.patchParagraph({ + paragraphId: 'A', + noteId: 'note', + patch, + baseChecksum: textChecksum('server text'), + // a checksum the local apply cannot produce, which is what marks the text as diverged + afterChecksum: textChecksum('text nobody holds') + }); + }; + + it('asks for the paragraph again when a patch does not reproduce the sender text', () => { + const { paragraph, getParagraph } = createRecoveryParagraph('server text'); + + divergeAndRequestRecovery(paragraph); + + expect(getParagraph).toHaveBeenCalledWith('A', 'note'); + }); + + it('keeps an edit made while the recovery request was in flight', () => { + const { paragraph } = createRecoveryParagraph('server text'); + divergeAndRequestRecovery(paragraph); + const diverged = paragraph.paragraph!.text; + paragraph.dirtyText = 'edit typed while waiting'; + + paragraph.updateAllScopeTexts( + { text: diverged } as ParagraphItem, + { text: 'recovered text' } as ParagraphItem, + 'fetch-1' + ); + + // the editor re-bases on the server text, and the later edit is still pending + expect(paragraph.paragraph?.text).toBe('recovered text'); + expect(paragraph.originalText).toBe('recovered text'); + expect(paragraph.dirtyText).toBe('edit typed while waiting'); + }); + + it('clears the local edit when the recovery answer already contains it', () => { + const { paragraph } = createRecoveryParagraph('server text'); + divergeAndRequestRecovery(paragraph); + const diverged = paragraph.paragraph!.text; + + paragraph.updateAllScopeTexts( + { text: diverged } as ParagraphItem, + { text: 'recovered text' } as ParagraphItem, + 'fetch-1' + ); + + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('does not treat an unrelated broadcast as a recovery answer', () => { + const { paragraph } = createRecoveryParagraph('server text'); + divergeAndRequestRecovery(paragraph); + const diverged = paragraph.paragraph!.text; + paragraph.dirtyText = 'local edit'; + + paragraph.updateAllScopeTexts({ text: diverged } as ParagraphItem, { text: 'someone else text' } as ParagraphItem); + + // without a matching msgId this is an ordinary remote edit, which keeps the existing behaviour + expect(paragraph.dirtyText).toBeUndefined(); + }); +}); + describe('ParagraphBase save responses', () => { it.each(['latest edit', ''])('preserves an unsaved edit %j when a broadcast carries the saved text', dirtyText => { const paragraph = createSaveTestParagraph(dirtyText, dirtyText); diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts index 628e0530cc1..ed354e76bb2 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts @@ -62,6 +62,9 @@ export abstract class ParagraphBase extends MessageListenersManager { private readonly outputState = new ParagraphOutputState(); private readonly pendingParagraphSaves = new Map(); private paragraphSaveSequence = 0; + // Recovery requests are tracked apart from saves: a save acknowledges text this client sent, + // while a recovery answer carries text it has not seen and must not discard edits made since. + private readonly pendingParagraphFetches = new Map(); constructor( public messageService: Message, @@ -215,7 +218,8 @@ export abstract class ParagraphBase extends MessageListenersManager { this.originalText = this.paragraph.text; if (startedFromSameText && data.afterChecksum !== textChecksum(this.paragraph.text)) { // we no longer hold the text the sender produced, so ask for this paragraph again - this.messageService.getParagraph(this.paragraph.id, data.noteId); + const msgId = this.messageService.getParagraph(this.paragraph.id, data.noteId); + this.pendingParagraphFetches.set(msgId, { dirtyText: this.dirtyText }); } this.cdr.markForCheck(); } @@ -379,6 +383,7 @@ export abstract class ParagraphBase extends MessageListenersManager { throw new Error('paragraph is not defined'); } const { acknowledged, hasNewerSave } = this.consumeParagraphSave(msgId, newPara.text); + const recovery = this.consumeParagraphFetch(msgId); if (oldPara.text !== newPara.text) { const hasLocalEdit = this.dirtyText !== undefined && this.dirtyText !== newPara.text; @@ -386,13 +391,27 @@ export abstract class ParagraphBase extends MessageListenersManager { const staleBroadcastOfSavedText = hasLocalEdit && this.originalText === newPara.text; if (!staleSaveAcknowledgement && !staleBroadcastOfSavedText) { this.paragraph.text = newPara.text; - this.dirtyText = undefined; + // A recovery answer re-bases the editor on the server text, but an edit typed while the + // request was in flight is not in it, so that edit stays pending instead of being lost. + this.dirtyText = recovery !== undefined && this.dirtyText !== recovery.dirtyText ? this.dirtyText : undefined; this.originalText = newPara.text; } } this.cdr.markForCheck(); } + /** Reports whether this message answers a recovery request, and what was pending when it was sent. */ + private consumeParagraphFetch(msgId: string | undefined): { dirtyText?: string } | undefined { + if (msgId === undefined) { + return undefined; + } + const pendingFetch = this.pendingParagraphFetches.get(msgId); + if (pendingFetch !== undefined) { + this.pendingParagraphFetches.delete(msgId); + } + return pendingFetch; + } + updateParagraphObjectWhenUpdated(newPara: ParagraphItem) { if (!this.paragraph) { throw new Error('paragraph is not defined'); diff --git a/zeppelin-web-angular/src/app/services/message.service.ts b/zeppelin-web-angular/src/app/services/message.service.ts index 1067eff5c4e..07ef62498a6 100644 --- a/zeppelin-web-angular/src/app/services/message.service.ts +++ b/zeppelin-web-angular/src/app/services/message.service.ts @@ -279,8 +279,8 @@ export class MessageService extends Message implements OnDestroy { super.patchParagraph(paragraphId, noteId, patch, baseChecksum, afterChecksum); } - getParagraph(paragraphId: string, noteId: string): void { - super.getParagraph(paragraphId, noteId); + getParagraph(paragraphId: string, noteId: string): string { + return super.getParagraph(paragraphId, noteId); } importNote(note: ImportNote['note']): void { From 5a8003e3d7f441f18918e562ee1253a407f88067 Mon Sep 17 00:00:00 2001 From: xhaktm00 <153787023+xhaktm00@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:35:22 +0900 Subject: [PATCH 3/5] [ZEPPELIN-6563] Recover from a rejected commit without losing pending edits Replay the patches sent while a checked commit is pending onto the server's answer, so the next commit cannot overwrite the server. --- .../paragraph-base/paragraph-base.spec.ts | 63 ++++++++++++++++++- .../app/core/paragraph-base/paragraph-base.ts | 42 ++++++++++--- .../notebook/paragraph/paragraph-patch.ts | 12 +++- .../notebook/paragraph/paragraph.component.ts | 15 ++--- 4 files changed, 107 insertions(+), 25 deletions(-) diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts index 53feffa4d68..c5f14edc012 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts @@ -269,8 +269,16 @@ class SaveTestParagraph extends ParagraphBase { changeColWidth(): void {} updateParagraphResult(): void {} - trackSave(msgId: string): void { - this.trackParagraphSave(msgId); + trackSave(msgId: string, checked?: boolean): void { + this.trackParagraphSave(msgId, checked); + } + + /** Types `text` in collaborative mode, which sends it to the server as a patch right away. */ + type(text: string): void { + this.recordOwnPatch(this.diffMatchPatch.patch_make(this.originalText!, text)); + this.paragraph!.text = text; + this.originalText = text; + this.dirtyText = text; } } @@ -567,3 +575,54 @@ describe('ParagraphBase save responses', () => { expect(paragraph.originalText).toBe('previous save'); }); }); + +describe('ParagraphBase rejected commits', () => { + // In collaborative mode a commit carries the checksum of the text it was based on, and the + // server answers a stale one with its own text instead of storing the commit. + const commitInCollaborativeMode = (text: string) => { + const paragraph = createSaveTestParagraph(text, text); + paragraph.originalText = text; + paragraph.trackSave('save-a', true); + return paragraph; + }; + + it('takes the server text when a commit is rejected', () => { + const paragraph = commitInCollaborativeMode('select a'); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'select a!' } as ParagraphItem, 'save-a'); + + expect(paragraph.paragraph?.text).toBe('select a!'); + expect(paragraph.originalText).toBe('select a!'); + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('keeps an edit typed while the rejected commit was waiting', () => { + const paragraph = commitInCollaborativeMode('select a'); + paragraph.type('select a, b'); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'select a -- B' } as ParagraphItem, 'save-a'); + + // the server applied the same patch after answering, so both now hold this text + expect(paragraph.paragraph?.text).toBe('select a, b -- B'); + expect(paragraph.originalText).toBe('select a, b -- B'); + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('does not apply a remote edit twice when it arrives before the rejection', () => { + const paragraph = commitInCollaborativeMode('select a'); + paragraph.paragraph!.id = 'A'; + // the server stored this edit before the commit, so the rejection already carries it + paragraph.patchParagraph({ + paragraphId: 'A', + noteId: 'note', + patch: paragraph.diffMatchPatch.patch_make('select a!', 'select a! -- B').toString(), + baseChecksum: textChecksum('select a!'), + afterChecksum: textChecksum('select a! -- B') + }); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'select a! -- B' } as ParagraphItem, 'save-a'); + + expect(paragraph.paragraph?.text).toBe('select a! -- B'); + expect(paragraph.originalText).toBe('select a! -- B'); + }); +}); diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts index ed354e76bb2..a1fcd63c8c8 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts @@ -60,7 +60,10 @@ export abstract class ParagraphBase extends MessageListenersManager { colWidthOption = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; editorSetting: ParagraphEditorSetting = {}; private readonly outputState = new ParagraphOutputState(); - private readonly pendingParagraphSaves = new Map(); + private readonly pendingParagraphSaves = new Map< + string, + { sequence: number; originalText?: string; checked: boolean; ownPatches: Array } + >(); private paragraphSaveSequence = 0; // Recovery requests are tracked apart from saves: a save acknowledges text this client sent, // while a recovery answer carries text it has not seen and must not discard edits made since. @@ -349,17 +352,29 @@ export abstract class ParagraphBase extends MessageListenersManager { ); } - protected trackParagraphSave(msgId: string): void { - this.pendingParagraphSaves.set(msgId, { sequence: ++this.paragraphSaveSequence, originalText: this.originalText }); + /** `checked` marks a commit that carries a base checksum, so the server may reject it. */ + protected trackParagraphSave(msgId: string, checked = false): void { + this.pendingParagraphSaves.set(msgId, { + sequence: ++this.paragraphSaveSequence, + originalText: this.originalText, + checked, + ownPatches: [] + }); + } + + protected recordOwnPatch(patches: Array): void { + for (const pendingSave of this.pendingParagraphSaves.values()) { + pendingSave.ownPatches.push(...patches); + } } private consumeParagraphSave( msgId: string | undefined, savedText: string - ): { acknowledged: boolean; hasNewerSave: boolean } { + ): { acknowledged: boolean; hasNewerSave: boolean; rebased: boolean } { const pendingSave = msgId === undefined ? undefined : this.pendingParagraphSaves.get(msgId); if (pendingSave === undefined) { - return { acknowledged: false, hasNewerSave: false }; + return { acknowledged: false, hasNewerSave: false, rebased: false }; } const hasNewerSave = Array.from(this.pendingParagraphSaves.values()).some( ({ sequence }) => sequence > pendingSave.sequence @@ -371,21 +386,28 @@ export abstract class ParagraphBase extends MessageListenersManager { this.pendingParagraphSaves.delete(pendingMsgId); } } - // Skip when a newer save or a patch has already moved the saved baseline past this acknowledgement. - if (!hasNewerSave && this.originalText === pendingSave.originalText) { + // A checked commit is answered with the text the server held then: the committed text, or its + // own text when it rejected the commit. The patches sent since then reached the server after + // that answer, so replaying them onto it gives the text the server holds now. + if (pendingSave.checked && this.paragraph) { + this.paragraph.text = this.diffMatchPatch.patch_apply(pendingSave.ownPatches, savedText)[0]; + this.originalText = this.paragraph.text; + this.dirtyText = undefined; + } else if (!hasNewerSave && this.originalText === pendingSave.originalText) { + // Skip when a newer save or a patch has already moved the saved baseline past this acknowledgement. this.originalText = savedText; } - return { acknowledged: true, hasNewerSave }; + return { acknowledged: true, hasNewerSave, rebased: pendingSave.checked }; } updateAllScopeTexts(oldPara: ParagraphItem, newPara: ParagraphItem, msgId?: string) { if (!this.paragraph) { throw new Error('paragraph is not defined'); } - const { acknowledged, hasNewerSave } = this.consumeParagraphSave(msgId, newPara.text); + const { acknowledged, hasNewerSave, rebased } = this.consumeParagraphSave(msgId, newPara.text); const recovery = this.consumeParagraphFetch(msgId); - if (oldPara.text !== newPara.text) { + if (!rebased && oldPara.text !== newPara.text) { const hasLocalEdit = this.dirtyText !== undefined && this.dirtyText !== newPara.text; const staleSaveAcknowledgement = acknowledged && (hasLocalEdit || hasNewerSave); const staleBroadcastOfSavedText = hasLocalEdit && this.originalText === newPara.text; diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts index 206a834c1c1..95836d15542 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts @@ -26,13 +26,21 @@ export function makeParagraphPatch( diffMatchPatch: DiffMatchPatch, originalText: string | undefined, dirtyText: string | undefined -): { patch: string; originalText: string; baseChecksum: number; afterChecksum: number } { +): { + patch: string; + patches: Array; + originalText: string; + baseChecksum: number; + afterChecksum: number; +} { if (dirtyText === undefined) { throw new Error('dirtyText is required'); } const previousText = originalText ? originalText : ''; + const patches = diffMatchPatch.patch_make(previousText, dirtyText); return { - patch: diffMatchPatch.patch_make(previousText, dirtyText).toString(), + patch: patches.toString(), + patches, originalText: dirtyText, baseChecksum: textChecksum(previousText), afterChecksum: textChecksum(dirtyText) diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts index 2594980fd6a..330ae4cb7a6 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts @@ -201,12 +201,13 @@ export class NotebookParagraphComponent } sendPatch() { - const { patch, originalText, baseChecksum, afterChecksum } = makeParagraphPatch( + const { patch, patches, originalText, baseChecksum, afterChecksum } = makeParagraphPatch( this.diffMatchPatch, this.originalText, this.dirtyText ); this.originalText = originalText; + this.recordOwnPatch(patches); this.messageService.patchParagraph(this.paragraph.id, this.note.id, patch, baseChecksum, afterChecksum); } @@ -521,16 +522,8 @@ export class NotebookParagraphComponent // in collaborative mode let the server reject this commit when our text is based on a // paragraph state the server no longer holds const baseChecksum = this.collaborativeMode ? textChecksum(this.originalText || '') : undefined; - const msgId = this.messageService.commitParagraph( - id, - title, - text, - config, - params, - this.note.id, - baseChecksum - ); - this.trackParagraphSave(msgId); + const msgId = this.messageService.commitParagraph(id, title, text, config, params, this.note.id, baseChecksum); + this.trackParagraphSave(msgId, baseChecksum !== undefined); this.cdr.markForCheck(); } From 464692525927bee750144f3fbd5c6269fba729ff Mon Sep 17 00:00:00 2001 From: xhaktm00 <153787023+xhaktm00@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:45:05 +0900 Subject: [PATCH 4/5] [ZEPPELIN-6563] Keep edits typed while a recovery request is in flight Replay the patches sent since GET_PARAGRAPH onto its answer, as a rejected commit already does. --- .../paragraph-base/paragraph-base.spec.ts | 17 +++----- .../app/core/paragraph-base/paragraph-base.ts | 40 +++++++++++-------- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts index c5f14edc012..96553a9425a 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts @@ -355,19 +355,14 @@ describe('ParagraphBase recovery responses', () => { it('keeps an edit made while the recovery request was in flight', () => { const { paragraph } = createRecoveryParagraph('server text'); divergeAndRequestRecovery(paragraph); - const diverged = paragraph.paragraph!.text; - paragraph.dirtyText = 'edit typed while waiting'; + paragraph.type(`${paragraph.paragraph!.text}!`); - paragraph.updateAllScopeTexts( - { text: diverged } as ParagraphItem, - { text: 'recovered text' } as ParagraphItem, - 'fetch-1' - ); + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'recovered text' } as ParagraphItem, 'fetch-1'); - // the editor re-bases on the server text, and the later edit is still pending - expect(paragraph.paragraph?.text).toBe('recovered text'); - expect(paragraph.originalText).toBe('recovered text'); - expect(paragraph.dirtyText).toBe('edit typed while waiting'); + // the server applied the same patch after answering, so both now hold this text + expect(paragraph.paragraph?.text).toBe('recovered text!'); + expect(paragraph.originalText).toBe('recovered text!'); + expect(paragraph.dirtyText).toBeUndefined(); }); it('clears the local edit when the recovery answer already contains it', () => { diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts index a1fcd63c8c8..6634e1d7f08 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts @@ -67,7 +67,7 @@ export abstract class ParagraphBase extends MessageListenersManager { private paragraphSaveSequence = 0; // Recovery requests are tracked apart from saves: a save acknowledges text this client sent, // while a recovery answer carries text it has not seen and must not discard edits made since. - private readonly pendingParagraphFetches = new Map(); + private readonly pendingParagraphFetches = new Map }>(); constructor( public messageService: Message, @@ -222,7 +222,7 @@ export abstract class ParagraphBase extends MessageListenersManager { if (startedFromSameText && data.afterChecksum !== textChecksum(this.paragraph.text)) { // we no longer hold the text the sender produced, so ask for this paragraph again const msgId = this.messageService.getParagraph(this.paragraph.id, data.noteId); - this.pendingParagraphFetches.set(msgId, { dirtyText: this.dirtyText }); + this.pendingParagraphFetches.set(msgId, { ownPatches: [] }); } this.cdr.markForCheck(); } @@ -363,8 +363,17 @@ export abstract class ParagraphBase extends MessageListenersManager { } protected recordOwnPatch(patches: Array): void { - for (const pendingSave of this.pendingParagraphSaves.values()) { - pendingSave.ownPatches.push(...patches); + for (const pending of [...this.pendingParagraphSaves.values(), ...this.pendingParagraphFetches.values()]) { + pending.ownPatches.push(...patches); + } + } + + /** The patches sent after `serverText` reached the server after it, so replaying them gives its current text. */ + private rebaseOnServerText(serverText: string, ownPatches: Array): void { + if (this.paragraph) { + this.paragraph.text = this.diffMatchPatch.patch_apply(ownPatches, serverText)[0]; + this.originalText = this.paragraph.text; + this.dirtyText = undefined; } } @@ -387,12 +396,9 @@ export abstract class ParagraphBase extends MessageListenersManager { } } // A checked commit is answered with the text the server held then: the committed text, or its - // own text when it rejected the commit. The patches sent since then reached the server after - // that answer, so replaying them onto it gives the text the server holds now. - if (pendingSave.checked && this.paragraph) { - this.paragraph.text = this.diffMatchPatch.patch_apply(pendingSave.ownPatches, savedText)[0]; - this.originalText = this.paragraph.text; - this.dirtyText = undefined; + // own text when it rejected the commit. + if (pendingSave.checked) { + this.rebaseOnServerText(savedText, pendingSave.ownPatches); } else if (!hasNewerSave && this.originalText === pendingSave.originalText) { // Skip when a newer save or a patch has already moved the saved baseline past this acknowledgement. this.originalText = savedText; @@ -407,23 +413,25 @@ export abstract class ParagraphBase extends MessageListenersManager { const { acknowledged, hasNewerSave, rebased } = this.consumeParagraphSave(msgId, newPara.text); const recovery = this.consumeParagraphFetch(msgId); - if (!rebased && oldPara.text !== newPara.text) { + if (recovery !== undefined) { + this.rebaseOnServerText(newPara.text, recovery.ownPatches); + } else if (!rebased && oldPara.text !== newPara.text) { const hasLocalEdit = this.dirtyText !== undefined && this.dirtyText !== newPara.text; const staleSaveAcknowledgement = acknowledged && (hasLocalEdit || hasNewerSave); const staleBroadcastOfSavedText = hasLocalEdit && this.originalText === newPara.text; if (!staleSaveAcknowledgement && !staleBroadcastOfSavedText) { this.paragraph.text = newPara.text; - // A recovery answer re-bases the editor on the server text, but an edit typed while the - // request was in flight is not in it, so that edit stays pending instead of being lost. - this.dirtyText = recovery !== undefined && this.dirtyText !== recovery.dirtyText ? this.dirtyText : undefined; + this.dirtyText = undefined; this.originalText = newPara.text; } } this.cdr.markForCheck(); } - /** Reports whether this message answers a recovery request, and what was pending when it was sent. */ - private consumeParagraphFetch(msgId: string | undefined): { dirtyText?: string } | undefined { + /** Reports whether this message answers a recovery request, and the patches sent since then. */ + private consumeParagraphFetch( + msgId: string | undefined + ): { ownPatches: Array } | undefined { if (msgId === undefined) { return undefined; } From 7e5cf8dd18480b81b367af881418f74aa318d4c0 Mon Sep 17 00:00:00 2001 From: xhaktm00 <153787023+xhaktm00@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:38:06 +0900 Subject: [PATCH 5/5] [ZEPPELIN-6563] Replay sent patches one message at a time The server applies each patch message on its own, so replaying them as one list could misplace or drop edits once the texts diverged. --- .../paragraph-base/paragraph-base.spec.ts | 11 +++++++++ .../app/core/paragraph-base/paragraph-base.ts | 23 +++++++++++-------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts index 96553a9425a..dd5f462ba39 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts @@ -603,6 +603,17 @@ describe('ParagraphBase rejected commits', () => { expect(paragraph.dirtyText).toBeUndefined(); }); + it('replays each sent patch in order, as the server applies them', () => { + const paragraph = commitInCollaborativeMode('a'); + paragraph.type('ab'); + paragraph.type('abc'); + + // the server text has diverged, so applying both patches as one list lands them wrongly + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: '' } as ParagraphItem, 'save-a'); + + expect(paragraph.paragraph?.text).toBe('bc'); + }); + it('does not apply a remote edit twice when it arrives before the rejection', () => { const paragraph = commitInCollaborativeMode('select a'); paragraph.paragraph!.id = 'A'; diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts index 6634e1d7f08..797db1ff20b 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts @@ -44,6 +44,9 @@ import { AngularContextManager } from './angular-context-manager'; import { NoteStatus } from './note-status'; import { ParagraphOutputState } from './paragraph-output-state'; +/** The patches of one patch message this client sent. */ +type SentPatch = Array; + export const ParagraphStatus = ParagraphStates; export abstract class ParagraphBase extends MessageListenersManager { @@ -60,14 +63,15 @@ export abstract class ParagraphBase extends MessageListenersManager { colWidthOption = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; editorSetting: ParagraphEditorSetting = {}; private readonly outputState = new ParagraphOutputState(); + // One entry per patch message sent, since the server applies each message on its own. private readonly pendingParagraphSaves = new Map< string, - { sequence: number; originalText?: string; checked: boolean; ownPatches: Array } + { sequence: number; originalText?: string; checked: boolean; ownPatches: SentPatch[] } >(); private paragraphSaveSequence = 0; // Recovery requests are tracked apart from saves: a save acknowledges text this client sent, // while a recovery answer carries text it has not seen and must not discard edits made since. - private readonly pendingParagraphFetches = new Map }>(); + private readonly pendingParagraphFetches = new Map(); constructor( public messageService: Message, @@ -362,16 +366,19 @@ export abstract class ParagraphBase extends MessageListenersManager { }); } - protected recordOwnPatch(patches: Array): void { + protected recordOwnPatch(patches: SentPatch): void { for (const pending of [...this.pendingParagraphSaves.values(), ...this.pendingParagraphFetches.values()]) { - pending.ownPatches.push(...patches); + pending.ownPatches.push(patches); } } /** The patches sent after `serverText` reached the server after it, so replaying them gives its current text. */ - private rebaseOnServerText(serverText: string, ownPatches: Array): void { + private rebaseOnServerText(serverText: string, ownPatches: SentPatch[]): void { if (this.paragraph) { - this.paragraph.text = this.diffMatchPatch.patch_apply(ownPatches, serverText)[0]; + this.paragraph.text = ownPatches.reduce( + (text, patches) => this.diffMatchPatch.patch_apply(patches, text)[0], + serverText + ); this.originalText = this.paragraph.text; this.dirtyText = undefined; } @@ -429,9 +436,7 @@ export abstract class ParagraphBase extends MessageListenersManager { } /** Reports whether this message answers a recovery request, and the patches sent since then. */ - private consumeParagraphFetch( - msgId: string | undefined - ): { ownPatches: Array } | undefined { + private consumeParagraphFetch(msgId: string | undefined): { ownPatches: SentPatch[] } | undefined { if (msgId === undefined) { return undefined; }