Skip to content

feat: spotlight-org sync from hr-syncer events#170

Merged
mliu33 merged 3 commits into
mainfrom
claude/spotlight-org-sync-design-fS2qh
Jul 1, 2026
Merged

feat: spotlight-org sync from hr-syncer events#170
mliu33 merged 3 commits into
mainfrom
claude/spotlight-org-sync-design-fS2qh

Conversation

@Joey0538

@Joey0538 Joey0538 commented May 11, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • New spotlight-org collection in search-sync-worker that consumes daily HR employee batches from hr-syncer and maintains a per-section ES index (spotlightorg-{siteID}-vN) keyed by sectId.
  • Adds the shared HR stream + subject builders (stream.OrgSyncStream, subject.OrgSyncEmployeesUpsert) — Go names deliberately scoped to "org sync" to avoid clashing with the internal repo's HRJOS builders; wire values still match hr-syncer's actual publish.
  • Threads a DEV_MODE toggle through the message + spotlight templates so single-node ES setups can run 1 shard / 0 replicas.

Design

  • Central-site topology. hr-syncer runs at one central site (e.g. foc in prod). Every fab site's search-sync-worker consumes from the shared HR_{centralSiteID} stream. The spotlightOrgCollection stores both a localSiteID and an hrCentralSiteID: stream config + filter subjects target the central site (where hr-syncer publishes), while the durable consumer name is scoped by local site (spotlight-org-sync-{localSiteID}) so each fab site keeps its own cursor.
  • Wire format. Payload is {timestamp int64, employees: [...]}; each employee element is a full Employee struct from hr-syncer's internal repo. On our side we decode straight into []SpotlightOrgIndex — JSON drops fields we don't declare, so we pick up only the nine org fields we care about.
  • Compression is signalled by the NATS Nats-Encoding: zstd header. Decompression is handled centrally in handler.go's Add (a shared compression.go helper with a pooled zstd.Decoder and a 16 MB WithDecoderMaxMemory cap). Collections never see the compressed frame; the Collection.BuildAction([]byte) interface stays codec-agnostic.
  • Doc-merge upsert + omitempty: partial-field publishes (e.g. only sectId + a renamed sectName) produce ES _update bodies containing only the changed keys. Doc-merge preserves other stored fields without any painless script.
  • Dedup by SectID: within a batch, employees sharing the same section collapse to one action (last-wins). Empty-SectID rows are skipped; all-empty batches return (nil, nil) so the handler acks with no ES write.
  • Stream ownership: HR_{centralSiteID} schema is owned by hr-syncer. search-sync-worker is a pure consumer and skips this stream in its bootstrap loop, matching how it already skips INBOX (owned by inbox-worker).

Commits

  1. feat(stream,subject): HR wire infrastructurestream.OrgSyncStream, subject.OrgSyncEmployeesUpsert.
  2. refactor(search-sync-worker): DEV_MODE toggle for message + spotlight templates — thread devMode through the two existing template builders (spotlight-org gets it too as part of commit 3).
  3. feat(search-sync-worker): spotlight-org collection consuming chat.hr.employees.upsert — new spotlightOrgCollection, shared compression.go, main.go wiring (SPOTLIGHT_ORG_INDEX + HR_CENTRAL_SITE_ID + DEV_MODE env vars, HR bootstrap skip), integration test, docker-compose.

New env vars for search-sync-worker

Var Required Purpose
SPOTLIGHT_ORG_INDEX yes (must end -vN) e.g. spotlightorg-foc-v1
HR_CENTRAL_SITE_ID yes Central site where hr-syncer publishes (e.g. foc)
DEV_MODE no (default false) Collapse every template to 1 shard / 0 replicas

Test plan

  • make test SERVICE=pkg/stream — passes
  • make test SERVICE=pkg/subject — passes
  • make test SERVICE=search-sync-worker — passes (spotlight-org unit tests + handler-level zstd decompression tests + all preexisting collection tests)
  • make lint — clean
  • go vet -tags=integration ./search-sync-worker/... — clean
  • Run make test-integration SERVICE=search-sync-worker against the testcontainers harness — pending CI (TestSearchSyncSpotlightOrg_Integration publishes zstd-compressed batches with Nats-Encoding: zstd header and verifies doc upsert + doc-merge field preservation)

Coordination with hr-syncer

Wire-format contract Mat needs to match on the publish side:

  • Subject: chat.hr.{centralSiteID}.employees.upsert
  • Stream: HR_{centralSiteID}
  • Body: {"timestamp": int64, "employees": [...]} where each employee has at minimum a sectId string field
  • Optional compression: set NATS header Nats-Encoding: zstd and publish the zstd-compressed body directly (no base64, no envelope wrapper).

Spec / plan

  • Design: docs/superpowers/specs/2026-05-11-spotlight-org-sync-design.md
  • Plan: docs/superpowers/plans/2026-05-11-spotlight-org-sync.md

Note: the spec and plan docs reflect an earlier iteration (envelope-based compression, single-site consumer) and haven't been updated for the central-site topology or header-based compression. The current implementation is authoritative.

https://claude.ai/code/session_01QLFefxiCHDP24LDLQzLLG2

@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds a new spotlight-org Elasticsearch index collection to search-sync-worker that consumes HR sync events from JetStream. It introduces shared template helpers (indexTopology, customAnalyzerSettings), threads a DEV_MODE toggle through existing collections (message, spotlight, user-room), and wires the new collection into the worker with comprehensive testing and Elasticsearch doc-merge upsert semantics.

Changes

Spotlight Org Sync Implementation

Layer / File(s) Summary
Design & Implementation Plans
docs/superpowers/specs/2026-05-11-spotlight-org-sync-design.md, docs/superpowers/plans/2026-05-11-spotlight-org-sync.md
Specifications and implementation plan for consuming HR sync envelopes, maintaining spotlight-org index keyed by sectId, doc-merge upsert semantics, dev-mode topology toggling, and end-to-end verification approach.
HRSync Model & Contracts
pkg/model/hrsync.go, pkg/model/model_test.go, pkg/stream/stream.go, pkg/stream/stream_test.go, pkg/subject/subject.go, pkg/subject/subject_test.go
New HRSyncEvent envelope struct (timestamp, batchId, gzip flag, raw payload). New stream.HRSync(siteID) stream configuration and HRSyncEmployeesUpsert/HRSyncUsersUpsert subject builders with unit tests.
Shared Template Infrastructure
search-sync-worker/template.go, search-sync-worker/template_test.go
Introduced indexTopology(prodShards, prodReplicas, devMode) that collapses index topology to 1 shard/0 replicas in dev mode, and customAnalyzerSettings() providing shared tokenizer/analyzer/filter configuration with token_chars. Unit tests validate both helpers.
DevMode Threading: Messages
search-sync-worker/messages.go, search-sync-worker/messages_test.go
Updated messageCollection to store devMode flag. Modified newMessageCollection(indexPrefix, devMode) and messageTemplateBody(prefix, devMode) to use indexTopology helper for shard/replica counts. Added dev-vs-prod template test.
DevMode Threading: Spotlight
search-sync-worker/spotlight.go, search-sync-worker/spotlight_test.go
Refactored existing spotlight template to use shared customAnalyzerSettings helper. Updated spotlightCollection to store devMode. Modified newSpotlightCollection(indexName, devMode) and spotlightTemplateBody(indexName, devMode) to use indexTopology and shared analyzer helpers. Added token_chars assertion and dev-vs-prod template tests.
DevMode Threading: User Room
search-sync-worker/user_room.go, search-sync-worker/user_room_test.go
Updated userRoomCollection to store devMode. Modified newUserRoomCollection(indexName, devMode) and userRoomTemplateBody(indexName, devMode) to use indexTopology helper. Added dev-vs-prod template test.
SpotlightOrg Collection
search-sync-worker/spotlight_org.go, search-sync-worker/spotlight_org_test.go
New spotlightOrgCollection consuming hr.sync.{siteID}.employees.upsert subjects. SpotlightOrgIndex document schema with nine org fields and omitempty JSON tags. BuildAction unmarshals HRSync envelopes, decompresses gzip when Gzip=true, deduplicates by SectID (last-wins), emits ES updates with doc_as_upsert semantics. Template generation uses shared helpers. Comprehensive unit tests cover dedup, gzip, partial fields, error paths, and template topology.
Worker Wiring
search-sync-worker/main.go
Added SpotlightOrgIndex and DevMode configuration fields loaded from env vars. Default index name derived from SITE_ID. Register spotlightOrgCollection alongside existing collections, passing DevMode to all constructors. Update stream bootstrap to skip HR_SYNC creation (owned by hr-syncer). Add startup logging for new config fields.
Test Harness Updates
search-sync-worker/handler_test.go, search-sync-worker/inbox_integration_test.go, search-sync-worker/integration_test.go
Updated all collection constructor calls to pass false for devMode argument in existing tests.
Integration Test
search-sync-worker/integration_test.go
New TestSearchSyncSpotlightOrg_Integration boots ES+NATS, creates HR_SYNC stream/consumer, publishes gzipped HRSync events with employee data, consumes messages, flushes to ES, and verifies index documents and doc-merge preservation across subsequent updates.
Local Dev Configuration
search-sync-worker/deploy/docker-compose.yml
Set DEV_MODE environment variable with default value true for local development.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • hmchangw/chat#109: Prior spotlight/user-room collection refactor that this PR builds upon with additional devMode threading and template helpers.
  • hmchangw/chat#64: Initial search-sync-worker implementation that introduced the collection pattern now extended by this PR.

Suggested reviewers

  • mliu33

Poem

🐰 A worker now syncs sections from the sky,
HRSync envelopes gzipped and dry.
Deduplicate, merge, let Elasticsearch play,
Doc-merge upserts save the forgotten day. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'feat: spotlight-org sync from hr-syncer events' accurately and concisely describes the primary change: adding spotlight organization synchronization functionality from hr-syncer events.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/spotlight-org-sync-design-fS2qh

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (2)
search-sync-worker/template_test.go (1)

22-35: 💤 Low value

Consider guarding type assertions with require.NotNil checks.

The type assertions on lines 25-34 will panic if customAnalyzerSettings() returns an unexpected structure. While test panics are acceptable failures, adding require.NotNil checks before each type assertion would make failures clearer and provide better diagnostics.

🛡️ Example: safer assertions
 func TestCustomAnalyzerSettings_Shape(t *testing.T) {
 	got := customAnalyzerSettings()
 
 	analyzer := got["analyzer"].(map[string]any)
+	require.NotNil(t, analyzer, "analyzer section must be present")
 	custom := analyzer["custom_analyzer"].(map[string]any)
+	require.NotNil(t, custom, "custom_analyzer must be present")
 	assert.Equal(t, "custom", custom["type"])
 	...
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@search-sync-worker/template_test.go` around lines 22 - 35,
TestCustomAnalyzerSettings_Shape uses unchecked type assertions on the structure
returned by customAnalyzerSettings(), which can panic and obscure failures;
before each assertion, add require.NotNil checks for got, analyzer :=
got["analyzer"], custom := analyzer["custom_analyzer"], tokenizer :=
got["tokenizer"], and tok := tokenizer["custom_tokenizer"] (or equivalent
intermediate values) to ensure those keys exist and are non-nil, then proceed
with the type assertions and existing assert.Equal checks in the
TestCustomAnalyzerSettings_Shape function.
search-sync-worker/spotlight_org.go (1)

135-142: 💤 Low value

Optional: surface gzip.Reader.Close() error instead of silently discarding via defer.

gr.Close() can return a checksum/truncation error after the body has already been read. With defer gr.Close() the error is dropped, so a corrupt-tail payload silently parses as a successful (possibly truncated) JSON. Low-impact in practice — io.ReadAll typically surfaces the same error first — but worth tightening since this is the trust boundary for an external publisher.

♻️ Suggested rewrite
 func gunzipBytes(b []byte) ([]byte, error) {
 	gr, err := gzip.NewReader(bytes.NewReader(b))
 	if err != nil {
 		return nil, err
 	}
-	defer gr.Close()
-	return io.ReadAll(gr)
+	data, readErr := io.ReadAll(gr)
+	closeErr := gr.Close()
+	if readErr != nil {
+		return nil, readErr
+	}
+	if closeErr != nil {
+		return nil, closeErr
+	}
+	return data, nil
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@search-sync-worker/spotlight_org.go` around lines 135 - 142, The current
gunzipBytes function defers gzip.NewReader.Close(), which discards any Close()
error (e.g., checksum/truncation) — change the function to explicitly call
io.ReadAll(gr) into a variable, then call gr.Close() and if Close() returns a
non-nil error return that error (or if both Read and Close produce errors prefer
the read error but surface the close error when present); update the
implementation around gzip.NewReader, io.ReadAll and gr.Close() so Close()
errors are not silently ignored.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@search-sync-worker/spotlight_org.go`:
- Around line 135-142: The current gunzipBytes function defers
gzip.NewReader.Close(), which discards any Close() error (e.g.,
checksum/truncation) — change the function to explicitly call io.ReadAll(gr)
into a variable, then call gr.Close() and if Close() returns a non-nil error
return that error (or if both Read and Close produce errors prefer the read
error but surface the close error when present); update the implementation
around gzip.NewReader, io.ReadAll and gr.Close() so Close() errors are not
silently ignored.

In `@search-sync-worker/template_test.go`:
- Around line 22-35: TestCustomAnalyzerSettings_Shape uses unchecked type
assertions on the structure returned by customAnalyzerSettings(), which can
panic and obscure failures; before each assertion, add require.NotNil checks for
got, analyzer := got["analyzer"], custom := analyzer["custom_analyzer"],
tokenizer := got["tokenizer"], and tok := tokenizer["custom_tokenizer"] (or
equivalent intermediate values) to ensure those keys exist and are non-nil, then
proceed with the type assertions and existing assert.Equal checks in the
TestCustomAnalyzerSettings_Shape function.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5e7e4d29-64c0-4fdf-a305-4b2423ad6386

📥 Commits

Reviewing files that changed from the base of the PR and between 7817eb6 and f9fff45.

📒 Files selected for processing (23)
  • docs/superpowers/plans/2026-05-11-spotlight-org-sync.md
  • docs/superpowers/specs/2026-05-11-spotlight-org-sync-design.md
  • pkg/model/hrsync.go
  • pkg/model/model_test.go
  • pkg/stream/stream.go
  • pkg/stream/stream_test.go
  • pkg/subject/subject.go
  • pkg/subject/subject_test.go
  • search-sync-worker/deploy/docker-compose.yml
  • search-sync-worker/handler_test.go
  • search-sync-worker/inbox_integration_test.go
  • search-sync-worker/integration_test.go
  • search-sync-worker/main.go
  • search-sync-worker/messages.go
  • search-sync-worker/messages_test.go
  • search-sync-worker/spotlight.go
  • search-sync-worker/spotlight_org.go
  • search-sync-worker/spotlight_org_test.go
  • search-sync-worker/spotlight_test.go
  • search-sync-worker/template.go
  • search-sync-worker/template_test.go
  • search-sync-worker/user_room.go
  • search-sync-worker/user_room_test.go

Joey0538 pushed a commit that referenced this pull request May 11, 2026
gzip.Reader.Close reports trailing checksum / truncation errors that
io.ReadAll can miss on a corrupted stream. Replace the deferred close
with an explicit one so a truncated publisher payload doesn't parse as
a successful (short) JSON. Per CodeRabbit review on PR #170.

https://claude.ai/code/session_01QLFefxiCHDP24LDLQzLLG2
@Joey0538 Joey0538 marked this pull request as draft May 12, 2026 01:54
@Joey0538 Joey0538 force-pushed the claude/spotlight-org-sync-design-fS2qh branch from 98c3e80 to e1618c4 Compare June 29, 2026 02:00
@Joey0538 Joey0538 marked this pull request as ready for review June 29, 2026 03:31
@Joey0538 Joey0538 added ready and removed dont merge labels Jun 29, 2026
@Joey0538 Joey0538 force-pushed the claude/spotlight-org-sync-design-fS2qh branch from 56b7b8f to 019f4d8 Compare June 29, 2026 04:52
Comment thread pkg/stream/stream.go Outdated
// publishes on hr.sync.{siteID}.>. Schema is owned by hr-syncer.
func HRSync(siteID string) Config {
return Config{
Name: fmt.Sprintf("HR_SYNC_%s", siteID),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is the old naming and subject names. It has been updated, plz check the latest one

Comment thread pkg/subject/subject.go Outdated
}

func HRSyncEmployeesUpsert(siteID string) string {
return fmt.Sprintf("hr.sync.%s.employees.upsert", siteID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is the old name

Comment thread pkg/subject/subject.go Outdated
}

func HRSyncUsersUpsert(siteID string) string {
return fmt.Sprintf("hr.sync.%s.users.upsert", siteID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is the old name

Comment thread search-sync-worker/main.go Outdated
// search-sync-worker is a pure consumer of both and must not create
// their schemas.
inboxName := stream.Inbox(cfg.SiteID).Name
hrSyncName := stream.HRSync(cfg.SiteID).Name

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

It has been updated. Plz check latest one

DeptTCName string `json:"deptTCName,omitempty" es:"search_as_you_type,custom_analyzer"`
DeptName string `json:"deptName,omitempty" es:"search_as_you_type,custom_analyzer"`
DeptDescription string `json:"deptDescription,omitempty" es:"search_as_you_type,custom_analyzer"`
DivisionID string `json:"divisionId,omitempty" es:"search_as_you_type,custom_analyzer"`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do we support searching division id in current behavior ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No, but this data was still present in ES

@Joey0538 Joey0538 force-pushed the claude/spotlight-org-sync-design-fS2qh branch 3 times, most recently from 8592ce1 to 58f1ee3 Compare July 1, 2026 06:57
claude added 3 commits July 1, 2026 08:00
- stream.HR(siteID) → HR_{siteID} stream carrying chat.hr.{siteID}.>
  publishes. Schema is owned by hr-syncer.
- subject.HREmployeesUpsert / HRUsersUpsert build the corresponding
  employees / users subjects.

https://claude.ai/code/session_01QLFefxiCHDP24LDLQzLLG2
… templates

Add a devMode field to messageCollection and spotlightCollection.
Each constructor takes devMode bool and threads it through TemplateBody
to *TemplateBody(prefix, devMode). Shard/replica counts are computed
inline:

  messages   prod 4/2 -> dev 1/0
  spotlight  prod 3/1 -> dev 1/0

Consumer wires cfg.DevMode into both new-collection callsites in main.go
(applied in the spotlight-org commit alongside the new collection's own
devMode plumbing). user-room is untouched.

https://claude.ai/code/session_01QLFefxiCHDP24LDLQzLLG2
…employees.upsert

Maintains a per-section ES index (spotlightorg-{siteID}-vN) keyed by
sectId, sourced from hr-syncer's batched HR account publishes on the
new HR stream.

Design highlights:
- SpotlightOrgIndex is one struct serving three roles: wire-side row
  unmarshal target, ES doc body on write, and source of truth for the
  ES mapping via esPropertiesFromStruct. Nine string fields with
  omitempty and search_as_you_type / custom_analyzer ES mapping.
- Local hrSyncEmployeeBatch{Timestamp, Employees} type in
  search-sync-worker (NOT pkg/model) — the full Employee struct lives
  in hr-syncer's internal repo, and JSON unmarshal into
  []SpotlightOrgIndex reads only the org fields we care about, ignoring
  the rest.
- Collection.BuildAction interface signature changes from ([]byte) to
  (jetstream.Msg) so BuildAction implementations can read NATS message
  headers. All existing collections updated to the new signature.
- Compression is signalled by the Nats-Encoding: zstd header (matching
  hr-syncer's convention). When present, the message body is a raw
  zstd frame decompressed with a 16MB size cap to prevent OOM on
  hostile payloads.
- BuildAction dedupes by SectID keeping last-wins per batch and emits
  one ES _update per unique sectId with doc_as_upsert:true. Doc-merge +
  omitempty means partial-field publishes preserve untouched stored
  fields — no painless script needed. Empty SectID rows and empty
  batches return (nil, nil) so the handler acks with no ES write.
- ActionUpdate is used WITHOUT external versioning; handler.go's 409
  logic for ActionUpdate depends on Version=0.
- StoredScripts() returns nil - the collection uses no inline scripts.
- devMode wired into all three new-collection callsites in main.go
  (messages, spotlight, spotlight-org). Includes SPOTLIGHT_ORG_INDEX
  as a required env var (vN-suffixed like other search indices) and
  the HR bootstrap skip (same as INBOX ownership pattern).

Integration test publishes zstd-compressed batches over NATS with the
Nats-Encoding header and verifies doc upsert + doc-merge field
preservation across subsequent updates.

Also carries: docker-compose SPOTLIGHT_ORG_INDEX + DEV_MODE entries;
klauspost/compress upgraded from indirect to direct dependency;
design + implementation-plan docs.

https://claude.ai/code/session_01QLFefxiCHDP24LDLQzLLG2
@Joey0538 Joey0538 force-pushed the claude/spotlight-org-sync-design-fS2qh branch from 58f1ee3 to 0114f16 Compare July 1, 2026 08:00
@mliu33 mliu33 merged commit 4bba9cd into main Jul 1, 2026
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants